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)
python类BooleanType()的实例源码
def getValueStrings( val, blnUgly=True ):
#Used by joinWithComma function to join list items for SQL queries.
#Expects to receive 'valid' types, as this was designed specifically for joining object attributes and nonvalid attributes were pulled.
#If the default blnUgly is set to false, then the nonvalid types are ignored and the output will be pretty, but the SQL Insert statement will
#probably be wrong.
tplStrings = (types.StringType, types.StringTypes )
tplNums = ( types.FloatType, types.IntType, types.LongType, types.BooleanType )
if isinstance( val, tplNums ):
return '#num#'+ str( val ) + '#num#'
elif isinstance( val, tplStrings ):
strDblQuote = '"'
return strDblQuote + val + strDblQuote
else:
if blnUgly == True:
return "Error: nonconvertable value passed - value type: %s" % type(val )
else:
return None
def str_to_bool(cver_str):
"""convert string to boolean
:param cver_str: string should to convert
:return: Boolean
"""
if isinstance(cver_str, types.BooleanType):
return cver_str
elif isinstance(cver_str, types.StringType):
bool_map = {'true': True, 'false': False}
bool_str = cver_str.lower() if cver_str else ""
if bool_str not in bool_map:
raise ValueError('%s is not valid boolean.' % cver_str)
else:
return bool_map[bool_str]
else:
raise ValueError('%s is not valid boolean.' % cver_str)
def __init__(self, name, value=None, fuzzable=True):
'''
:param name: block name
:type value: bool
:param value: value to be used, if None - generate both 'true' and 'false' (default: None)
:param fuzzable: should we fuzz this field (only if value is not None) (default: True)
'''
if value is None:
field = Group(['true', 'false'], name=_valuename(name))
else:
if not isinstance(value, types.BooleanType):
raise ValueError('value should be bool, not %s' % type(value))
# fix python and json boolean incompitability
value = 'true' if value else 'false'
field = String(value, fuzzable=fuzzable, name=_valuename(name))
super(JsonBoolean, self).__init__(field, name=name)
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
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
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
def __init__(self, name, value=None, fuzzable=True):
'''
:param name: block name
:type value: bool
:param value: value to be used, if None - generate both 'true' and 'false' (default: None)
:param fuzzable: should we fuzz this field (only if value is not None) (default: True)
'''
if value is None:
field = Group(['true', 'false'], name=_valuename(name))
else:
if not isinstance(value, types.BooleanType):
raise ValueError('value should be bool, not %s' % type(value))
# fix python and json boolean incompitability
value = 'true' if value else 'false'
field = String(value, fuzzable=fuzzable, name=_valuename(name))
super(JsonBoolean, self).__init__(field, name=name)
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup is not None and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif (isList(matchAgainst)
and (markup is not None or not isString(matchAgainst))):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
def makeObjInsertStrings( obj, tplObjects = None, blnUseParens=True, blnGetAllAttrib=True ):
# Returns a 3 val tuple, the first two of which are strings which can be dropped into a MySQL Insert statement for (1) column names and (2) values
if not tplObjects:
return None, None, None
if isinstance( obj, tplObjects ): #find out what got passed - valid objects must be included in tuple tplObjects
strDblQuote = '"'
lstCols = list()
lstVals = list()
lstExcludedAttrib = list()
dctObj = vars( obj )
lstObjVarNames = dctObj.keys()
if blnGetAllAttrib:
tplValidTypes = ( types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.StringTypes, types.NoneType )
for varName in lstObjVarNames:
val = dctObj[ varName ]
if isinstance( val, tplValidTypes ):
lstCols.append( varName )
if val or val == 0:
lstVals.append( dctObj[ varName ] )
else:
lstVals.append('')
else:
lstExcludedAttrib.append( varName )
if blnUseParens:
strCols = joinListItems( lstCols )
strVals = joinListItems( lstVals )
else:
strCols = joinListItems( lstCols, blnUseParens=False )
strCols = joinListItems( lstVals, blnUseParens=False )
strCols = strCols.replace('"', '')
return strCols, strVals, lstExcludedAttrib
else:
print 'No object passed.'
return None, None, None
def get_default_instances():
return [
types.StringType(), types.DecimalType(), types.IntegerType(),
types.DateType('%Y-%m-%d %H:%M:%S'), types.BooleanType()
]
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
def _unjelly_boolean(self, exp):
if BooleanType:
assert exp[0] in ('true', 'false')
return exp[0] == 'true'
else:
return Unpersistable(exp[0])
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
def testReturnTypeMutateFuzzable(self):
field = self.get_default_field(fuzzable=True)
self.assertIsInstance(field.mutate(), types.BooleanType)
field.reset()
self.assertIsInstance(field.mutate(), types.BooleanType)
def testReturnTypeMutateNotFuzzable(self):
field = self.get_default_field(fuzzable=False)
self.assertIsInstance(field.mutate(), types.BooleanType)
field.reset()
self.assertIsInstance(field.mutate(), types.BooleanType)
def setInteractiveMode(self, flag=True):
""" Enable/disable the interactive mode
:param flag: True or False
.. versionadded: 0.6
The *setInteractiveMode* method.
"""
if type(flag) != BooleanType:
utils.raiseException("Interactive Mode option must be True or False", TypeError)
self.interactiveMode = flag
# -----------------------------------------------------------------
def setElitism(self, flag):
""" Sets the elitism option, True or False
:param flag: True or False
"""
if type(flag) != BooleanType:
utils.raiseException("Elitism option must be True or False", TypeError)
self.elitism = flag
# -----------------------------------------------------------------
def setRandomApply(self, flag=True):
"""
Sets the random function application, in this mode, the
function will randomly choose one slot to apply
:param flag: True or False
"""
if type(flag) != BooleanType:
utils.raiseException("Random option must be True or False", TypeError)
self.rand_apply = flag
# -----------------------------------------------------------------
def setInteractiveMode(self, flag=True):
""" Enable/disable the interactive mode
:param flag: True or False
.. versionadded: 0.6
The *setInteractiveMode* method.
"""
if type(flag) != BooleanType:
utils.raiseException("Interactive Mode option must be True or False", TypeError)
self.interactiveMode = flag
# -----------------------------------------------------------------
def setElitism(self, flag):
""" Sets the elitism option, True or False
:param flag: True or False
"""
if type(flag) != BooleanType:
utils.raiseException("Elitism option must be True or False", TypeError)
self.elitism = flag
# -----------------------------------------------------------------
def setRandomApply(self, flag=True):
"""
Sets the random function application, in this mode, the
function will randomly choose one slot to apply
:param flag: True or False
"""
if type(flag) != BooleanType:
utils.raiseException("Random option must be True or False", TypeError)
self.rand_apply = flag
# -----------------------------------------------------------------
def _unjelly_boolean(self, exp):
if BooleanType:
assert exp[0] in ('true', 'false')
return exp[0] == 'true'
else:
return Unpersistable(exp[0])
def to_boolean(choice, default=False):
"""Convert the yes/no to true/false
:param choice: the text string input
:type choice: string
"""
if type(choice) == types.BooleanType:
return choice
valid = {"True": True, "true": True, "yes":True, "ye":True, "y":True,
"False":False, "false":False, "no":False, "n":False}
choice_lower = choice.lower()
if choice_lower in valid:
return valid[choice_lower]
return default
def dict_to_JsonObject(the_dict, name=None, ctx=None):
'''
Create a JsonObject from a dictionary.
The context parameter is used for recursive calls,
no need to pass it from outside.
:param the_dict: dictionary to base the `JsonObject` on
:param ctx: context for the parser (default: None)
:rtype: :class:`~katnip.legos.json.JsonObject`
:return: JSON object that represents the dictionary
'''
if type(the_dict) != dict:
raise ValueError('expecting dictionary as first argument')
if ctx is None:
ctx = _JsonStringContext()
members = {}
for (k, v) in the_dict.items():
if v is None:
val = JsonNull(name=ctx.uname(k), fuzzable=False)
elif isinstance(v, types.BooleanType):
val = JsonBoolean(name=ctx.uname(k), value=v, fuzzable=True)
elif isinstance(v, types.StringTypes):
val = JsonString(name=ctx.uname(k), value=v, fuzzable=True)
elif isinstance(v, types.ListType):
val = list_to_JsonArray(v, k, ctx)
elif isinstance(v, types.DictionaryType):
val = dict_to_JsonObject(v, k, ctx)
elif isinstance(v, types.IntType):
val = SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname(k))
else:
raise ValueError('type not supported: %s' % type(v))
members[k] = val
if name is None:
name = 'obj'
return JsonObject(name=ctx.uname(name, False), member_dict=members, fuzz_keys=False)
def list_to_JsonArray(the_list, name=None, ctx=None):
'''
Create a JsonArray from a list.
The context parameter is used for recursive calls,
no need to pass it from outside.
:param the_list: list to base the JsonArray on
:param ctx: context for the parser (default: None)
:rtype: :class:`~katnip.legos.json.JsonArray`
:return: JSON object that represents the list
'''
if type(the_list) != list:
raise ValueError('expecting list as first argument')
if ctx is None:
ctx = _JsonStringContext()
elements = []
for v in the_list:
if v is None:
elements.append(JsonNull(ctx.uname('null'), fuzzable=False))
elif isinstance(v, types.BooleanType):
elements.append(JsonBoolean(ctx.uname('bool'), value=v, fuzzable=True))
elif isinstance(v, types.StringTypes):
elements.append(JsonString(ctx.uname('string'), v, fuzzable=True))
elif isinstance(v, types.ListType):
elements.append(list_to_JsonArray(v, None, ctx))
elif isinstance(v, types.DictionaryType):
elements.append(dict_to_JsonObject(v, None, ctx))
elif isinstance(v, types.IntType):
elements.append(SInt32(v, encoder=ENC_INT_DEC, name=ctx.uname('int')))
else:
raise ValueError('type not supported: %s' % type(v))
if name is None:
name = 'array'
return JsonArray(name=ctx.uname(name, False), values=elements)
def object_properties_count(self, o):
""" returns the number of user browsable properties of an object. """
o_type = type(o)
if isinstance(o, (types.DictType, types.ListType, types.TupleType, set,)):
return len(o)
elif isinstance(o, (types.NoneType, types.BooleanType, types.FloatType,
types.UnicodeType, types.FloatType, types.IntType,
types.StringType, types.LongType, types.ModuleType,
types.MethodType, types.FunctionType,)):
return 0
else:
# Following lines are used to debug variables members browsing
# and counting
# if False and str(o_type) == "<class 'socket._socketobject'>":
# print "@378"
# print dir(o)
# print "hasattr(o, '__dict__')=%s" % hasattr(o,'__dict__')
# count = 0
# if hasattr(o, '__dict__'):
# for m_name, m_value in o.__dict__.iteritems():
# if m_name.startswith('__'):
# print " %s=>False" % (m_name,)
# continue
# if type(m_value) in (types.ModuleType, types.MethodType, types.FunctionType,):
# print " %s=>False" % (m_name,)
# continue
# print " %s=>True" % (m_name,)
# count +=1
# print " %s => %s = %s" % (o, count, dir(o),)
# else:
if hasattr(o, '__dict__'):
count = len([m_name for m_name, m_value in o.__dict__.iteritems()
if not m_name.startswith('__')
and not type(m_value) in (types.ModuleType,
types.MethodType,
types.FunctionType,) ])
else:
count = 0
return count
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.syntax = d['SYNTAX'][0]
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 self.syntax is None or type(self.syntax)==StringType
return
def _set_attrs(self,l,d):
self.names = d['NAME']
self.desc = d['DESC'][0]
self.obsolete = d['OBSOLETE']!=None
self.applies = d['APPLIES']
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.applies)==TupleType
return