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)
python类IntType()的实例源码
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)
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)
def index(self, index):
listLength = len(self._itemList)
if type(index) == types.IntType:
if index < listLength:
return index
else:
raise ValueError, 'index "%s" is out of range' % index
elif index is END:
if listLength > 0:
return listLength - 1
else:
raise ValueError, 'OptionMenu has no items'
else:
if index is SELECT:
if listLength > 0:
index = self.getcurselection()
else:
raise ValueError, 'OptionMenu has no items'
if index in self._itemList:
return self._itemList.index(index)
raise ValueError, \
'bad index "%s": must be a ' \
'name, a number, END or SELECT' % (index,)
def __init__(self, depends_on, length, correction=None, encoder=ENC_INT_DEFAULT, fuzzable=False, name=None):
'''
:param depends_on: (name of) field we depend on
:param length: length of the FieldIntProperty field (in bits)
:type corrention: int or func(int) -> int
:param correction: correction function, or value for the index
:type encoder: :class:`~kitty.model.low_level.encoder.BitFieldEncoder`
:param encoder: encoder for the field (default: ENC_INT_DEFAULT)
:param fuzzable: is container fuzzable
:param name: (unique) name of the container (default: None)
'''
if correction:
if not callable(correction):
if not isinstance(correction, types.IntType):
raise KittyException('correction must be int, function or None!')
self._correction = correction
bit_field = BitField(value=0, length=length, encoder=encoder)
super(FieldIntProperty, self).__init__(depends_on=depends_on, bit_field=bit_field, calc_func=None, fuzzable=fuzzable, name=name)
self.dependency_type = Calculated.FIELD_PROP_BASED
def _getPlugIns(plugInType, debugInspection=None, showProgress=None):
if isinstance(debugInspection, types.IntType):
warnings.warn(
"int parameter for debugInspection is deprecated, pass None or "
"a function that takes a single argument instead.",
DeprecationWarning, 3
)
if isinstance(showProgress, types.IntType):
warnings.warn(
"int parameter for showProgress is deprecated, pass None or "
"a function that takes a single argument instead.",
DeprecationWarning, 3
)
debugInspection, showProgress = _prepCallbacks(debugInspection, showProgress)
firstHalf = secondHalf = lambda x: None
if showProgress:
firstHalf = lambda x: showProgress(x / 2.0)
secondHalf = lambda x: showProgress(x / 2.0 + 0.5)
tmlFiles = getPluginFileList(debugInspection, firstHalf)
if not tmlFiles:
return []
return loadPlugins(plugInType, tmlFiles, debugInspection, secondHalf)
def p_prop(self, p):
'''prop : prop_name operator prop_value
'''
if p[1].value.upper() in self.INT_TYPE_PROPNAMES:
if p[2].value == '~=':
self._error('"%s"???????"~="???'%(p[1].value), p[2], p[2].lexpos)
if not isinstance(p[3].value, types.IntType):
try:
p[3].value = int(p[3].value)
except ValueError:
self._error('"%s"??????"%s"??????int??'%(p[1].value, type(p[3].value)), p[3], p[3].lexpos)
if p[1].value.upper() == 'MAXDEPTH':
if p[3].value <= 0:
self._error("MaxDepth?????>0", p[3], p[3].lexpos)
elif p[2].value == '~=':
if not isinstance(p[3].value, types.StringTypes):
self._error('???"~="?????"%s"?????'%(type(p[3].value)), p[2], p[2].lexpos)
p[0] = UIObjectProperty(p[1], p[2], p[3])
def ignoreValue(ignoreEmptyField,
fieldValue):
"""
Evaluate the value of a field and indicate whether to ignore it or not.
Internal function.
ignoreEmptyField: If set to 1 indicates that the field should be
ignored if it is an empty string (integer/0|1).
fieldValue: Value of field (string).
Returns: 1 if field should be ignored, otherwise 0
(integer/0|1).
"""
if (type(fieldValue) == types.IntType):
if (ignoreEmptyField and (fieldValue == -1)): return 1
elif (ignoreEmptyField and (str(fieldValue).strip() == "")):
return 1
return 0
def __getslice__(self, i, j):
if not isinstance(i, types.IntType) or \
not isinstance(j, types.IntType):
raise KeyError("Indices must be integer")
slice = {}
K = self.keys()
K.sort()
if i <= j:
size = j-i
for k in K:
if i <= k and k < j:
slice[k] = self.values[k]
else:
size = self.n
for k in K:
if j > k or k >= i:
slice[k] = self.values[k]
return SparseVector(size, slice)
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
def __init__(self, depends_on, length, correction=None, encoder=ENC_INT_DEFAULT, fuzzable=False, name=None):
'''
:param depends_on: (name of) field we depend on
:param length: length of the FieldIntProperty field (in bits)
:type corrention: int or func(int) -> int
:param correction: correction function, or value for the index
:type encoder: :class:`~kitty.model.low_level.encoder.BitFieldEncoder`
:param encoder: encoder for the field (default: ENC_INT_DEFAULT)
:param fuzzable: is container fuzzable
:param name: (unique) name of the container (default: None)
'''
if correction:
if not callable(correction):
if not isinstance(correction, types.IntType):
raise KittyException('correction must be int, function or None!')
self._correction = correction
bit_field = BitField(value=0, length=length, encoder=encoder)
super(FieldIntProperty, self).__init__(depends_on=depends_on, bit_field=bit_field, calc_func=None, fuzzable=fuzzable, name=name)
self.dependency_type = Calculated.FIELD_PROP_BASED
def __init__(self, name, attribute, value, fuzz_attribute=False, fuzz_value=True):
'''
:param name: name of the block
:param attribute: attribute
:type value: str/unicode/int
:param value: value of the attribute
:param fuzz_attribute: should we fuzz the attribute field (default: False)
:param fuzz_value: should we fuzz the value field (default: True)
'''
_check_type(attribute, StringTypes, 'attribute')
_check_type(value, StringTypes + (IntType, ), 'value')
value_name = _valuename(name)
if isinstance(value, StringTypes):
value_field = String(value, name=value_name, fuzzable=fuzz_value)
else:
value_field = SInt32(value, encoder=ENC_INT_DEC, fuzzable=fuzz_value, name=value_name)
fields = [
String(attribute, fuzzable=fuzz_attribute, name='%s_attribute' % name),
Static('='),
Static('"'),
value_field,
Static('"')
]
super(XmlAttribute, self).__init__(fields, name=name)
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
def int2bytes(number):
"""Converts a number to a string of bytes
>>> bytes2int(int2bytes(123456789))
123456789
"""
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
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)
test_distribution_centers_service.py 文件源码
项目:logistics-wizard-controller
作者: IBM-Cloud
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def test_get_distribution_center_inventory_success(self):
"""With correct values, is valid inventory returned?"""
# Get distribution center
distribution_centers = distribution_center_service.get_distribution_centers(self.loopback_token)
dc_id = loads(distribution_centers)[0].get('id')
inventory = distribution_center_service.get_distribution_center_inventory(self.loopback_token, dc_id)
# TODO: Update to use assertIsInstance(a,b)
# Check all expected object values are present
inventories_json = loads(inventory)
for inventory_json in inventories_json:
self.assertTrue(inventory_json.get('id'))
self.assertIsInstance(inventory_json.get('quantity'), IntType)
self.assertTrue(inventory_json.get('productId'))
self.assertTrue(inventory_json.get('locationId'))
self.assertTrue(inventory_json.get('locationType'))
test_retailers_service.py 文件源码
项目:logistics-wizard-controller
作者: IBM-Cloud
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_get_retailer_inventory_success(self):
"""With correct values, is valid inventory returned?"""
# Get retailer
retailers = retailer_service.get_retailers(self.loopback_token)
retailer_id = loads(retailers)[0].get('id')
inventory = retailer_service.get_retailer_inventory(self.loopback_token, retailer_id)
# TODO: Update to use assertIsInstance(a,b)
# Check all expected object values are present
inventories_json = loads(inventory)
for inventory_json in inventories_json:
self.assertTrue(inventory_json.get('id'))
self.assertIsInstance(inventory_json.get('quantity'), IntType)
self.assertTrue(inventory_json.get('productId'))
self.assertTrue(inventory_json.get('locationId'))
self.assertTrue(inventory_json.get('locationType'))
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)
def _escape_json(json):
"""Escapes all string fields of JSON data.
Operates recursively."""
t = type(json)
if t == types.StringType or t == types.UnicodeType:
return cgi.escape(json)
elif t == types.IntType:
return json
elif t == types.FloatType:
return json
elif t == types.DictType:
result = {}
for f in json.keys():
result[f] = _escape_json(json[f])
return result
elif t == types.ListType:
result = []
for f in json:
result.append(_escape_json(f))
return result
else:
raise RuntimeError, "Unsupported type: %s" % str(t)
def convert(cf):
rc = []
for i in cf.keys():
if cf[i]['type'] == types.StringType:
rc.append([i, cf[i]['val'], None])
elif cf[i]['type'] == types.FloatType:
rc.append([i, `cf[i]['val']`, None])
elif cf[i]['type'] == types.IntType:
rc.append([i, `cf[i]['val']`, None])
elif cf[i]['type'] == 'toggle':
rc.append([i, write_yes(cf[i]['val']), 'toggle'])
elif cf[i]['type'] == types.ListType:
rc.append([i, `cf[i]['val']`, None])
else:
error("don't know how to handle " + `cf[i]['type']`)
return rc