Python types 模块,TupleType() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.TupleType()

项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
def _buildItemList(self, values, typehint=None):
        if isinstance(values, OSCMessage):
            items = values.items()
        elif type(values) == types.ListType:
            items = []
            for val in values:
                if type(val) == types.TupleType:
                    items.append(val[:2])
                else:
                    items.append((typehint, val))
        elif type(values) == types.TupleType:
            items = [values[:2]]
        else:       
            items = [(typehint, values)]

        return items
项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
def setOSCTarget(self, address, prefix=None, filters=None):
        """Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
          the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
            or a 'host' (string) : The host will be looked-up 
          - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
          sent to this OSCTarget (optional)
        """
        if type(address) in types.StringTypes:
            address = self._searchHostAddr(address)

        elif (type(address) == types.TupleType):
            (host, port) = address[:2]
            try:
                host = socket.gethostbyname(host)
            except:
                pass

            address = (host, port)
        else:
            raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")

        self._setTarget(address, prefix, filters)
项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
def delOSCTarget(self, address, prefix=None):
        """Delete the specified OSCTarget from the Client's dict.
        the 'address' argument can be a ((host, port) tuple), or a hostname.
        If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
        """
        if type(address) in types.StringTypes:
            address = self._searchHostAddr(address) 

        if type(address) == types.TupleType:
            (host, port) = address[:2]
            try:
                host = socket.gethostbyname(host)
            except socket.error:
                pass
            address = (host, port)

            self._delTarget(address, prefix)
项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
def getOSCTarget(self, address):
        """Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
        'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
        Returns (None, ['',{}]) if address not found.
        """
        if type(address) in types.StringTypes:
            address = self._searchHostAddr(address) 

        if (type(address) == types.TupleType): 
            (host, port) = address[:2]
            try:
                host = socket.gethostbyname(host)
            except socket.error:
                pass
            address = (host, port)

            if (address in self.targets.keys()):
                try:
                    (host, _, _) = socket.gethostbyaddr(host)
                except socket.error:
                    pass

                return ((host, port), self.targets[address])

        return (None, ['',{}])
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)))
项目:abe-bootstrap    作者:TryCoin-Team    | 项目源码 | 文件源码
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
项目:abe-bootstrap    作者:TryCoin-Team    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)
项目:electrum-martexcoin-server    作者:martexcoin    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)))
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __iadd__(self, other):
        """Suma un vector con otro"""
        if isinstance(other, Vector3):
            self.x += other.get_x()
            self.y += other.get_y()
            self.z += other.get_z()
            return self
        elif isinstance(other, types.TupleType) or isinstance(other, types.ListType):
            if len(other) == 3:
                self.x += other[0]
                self.y += other[1]
                self.z += other[2]
                return self
        else:
            self.throwError(2, "__iadd__")
            return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __isub__(self, other):
        """Resta un vector con otro"""
        if isinstance(other, Vector3):
            self.x -= other.get_x()
            self.y -= other.get_y()
            self.z -= other.get_z()
            return self
        elif isinstance(other, types.TupleType) or isinstance(other, types.ListType):
            if len(other) == 3:
                self.x -= other[0]
                self.y -= other[1]
                self.z -= other[2]
                return self
        else:
            self.throwError(2, "__isub__")
            return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __idiv__(self, other):
        """Division con otro vector por valor"""
        if isinstance(other, Vector3):
            self.x /= other.get_x()
            self.y /= other.get_y()
            self.z /= other.get_z()
            return self
        else:
            if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
                self.x /= other[0]
                self.y /= other[1]
                self.z /= other[2]
                return self
            elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
                self.x /= other
                self.y /= other
                self.z /= other
                return self
            else:
                self.throwError(2, "__idiv__")
                return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def normal3points(a, b, c):
    """Retorna el vector normal dado tres puntos a, b, c"""
    if isinstance(a, types.ListType) or isinstance(a, types.TupleType):
        a = Vector3(*a)
        b = Vector3(*b)
        c = Vector3(*c)
    elif isinstance(a, Point3):
        a = Vector3(*a.export_to_list())
        b = Vector3(*b.export_to_list())
        c = Vector3(*c.export_to_list())
    cross_result = (a - c).cross(b - c).get_normalized()
    if cross_result.get_x() == -0.0:
        cross_result.set_x(0.0)
    if cross_result.get_y() == -0.0:
        cross_result.set_y(0.0)
    if cross_result.get_z() == -0.0:
        cross_result.set_z(0.0)
    return cross_result
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __iadd__(self, other):
        """Suma un vector con otro"""
        if isinstance(other, Vector3):
            self.x += other.get_x()
            self.y += other.get_y()
            self.z += other.get_z()
            return self
        elif isinstance(other, types.TupleType) or isinstance(other, types.ListType):
            if len(other) == 3:
                self.x += other[0]
                self.y += other[1]
                self.z += other[2]
                return self
        else:
            self.throwError(2, "__iadd__")
            return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __isub__(self, other):
        """Resta un vector con otro"""
        if isinstance(other, Vector3):
            self.x -= other.get_x()
            self.y -= other.get_y()
            self.z -= other.get_z()
            return self
        elif isinstance(other, types.TupleType) or isinstance(other, types.ListType):
            if len(other) == 3:
                self.x -= other[0]
                self.y -= other[1]
                self.z -= other[2]
                return self
        else:
            self.throwError(2, "__isub__")
            return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __imul__(self, other):
        """Producto punto con otro"""
        if isinstance(other, Vector3):
            self.x *= other.get_x()
            self.y *= other.get_y()
            self.z *= other.get_z()
            return self
        else:
            if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
                self.x *= other[0]
                self.y *= other[1]
                self.z *= other[2]
                return self
            elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
                self.x *= other
                self.y *= other
                self.z *= other
                return self
            else:
                self.throwError(2, "__imul__")
                return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def __idiv__(self, other):
        """Division con otro vector por valor"""
        if isinstance(other, Vector3):
            self.x /= other.get_x()
            self.y /= other.get_y()
            self.z /= other.get_z()
            return self
        else:
            if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
                self.x /= other[0]
                self.y /= other[1]
                self.z /= other[2]
                return self
            elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
                self.x /= other
                self.y /= other
                self.z /= other
                return self
            else:
                self.throwError(2, "__idiv__")
                return self
项目:CC3501-2017-1    作者:ppizarror    | 项目源码 | 文件源码
def normal3points(a, b, c):
    """Retorna el vector normal dado tres puntos a, b, c"""
    if isinstance(a, types.ListType) or isinstance(a, types.TupleType):
        a = Vector3(*a)
        b = Vector3(*b)
        c = Vector3(*c)
    elif isinstance(a, Point3):
        a = Vector3(*a.export_to_list())
        b = Vector3(*b.export_to_list())
        c = Vector3(*c.export_to_list())
    cross_result = (a - c).cross(b - c).get_normalized()
    if cross_result.get_x() == -0.0:
        cross_result.set_x(0.0)
    if cross_result.get_y() == -0.0:
        cross_result.set_y(0.0)
    if cross_result.get_z() == -0.0:
        cross_result.set_z(0.0)
    return cross_result
项目:watchmen    作者:lycclsltt    | 项目源码 | 文件源码
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
项目:lbryum-server    作者:lbryio    | 项目源码 | 文件源码
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
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def unwrap(value):
    t = type(value)
    if t is types.InstanceType and isinstance(value, DynamicProxy):
        if pyro_daemon:
            try:
                return pyro_daemon.getLocalObject(value.objectID)
            except KeyError:
                pass
        return value
    elif t is types.ListType:
        for i in range(len(value)):
            value[i] = unwrap(value[i])
    elif t is types.TupleType:
        value = list(value)
        for i in range(len(value)):
            value[i] = unwrap(value[i])
        return tuple(value)
    elif t is types.DictType:
        for k, v in value.items():
            value[k] = unwrap(v)
    return value
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
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
项目:git_intgrtn_aws_s3    作者:droidlabour    | 项目源码 | 文件源码
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
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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)))
项目:Bitly-Symbian    作者:gauravssnl    | 项目源码 | 文件源码
def _generateSignature(self, params, secret):
        if not params or not secret:
            return ""
        hash_string = ""
        if not params.get('t'):
            # note, this uses a utc timestamp not a local timestamp
            params['t'] = str(int(time.mktime(time.gmtime())))

        keys = params.keys()
        keys.sort()
        for k in keys:
            if type(params[k]) in [types.ListType, types.TupleType]:
                for v in params[k]:
                    hash_string += v
            else:
                hash_string += params[k]
        hash_string += secret
        signature = hashlib.md5(hash_string).hexdigest()[:10]
        return signature
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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)))
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
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
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
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
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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)))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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)))
项目:opc-rest-api    作者:matzpersson    | 项目源码 | 文件源码
def type_check(tags):
   """Perform a type check on a list of tags"""

   if type(tags) in (types.ListType, types.TupleType):
      single = False
   elif tags == None:
      tags = []
      single = False
   else:
      tags = [tags]
      single = True

   if len([t for t in tags if type(t) not in types.StringTypes]) == 0:
      valid = True
   else:
      valid = False

   return tags, single, valid
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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)))
项目:Encryped-file-system    作者:kittenish    | 项目源码 | 文件源码
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
项目:Flask-NvRay-Blog    作者:rui7157    | 项目源码 | 文件源码
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)))
项目:Flask-NvRay-Blog    作者:rui7157    | 项目源码 | 文件源码
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)))
项目:ngas    作者:ICRAR    | 项目源码 | 文件源码
def _genFileKey(fileInfo):
    """
    Generate a dictionary key from information in the File Info object,
    which is either a list with information from ngas_files, or an
    ngamsFileInfo object.

    fileInfo:       File Info as read from the ngas_files table or
                    an instance of ngamsFileInfo (list|ngamsFileInfo).

    Returns:        File key (string).
    """
    if ((type(fileInfo) == types.ListType) or
        (type(fileInfo) == types.TupleType)):
        fileId  = fileInfo[ngamsDbCore.NGAS_FILES_FILE_ID]
        fileVer = fileInfo[ngamsDbCore.NGAS_FILES_FILE_VER]
    else:
        fileId  = fileInfo.getFileId()
        fileVer = fileInfo.getFileVersion()
    return ngamsLib.genFileKey(None, fileId, fileVer)
项目:deb-python-jsonrpclib    作者:openstack    | 项目源码 | 文件源码
def validate_request(request):
    if not isinstance(request, dict):
        fault = Fault(
            -32600, 'Request must be {}, not %s.' % type(request)
        )
        return fault
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        fault = Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
        return fault
    request.setdefault('params', [])
    method = request.get('method', None)
    params = request.get('params')
    param_types = (types.ListType, types.DictType, types.TupleType)
    if not method or type(method) not in types.StringTypes or \
            type(params) not in param_types:
        fault = Fault(
            -32600, 'Invalid request parameters or method.', rpcid=rpcid
        )
        return fault
    return True
项目:deb-python-jsonrpclib    作者:openstack    | 项目源码 | 文件源码
def isbatch(result):
    if type(result) not in (types.ListType, types.TupleType):
        return False
    if len(result) < 1:
        return False
    if not isinstance(result[0], dict):
        return False
    if 'jsonrpc' not in result[0].keys():
        return False
    try:
        version = float(result[0]['jsonrpc'])
    except ValueError:
        raise ProtocolError('"jsonrpc" key must be a float(able) value.')
    if version < 2:
        return False
    return True
项目:isf    作者:w3h    | 项目源码 | 文件源码
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
项目:lbryum    作者:lbryio    | 项目源码 | 文件源码
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: " + x
            if not isinstance(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
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
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()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
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()
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def _set_attrs(self,l,d):
    self.obsolete = d['OBSOLETE']!=None
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    # Default is STRUCTURAL, see RFC2552 or draft-ietf-ldapbis-syntaxes
    self.kind = 0
    if d['ABSTRACT']!=None:
      self.kind = 1
    elif d['AUXILIARY']!=None:
      self.kind = 2
    if self.kind==0 and not d['SUP'] and self.oid!='2.5.6.0':
      # STRUCTURAL object classes are sub-classes of 'top' by default
      self.sup = ('top',)
    else:
      self.sup = d['SUP']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.sup)==TupleType
    assert type(self.kind)==IntType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def _set_attrs(self,l,d):
    self.obsolete = d['OBSOLETE']!=None
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    # Default is STRUCTURAL, see RFC2552 or draft-ietf-ldapbis-syntaxes
    self.kind = 0
    if d['ABSTRACT']!=None:
      self.kind = 1
    elif d['AUXILIARY']!=None:
      self.kind = 2
    if self.kind==0 and not d['SUP'] and self.oid!='2.5.6.0':
      # STRUCTURAL object classes are sub-classes of 'top' by default
      self.sup = ('top',)
    else:
      self.sup = d['SUP']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.sup)==TupleType
    assert type(self.kind)==IntType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.aux = d['AUX']
    self.must = d['MUST']
    self.may = d['MAY']
    self.nots = d['NOT']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.aux)==TupleType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    assert type(self.nots)==TupleType
    return
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
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()