Python types.LongType() Examples

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

Example 1
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 2
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 3
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 4
Project: dumpDex   Author: CvvT   File: idc.py    Apache License 2.0 6 votes vote down vote up
def SetRegValue(value, name):
    """
    Set register value

    @param name: the register name
    @param value: new register value

    @note: The debugger should be running
           It is not necessary to use this function to set register values.
           A register name in the left side of an assignment will do too.
    """
    rv = idaapi.regval_t()
    if type(value) == types.StringType:
        value = int(value, 16)
    elif type(value) != types.IntType and type(value) != types.LongType:
        print "SetRegValue: value must be integer!"
        return BADADDR

    if value < 0:
        #ival_set cannot handle negative numbers
        value &= 0xFFFFFFFF

    rv.ival = value
    return idaapi.set_reg_val(name, rv) 
Example 5
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: IPy.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 6
Project: Squirt   Author: CybernetiX-S3C   File: IPy.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 7
Project: InfoSploit   Author: CybernetiX-S3C   File: IPy.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 8
Project: geofire-python   Author: ininex   File: _version200.py    MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 9
Project: geofire-python   Author: ininex   File: _version200.py    MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 10
Project: geofire-python   Author: ininex   File: _version200.py    MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 11
Project: Niallbot   Author: kafejo   File: _version200.py    MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 12
Project: Niallbot   Author: kafejo   File: _version200.py    MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 13
Project: Niallbot   Author: kafejo   File: _version200.py    MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 14
Project: aqua-monitor   Author: Deltares   File: _version200.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 15
Project: aqua-monitor   Author: Deltares   File: _version200.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 16
Project: aqua-monitor   Author: Deltares   File: _version200.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 17
Project: NoobSec-Toolkit   Author: krintoxi   File: IPy.py    GNU General Public License v2.0 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 18
Project: NoobSec-Toolkit   Author: krintoxi   File: IPy.py    GNU General Public License v2.0 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 19
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def make_arrays(**attrs):
    """
    Makes an array of same type from all attributes in attrs dictionary
    A bit slow! Avoid using this function!
    """
    for attr in attrs.keys():
        obj = attrs[attr]
        if type(attrs[attr]) == ndarray:
            attrs[attr] = attrs[attr].reshape((1,) + obj.shape)
        elif type(obj) in (types.FloatType, types.LongType):
            attrs[attr] = array([obj], float)
        elif type(obj) == types.IntType:
            attrs[attr] = array([obj], int)
        elif type(obj) == types.BooleanType:
            attrs[attr] = array([obj], bool)
        else:
            # another strange type
            dt = 'O'
            for typename in dir(types):
                if type(obj) == types.__dict__[typename]:
                    dt = get_dtype(typename)
                    break
            attrs[attr] = array([obj], dtype=dt)
    return attrs 
Example 20
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def get_printformat(self, attr):
        """
        Returnes the standad fortran stringformat for attribute.
        """
        config = self.get_config(attr)
        tt = config['type'][0]
        if tt in ('IntType', 'LongType'):
            return '%' + str(config['digits_integer']) + 'd'

        elif tt in ('FloatType', 'ComplexType'):
            return '%' + str(config['digits_integer']) + '.'\
                + str(config['digits_fraction']) + 'f'

        else:
            # its a string
            return '%s'

        return printformat 
Example 21
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def get_numformat(self, attr, confog=None):
        """
        Returns a dictionary with all formatting infos on attribute.
        It is tried to detect the numerical datatype and define
        formatting info, if not already defined.
        """
        # determine format of numeric value

        config = self.get_config(attr)

        # take top level type
        tt = config['type'][0]
        numformat = {}
        if tt in ('IntType', 'LongType'):
            numformat['digits_integer'] = config.get('digits_integer', 13)
            numformat['digits_fraction'] = config.get('digits_fraction', 0)
        else:
            numformat['digits_integer'] = config.get('digits_integer', 9)
            numformat['digits_fraction'] = config.get('digits_fraction', 8)

        numformat['min'] = config.get('min', None)
        numformat['max'] = config.get('max', None)

        # print 'get_numformat',attr,numformat
        return numformat 
Example 22
Project: NLP.py   Author: PythonOptimizers   File: sparse_vector_class.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __pow__(self, other):
        """Raise each element of sparse vector to a power.

        If power is another sparse vector, compute elementwise power.
        In this latter case, by convention, 0^0 = 0.
        """
        if not isSparseVector(self):
            raise TypeError("Argument must be a SparseVector")
        if isSparseVector(other):
            rv = SparseVector(max(self.n, other.n), {})
            for k in self.values.keys():
                rv[k] = self[k]**other[k]
            return rv
        if not isinstance(other, types.IntType) and \
           not isinstance(other, types.LongType) and \
           not isinstance(other, types.FloatType):
                raise TypeError("Power must be numeric or a sparse vector")
        rv = SparseVector(self.n, {})
        for k in self.values.keys():
            rv[k] = math.pow(self[k], other)
        return rv 
Example 23
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 24
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 25
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 26
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 27
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo
    n"""

    if type(message) is types.IntType:
        return encrypt_int(long(message), ekey, n)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or an int")

    if message > 0 and \
            math.floor(math.log(message, 2)) > math.floor(math.log(n, 2)):
        raise OverflowError("The message is too long")

    return fast_exponentiation(message, ekey, n) 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """
    Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 29
Project: hackerdroid   Author: CreatorB   File: androconf.py    MIT License 5 votes vote down vote up
def long2str(l):
    """Convert an integer to a string."""
    if type(l) not in (types.IntType, types.LongType):
        raise ValueError, 'the input must be an integer'

    if l < 0:
        raise ValueError, 'the input must be greater than 0'
    s = ''
    while l:
        s = s + chr(l & 255L)
        l >>= 8

    return s 
Example 30
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 5 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        # !! long to int conversion isn't safe!
        self.type_name = 'long'
        self.check_func = 'PyLong_Check'
        self.c_type = 'longlong'
        self.return_type = 'longlong'
        self.to_c_return = "(longlong) PyLong_AsLongLong(py_obj)"
        self.matching_types = [types.LongType] 
Example 31
Project: TESTGIT   Author: B-ROY   File: androconf.py    Apache License 2.0 5 votes vote down vote up
def long2str(l):
    """Convert an integer to a string."""
    if type(l) not in (types.IntType, types.LongType):
        raise ValueError, 'the input must be an integer'

    if l < 0:
        raise ValueError, 'the input must be greater than 0'
    s = ''
    while l:
        s = s + chr(l & 255L)
        l >>= 8

    return s 
Example 32
Project: Android-Malware-Detection   Author: aup8497   File: androconf.py    MIT License 5 votes vote down vote up
def long2str(l):
    """Convert an integer to a string."""
    if type(l) not in (types.IntType, types.LongType):
        raise ValueError, 'the input must be an integer'

    if l < 0:
        raise ValueError, 'the input must be greater than 0'
    s = ''
    while l:
        s = s + chr(l & 255L)
        l >>= 8

    return s 
Example 33
Project: bacnet   Author: tgrosch   File: properties.py    GNU General Public License v2.0 5 votes vote down vote up
def WriteProperty(self, obj, value, arrayIndex=None, priority=None, direct=False):
        """
        This function handles writing.

        :param obj: property
        :param value: property value
        :param arrayIndex: index
        :param priority: priority
        :param direct: direct
        :return: property value
        """

        self._debug(
            'WriteProperty %r %r arrayIndex=%r priority=%r',
            obj,
            value,
            arrayIndex,
            priority
        )

        # check if value was provided
        if value is None:
            pass

        # check if value is valid
        elif isinstance(value, (types.IntType, types.LongType)):
            value = (obj.objectType, value)

        # check if object type within value is correct
        elif isinstance(value, types.TupleType) and len(value) == 2:
            if value[0] != obj.objectType:
                raise ValueError('%s required' % obj.objectType)

        else:
            raise TypeError('object identifier invalid')

        # perform actual write procedure
        return ReadableProperty.WriteProperty(self, obj, value, arrayIndex, priority, direct) 
Example 34
Project: xuemc   Author: skycucumber   File: Utility.py    GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, key):
        NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
        if isinstance(key, NumberTypes):
            return self.list[key]
        return self.data[key] 
Example 35
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        # !! long to int conversion isn't safe!
        self.type_name = 'long'
        self.check_func = 'PyLong_Check'
        self.c_type = 'longlong'
        self.return_type = 'longlong'
        self.to_c_return = "(longlong) PyLong_AsLongLong(py_obj)"
        self.matching_types = [types.LongType] 
Example 36
Project: poker   Author: surgebiswas   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        # !! long to int conversion isn't safe!
        self.type_name = 'long'
        self.check_func = 'PyLong_Check'
        self.c_type = 'longlong'
        self.return_type = 'longlong'
        self.to_c_return = "(longlong) PyLong_AsLongLong(py_obj)"
        self.matching_types = [types.LongType] 
Example 37
Project: openode   Author: JvGinkel   File: util.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_py_to_js_data(val, id_):
    """
    Converts Python data type to JS data type.

    Practically what this means is, convert ``False`` to ``false``, ``True`` to ``true`` and so on.
    It also takes care of the conversion of :py:class:`.JSVar`, :py:class:`.JSFunction`
    and :py:class:`.JSFunctionInContext`. It takes care of recursively converting lists and dictionaries
    too.

    :param val: The Python data to convert.
    :type val: Any

    :param id_: The DOM id of the element in which context :py:class:`.JSFunctionInContext` functions
        should run. (This is not needed if ``val`` contains no :py:class:`.JSFunctionInContext`)
    :type id_: :py:obj:`str`

    :rtype: :py:obj:`unicode`
    """
    if type(val) == types.BooleanType:
        return u'true' if val else u'false'
    elif type(val) in [types.IntType, types.LongType, types.FloatType]:
        return force_unicode(val)
    elif isinstance(val, JSFunctionInContext):
        return u"django_select2.runInContextHelper(%s, '%s')" % (val, id_)
    elif isinstance(val, JSVar):
        return val  # No quotes here
    elif isinstance(val, dict):
        return convert_dict_to_js_map(val, id_)
    elif isinstance(val, list):
        return convert_to_js_arr(val, id_)
    else:
        return convert_to_js_str(val) 
Example 38
Project: apk_sdk_analysis   Author: ybdesire   File: androconf.py    GNU General Public License v3.0 5 votes vote down vote up
def long2str(l):
    """Convert an integer to a string."""
    if type(l) not in (types.IntType, types.LongType):
        raise ValueError, 'the input must be an integer'

    if l < 0:
        raise ValueError, 'the input must be greater than 0'
    s = ''
    while l:
        s = s + chr(l & 255L)
        l >>= 8

    return s 
Example 39
Project: syndicate-core   Author: syndicate-storage   File: entry.py    Apache License 2.0 5 votes vote down vote up
def is_serialized_id( self, i ):
      """
      Is this a serialized ID?  i.e. is it an int?
      """
      return isinstance( i, types.IntType ) or isinstance( i, types.LongType ) 
Example 40
Project: ops   Author: xiaomatech   File: IPy.py    MIT License 5 votes vote down vote up
def _printPrefix(self, want):
        """Prints Prefixlen/Netmask.
        Not really. In fact it is our universal Netmask/Prefixlen printer.
        This is considered an internal function.
        want == 0 / None        don't return anything    1.2.3.0
        want == 1               /prefix                  1.2.3.0/24
        want == 2               /netmask                 1.2.3.0/255.255.255.0
        want == 3               -lastip                  1.2.3.0-1.2.3.255
        """

        if (self._ipversion == 4 and self._prefixlen == 32) or \
                (self._ipversion == 6 and self._prefixlen == 128):
            if self.NoPrefixForSingleIp:
                want = 0
        if want == None:
            want = self.WantPrefixLen
            if want == None:
                want = 1
        if want:
            if want == 2:
                # this should work with IP and IPint
                netmask = self.netmask()
                if type(netmask) != types.IntType \
                        and type(netmask) != types.LongType:
                    netmask = netmask.int()
                return "/%s" % (intToIp(netmask, self._ipversion))
            elif want == 3:
                return "-%s" % (intToIp(self.ip + self.len() - 1,
                                        self._ipversion))
            else:
                # default
                return "/%d" % (self._prefixlen)
        else:
            return ''

            # We have different flavours to convert to:
            # strFullsize   127.0.0.1    2001:0658:022a:cafe:0200:c0ff:fe8d:08fa
            # strNormal     127.0.0.1    2001:658:22a:cafe:200:c0ff:fe8d:08fa
            # strCompressed 127.0.0.1    2001:658:22a:cafe::1
            # strHex        0x7F000001L  0x20010658022ACAFE0200C0FFFE8D08FA
            # strDec        2130706433   42540616829182469433547974687817795834 
Example 41
Project: ops   Author: xiaomatech   File: IPy.py    MIT License 5 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].
        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print repr(x)
        ...
        IP('127.0.0.0')
        IP('127.0.0.1')
        IP('127.0.0.2')
        IP('127.0.0.3')
        >>> ip[2]
        IP('127.0.0.2')
        >>> ip[-1]
        IP('127.0.0.3')
        """

        if type(key) != types.IntType and type(key) != types.LongType:
            raise TypeError
        if key < 0:
            if abs(key) <= self.len():
                key = self.len() - abs(key)
            else:
                raise IndexError
        else:
            if key >= self.len():
                raise IndexError

        return self.ip + long(key) 
Example 42
Project: TimeMachine   Author: DroidTest   File: androconf.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def long2str(l):
    """Convert an integer to a string."""
    if type(l) not in (types.IntType, types.LongType):
        raise ValueError, 'the input must be an integer'

    if l < 0:
        raise ValueError, 'the input must be greater than 0'
    s = ''
    while l:
        s = s + chr(l & 255L)
        l >>= 8

    return s 
Example 43
Project: suma   Author: rach   File: task.py    Apache License 2.0 5 votes vote down vote up
def add_click(self, link_id, ip=None, referer=None):
        assert type(link_id) in [IntType, LongType], "link_id is not an integer: %r" % link_id
        tasks.add_click_task.apply_async((link_id, ip, referer), serializer='json') 
Example 44
Project: suma   Author: rach   File: task.py    Apache License 2.0 5 votes vote down vote up
def get_link_data(self, link_id):
        assert type(link_id) in [IntType, LongType], "link_id is not an integer: %r" % link_id
        tasks.get_link_data_task.apply_async((link_id, ), serializer='json') 
Example 45
Project: suma   Author: rach   File: stat.py    Apache License 2.0 5 votes vote down vote up
def add_click(self, link_id, ip=None, referer=None):
        """
        The code may look more complex than it should but it was made to handle
        the edge case of concurrent transaction. Counter doesn't exist yet when
        we fetch but it exist when we try to write it to the DB.
        """
        assert type(link_id) in [IntType, LongType], "link_id is not an integer: %r" % link_id

        lcounter = self.get_counter_by_link_id(link_id)
        if lcounter:
            lcounter.counter = lcounter.counter + 1
            self.dbsession.add(lcounter)
        if not lcounter:
            lcounter = ClickCounter(
                id=link_id,
                counter=1
            )
            self.dbsession.begin_nested()
            try:
                self.dbsession.add(lcounter)
                self.dbsession.commit()
            except IntegrityError:
                self.dbsession.rollback()
                lcounter = self.get_counter_by_link_id(link_id)
                lcounter.counter = lcounter.counter + 1
                self.dbsession.add(lcounter)

        stat = Stat(
            link_id=link_id,
            ip=ip,
            referer=referer
        )
        self.dbsession.add(stat)
        return lcounter, stat 
Example 46
Project: eve-metrics   Author: ccpgames   File: Elements.py    MIT License 5 votes vote down vote up
def AddRow( self, *cells ) :
        height = None
        if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ):
            height = int( cells[ 0 ] )
            cells  = cells[ 1 : ]

        #  make sure all of the spans add up to the number of columns
        #  otherwise the table will get corrupted
        if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) :
            raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' )

        self.Rows.append( ( height, cells ) ) 
Example 47
Project: emulated-sdn-application   Author: tranlyvu   File: base.py    Apache License 2.0 5 votes vote down vote up
def validate_max_prefixes(max_prefixes):
    if not isinstance(max_prefixes, (IntType, LongType)):
        raise ConfigTypeError(desc='Max. prefixes value should be of type '
                              'int or long but found %s' % type(max_prefixes))
    if max_prefixes < 0:
        raise ConfigValueError(desc='Invalid max. prefixes value: %s' %
                               max_prefixes)
    return max_prefixes 
Example 48
Project: geofire-python   Author: ininex   File: _version133.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 49
Project: geofire-python   Author: ininex   File: _version133.py    MIT License 5 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo
    n"""

    if type(message) is types.IntType:
        return encrypt_int(long(message), ekey, n)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or an int")

    if message > 0 and \
            math.floor(math.log(message, 2)) > math.floor(math.log(n, 2)):
        raise OverflowError("The message is too long")

    return fast_exponentiation(message, ekey, n) 
Example 50
Project: geofire-python   Author: ininex   File: _version200.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """
    Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string