def mapGetPred(map, *keysAndValues): if not isMap(map): raise RuntimeException("First argument to MapGet must be a map") result = list(keysAndValues) for index in range(0, len(result)-1, 2): key = result[index] if key == None: raise RuntimeException("Must have bound values for keys in MapGet") if isString(key): default = None elif isList(key) and len(key) == 2 and isString(key[0]): default = key[1] key = key[0] else: raise RuntimeException("Each MapGet key must be a String or a List of a String and a default value") val = mapGet(map, key) if val == None: # key isn't found if default == None: return None else: val = default if result[index+1] == None: # No value specified result[index+1] = val elif result[index+1] != val: # Incorrect value specified return None if len(result)%2 != 0: # odd number of arguments key = result[-1] if key == None: raise RuntimeException("Final MapGet key must be supplied") if not isString(key): raise RuntimeException("Final MapGet key must be a String") if mapGet(map, key) == None: # specified key is not present return None return result
def parseAndConclude(agent, statement, packagename): if not (isinstance(agent, Agent)): raise AssertionError if not (isString(statement)): raise AssertionError if not (isString(packagename)): raise AssertionError spu = PseudoFileSPU(packagename) spu.textUpdate(None, statement) if spu.if_OK2_insert_info_FILENAME_SPU(): if load_file_into_agent(spu.filename, agent): return List(spu.getExprs()) w = Writeable() printErrors(spu, False, w) raise UnlocatedError(str(w))
def executeTask(self, listener, taskname, taskargs): if self.agent == None: self.agent = G._AGENT staskargs = fromXPS(taskargs) log_incoming_request(listener, "executeTask", (listener, taskname, staskargs)) symOrError = taskNameToSymOrError(self.agent, taskname) if isString(symOrError): requestType = FAIL_REQUEST term = symOrError else: mode = optMode(self.agent, symOrError, ACTION_DO) if mode: requestType = "d" inargs = [ _if(usage == TERM_EVAL, x, None) for (x, usage) in zip(staskargs, mode) ] debug("inargs = %r", inargs) term = Structure(symOrError, List(inargs)) else: requestType = FAIL_REQUEST term = "Cannot find argument modes" #debug("initiating task via (%s, %r, %r, %r)", S_ExecuteTask.id, requestType, listener, term) self.agent.add_ephemeral(S_ExecuteTask, requestType, listener, term)
def setTimeSpeed(simtime, simspeed): """Set the simlated time speed and the current simulated time. A simspeed of 10 means simulated time progresses at 10x realtime. A simspeed of 0 or less means leave the simspeed the same as it was. If simtime is None or 'NOW', the simulated tme does not change.""" global _TIMEWARP realtime = _time.time() if simtime is None or simtime == SIMULATED_TIME: simtime = _realtimeToSimtime(realtime) elif simtime is REAL_TIME: simtime = realtime elif isString(simtime): simtime = getTime(simtime) elif isFloat(simtime): pass elif isInteger(simtime): simtime = float(simtime) else: raise LowError('Invalid time argument') if simspeed <= 0: simspeed = _TIMEWARP[2] else: simspeed = float(simspeed) if realtime == simtime and simspeed == 1.0: _TIMEWARP = NULL_TIMEWARP else: _TIMEWARP = (realtime, simtime, simspeed)
def builtin_evaluate(agent, value): if (isSymbol(value)): raise AssertionError, \ "A naked symbol is not evaluable" if isString(value): return value elif isList(value): elements = [builtin_evaluate(agent, v) for v in value] return List(elements) elif isInteger(value): return value elif isFloat(value): return value elif isStructure(value): sym = value.functor if sym == BACKQUOTE_SYMBOL: return builtin_quoted(agent, value[0]) else: argvalues = [builtin_evaluate(agent, v) for v in value] fullsym = Symbol(BUILTIN_PACKAGE_NAME + "." + sym.id) imp = agent.getImp(fullsym) #if not (isinstance(imp, FunImpInt)): raise AssertionError, \ # "Not a function: %s"%sym b, z = valuesBZ(argvalues) result = imp.call(agent, b, z) return result else: return value
def builtin_evaluate(agent, value): if isSymbol(value): raise AssertionError, "A naked symbol is not evaluable" if isString(value): return value elif isList(value): elements = [builtin_evaluate(agent, v) for v in value] return List(elements) elif isInteger(value): return value elif isFloat(value): return value elif isStructure(value): sym = value.functor if sym == BACKQUOTE_SYMBOL: return builtin_quoted(agent, value[0]) else: argvalues = [builtin_evaluate(agent, v) for v in value] fullsym = Symbol(BUILTIN_PACKAGE_NAME + "." + sym.id) imp = agent.getImp(fullsym) # if not (isinstance(imp, FunImpInt)): raise AssertionError, \ # "Not a function: %s"%sym b, z = valuesBZ(argvalues) result = imp.call(agent, b, z) return result else: return value
def value_km_str(x): "convert x to a KM string" # TODO: make this work for real if isString(x) or isInteger(x) \ or isFloat(x) or isSymbol(x): return value_str(x) else: return None
def __init__(self, tframe, exception, errid=None): from spark.internal.parse.basicvalues import String, isString self._errid = errid self._exception = exception if isString(exception): # restoring from persist # Cannot save real Exception, just using the string errstring = exception else: errstring = "[%d] %s" % (errid, exception) Failure.__init__(self, tframe, errstring)
def __init__(self, tframe, exception, errid=None): from spark.internal.parse.basicvalues import String, isString self._errid = errid self._exception = exception if isString(exception): # restoring from persist # Cannot save real Exception, just using the string errstring = exception else: errstring = "[%d] %s"%(errid, exception) Failure.__init__(self, tframe, errstring)
def mapChange(map, *keysAndValues): d = mapDict(map) if d == None: raise LowError("Non-map passed to mapChange") numKeysAndValues = len(keysAndValues) if numKeysAndValues%2: raise LowError("mapChange takes an odd number of arguments") for index in range(0, numKeysAndValues-1, 2): key = keysAndValues[index] if not isString(key): raise RuntimeException("mapChange keys must be Strings") val = keysAndValues[index+1] d[key] = val return dictMap(d)
def mapChange(map, *keysAndValues): d = mapDict(map) if d == None: raise LowError("Non-map passed to mapChange") numKeysAndValues = len(keysAndValues) if numKeysAndValues % 2: raise LowError("mapChange takes an odd number of arguments") for index in range(0, numKeysAndValues - 1, 2): key = keysAndValues[index] if not isString(key): raise RuntimeException("mapChange keys must be Strings") val = keysAndValues[index + 1] d[key] = val return dictMap(d)
def mapGetPred(map, *keysAndValues): if not isMap(map): raise RuntimeException("First argument to MapGet must be a map") result = list(keysAndValues) for index in range(0, len(result) - 1, 2): key = result[index] if key == None: raise RuntimeException("Must have bound values for keys in MapGet") if isString(key): default = None elif isList(key) and len(key) == 2 and isString(key[0]): default = key[1] key = key[0] else: raise RuntimeException( "Each MapGet key must be a String or a List of a String and a default value" ) val = mapGet(map, key) if val == None: # key isn't found if default == None: return None else: val = default if result[index + 1] == None: # No value specified result[index + 1] = val elif result[index + 1] != val: # Incorrect value specified return None if len(result) % 2 != 0: # odd number of arguments key = result[-1] if key == None: raise RuntimeException("Final MapGet key must be supplied") if not isString(key): raise RuntimeException("Final MapGet key must be a String") if mapGet(map, key) == None: # specified key is not present return None return result
def executeTask(self, listener, taskname, taskargs): if self.agent == None: self.agent = G._AGENT staskargs = fromXPS(taskargs) log_incoming_request(listener, "executeTask", (listener, taskname, staskargs)) symOrError = taskNameToSymOrError(self.agent, taskname) if isString(symOrError): requestType = FAIL_REQUEST term = symOrError else: mode = optMode(self.agent, symOrError, ACTION_DO) if mode: requestType = "d" inargs = [_if(usage == TERM_EVAL, x, None) for (x, usage) in zip(staskargs, mode)] debug("inargs = %r", inargs) term = Structure(symOrError, List(inargs)) else: requestType = FAIL_REQUEST term = "Cannot find argument modes" #debug("initiating task via (%s, %r, %r, %r)", S_ExecuteTask.id, requestType, listener, term) self.agent.add_ephemeral(S_ExecuteTask, requestType, listener, term)
def getTime(arg=None): """Get the time as a floating point number arg=None or arg="NOW": get the current simulated time arg="REAL": get the current real time arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>]': get from localtime string arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>]Z': get from UT string arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>][+-]<HH>:<MM>': use given timezone arg='<yyyy>-<mm>-<dd>; represent date by 00:00 UT arg='P<d>D<H>H<M>M<S>[.<frac>]' treat as a duration arg='-P<d>D<H>H<M>M<S>[.<frac>]' treat as a negative duration arg is a float: leave it unchanged Note: the - and : separators and some unused components can be left out """ if arg is None or arg == SIMULATED_TIME: return _realtimeToSimtime(_time.time()) elif arg == REAL_TIME: return _time.time() elif isString(arg): match = DURATION.match(arg) if match: (neg, d, h, m, s) = match.groups() dur = ((optInt(d) * 24 + optInt(h)) * 60 + optInt(m)) * 60 + optFloat(s) if neg: return -dur else: return dur match = DATE_TIME.match(arg) if match: (Y, M, D, h, m, s, z, tzh, tzm) = match.groups() year = int(Y) month = int(M) day = int(D) hour = optInt(h) min = optInt(m) sec = optFloat(s) if z or h == None: # explicit GMT suffix or date without time return calendar.timegm( (year, month, day, hour, min, 0, 0, 1, 0)) + sec elif tzh: offset = (int(tzh) * 60 + optInt(tzm)) * 60 gmt = calendar.timegm( (year, month, day, hour, min, 0, 0, 1, 0)) + sec return gmt - offset else: return _time.mktime( (year, month, day, hour, min, 0, 0, 1, -1)) + sec else: raise LowError('Invalid datetime string: %s' % arg) # try: # if arg[8] != "T": # raise LowError("Invalid datetime string: %s"%arg) # year = int(arg[0:4]) # month = int(arg[4:6]) # day = int(arg[6:8]) # hour = int(arg[9:11]) # min = int(arg[11:13]) # if arg.endswith('Z'): # UT # sec = float(arg[13:-1] or 0) # return calendar.timegm((year,month,day,hour,min,0,0,1,0)) + sec # else: # localtime # sec = float(arg[13:] or 0) # return _time.mktime((year,month,day,hour,min,0,0,1,-1)) + sec # except (ValueError, IndexError): # raise LowError('Invalid datetime string: %s'%arg) elif isFloat(arg): return arg elif isInteger(arg): return float(arg) else: raise LowError('Invalid time argument of type %s: %r' % (type(arg), arg))
def __init__(self, modestring): if not isString(modestring): raise LowError("Mode should be a string: %r", modestring) self._modestring = modestring self._bitmap = modestring_bitmap(modestring, \ self.zerochar, self.onechar)
def stringJoin(strings, connective): if isString(strings): print "WARNING: the parameter order of spark.lang.string.join has changed" print " Please use (join $strings $connective)" connective,strings = strings,connective return to_string(connective).join([to_string(x) for x in strings])
def stringJoin(strings, connective): if isString(strings): print "WARNING: the parameter order of spark.lang.string.join has changed" print " Please use (join $strings $connective)" connective, strings = strings, connective return to_string(connective).join([to_string(x) for x in strings])
def getTime(arg=None): """Get the time as a floating point number arg=None or arg="NOW": get the current simulated time arg="REAL": get the current real time arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>]': get from localtime string arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>]Z': get from UT string arg='<yyyy>-<mm>-<dd>T<HH>:<MM>:<SS>[.<frac>][+-]<HH>:<MM>': use given timezone arg='<yyyy>-<mm>-<dd>; represent date by 00:00 UT arg='P<d>D<H>H<M>M<S>[.<frac>]' treat as a duration arg='-P<d>D<H>H<M>M<S>[.<frac>]' treat as a negative duration arg is a float: leave it unchanged Note: the - and : separators and some unused components can be left out """ if arg is None or arg == SIMULATED_TIME: return _realtimeToSimtime(_time.time()) elif arg == REAL_TIME: return _time.time() elif isString(arg): match = DURATION.match(arg) if match: (neg, d,h,m,s) = match.groups() dur = ((optInt(d)*24 + optInt(h))*60 + optInt(m))*60 + optFloat(s) if neg: return -dur else: return dur match = DATE_TIME.match(arg) if match: (Y, M, D, h, m, s, z, tzh, tzm) = match.groups() year = int(Y) month = int(M) day = int(D) hour = optInt(h) min = optInt(m) sec = optFloat(s) if z or h == None: # explicit GMT suffix or date without time return calendar.timegm((year,month,day,hour,min,0,0,1,0)) + sec elif tzh: offset = (int(tzh)*60 + optInt(tzm))*60 gmt = calendar.timegm((year,month,day,hour,min,0,0,1,0)) + sec return gmt - offset else: return _time.mktime((year,month,day,hour,min,0,0,1,-1)) + sec else: raise LowError('Invalid datetime string: %s'%arg) # try: # if arg[8] != "T": # raise LowError("Invalid datetime string: %s"%arg) # year = int(arg[0:4]) # month = int(arg[4:6]) # day = int(arg[6:8]) # hour = int(arg[9:11]) # min = int(arg[11:13]) # if arg.endswith('Z'): # UT # sec = float(arg[13:-1] or 0) # return calendar.timegm((year,month,day,hour,min,0,0,1,0)) + sec # else: # localtime # sec = float(arg[13:] or 0) # return _time.mktime((year,month,day,hour,min,0,0,1,-1)) + sec # except (ValueError, IndexError): # raise LowError('Invalid datetime string: %s'%arg) elif isFloat(arg): return arg elif isInteger(arg): return float(arg) else: raise LowError('Invalid time argument of type %s: %r'%(type(arg), arg))