我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.BooleanType()。
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)
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 _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 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 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
def _set_attrs(self,l,d): self.names = d['NAME'] self.desc = d['DESC'][0] self.obsolete = d['OBSOLETE']!=None self.oc = d['OC'][0] self.must = d['MUST'] self.may = d['MAY'] 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.oc)==StringType 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.form = d['FORM'][0] 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.form)==StringType assert type(self.sup)==TupleType return
def isTrue(v): if type(v) == types.BooleanType: return v elif type(v) == types.StringType: return v.lower() in ("yes", "true", "t", "1") else: return False
def str2bool(v): if type(v) == types.BooleanType: return v return v.lower() in ("yes", "true", "t", "1")
def tobool(val): """Convert `val` to boolean value True or False. Parameters ---------- val : bool, string, integer '.true.', '1', 'true', 'on', 'yes', integers != 0 -> True '.false.','0', 'false', 'off', 'no', integers == 0 -> False Returns ------- True or False Notes ----- All string vals are case-insensitive. """ if isinstance(val, types.BooleanType): if val == True: return True else: return False got_str = False got_int = False if isinstance(val, types.StringType): got_str = True val = val.lower() elif isinstance(val, types.IntType): got_int = True else: raise StandardError, "input value must be string or integer" if (got_str and (val in ['.true.', 'true', 'on', 'yes', '1'])) \ or (got_int and (val != 0)): ret = True elif (got_str and (val in ['.false.', 'false', 'off', 'no', '0'])) \ or (got_int and (val == 0)): ret = False else: raise StandardError("illegal input value '%s'" %frepr(val)) return ret
def get_bool_key_map(cls, key_map): bool_key_map = {} for (key,value) in key_map.items(): if type(value) == types.BooleanType: bool_key_map[key] = value elif type(value) == types.DictType: for (key2,value2) in value.items(): if type(value2) == types.BooleanType: bool_key_map[key2] = value2 return bool_key_map
def dump(self, pickler): pickler.dump(self.tag) pickler.dump(self._what) pickler.dump(self._extra) pickler.dump(self._comment) if self.prop: # Skip system variables pickler.dump([x for x in self.prop.items() if type(x[1]) in (IntType, LongType, FloatType, BooleanType, StringType, UnicodeType)]) else: pickler.dump(None) pickler.dump(self.enable) # ---------------------------------------------------------------------- # Load card from unpickler # ----------------------------------------------------------------------
def humannum(data, unit=None, include=None, exclude=None): if isinstance(data, types.DictType): data = data.copy() keys = set(data.keys()) if include is not None: keys = keys & set(include) if exclude is not None: keys = keys - set(exclude) for k in keys: data[k] = humannum(data[k]) return data elif isinstance(data, types.BooleanType): # We have to deal with bool because for historical reason bool is # subclass of int. # When bool is introduced into python 2.2 it is represented with int, # similar to C. return data elif isinstance(data, types.ListType): return [humannum(x) for x in data] elif isinstance(data, types.StringTypes): return data elif isinstance(data, integer_types): return humannum_int(data, unit=unit) elif isinstance(data, types.FloatType): if data > 999: return humannum_int(int(data), unit=unit) elif abs(data) < 0.0000000001: return '0' else: return '%.2f' % (data) else: return data
def __init__(self, genome, interactiveMode=True): """ Initializator of GSimpleGA """ #if seed is not None: random.seed(seed) # used to be like this if type(interactiveMode) != BooleanType: utils.raiseException("Interactive Mode option must be True or False", TypeError) if not isinstance(genome, GenomeBase): utils.raiseException("The genome must be a GenomeBase subclass", TypeError) self.internalPop = GPopulation(genome) self.nGenerations = constants.CDefGAGenerations self.pMutation = constants.CDefGAMutationRate self.pCrossover = constants.CDefGACrossoverRate self.nElitismReplacement = constants.CDefGAElitismReplacement self.setPopulationSize(constants.CDefGAPopulationSize) self.minimax = constants.minimaxType["maximize"] self.elitism = True # NEW self.new_population = None # Adapters self.dbAdapter = None self.migrationAdapter = None self.time_init = None self.max_time = None self.interactiveMode = interactiveMode self.interactiveGen = -1 self.GPMode = False self.selector = FunctionSlot("Selector") self.stepCallback = FunctionSlot("Generation Step Callback") self.terminationCriteria = FunctionSlot("Termination Criteria") self.selector.set(constants.CDefGASelector) self.allSlots = (self.selector, self.stepCallback, self.terminationCriteria) self.internalParams = {} self.currentGeneration = 0 # GP Testing for classes in constants.CDefGPGenomes: if isinstance(self.internalPop.oneSelfGenome, classes): self.setGPMode(True) break log.debug("A GA Engine was created, nGenerations=%d", self.nGenerations) # New self.path = None # -----------------------------------------------------------------
def setMultiProcessing(self, flag=True, full_copy=False, max_processes=None): """ Sets the flag to enable/disable the use of python multiprocessing module. Use this option when you have more than one core on your CPU and when your evaluation function is very slow. Pyevolve will automaticly check if your Python version has **multiprocessing** support and if you have more than one single CPU core. If you don't have support or have just only one core, Pyevolve will not use the **multiprocessing** feature. Pyevolve uses the **multiprocessing** to execute the evaluation function over the individuals, so the use of this feature will make sense if you have a truly slow evaluation function (which is commom in GAs). The parameter "full_copy" defines where the individual data should be copied back after the evaluation or not. This parameter is useful when you change the individual in the evaluation function. :param flag: True (default) or False :param full_copy: True or False (default) :param max_processes: None (default) or an integer value .. warning:: Use this option only when your evaluation function is slow, so you'll get a good tradeoff between the process communication speed and the parallel evaluation. The use of the **multiprocessing** doesn't means always a better performance. .. note:: To enable the multiprocessing option, you **MUST** add the *__main__* check on your application, otherwise, it will result in errors. See more on the `Python Docs <http://docs.python.org/library/multiprocessing.html#multiprocessing-programming>`__ site. .. versionadded:: 0.6 The `setMultiProcessing` method. """ if type(flag) != BooleanType: utils.raiseException("Multiprocessing option must be True or False", TypeError) if type(full_copy) != BooleanType: utils.raiseException("Multiprocessing 'full_copy' option must be True or False", TypeError) self.internalPop.setMultiProcessing(flag, full_copy, max_processes) # -----------------------------------------------------------------
def _set_attrs(self,l,d): self.names = d['NAME'] self.desc = d['DESC'][0] self.obsolete = d['OBSOLETE']!=None self.sup = d['SUP'] self.equality = d['EQUALITY'][0] self.ordering = d['ORDERING'][0] self.substr = d['SUBSTR'][0] try: syntax = d['SYNTAX'][0] except IndexError: self.syntax = None self.syntax_len = None else: if syntax is None: self.syntax = None self.syntax_len = None else: try: self.syntax,syntax_len = d['SYNTAX'][0].split("{") except ValueError: self.syntax = d['SYNTAX'][0] self.syntax_len = None for i in l: if i.startswith("{") and i.endswith("}"): self.syntax_len=long(i[1:-1]) else: self.syntax_len = long(syntax_len[:-1]) self.single_value = d['SINGLE-VALUE']!=None self.collective = d['COLLECTIVE']!=None self.no_user_mod = d['NO-USER-MODIFICATION']!=None try: self.usage = AttributeUsage[d['USAGE'][0]] except KeyError: raise self.usage = AttributeUsage.get(d['USAGE'][0],0) assert type(self.names)==TupleType assert self.desc is None or type(self.desc)==StringType assert type(self.sup)==TupleType,'attribute sup has type %s' % (type(self.sup)) assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1) assert type(self.single_value)==BooleanType and (self.single_value==0 or self.single_value==1) assert type(self.no_user_mod)==BooleanType and (self.no_user_mod==0 or self.no_user_mod==1) assert self.syntax is None or type(self.syntax)==StringType assert self.syntax_len is None or type(self.syntax_len)==type(0L) return