PythonUtil.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745
  1. """Contains miscellaneous utility functions and classes."""
  2. __all__ = ['indent',
  3. 'doc', 'adjust', 'difference', 'intersection', 'union',
  4. 'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
  5. 'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
  6. 'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src',
  7. 'closestDestAngle2', 'closestDestAngle', 'getSetterName',
  8. 'getSetter', 'Functor', 'Stack', 'Queue',
  9. 'bound', 'clamp', 'lerp', 'average', 'addListsByValue',
  10. 'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
  11. 'findPythonModule', 'mostDerivedLast',
  12. 'weightedChoice', 'randFloat', 'normalDistrib',
  13. 'weightedRand', 'randUint31', 'randInt32',
  14. 'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
  15. 'SingletonError', 'printListEnum', 'safeRepr',
  16. 'fastRepr', 'isDefaultValue',
  17. 'ScratchPad', 'Sync', 'itype', 'getNumberedTypedString',
  18. 'getNumberedTypedSortedString',
  19. 'printNumberedTyped', 'DelayedCall', 'DelayedFunctor',
  20. 'FrameDelayedCall', 'SubframeCall', 'getBase', 'GoldenRatio',
  21. 'GoldenRectangle', 'rad90', 'rad180', 'rad270', 'rad360',
  22. 'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel',
  23. 'listToIndex2item', 'listToItem2index',
  24. 'formatTimeCompact','deeptype','StdoutCapture','StdoutPassthrough',
  25. 'Averager', 'getRepository', 'formatTimeExact', 'startSuperLog', 'endSuperLog',
  26. 'typeName', 'safeTypeName', 'histogramDict', 'unescapeHtmlString']
  27. if __debug__:
  28. __all__ += ['StackTrace', 'traceFunctionCall', 'traceParentCall', 'printThisCall',
  29. 'stackEntryInfo', 'lineInfo', 'callerInfo', 'lineTag',
  30. 'profileFunc', 'profiled', 'startProfile', 'printProfile',
  31. 'getProfileResultString', 'printStack', 'printReverseStack']
  32. import types
  33. import math
  34. import os
  35. import sys
  36. import random
  37. import time
  38. __report_indent = 3
  39. from panda3d.core import ConfigVariableBool
  40. if sys.version_info >= (3, 0):
  41. import builtins
  42. xrange = range
  43. else:
  44. import __builtin__ as builtins
  45. """
  46. # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
  47. def Functor(function, *args, **kArgs):
  48. argsCopy = args[:]
  49. def functor(*cArgs, **ckArgs):
  50. kArgs.update(ckArgs)
  51. return function(*(argsCopy + cArgs), **kArgs)
  52. return functor
  53. """
  54. try:
  55. import importlib
  56. except ImportError:
  57. # Backward compatibility for Python 2.6.
  58. def _resolve_name(name, package, level):
  59. if not hasattr(package, 'rindex'):
  60. raise ValueError("'package' not set to a string")
  61. dot = len(package)
  62. for x in xrange(level, 1, -1):
  63. try:
  64. dot = package.rindex('.', 0, dot)
  65. except ValueError:
  66. raise ValueError("attempted relative import beyond top-level "
  67. "package")
  68. return "%s.%s" % (package[:dot], name)
  69. def import_module(name, package=None):
  70. if name.startswith('.'):
  71. if not package:
  72. raise TypeError("relative imports require the 'package' argument")
  73. level = 0
  74. for character in name:
  75. if character != '.':
  76. break
  77. level += 1
  78. name = _resolve_name(name[level:], package, level)
  79. __import__(name)
  80. return sys.modules[name]
  81. imp = import_module('imp')
  82. importlib = imp.new_module("importlib")
  83. importlib._resolve_name = _resolve_name
  84. importlib.import_module = import_module
  85. sys.modules['importlib'] = importlib
  86. class Functor:
  87. def __init__(self, function, *args, **kargs):
  88. assert callable(function), "function should be a callable obj"
  89. self._function = function
  90. self._args = args
  91. self._kargs = kargs
  92. if hasattr(self._function, '__name__'):
  93. self.__name__ = self._function.__name__
  94. else:
  95. self.__name__ = str(itype(self._function))
  96. if hasattr(self._function, '__doc__'):
  97. self.__doc__ = self._function.__doc__
  98. else:
  99. self.__doc__ = self.__name__
  100. def destroy(self):
  101. del self._function
  102. del self._args
  103. del self._kargs
  104. del self.__name__
  105. del self.__doc__
  106. def _do__call__(self, *args, **kargs):
  107. _kargs = self._kargs.copy()
  108. _kargs.update(kargs)
  109. return self._function(*(self._args + args), **_kargs)
  110. __call__ = _do__call__
  111. def __repr__(self):
  112. s = 'Functor(%s' % self._function.__name__
  113. for arg in self._args:
  114. try:
  115. argStr = repr(arg)
  116. except:
  117. argStr = 'bad repr: %s' % arg.__class__
  118. s += ', %s' % argStr
  119. for karg, value in list(self._kargs.items()):
  120. s += ', %s=%s' % (karg, repr(value))
  121. s += ')'
  122. return s
  123. class Stack:
  124. def __init__(self):
  125. self.__list = []
  126. def push(self, item):
  127. self.__list.append(item)
  128. def top(self):
  129. # return the item on the top of the stack without popping it off
  130. return self.__list[-1]
  131. def pop(self):
  132. return self.__list.pop()
  133. def clear(self):
  134. self.__list = []
  135. def isEmpty(self):
  136. return len(self.__list) == 0
  137. def __len__(self):
  138. return len(self.__list)
  139. class Queue:
  140. # FIFO queue
  141. # interface is intentionally identical to Stack (LIFO)
  142. def __init__(self):
  143. self.__list = []
  144. def push(self, item):
  145. self.__list.append(item)
  146. def top(self):
  147. # return the next item at the front of the queue without popping it off
  148. return self.__list[0]
  149. def front(self):
  150. return self.__list[0]
  151. def back(self):
  152. return self.__list[-1]
  153. def pop(self):
  154. return self.__list.pop(0)
  155. def clear(self):
  156. self.__list = []
  157. def isEmpty(self):
  158. return len(self.__list) == 0
  159. def __len__(self):
  160. return len(self.__list)
  161. if __debug__ and __name__ == '__main__':
  162. q = Queue()
  163. assert q.isEmpty()
  164. q.clear()
  165. assert q.isEmpty()
  166. q.push(10)
  167. assert not q.isEmpty()
  168. q.push(20)
  169. assert not q.isEmpty()
  170. assert len(q) == 2
  171. assert q.front() == 10
  172. assert q.back() == 20
  173. assert q.top() == 10
  174. assert q.top() == 10
  175. assert q.pop() == 10
  176. assert len(q) == 1
  177. assert not q.isEmpty()
  178. assert q.pop() == 20
  179. assert len(q) == 0
  180. assert q.isEmpty()
  181. def indent(stream, numIndents, str):
  182. """
  183. Write str to stream with numIndents in front of it
  184. """
  185. # To match emacs, instead of a tab character we will use 4 spaces
  186. stream.write(' ' * numIndents + str)
  187. if __debug__:
  188. import traceback
  189. import marshal
  190. class StackTrace:
  191. def __init__(self, label="", start=0, limit=None):
  192. """
  193. label is a string (or anything that be be a string)
  194. that is printed as part of the trace back.
  195. This is just to make it easier to tell what the
  196. stack trace is referring to.
  197. start is an integer number of stack frames back
  198. from the most recent. (This is automatically
  199. bumped up by one to skip the __init__ call
  200. to the StackTrace).
  201. limit is an integer number of stack frames
  202. to record (or None for unlimited).
  203. """
  204. self.label = label
  205. if limit is not None:
  206. self.trace = traceback.extract_stack(sys._getframe(1+start),
  207. limit=limit)
  208. else:
  209. self.trace = traceback.extract_stack(sys._getframe(1+start))
  210. def compact(self):
  211. r = ''
  212. comma = ','
  213. for filename, lineNum, funcName, text in self.trace:
  214. r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
  215. if len(r):
  216. r = r[:-len(comma)]
  217. return r
  218. def reverseCompact(self):
  219. r = ''
  220. comma = ','
  221. for filename, lineNum, funcName, text in self.trace:
  222. r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
  223. if len(r):
  224. r = r[:-len(comma)]
  225. return r
  226. def __str__(self):
  227. r = "Debug stack trace of %s (back %s frames):\n"%(
  228. self.label, len(self.trace),)
  229. for i in traceback.format_list(self.trace):
  230. r+=i
  231. r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
  232. return r
  233. def printStack():
  234. print(StackTrace(start=1).compact())
  235. return True
  236. def printReverseStack():
  237. print(StackTrace(start=1).reverseCompact())
  238. return True
  239. def printVerboseStack():
  240. print(StackTrace(start=1))
  241. return True
  242. #-----------------------------------------------------------------------------
  243. def traceFunctionCall(frame):
  244. """
  245. return a string that shows the call frame with calling arguments.
  246. e.g.
  247. foo(x=234, y=135)
  248. """
  249. f = frame
  250. co = f.f_code
  251. dict = f.f_locals
  252. n = co.co_argcount
  253. if co.co_flags & 4: n = n+1
  254. if co.co_flags & 8: n = n+1
  255. r=''
  256. if 'self' in dict:
  257. r = '%s.'%(dict['self'].__class__.__name__,)
  258. r+="%s("%(f.f_code.co_name,)
  259. comma=0 # formatting, whether we should type a comma.
  260. for i in range(n):
  261. name = co.co_varnames[i]
  262. if name=='self':
  263. continue
  264. if comma:
  265. r+=', '
  266. else:
  267. # ok, we skipped the first one, the rest get commas:
  268. comma=1
  269. r+=name
  270. r+='='
  271. if name in dict:
  272. v=safeRepr(dict[name])
  273. if len(v)>2000:
  274. # r+="<too big for debug>"
  275. r += (v[:2000] + "...")
  276. else:
  277. r+=v
  278. else: r+="*** undefined ***"
  279. return r+')'
  280. def traceParentCall():
  281. return traceFunctionCall(sys._getframe(2))
  282. def printThisCall():
  283. print(traceFunctionCall(sys._getframe(1)))
  284. return 1 # to allow "assert printThisCall()"
  285. # Magic numbers: These are the bit masks in func_code.co_flags that
  286. # reveal whether or not the function has a *arg or **kw argument.
  287. _POS_LIST = 4
  288. _KEY_DICT = 8
  289. def doc(obj):
  290. if (isinstance(obj, types.MethodType)) or \
  291. (isinstance(obj, types.FunctionType)):
  292. print(obj.__doc__)
  293. def adjust(command = None, dim = 1, parent = None, **kw):
  294. """
  295. adjust(command = None, parent = None, **kw)
  296. Popup and entry scale to adjust a parameter
  297. Accepts any Slider keyword argument. Typical arguments include:
  298. command: The one argument command to execute
  299. min: The min value of the slider
  300. max: The max value of the slider
  301. resolution: The resolution of the slider
  302. text: The label on the slider
  303. These values can be accessed and/or changed after the fact
  304. >>> vg = adjust()
  305. >>> vg['min']
  306. 0.0
  307. >>> vg['min'] = 10.0
  308. >>> vg['min']
  309. 10.0
  310. """
  311. # Make sure we enable Tk
  312. # Don't use a regular import, to prevent ModuleFinder from picking
  313. # it up as a dependency when building a .p3d package.
  314. Valuator = importlib.import_module('direct.tkwidgets.Valuator')
  315. # Set command if specified
  316. if command:
  317. kw['command'] = lambda x: command(*x)
  318. if parent is None:
  319. kw['title'] = command.__name__
  320. kw['dim'] = dim
  321. # Create toplevel if needed
  322. if not parent:
  323. vg = Valuator.ValuatorGroupPanel(parent, **kw)
  324. else:
  325. vg = Valuator.ValuatorGroup(parent, **kw)
  326. vg.pack(expand = 1, fill = 'x')
  327. return vg
  328. def difference(a, b):
  329. """
  330. difference(list, list):
  331. """
  332. if not a: return b
  333. if not b: return a
  334. d = []
  335. for i in a:
  336. if (i not in b) and (i not in d):
  337. d.append(i)
  338. for i in b:
  339. if (i not in a) and (i not in d):
  340. d.append(i)
  341. return d
  342. def intersection(a, b):
  343. """
  344. intersection(list, list):
  345. """
  346. if not a: return []
  347. if not b: return []
  348. d = []
  349. for i in a:
  350. if (i in b) and (i not in d):
  351. d.append(i)
  352. for i in b:
  353. if (i in a) and (i not in d):
  354. d.append(i)
  355. return d
  356. def union(a, b):
  357. """
  358. union(list, list):
  359. """
  360. # Copy a
  361. c = a[:]
  362. for i in b:
  363. if (i not in c):
  364. c.append(i)
  365. return c
  366. def sameElements(a, b):
  367. if len(a) != len(b):
  368. return 0
  369. for elem in a:
  370. if elem not in b:
  371. return 0
  372. for elem in b:
  373. if elem not in a:
  374. return 0
  375. return 1
  376. def makeList(x):
  377. """returns x, converted to a list"""
  378. if type(x) is list:
  379. return x
  380. elif type(x) is tuple:
  381. return list(x)
  382. else:
  383. return [x,]
  384. def makeTuple(x):
  385. """returns x, converted to a tuple"""
  386. if type(x) is list:
  387. return tuple(x)
  388. elif type(x) is tuple:
  389. return x
  390. else:
  391. return (x,)
  392. def list2dict(L, value=None):
  393. """creates dict using elements of list, all assigned to same value"""
  394. return dict([(k, value) for k in L])
  395. def listToIndex2item(L):
  396. """converts list to dict of list index->list item"""
  397. d = {}
  398. for i, item in enumerate(L):
  399. d[i] = item
  400. return d
  401. assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
  402. def listToItem2index(L):
  403. """converts list to dict of list item->list index
  404. This is lossy if there are duplicate list items"""
  405. d = {}
  406. for i, item in enumerate(L):
  407. d[item] = i
  408. return d
  409. assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
  410. def invertDict(D, lossy=False):
  411. """creates a dictionary by 'inverting' D; keys are placed in the new
  412. dictionary under their corresponding value in the old dictionary.
  413. It is an error if D contains any duplicate values.
  414. >>> old = {'key1':1, 'key2':2}
  415. >>> invertDict(old)
  416. {1: 'key1', 2: 'key2'}
  417. """
  418. n = {}
  419. for key, value in D.items():
  420. if not lossy and value in n:
  421. raise Exception('duplicate key in invertDict: %s' % value)
  422. n[value] = key
  423. return n
  424. def invertDictLossless(D):
  425. """similar to invertDict, but values of new dict are lists of keys from
  426. old dict. No information is lost.
  427. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  428. >>> invertDictLossless(old)
  429. {1: ['key1'], 2: ['key2', 'keyA']}
  430. """
  431. n = {}
  432. for key, value in D.items():
  433. n.setdefault(value, [])
  434. n[value].append(key)
  435. return n
  436. def uniqueElements(L):
  437. """are all elements of list unique?"""
  438. return len(L) == len(list2dict(L))
  439. def disjoint(L1, L2):
  440. """returns non-zero if L1 and L2 have no common elements"""
  441. used = dict([(k, None) for k in L1])
  442. for k in L2:
  443. if k in used:
  444. return 0
  445. return 1
  446. def contains(whole, sub):
  447. """
  448. Return 1 if whole contains sub, 0 otherwise
  449. """
  450. if (whole == sub):
  451. return 1
  452. for elem in sub:
  453. # The first item you find not in whole, return 0
  454. if elem not in whole:
  455. return 0
  456. # If you got here, whole must contain sub
  457. return 1
  458. def replace(list, old, new, all=0):
  459. """
  460. replace 'old' with 'new' in 'list'
  461. if all == 0, replace first occurrence
  462. otherwise replace all occurrences
  463. returns the number of items replaced
  464. """
  465. if old not in list:
  466. return 0
  467. if not all:
  468. i = list.index(old)
  469. list[i] = new
  470. return 1
  471. else:
  472. numReplaced = 0
  473. for i in xrange(len(list)):
  474. if list[i] == old:
  475. numReplaced += 1
  476. list[i] = new
  477. return numReplaced
  478. rad90 = math.pi / 2.
  479. rad180 = math.pi
  480. rad270 = 1.5 * math.pi
  481. rad360 = 2. * math.pi
  482. def reduceAngle(deg):
  483. """
  484. Reduces an angle (in degrees) to a value in [-180..180)
  485. """
  486. return (((deg + 180.) % 360.) - 180.)
  487. def fitSrcAngle2Dest(src, dest):
  488. """
  489. given a src and destination angle, returns an equivalent src angle
  490. that is within [-180..180) of dest
  491. examples:
  492. fitSrcAngle2Dest(30, 60) == 30
  493. fitSrcAngle2Dest(60, 30) == 60
  494. fitSrcAngle2Dest(0, 180) == 0
  495. fitSrcAngle2Dest(-1, 180) == 359
  496. fitSrcAngle2Dest(-180, 180) == 180
  497. """
  498. return dest + reduceAngle(src - dest)
  499. def fitDestAngle2Src(src, dest):
  500. """
  501. given a src and destination angle, returns an equivalent dest angle
  502. that is within [-180..180) of src
  503. examples:
  504. fitDestAngle2Src(30, 60) == 60
  505. fitDestAngle2Src(60, 30) == 30
  506. fitDestAngle2Src(0, 180) == -180
  507. fitDestAngle2Src(1, 180) == 180
  508. """
  509. return src + (reduceAngle(dest - src))
  510. def closestDestAngle2(src, dest):
  511. # The function above didn't seem to do what I wanted. So I hacked
  512. # this one together. I can't really say I understand it. It's more
  513. # from impirical observation... GRW
  514. diff = src - dest
  515. if diff > 180:
  516. # if the difference is greater that 180 it's shorter to go the other way
  517. return dest - 360
  518. elif diff < -180:
  519. # or perhaps the OTHER other way...
  520. return dest + 360
  521. else:
  522. # otherwise just go to the original destination
  523. return dest
  524. def closestDestAngle(src, dest):
  525. # The function above didn't seem to do what I wanted. So I hacked
  526. # this one together. I can't really say I understand it. It's more
  527. # from impirical observation... GRW
  528. diff = src - dest
  529. if diff > 180:
  530. # if the difference is greater that 180 it's shorter to go the other way
  531. return src - (diff - 360)
  532. elif diff < -180:
  533. # or perhaps the OTHER other way...
  534. return src - (360 + diff)
  535. else:
  536. # otherwise just go to the original destination
  537. return dest
  538. class StdoutCapture:
  539. # redirects stdout to a string
  540. def __init__(self):
  541. self._oldStdout = sys.stdout
  542. sys.stdout = self
  543. self._string = ''
  544. def destroy(self):
  545. sys.stdout = self._oldStdout
  546. del self._oldStdout
  547. def getString(self):
  548. return self._string
  549. # internal
  550. def write(self, string):
  551. self._string = ''.join([self._string, string])
  552. class StdoutPassthrough(StdoutCapture):
  553. # like StdoutCapture but also allows output to go through to the OS as normal
  554. # internal
  555. def write(self, string):
  556. self._string = ''.join([self._string, string])
  557. self._oldStdout.write(string)
  558. # constant profile defaults
  559. if __debug__:
  560. from io import StringIO
  561. PyUtilProfileDefaultFilename = 'profiledata'
  562. PyUtilProfileDefaultLines = 80
  563. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  564. _ProfileResultStr = ''
  565. def getProfileResultString():
  566. # if you called profile with 'log' not set to True,
  567. # you can call this function to get the results as
  568. # a string
  569. global _ProfileResultStr
  570. return _ProfileResultStr
  571. def profileFunc(callback, name, terse, log=True):
  572. global _ProfileResultStr
  573. if 'globalProfileFunc' in builtins.__dict__:
  574. # rats. Python profiler is not re-entrant...
  575. base.notify.warning(
  576. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  577. #'\nStack Trace:\n%s'
  578. % (name, builtins.globalProfileFunc,
  579. #StackTrace()
  580. ))
  581. return
  582. builtins.globalProfileFunc = callback
  583. builtins.globalProfileResult = [None]
  584. prefix = '***** START PROFILE: %s *****' % name
  585. if log:
  586. print(prefix)
  587. startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
  588. suffix = '***** END PROFILE: %s *****' % name
  589. if log:
  590. print(suffix)
  591. else:
  592. _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
  593. result = globalProfileResult[0]
  594. del builtins.__dict__['globalProfileFunc']
  595. del builtins.__dict__['globalProfileResult']
  596. return result
  597. def profiled(category=None, terse=False):
  598. """ decorator for profiling functions
  599. turn categories on and off via "want-profile-categoryName 1"
  600. e.g.
  601. @profiled('particles')
  602. def loadParticles():
  603. ...
  604. want-profile-particles 1
  605. """
  606. assert type(category) in (str, type(None)), "must provide a category name for @profiled"
  607. # allow profiling in published versions
  608. """
  609. try:
  610. null = not __dev__
  611. except:
  612. null = not __debug__
  613. if null:
  614. # if we're not in __dev__, just return the function itself. This
  615. # results in zero runtime overhead, since decorators are evaluated
  616. # at module-load.
  617. def nullDecorator(f):
  618. return f
  619. return nullDecorator
  620. """
  621. def profileDecorator(f):
  622. def _profiled(*args, **kArgs):
  623. name = '(%s) %s from %s' % (category, f.__name__, f.__module__)
  624. # showbase might not be loaded yet, so don't use
  625. # base.config. Instead, query the ConfigVariableBool.
  626. if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
  627. return profileFunc(Functor(f, *args, **kArgs), name, terse)
  628. else:
  629. return f(*args, **kArgs)
  630. _profiled.__doc__ = f.__doc__
  631. return _profiled
  632. return profileDecorator
  633. # intercept profile-related file operations to avoid disk access
  634. movedOpenFuncs = []
  635. movedDumpFuncs = []
  636. movedLoadFuncs = []
  637. profileFilenames = set()
  638. profileFilenameList = Stack()
  639. profileFilename2file = {}
  640. profileFilename2marshalData = {}
  641. def _profileOpen(filename, *args, **kArgs):
  642. # this is a replacement for the file open() builtin function
  643. # for use during profiling, to intercept the file open
  644. # operation used by the Python profiler and profile stats
  645. # systems
  646. if filename in profileFilenames:
  647. # if this is a file related to profiling, create an
  648. # in-RAM file object
  649. if filename not in profileFilename2file:
  650. file = StringIO()
  651. file._profFilename = filename
  652. profileFilename2file[filename] = file
  653. else:
  654. file = profileFilename2file[filename]
  655. else:
  656. file = movedOpenFuncs[-1](filename, *args, **kArgs)
  657. return file
  658. def _profileMarshalDump(data, file):
  659. # marshal.dump doesn't work with StringIO objects
  660. # simulate it
  661. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  662. if file._profFilename in profileFilenames:
  663. profileFilename2marshalData[file._profFilename] = data
  664. return None
  665. return movedDumpFuncs[-1](data, file)
  666. def _profileMarshalLoad(file):
  667. # marshal.load doesn't work with StringIO objects
  668. # simulate it
  669. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  670. if file._profFilename in profileFilenames:
  671. return profileFilename2marshalData[file._profFilename]
  672. return movedLoadFuncs[-1](file)
  673. def _installProfileCustomFuncs(filename):
  674. assert filename not in profileFilenames
  675. profileFilenames.add(filename)
  676. profileFilenameList.push(filename)
  677. movedOpenFuncs.append(builtins.open)
  678. builtins.open = _profileOpen
  679. movedDumpFuncs.append(marshal.dump)
  680. marshal.dump = _profileMarshalDump
  681. movedLoadFuncs.append(marshal.load)
  682. marshal.load = _profileMarshalLoad
  683. def _getProfileResultFileInfo(filename):
  684. return (profileFilename2file.get(filename, None),
  685. profileFilename2marshalData.get(filename, None))
  686. def _setProfileResultsFileInfo(filename, info):
  687. f, m = info
  688. if f:
  689. profileFilename2file[filename] = f
  690. if m:
  691. profileFilename2marshalData[filename] = m
  692. def _clearProfileResultFileInfo(filename):
  693. profileFilename2file.pop(filename, None)
  694. profileFilename2marshalData.pop(filename, None)
  695. def _removeProfileCustomFuncs(filename):
  696. assert profileFilenameList.top() == filename
  697. marshal.load = movedLoadFuncs.pop()
  698. marshal.dump = movedDumpFuncs.pop()
  699. builtins.open = movedOpenFuncs.pop()
  700. profileFilenames.remove(filename)
  701. profileFilenameList.pop()
  702. profileFilename2file.pop(filename, None)
  703. # don't let marshalled data pile up
  704. profileFilename2marshalData.pop(filename, None)
  705. # call this from the prompt, and break back out to the prompt
  706. # to stop profiling
  707. #
  708. # OR to do inline profiling, you must make a globally-visible
  709. # function to be profiled, i.e. to profile 'self.load()', do
  710. # something like this:
  711. #
  712. # def func(self=self):
  713. # self.load()
  714. # import builtins
  715. # builtins.func = func
  716. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  717. # del builtins.func
  718. #
  719. def _profileWithoutGarbageLeak(cmd, filename):
  720. # The profile module isn't necessarily installed on every Python
  721. # installation, so we import it here, instead of in the module
  722. # scope.
  723. import profile
  724. # this is necessary because the profile module creates a memory leak
  725. Profile = profile.Profile
  726. statement = cmd
  727. sort = -1
  728. retVal = None
  729. #### COPIED FROM profile.run ####
  730. prof = Profile()
  731. try:
  732. prof = prof.run(statement)
  733. except SystemExit:
  734. pass
  735. if filename is not None:
  736. prof.dump_stats(filename)
  737. else:
  738. #return prof.print_stats(sort) #DCR
  739. retVal = prof.print_stats(sort) #DCR
  740. #################################
  741. # eliminate the garbage leak
  742. del prof.dispatcher
  743. return retVal
  744. def startProfile(filename=PyUtilProfileDefaultFilename,
  745. lines=PyUtilProfileDefaultLines,
  746. sorts=PyUtilProfileDefaultSorts,
  747. silent=0,
  748. callInfo=1,
  749. useDisk=False,
  750. cmd='run()'):
  751. # uniquify the filename to allow multiple processes to profile simultaneously
  752. filename = '%s.%s%s' % (filename, randUint31(), randUint31())
  753. if not useDisk:
  754. # use a RAM file
  755. _installProfileCustomFuncs(filename)
  756. _profileWithoutGarbageLeak(cmd, filename)
  757. if silent:
  758. extractProfile(filename, lines, sorts, callInfo)
  759. else:
  760. printProfile(filename, lines, sorts, callInfo)
  761. if not useDisk:
  762. # discard the RAM file
  763. _removeProfileCustomFuncs(filename)
  764. else:
  765. os.remove(filename)
  766. # call these to see the results again, as a string or in the log
  767. def printProfile(filename=PyUtilProfileDefaultFilename,
  768. lines=PyUtilProfileDefaultLines,
  769. sorts=PyUtilProfileDefaultSorts,
  770. callInfo=1):
  771. import pstats
  772. s = pstats.Stats(filename)
  773. s.strip_dirs()
  774. for sort in sorts:
  775. s.sort_stats(sort)
  776. s.print_stats(lines)
  777. if callInfo:
  778. s.print_callees(lines)
  779. s.print_callers(lines)
  780. # same args as printProfile
  781. def extractProfile(*args, **kArgs):
  782. global _ProfileResultStr
  783. # capture print output
  784. sc = StdoutCapture()
  785. # print the profile output, redirected to the result string
  786. printProfile(*args, **kArgs)
  787. # make a copy of the print output
  788. _ProfileResultStr = sc.getString()
  789. # restore stdout to what it was before
  790. sc.destroy()
  791. def getSetterName(valueName, prefix='set'):
  792. # getSetterName('color') -> 'setColor'
  793. # getSetterName('color', 'get') -> 'getColor'
  794. return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:])
  795. def getSetter(targetObj, valueName, prefix='set'):
  796. # getSetter(smiley, 'pos') -> smiley.setPos
  797. return getattr(targetObj, getSetterName(valueName, prefix))
  798. def mostDerivedLast(classList):
  799. """pass in list of classes. sorts list in-place, with derived classes
  800. appearing after their bases"""
  801. class ClassSortKey(object):
  802. __slots__ = 'classobj',
  803. def __init__(self, classobj):
  804. self.classobj = classobj
  805. def __lt__(self, other):
  806. return issubclass(other.classobj, self.classobj)
  807. classList.sort(key=ClassSortKey)
  808. def bound(value, bound1, bound2):
  809. """
  810. returns value if value is between bound1 and bound2
  811. otherwise returns bound that is closer to value
  812. """
  813. if bound1 > bound2:
  814. return min(max(value, bound2), bound1)
  815. else:
  816. return min(max(value, bound1), bound2)
  817. clamp = bound
  818. def lerp(v0, v1, t):
  819. """
  820. returns a value lerped between v0 and v1, according to t
  821. t == 0 maps to v0, t == 1 maps to v1
  822. """
  823. return v0 + ((v1 - v0) * t)
  824. def getShortestRotation(start, end):
  825. """
  826. Given two heading values, return a tuple describing
  827. the shortest interval from 'start' to 'end'. This tuple
  828. can be used to lerp a camera between two rotations
  829. while avoiding the 'spin' problem.
  830. """
  831. start, end = start % 360, end % 360
  832. if abs(end - start) > 180:
  833. if end < start:
  834. end += 360
  835. else:
  836. start += 360
  837. return (start, end)
  838. def average(*args):
  839. """ returns simple average of list of values """
  840. val = 0.
  841. for arg in args:
  842. val += arg
  843. return val / len(args)
  844. class Averager:
  845. def __init__(self, name):
  846. self._name = name
  847. self.reset()
  848. def reset(self):
  849. self._total = 0.
  850. self._count = 0
  851. def addValue(self, value):
  852. self._total += value
  853. self._count += 1
  854. def getAverage(self):
  855. return self._total / self._count
  856. def getCount(self):
  857. return self._count
  858. def addListsByValue(a, b):
  859. """
  860. returns a new array containing the sums of the two array arguments
  861. (c[0] = a[0 + b[0], etc.)
  862. """
  863. c = []
  864. for x, y in zip(a, b):
  865. c.append(x + y)
  866. return c
  867. def boolEqual(a, b):
  868. """
  869. returns true if a and b are both true or both false.
  870. returns false otherwise
  871. (a.k.a. xnor -- eXclusive Not OR).
  872. """
  873. return (a and b) or not (a or b)
  874. def lineupPos(i, num, spacing):
  875. """
  876. use to line up a series of 'num' objects, in one dimension,
  877. centered around zero
  878. 'i' is the index of the object in the lineup
  879. 'spacing' is the amount of space between objects in the lineup
  880. """
  881. assert num >= 1
  882. assert i >= 0 and i < num
  883. pos = float(i) * spacing
  884. return pos - ((float(spacing) * (num-1))/2.)
  885. def formatElapsedSeconds(seconds):
  886. """
  887. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  888. representing the indicated elapsed time in seconds.
  889. """
  890. sign = ''
  891. if seconds < 0:
  892. seconds = -seconds
  893. sign = '-'
  894. # We use math.floor() instead of casting to an int, so we avoid
  895. # problems with numbers that are too large to represent as
  896. # type int.
  897. seconds = math.floor(seconds)
  898. hours = math.floor(seconds / (60 * 60))
  899. if hours > 36:
  900. days = math.floor((hours + 12) / 24)
  901. return "%s%d days" % (sign, days)
  902. seconds -= hours * (60 * 60)
  903. minutes = (int)(seconds / 60)
  904. seconds -= minutes * 60
  905. if hours != 0:
  906. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  907. else:
  908. return "%s%d:%02d" % (sign, minutes, seconds)
  909. def solveQuadratic(a, b, c):
  910. # quadratic equation: ax^2 + bx + c = 0
  911. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  912. # returns None, root, or [root1, root2]
  913. # a cannot be zero.
  914. if a == 0.:
  915. return None
  916. # calculate the determinant (b^2 - 4ac)
  917. D = (b * b) - (4. * a * c)
  918. if D < 0:
  919. # there are no solutions (sqrt(negative number) is undefined)
  920. return None
  921. elif D == 0:
  922. # only one root
  923. return (-b) / (2. * a)
  924. else:
  925. # OK, there are two roots
  926. sqrtD = math.sqrt(D)
  927. twoA = 2. * a
  928. root1 = ((-b) - sqrtD) / twoA
  929. root2 = ((-b) + sqrtD) / twoA
  930. return [root1, root2]
  931. if __debug__:
  932. def stackEntryInfo(depth=0, baseFileName=1):
  933. """
  934. returns the sourcefilename, line number, and function name of
  935. an entry in the stack.
  936. 'depth' is how far back to go in the stack; 0 is the caller of this
  937. function, 1 is the function that called the caller of this function, etc.
  938. by default, strips off the path of the filename; override with baseFileName
  939. returns (fileName, lineNum, funcName) --> (string, int, string)
  940. returns (None, None, None) on error
  941. """
  942. import inspect
  943. try:
  944. stack = None
  945. frame = None
  946. try:
  947. stack = inspect.stack()
  948. # add one to skip the frame associated with this function
  949. frame = stack[depth+1]
  950. filename = frame[1]
  951. if baseFileName:
  952. filename = os.path.basename(filename)
  953. lineNum = frame[2]
  954. funcName = frame[3]
  955. result = (filename, lineNum, funcName)
  956. finally:
  957. del stack
  958. del frame
  959. except:
  960. result = (None, None, None)
  961. return result
  962. def lineInfo(baseFileName=1):
  963. """
  964. returns the sourcefilename, line number, and function name of the
  965. code that called this function
  966. (answers the question: 'hey lineInfo, where am I in the codebase?')
  967. see stackEntryInfo, above, for info on 'baseFileName' and return types
  968. """
  969. return stackEntryInfo(1, baseFileName)
  970. def callerInfo(baseFileName=1, howFarBack=0):
  971. """
  972. returns the sourcefilename, line number, and function name of the
  973. caller of the function that called this function
  974. (answers the question: 'hey callerInfo, who called me?')
  975. see stackEntryInfo, above, for info on 'baseFileName' and return types
  976. """
  977. return stackEntryInfo(2+howFarBack, baseFileName)
  978. def lineTag(baseFileName=1, verbose=0, separator=':'):
  979. """
  980. returns a string containing the sourcefilename and line number
  981. of the code that called this function
  982. (equivalent to lineInfo, above, with different return type)
  983. see stackEntryInfo, above, for info on 'baseFileName'
  984. if 'verbose' is false, returns a compact string of the form
  985. 'fileName:lineNum:funcName'
  986. if 'verbose' is true, returns a longer string that matches the
  987. format of Python stack trace dumps
  988. returns empty string on error
  989. """
  990. fileName, lineNum, funcName = callerInfo(baseFileName)
  991. if fileName is None:
  992. return ''
  993. if verbose:
  994. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  995. else:
  996. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  997. funcName)
  998. def findPythonModule(module):
  999. # Look along the python load path for the indicated filename.
  1000. # Returns the located pathname, or None if the filename is not
  1001. # found.
  1002. filename = module + '.py'
  1003. for dir in sys.path:
  1004. pathname = os.path.join(dir, filename)
  1005. if os.path.exists(pathname):
  1006. return pathname
  1007. return None
  1008. def weightedChoice(choiceList, rng=random.random, sum=None):
  1009. """given a list of (weight, item) pairs, chooses an item based on the
  1010. weights. rng must return 0..1. if you happen to have the sum of the
  1011. weights, pass it in 'sum'."""
  1012. # TODO: add support for dicts
  1013. if sum is None:
  1014. sum = 0.
  1015. for weight, item in choiceList:
  1016. sum += weight
  1017. rand = rng()
  1018. accum = rand * sum
  1019. for weight, item in choiceList:
  1020. accum -= weight
  1021. if accum <= 0.:
  1022. return item
  1023. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1024. # Or you passed in a 'sum' that was was too large.
  1025. # Return the last item.
  1026. return item
  1027. def randFloat(a, b=0., rng=random.random):
  1028. """returns a random float in [a, b]
  1029. call with single argument to generate random float between arg and zero
  1030. """
  1031. return lerp(a, b, rng())
  1032. def normalDistrib(a, b, gauss=random.gauss):
  1033. """
  1034. NOTE: assumes a < b
  1035. Returns random number between a and b, using gaussian distribution, with
  1036. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1037. between a and b.
  1038. For ease of use, outlying results are re-computed until result is in [a, b]
  1039. This should fit the remaining .3% of the curve that lies outside [a, b]
  1040. uniformly onto the curve inside [a, b]
  1041. ------------------------------------------------------------------------
  1042. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1043. The 68-95-99.7% Rule
  1044. ====================
  1045. All normal density curves satisfy the following property which is often
  1046. referred to as the Empirical Rule:
  1047. 68% of the observations fall within 1 standard deviation of the mean.
  1048. 95% of the observations fall within 2 standard deviations of the mean.
  1049. 99.7% of the observations fall within 3 standard deviations of the mean.
  1050. Thus, for a normal distribution, almost all values lie within 3 standard
  1051. deviations of the mean.
  1052. ------------------------------------------------------------------------
  1053. In calculating our standard deviation, we divide (b-a) by 6, since the
  1054. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1055. """
  1056. while True:
  1057. r = gauss((a+b)*.5, (b-a)/6.)
  1058. if (r >= a) and (r <= b):
  1059. return r
  1060. def weightedRand(valDict, rng=random.random):
  1061. """
  1062. pass in a dictionary with a selection -> weight mapping. Eg.
  1063. {"Choice 1": 10,
  1064. "Choice 2": 30,
  1065. "bear": 100}
  1066. -Weights need not add up to any particular value.
  1067. -The actual selection will be returned.
  1068. """
  1069. selections = list(valDict.keys())
  1070. weights = list(valDict.values())
  1071. totalWeight = 0
  1072. for weight in weights:
  1073. totalWeight += weight
  1074. # get a random value between 0 and the total of the weights
  1075. randomWeight = rng() * totalWeight
  1076. # find the index that corresponds with this weight
  1077. for i in range(len(weights)):
  1078. totalWeight -= weights[i]
  1079. if totalWeight <= randomWeight:
  1080. return selections[i]
  1081. assert True, "Should never get here"
  1082. return selections[-1]
  1083. def randUint31(rng=random.random):
  1084. """returns a random integer in [0..2^31).
  1085. rng must return float in [0..1]"""
  1086. return int(rng() * 0x7FFFFFFF)
  1087. def randInt32(rng=random.random):
  1088. """returns a random integer in [-2147483648..2147483647].
  1089. rng must return float in [0..1]
  1090. """
  1091. i = int(rng() * 0x7FFFFFFF)
  1092. if rng() < .5:
  1093. i *= -1
  1094. return i
  1095. class SerialNumGen:
  1096. """generates serial numbers"""
  1097. def __init__(self, start=None):
  1098. if start is None:
  1099. start = 0
  1100. self.__counter = start-1
  1101. def next(self):
  1102. self.__counter += 1
  1103. return self.__counter
  1104. class SerialMaskedGen(SerialNumGen):
  1105. def __init__(self, mask, start=None):
  1106. self._mask = mask
  1107. SerialNumGen.__init__(self, start)
  1108. def next(self):
  1109. v = SerialNumGen.next(self)
  1110. return v & self._mask
  1111. _serialGen = SerialNumGen()
  1112. def serialNum():
  1113. global _serialGen
  1114. return _serialGen.next()
  1115. def uniqueName(name):
  1116. global _serialGen
  1117. return '%s-%s' % (name, _serialGen.next())
  1118. class EnumIter:
  1119. def __init__(self, enum):
  1120. self._values = list(enum._stringTable.keys())
  1121. self._index = 0
  1122. def __iter__(self):
  1123. return self
  1124. def __next__(self):
  1125. if self._index >= len(self._values):
  1126. raise StopIteration
  1127. self._index += 1
  1128. return self._values[self._index-1]
  1129. next = __next__
  1130. class Enum:
  1131. """Pass in list of strings or string of comma-separated strings.
  1132. Items are accessible as instance.item, and are assigned unique,
  1133. increasing integer values. Pass in integer for 'start' to override
  1134. starting value.
  1135. Example:
  1136. >>> colors = Enum('red, green, blue')
  1137. >>> colors.red
  1138. 0
  1139. >>> colors.green
  1140. 1
  1141. >>> colors.blue
  1142. 2
  1143. >>> colors.getString(colors.red)
  1144. 'red'
  1145. """
  1146. if __debug__:
  1147. # chars that cannot appear within an item string.
  1148. def _checkValidIdentifier(item):
  1149. import string
  1150. invalidChars = string.whitespace + string.punctuation
  1151. invalidChars = invalidChars.replace('_', '')
  1152. invalidFirstChars = invalidChars+string.digits
  1153. if item[0] in invalidFirstChars:
  1154. raise SyntaxError("Enum '%s' contains invalid first char" %
  1155. item)
  1156. if not disjoint(item, invalidChars):
  1157. for char in item:
  1158. if char in invalidChars:
  1159. raise SyntaxError(
  1160. "Enum\n'%s'\ncontains illegal char '%s'" %
  1161. (item, char))
  1162. return 1
  1163. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1164. def __init__(self, items, start=0):
  1165. if isinstance(items, str):
  1166. items = items.split(',')
  1167. self._stringTable = {}
  1168. # make sure we don't overwrite an existing element of the class
  1169. assert self._checkExistingMembers(items)
  1170. assert uniqueElements(items)
  1171. i = start
  1172. for item in items:
  1173. # remove leading/trailing whitespace
  1174. item = item.strip()
  1175. # is there anything left?
  1176. if len(item) == 0:
  1177. continue
  1178. # make sure there are no invalid characters
  1179. assert Enum._checkValidIdentifier(item)
  1180. self.__dict__[item] = i
  1181. self._stringTable[i] = item
  1182. i += 1
  1183. def __iter__(self):
  1184. return EnumIter(self)
  1185. def hasString(self, string):
  1186. return string in set(self._stringTable.values())
  1187. def fromString(self, string):
  1188. if self.hasString(string):
  1189. return self.__dict__[string]
  1190. # throw an error
  1191. {}[string]
  1192. def getString(self, value):
  1193. return self._stringTable[value]
  1194. def __contains__(self, value):
  1195. return value in self._stringTable
  1196. def __len__(self):
  1197. return len(self._stringTable)
  1198. def copyTo(self, obj):
  1199. # copies all members onto obj
  1200. for name, value in self._stringTable:
  1201. setattr(obj, name, value)
  1202. if __debug__:
  1203. def _checkExistingMembers(self, items):
  1204. for item in items:
  1205. if hasattr(self, item):
  1206. return 0
  1207. return 1
  1208. ############################################################
  1209. # class: Singleton
  1210. # Purpose: This provides a base metaclass for all classes
  1211. # that require one and only one instance.
  1212. #
  1213. # Example: class mySingleton:
  1214. # __metaclass__ = PythonUtil.Singleton
  1215. # def __init__(self, ...):
  1216. # ...
  1217. #
  1218. # Note: This class is based on Python's New-Style Class
  1219. # design. An error will occur if a defined class
  1220. # attemps to inherit from a Classic-Style Class only,
  1221. # ie: class myClassX:
  1222. # def __init__(self, ...):
  1223. # ...
  1224. #
  1225. # class myNewClassX(myClassX):
  1226. # __metaclass__ = PythonUtil.Singleton
  1227. # def __init__(self, ...):
  1228. # myClassX.__init__(self, ...)
  1229. # ...
  1230. #
  1231. # This causes problems because myNewClassX is a
  1232. # New-Style class that inherits from only a
  1233. # Classic-Style base class. There are two ways
  1234. # simple ways to resolve this issue.
  1235. #
  1236. # First, if possible, make myClassX a
  1237. # New-Style class by inheriting from object
  1238. # object. IE: class myClassX(object):
  1239. #
  1240. # If for some reason that is not an option, make
  1241. # myNewClassX inherit from object and myClassX.
  1242. # IE: class myNewClassX(object, myClassX):
  1243. ############################################################
  1244. class Singleton(type):
  1245. def __init__(cls, name, bases, dic):
  1246. super(Singleton, cls).__init__(name, bases, dic)
  1247. cls.instance=None
  1248. def __call__(cls, *args, **kw):
  1249. if cls.instance is None:
  1250. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  1251. return cls.instance
  1252. class SingletonError(ValueError):
  1253. """ Used to indicate an inappropriate value for a Singleton."""
  1254. def printListEnumGen(l):
  1255. # log each individual item with a number in front of it
  1256. digits = 0
  1257. n = len(l)
  1258. while n > 0:
  1259. digits += 1
  1260. n //= 10
  1261. format = '%0' + '%s' % digits + 'i:%s'
  1262. for i in range(len(l)):
  1263. print(format % (i, l[i]))
  1264. yield None
  1265. def printListEnum(l):
  1266. for result in printListEnumGen(l):
  1267. pass
  1268. # base class for all Panda C++ objects
  1269. # libdtoolconfig doesn't seem to have this, grab it off of TypedObject
  1270. dtoolSuperBase = None
  1271. def _getDtoolSuperBase():
  1272. global dtoolSuperBase
  1273. from panda3d.core import TypedObject
  1274. dtoolSuperBase = TypedObject.__bases__[0]
  1275. assert dtoolSuperBase.__name__ == 'DTOOL_SUPER_BASE'
  1276. safeReprNotify = None
  1277. def _getSafeReprNotify():
  1278. global safeReprNotify
  1279. from direct.directnotify.DirectNotifyGlobal import directNotify
  1280. safeReprNotify = directNotify.newCategory("safeRepr")
  1281. return safeReprNotify
  1282. def safeRepr(obj):
  1283. global dtoolSuperBase
  1284. if dtoolSuperBase is None:
  1285. _getDtoolSuperBase()
  1286. global safeReprNotify
  1287. if safeReprNotify is None:
  1288. _getSafeReprNotify()
  1289. if isinstance(obj, dtoolSuperBase):
  1290. # repr of C++ object could crash, particularly if the object has been deleted
  1291. # log that we're calling repr
  1292. safeReprNotify.info('calling repr on instance of %s.%s' % (obj.__class__.__module__, obj.__class__.__name__))
  1293. sys.stdout.flush()
  1294. try:
  1295. return repr(obj)
  1296. except:
  1297. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1298. def safeReprTypeOnFail(obj):
  1299. global dtoolSuperBase
  1300. if dtoolSuperBase is None:
  1301. _getDtoolSuperBase()
  1302. global safeReprNotify
  1303. if safeReprNotify is None:
  1304. _getSafeReprNotify()
  1305. if isinstance(obj, dtoolSuperBase):
  1306. return type(obj)
  1307. try:
  1308. return repr(obj)
  1309. except:
  1310. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1311. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  1312. """ caps the length of iterable types, so very large objects will print faster.
  1313. also prevents infinite recursion """
  1314. try:
  1315. if _visitedIds is None:
  1316. _visitedIds = set()
  1317. if id(obj) in _visitedIds:
  1318. return '<ALREADY-VISITED %s>' % itype(obj)
  1319. if type(obj) in (tuple, list):
  1320. s = ''
  1321. s += {tuple: '(',
  1322. list: '[',}[type(obj)]
  1323. if maxLen is not None and len(obj) > maxLen:
  1324. o = obj[:maxLen]
  1325. ellips = '...'
  1326. else:
  1327. o = obj
  1328. ellips = ''
  1329. _visitedIds.add(id(obj))
  1330. for item in o:
  1331. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  1332. s += ', '
  1333. _visitedIds.remove(id(obj))
  1334. s += ellips
  1335. s += {tuple: ')',
  1336. list: ']',}[type(obj)]
  1337. return s
  1338. elif type(obj) is dict:
  1339. s = '{'
  1340. if maxLen is not None and len(obj) > maxLen:
  1341. o = list(obj.keys())[:maxLen]
  1342. ellips = '...'
  1343. else:
  1344. o = list(obj.keys())
  1345. ellips = ''
  1346. _visitedIds.add(id(obj))
  1347. for key in o:
  1348. value = obj[key]
  1349. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  1350. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  1351. _visitedIds.remove(id(obj))
  1352. s += ellips
  1353. s += '}'
  1354. return s
  1355. elif type(obj) is str:
  1356. if maxLen is not None:
  1357. maxLen *= strFactor
  1358. if maxLen is not None and len(obj) > maxLen:
  1359. return safeRepr(obj[:maxLen])
  1360. else:
  1361. return safeRepr(obj)
  1362. else:
  1363. r = safeRepr(obj)
  1364. maxLen *= strFactor
  1365. if len(r) > maxLen:
  1366. r = r[:maxLen]
  1367. return r
  1368. except:
  1369. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  1370. def convertTree(objTree, idList):
  1371. newTree = {}
  1372. for key in list(objTree.keys()):
  1373. obj = (idList[key],)
  1374. newTree[obj] = {}
  1375. r_convertTree(objTree[key], newTree[obj], idList)
  1376. return newTree
  1377. def r_convertTree(oldTree, newTree, idList):
  1378. for key in list(oldTree.keys()):
  1379. obj = idList.get(key)
  1380. if(not obj):
  1381. continue
  1382. obj = str(obj)[:100]
  1383. newTree[obj] = {}
  1384. r_convertTree(oldTree[key], newTree[obj], idList)
  1385. def pretty_print(tree):
  1386. for name in tree.keys():
  1387. print(name)
  1388. r_pretty_print(tree[name], 0)
  1389. def r_pretty_print(tree, num):
  1390. num+=1
  1391. for name in tree.keys():
  1392. print(" "*num,name)
  1393. r_pretty_print(tree[name],num)
  1394. def isDefaultValue(x):
  1395. return x == type(x)()
  1396. def appendStr(obj, st):
  1397. """adds a string onto the __str__ output of an instance"""
  1398. def appendedStr(oldStr, st, self):
  1399. return oldStr() + st
  1400. oldStr = getattr(obj, '__str__', None)
  1401. if oldStr is None:
  1402. def stringer(s):
  1403. return s
  1404. oldStr = Functor(stringer, str(obj))
  1405. stringer = None
  1406. obj.__str__ = types.MethodType(Functor(appendedStr, oldStr, st), obj, obj.__class__)
  1407. appendedStr = None
  1408. return obj
  1409. class ScratchPad:
  1410. """empty class to stick values onto"""
  1411. def __init__(self, **kArgs):
  1412. for key, value in kArgs.items():
  1413. setattr(self, key, value)
  1414. self._keys = set(kArgs.keys())
  1415. def add(self, **kArgs):
  1416. for key, value in kArgs.items():
  1417. setattr(self, key, value)
  1418. self._keys.update(list(kArgs.keys()))
  1419. def destroy(self):
  1420. for key in self._keys:
  1421. delattr(self, key)
  1422. # allow dict [] syntax
  1423. def __getitem__(self, itemName):
  1424. return getattr(self, itemName)
  1425. def get(self, itemName, default=None):
  1426. return getattr(self, itemName, default)
  1427. # allow 'in'
  1428. def __contains__(self, itemName):
  1429. return itemName in self._keys
  1430. class Sync:
  1431. _SeriesGen = SerialNumGen()
  1432. def __init__(self, name, other=None):
  1433. self._name = name
  1434. if other is None:
  1435. self._series = self._SeriesGen.next()
  1436. self._value = 0
  1437. else:
  1438. self._series = other._series
  1439. self._value = other._value
  1440. def invalidate(self):
  1441. self._value = None
  1442. def change(self):
  1443. self._value += 1
  1444. def sync(self, other):
  1445. if (self._series != other._series) or (self._value != other._value):
  1446. self._series = other._series
  1447. self._value = other._value
  1448. return True
  1449. else:
  1450. return False
  1451. def isSynced(self, other):
  1452. return ((self._series == other._series) and
  1453. (self._value == other._value))
  1454. def __repr__(self):
  1455. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  1456. self._name, self._series, self._value)
  1457. def itype(obj):
  1458. # version of type that gives more complete information about instance types
  1459. global dtoolSuperBase
  1460. t = type(obj)
  1461. if t is types.InstanceType:
  1462. return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
  1463. str(obj.__class__))
  1464. else:
  1465. # C++ object instances appear to be types via type()
  1466. # check if this is a C++ object
  1467. if dtoolSuperBase is None:
  1468. _getDtoolSuperBase()
  1469. if isinstance(obj, dtoolSuperBase):
  1470. return '%s of %s>' % (repr(types.InstanceType)[:-1],
  1471. str(obj.__class__))
  1472. return t
  1473. def deeptype(obj, maxLen=100, _visitedIds=None):
  1474. if _visitedIds is None:
  1475. _visitedIds = set()
  1476. if id(obj) in _visitedIds:
  1477. return '<ALREADY-VISITED %s>' % itype(obj)
  1478. t = type(obj)
  1479. if t in (tuple, list):
  1480. s = ''
  1481. s += {tuple: '(',
  1482. list: '[',}[type(obj)]
  1483. if maxLen is not None and len(obj) > maxLen:
  1484. o = obj[:maxLen]
  1485. ellips = '...'
  1486. else:
  1487. o = obj
  1488. ellips = ''
  1489. _visitedIds.add(id(obj))
  1490. for item in o:
  1491. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  1492. s += ', '
  1493. _visitedIds.remove(id(obj))
  1494. s += ellips
  1495. s += {tuple: ')',
  1496. list: ']',}[type(obj)]
  1497. return s
  1498. elif type(obj) is dict:
  1499. s = '{'
  1500. if maxLen is not None and len(obj) > maxLen:
  1501. o = list(obj.keys())[:maxLen]
  1502. ellips = '...'
  1503. else:
  1504. o = list(obj.keys())
  1505. ellips = ''
  1506. _visitedIds.add(id(obj))
  1507. for key in o:
  1508. value = obj[key]
  1509. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  1510. deeptype(value, maxLen, _visitedIds=_visitedIds))
  1511. _visitedIds.remove(id(obj))
  1512. s += ellips
  1513. s += '}'
  1514. return s
  1515. else:
  1516. return str(itype(obj))
  1517. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  1518. """get a string that has each item of the list on its own line,
  1519. and each item is numbered on the left from zero"""
  1520. digits = 0
  1521. n = len(items)
  1522. while n > 0:
  1523. digits += 1
  1524. n //= 10
  1525. digits = digits
  1526. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1527. first = True
  1528. s = ''
  1529. snip = '<SNIP>'
  1530. for i in xrange(len(items)):
  1531. if not first:
  1532. s += '\n'
  1533. first = False
  1534. objStr = fastRepr(items[i])
  1535. if len(objStr) > maxLen:
  1536. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1537. s += format % (i, itype(items[i]), objStr)
  1538. return s
  1539. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  1540. """get a string that has each item of the list on its own line,
  1541. the items are stringwise-sorted, and each item is numbered on
  1542. the left from zero"""
  1543. digits = 0
  1544. n = len(items)
  1545. while n > 0:
  1546. digits += 1
  1547. n //= 10
  1548. digits = digits
  1549. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1550. snip = '<SNIP>'
  1551. strs = []
  1552. for item in items:
  1553. objStr = fastRepr(item)
  1554. if len(objStr) > maxLen:
  1555. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1556. strs.append(objStr)
  1557. first = True
  1558. s = ''
  1559. strs.sort()
  1560. for i in xrange(len(strs)):
  1561. if not first:
  1562. s += '\n'
  1563. first = False
  1564. objStr = strs[i]
  1565. s += format % (i, itype(items[i]), strs[i])
  1566. return s
  1567. def printNumberedTyped(items, maxLen=5000):
  1568. """print out each item of the list on its own line,
  1569. with each item numbered on the left from zero"""
  1570. digits = 0
  1571. n = len(items)
  1572. while n > 0:
  1573. digits += 1
  1574. n //= 10
  1575. digits = digits
  1576. format = '%0' + '%s' % digits + 'i:%s \t%s'
  1577. for i in xrange(len(items)):
  1578. objStr = fastRepr(items[i])
  1579. if len(objStr) > maxLen:
  1580. snip = '<SNIP>'
  1581. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1582. print(format % (i, itype(items[i]), objStr))
  1583. def printNumberedTypesGen(items, maxLen=5000):
  1584. digits = 0
  1585. n = len(items)
  1586. while n > 0:
  1587. digits += 1
  1588. n //= 10
  1589. digits = digits
  1590. format = '%0' + '%s' % digits + 'i:%s'
  1591. for i in xrange(len(items)):
  1592. print(format % (i, itype(items[i])))
  1593. yield None
  1594. def printNumberedTypes(items, maxLen=5000):
  1595. """print out the type of each item of the list on its own line,
  1596. with each item numbered on the left from zero"""
  1597. for result in printNumberedTypesGen(items, maxLen):
  1598. yield result
  1599. class DelayedCall:
  1600. """ calls a func after a specified delay """
  1601. def __init__(self, func, name=None, delay=None):
  1602. if name is None:
  1603. name = 'anonymous'
  1604. if delay is None:
  1605. delay = .01
  1606. self._func = func
  1607. self._taskName = 'DelayedCallback-%s' % name
  1608. self._delay = delay
  1609. self._finished = False
  1610. self._addDoLater()
  1611. def destroy(self):
  1612. self._finished = True
  1613. self._removeDoLater()
  1614. def finish(self):
  1615. if not self._finished:
  1616. self._doCallback()
  1617. self.destroy()
  1618. def _addDoLater(self):
  1619. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  1620. def _removeDoLater(self):
  1621. taskMgr.remove(self._taskName)
  1622. def _doCallback(self, task):
  1623. self._finished = True
  1624. func = self._func
  1625. del self._func
  1626. func()
  1627. class FrameDelayedCall:
  1628. """ calls a func after N frames """
  1629. def __init__(self, name, callback, frames=None, cancelFunc=None):
  1630. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  1631. # and callback is not called
  1632. if frames is None:
  1633. frames = 1
  1634. self._name = name
  1635. self._frames = frames
  1636. self._callback = callback
  1637. self._cancelFunc = cancelFunc
  1638. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  1639. self._finished = False
  1640. self._startTask()
  1641. def destroy(self):
  1642. self._finished = True
  1643. self._stopTask()
  1644. def finish(self):
  1645. if not self._finished:
  1646. self._finished = True
  1647. self._callback()
  1648. self.destroy()
  1649. def _startTask(self):
  1650. taskMgr.add(self._frameTask, self._taskName)
  1651. self._counter = 0
  1652. def _stopTask(self):
  1653. taskMgr.remove(self._taskName)
  1654. def _frameTask(self, task):
  1655. if self._cancelFunc and self._cancelFunc():
  1656. self.destroy()
  1657. return task.done
  1658. self._counter += 1
  1659. if self._counter >= self._frames:
  1660. self.finish()
  1661. return task.done
  1662. return task.cont
  1663. class DelayedFunctor:
  1664. """ Waits for this object to be called, then calls supplied functor after a delay.
  1665. Effectively inserts a time delay between the caller and the functor. """
  1666. def __init__(self, functor, name=None, delay=None):
  1667. self._functor = functor
  1668. self._name = name
  1669. # FunctionInterval requires __name__
  1670. self.__name__ = self._name
  1671. self._delay = delay
  1672. def _callFunctor(self):
  1673. cb = Functor(self._functor, *self._args, **self._kwArgs)
  1674. del self._functor
  1675. del self._name
  1676. del self._delay
  1677. del self._args
  1678. del self._kwArgs
  1679. del self._delayedCall
  1680. del self.__name__
  1681. cb()
  1682. def __call__(self, *args, **kwArgs):
  1683. self._args = args
  1684. self._kwArgs = kwArgs
  1685. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  1686. class SubframeCall:
  1687. """Calls a callback at a specific time during the frame using the
  1688. task system"""
  1689. def __init__(self, functor, taskPriority, name=None):
  1690. self._functor = functor
  1691. self._name = name
  1692. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  1693. taskMgr.add(self._doCallback,
  1694. self._taskName,
  1695. priority=taskPriority)
  1696. def _doCallback(self, task):
  1697. functor = self._functor
  1698. del self._functor
  1699. functor()
  1700. del self._name
  1701. self._taskName = None
  1702. return task.done
  1703. def cleanup(self):
  1704. if (self._taskName):
  1705. taskMgr.remove(self._taskName)
  1706. self._taskName = None
  1707. class PStatScope:
  1708. collectors = {}
  1709. def __init__(self, level = None):
  1710. self.levels = []
  1711. if level:
  1712. self.levels.append(level)
  1713. def copy(self, push = None):
  1714. c = PStatScope()
  1715. c.levels = self.levels[:]
  1716. if push:
  1717. c.push(push)
  1718. return c
  1719. def __repr__(self):
  1720. return 'PStatScope - \'%s\'' % (self,)
  1721. def __str__(self):
  1722. return ':'.join(self.levels)
  1723. def push(self, level):
  1724. self.levels.append(level.replace('_',''))
  1725. def pop(self):
  1726. return self.levels.pop()
  1727. def start(self, push = None):
  1728. if push:
  1729. self.push(push)
  1730. pass
  1731. self.getCollector().start()
  1732. def stop(self, pop = False):
  1733. self.getCollector().stop()
  1734. if pop:
  1735. self.pop()
  1736. def getCollector(self):
  1737. label = str(self)
  1738. if label not in self.collectors:
  1739. from panda3d.core import PStatCollector
  1740. self.collectors[label] = PStatCollector(label)
  1741. pass
  1742. # print ' ',self.collectors[label]
  1743. return self.collectors[label]
  1744. def pstatcollect(scope, level = None):
  1745. def decorator(f):
  1746. return f
  1747. try:
  1748. if not (__dev__ or ConfigVariableBool('force-pstatcollect', False)) or \
  1749. not scope:
  1750. return decorator
  1751. def decorator(f):
  1752. def wrap(*args, **kw):
  1753. scope.start(push = (level or f.__name__))
  1754. val = f(*args, **kw)
  1755. scope.stop(pop = True)
  1756. return val
  1757. return wrap
  1758. pass
  1759. except:
  1760. pass
  1761. return decorator
  1762. __report_indent = 0
  1763. def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigParam = []):
  1764. """
  1765. This is a decorator generating function. Use is similar to
  1766. a @decorator, except you must be sure to call it as a function.
  1767. It actually returns the decorator which is then used to transform
  1768. your decorated function. Confusing at first, I know.
  1769. Decoration occurs at function definition time.
  1770. If __dev__ is not defined, or resolves to False, this function
  1771. has no effect and no wrapping/transform occurs. So in production,
  1772. it's as if the report has been asserted out.
  1773. Parameters::
  1774. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  1775. This allows you to specify certain useful bits of info.
  1776. module: Prints the module that this report statement
  1777. can be found in.
  1778. args: Prints the arguments as they were passed to
  1779. this function.
  1780. timeStamp: Adds the current frame time to the output.
  1781. deltaStamp: Adds the current AI synched frame time to
  1782. the output
  1783. frameCount: Adds the current frame count to the output.
  1784. Usually cleaner than the timeStamp output.
  1785. avLocation: Adds the localAvatar's network location
  1786. to the output. Useful for interest debugging.
  1787. interests: Prints the current interest state after the
  1788. report.
  1789. stackTrace: Prints a stack trace after the report.
  1790. prefix: Optional string to prepend to output, just before the function.
  1791. Allows for easy grepping and is useful when merging AI/Client
  1792. reports into a single file.
  1793. xform: Optional callback that accepts a single parameter: argument 0 to
  1794. the decorated function. (assumed to be 'self')
  1795. It should return a value to be inserted into the report output string.
  1796. notifyFunc: A notify function such as info, debug, warning, etc.
  1797. By default the report will be printed to stdout. This
  1798. will allow you send the report to a designated 'notify'
  1799. output.
  1800. dConfigParam: A list of Config.prc string variables.
  1801. By default the report will always print. If you
  1802. specify this param, it will only print if one of the
  1803. specified config strings resolve to True.
  1804. """
  1805. def indent(str):
  1806. global __report_indent
  1807. return ' '*__report_indent+str
  1808. def decorator(f):
  1809. return f
  1810. try:
  1811. if not (__dev__ or config.GetBool('force-reports', 0)):
  1812. return decorator
  1813. # determine whether we should use the decorator
  1814. # based on the value of dConfigParam.
  1815. dConfigParamList = []
  1816. doPrint = False
  1817. if not dConfigParam:
  1818. doPrint = True
  1819. else:
  1820. if not isinstance(dConfigParam, (list,tuple)):
  1821. dConfigParams = (dConfigParam,)
  1822. else:
  1823. dConfigParams = dConfigParam
  1824. dConfigParamList = [param for param in dConfigParams \
  1825. if config.GetBool('want-%s-report' % (param,), 0)]
  1826. doPrint = bool(dConfigParamList)
  1827. pass
  1828. if not doPrint:
  1829. return decorator
  1830. # Determine any prefixes defined in our Config.prc.
  1831. if prefix:
  1832. prefixes = set([prefix])
  1833. else:
  1834. prefixes = set()
  1835. pass
  1836. for param in dConfigParamList:
  1837. prefix = config.GetString('prefix-%s-report' % (param,), '')
  1838. if prefix:
  1839. prefixes.add(prefix)
  1840. pass
  1841. pass
  1842. except NameError as e:
  1843. return decorator
  1844. globalClockDelta = importlib.import_module("direct.distributed.ClockDelta").globalClockDelta
  1845. def decorator(f):
  1846. def wrap(*args,**kwargs):
  1847. if args:
  1848. rArgs = [args[0].__class__.__name__ + ', ']
  1849. else:
  1850. rArgs = []
  1851. if 'args' in types:
  1852. rArgs += [repr(x)+', ' for x in args[1:]] + \
  1853. [ x + ' = ' + '%s, ' % repr(y) for x,y in kwargs.items()]
  1854. if not rArgs:
  1855. rArgs = '()'
  1856. else:
  1857. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  1858. outStr = '%s%s' % (f.__name__, rArgs)
  1859. # Insert prefix place holder, if needed
  1860. if prefixes:
  1861. outStr = '%%s %s' % (outStr,)
  1862. if 'module' in types:
  1863. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  1864. if 'frameCount' in types:
  1865. outStr = '%-8d : %s' % (globalClock.getFrameCount(), outStr)
  1866. if 'timeStamp' in types:
  1867. outStr = '%-8.3f : %s' % (globalClock.getFrameTime(), outStr)
  1868. if 'deltaStamp' in types:
  1869. outStr = '%-8.2f : %s' % (globalClock.getRealTime() - \
  1870. globalClockDelta.delta, outStr)
  1871. if 'avLocation' in types:
  1872. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  1873. if xform:
  1874. outStr = '%s : %s' % (outStr, xform(args[0]))
  1875. if prefixes:
  1876. # This will print the same report once for each prefix
  1877. for prefix in prefixes:
  1878. if notifyFunc:
  1879. notifyFunc(outStr % (prefix,))
  1880. else:
  1881. print(indent(outStr % (prefix,)))
  1882. else:
  1883. if notifyFunc:
  1884. notifyFunc(outStr)
  1885. else:
  1886. print(indent(outStr))
  1887. if 'interests' in types:
  1888. base.cr.printInterestSets()
  1889. if 'stackTrace' in types:
  1890. print(StackTrace())
  1891. global __report_indent
  1892. rVal = None
  1893. try:
  1894. __report_indent += 1
  1895. rVal = f(*args,**kwargs)
  1896. finally:
  1897. __report_indent -= 1
  1898. if rVal is not None:
  1899. print(indent(' -> '+repr(rVal)))
  1900. pass
  1901. pass
  1902. return rVal
  1903. wrap.__name__ = f.__name__
  1904. wrap.__dict__ = f.__dict__
  1905. wrap.__doc__ = f.__doc__
  1906. wrap.__module__ = f.__module__
  1907. return wrap
  1908. return decorator
  1909. def getBase():
  1910. try:
  1911. return base
  1912. except:
  1913. return simbase
  1914. def getRepository():
  1915. try:
  1916. return base.cr
  1917. except:
  1918. return simbase.air
  1919. exceptionLoggedNotify = None
  1920. if __debug__:
  1921. def exceptionLogged(append=True):
  1922. """decorator that outputs the function name and all arguments
  1923. if an exception passes back through the stack frame
  1924. if append is true, string is appended to the __str__ output of
  1925. the exception. if append is false, string is printed to the log
  1926. directly. If the output will take up many lines, it's recommended
  1927. to set append to False so that the exception stack is not hidden
  1928. by the output of this decorator.
  1929. """
  1930. try:
  1931. null = not __dev__
  1932. except:
  1933. null = not __debug__
  1934. if null:
  1935. # if we're not in __dev__, just return the function itself. This
  1936. # results in zero runtime overhead, since decorators are evaluated
  1937. # at module-load.
  1938. def nullDecorator(f):
  1939. return f
  1940. return nullDecorator
  1941. def _decoratorFunc(f, append=append):
  1942. global exceptionLoggedNotify
  1943. if exceptionLoggedNotify is None:
  1944. from direct.directnotify.DirectNotifyGlobal import directNotify
  1945. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  1946. def _exceptionLogged(*args, **kArgs):
  1947. try:
  1948. return f(*args, **kArgs)
  1949. except Exception as e:
  1950. try:
  1951. s = '%s(' % f.__name__
  1952. for arg in args:
  1953. s += '%s, ' % arg
  1954. for key, value in list(kArgs.items()):
  1955. s += '%s=%s, ' % (key, value)
  1956. if len(args) or len(kArgs):
  1957. s = s[:-2]
  1958. s += ')'
  1959. if append:
  1960. appendStr(e, '\n%s' % s)
  1961. else:
  1962. exceptionLoggedNotify.info(s)
  1963. except:
  1964. exceptionLoggedNotify.info(
  1965. '%s: ERROR IN PRINTING' % f.__name__)
  1966. raise
  1967. _exceptionLogged.__doc__ = f.__doc__
  1968. return _exceptionLogged
  1969. return _decoratorFunc
  1970. # http://en.wikipedia.org/wiki/Golden_ratio
  1971. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  1972. class GoldenRectangle:
  1973. @staticmethod
  1974. def getLongerEdge(shorter):
  1975. return shorter * GoldenRatio
  1976. @staticmethod
  1977. def getShorterEdge(longer):
  1978. return longer / GoldenRatio
  1979. def nullGen():
  1980. # generator that ends immediately
  1981. if False:
  1982. # yield that never runs but still exists, making this func a generator
  1983. yield None
  1984. def loopGen(l):
  1985. # generator that yields the items of an iterable object forever
  1986. def _gen(l):
  1987. while True:
  1988. for item in l:
  1989. yield item
  1990. gen = _gen(l)
  1991. # don't leak
  1992. _gen = None
  1993. return gen
  1994. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  1995. # iterates and finally yields a flywheel generator object
  1996. # the number of appearances for each object is controlled by passing in
  1997. # a list of counts, or a functor that returns a count when called with
  1998. # an object from the 'objects' list.
  1999. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  2000. def flywheel(index2objectAndCount):
  2001. # generator to produce a sequence whose elements appear a specific number of times
  2002. while len(index2objectAndCount):
  2003. keyList = list(index2objectAndCount.keys())
  2004. for key in keyList:
  2005. if index2objectAndCount[key][1] > 0:
  2006. yield index2objectAndCount[key][0]
  2007. index2objectAndCount[key][1] -= 1
  2008. if index2objectAndCount[key][1] <= 0:
  2009. del index2objectAndCount[key]
  2010. # if we were not given a list of counts, create it by calling countFunc
  2011. if countList is None:
  2012. countList = []
  2013. for object in objects:
  2014. yield None
  2015. countList.append(countFunc(object))
  2016. if scale is not None:
  2017. # scale the counts if we've got a scale factor
  2018. for i in xrange(len(countList)):
  2019. yield None
  2020. if countList[i] > 0:
  2021. countList[i] = max(1, int(countList[i] * scale))
  2022. # create a dict for the flywheel to use during its iteration to efficiently select
  2023. # the objects for the sequence
  2024. index2objectAndCount = {}
  2025. for i in xrange(len(countList)):
  2026. yield None
  2027. index2objectAndCount[i] = [objects[i], countList[i]]
  2028. # create the flywheel generator
  2029. yield flywheel(index2objectAndCount)
  2030. def flywheel(*args, **kArgs):
  2031. # create a flywheel generator
  2032. # see arguments and comments in flywheelGen above
  2033. # example usage:
  2034. """
  2035. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  2036. ... print i,
  2037. ...
  2038. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  2039. """
  2040. for flywheel in makeFlywheelGen(*args, **kArgs):
  2041. pass
  2042. return flywheel
  2043. if __debug__ and __name__ == '__main__':
  2044. f = flywheel(['a','b','c','d'], countList=[11,20,3,4])
  2045. obj2count = {}
  2046. for obj in f:
  2047. obj2count.setdefault(obj, 0)
  2048. obj2count[obj] += 1
  2049. assert obj2count['a'] == 11
  2050. assert obj2count['b'] == 20
  2051. assert obj2count['c'] == 3
  2052. assert obj2count['d'] == 4
  2053. f = flywheel([1,2,3,4], countFunc=lambda x: x*2)
  2054. obj2count = {}
  2055. for obj in f:
  2056. obj2count.setdefault(obj, 0)
  2057. obj2count[obj] += 1
  2058. assert obj2count[1] == 2
  2059. assert obj2count[2] == 4
  2060. assert obj2count[3] == 6
  2061. assert obj2count[4] == 8
  2062. f = flywheel([1,2,3,4], countFunc=lambda x: x, scale = 3)
  2063. obj2count = {}
  2064. for obj in f:
  2065. obj2count.setdefault(obj, 0)
  2066. obj2count[obj] += 1
  2067. assert obj2count[1] == 1 * 3
  2068. assert obj2count[2] == 2 * 3
  2069. assert obj2count[3] == 3 * 3
  2070. assert obj2count[4] == 4 * 3
  2071. if __debug__:
  2072. def quickProfile(name="unnamed"):
  2073. import pstats
  2074. def profileDecorator(f):
  2075. if(not config.GetBool("use-profiler",0)):
  2076. return f
  2077. def _profiled(*args, **kArgs):
  2078. # must do this in here because we don't have base/simbase
  2079. # at the time that PythonUtil is loaded
  2080. if(not config.GetBool("profile-debug",0)):
  2081. #dumb timings
  2082. st=globalClock.getRealTime()
  2083. f(*args,**kArgs)
  2084. s=globalClock.getRealTime()-st
  2085. print("Function %s.%s took %s seconds"%(f.__module__, f.__name__,s))
  2086. else:
  2087. import profile as prof, pstats
  2088. #detailed profile, stored in base.stats under (
  2089. if(not hasattr(base,"stats")):
  2090. base.stats={}
  2091. if(not base.stats.get(name)):
  2092. base.stats[name]=[]
  2093. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  2094. s=pstats.Stats("t.prof")
  2095. #p=hotshot.Profile("t.prof")
  2096. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  2097. #s = hotshot.stats.load("t.prof")
  2098. s.strip_dirs()
  2099. s.sort_stats("cumulative")
  2100. base.stats[name].append(s)
  2101. _profiled.__doc__ = f.__doc__
  2102. return _profiled
  2103. return profileDecorator
  2104. def getTotalAnnounceTime():
  2105. td=0
  2106. for objs in base.stats.values():
  2107. for stat in objs:
  2108. td+=getAnnounceGenerateTime(stat)
  2109. return td
  2110. def getAnnounceGenerateTime(stat):
  2111. val=0
  2112. stats=stat.stats
  2113. for i in list(stats.keys()):
  2114. if(i[2]=="announceGenerate"):
  2115. newVal=stats[i][3]
  2116. if(newVal>val):
  2117. val=newVal
  2118. return val
  2119. class MiniLog:
  2120. def __init__(self, name):
  2121. self.indent = 1
  2122. self.name = name
  2123. self.lines = []
  2124. def __str__(self):
  2125. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  2126. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  2127. def enterFunction(self, funcName, *args, **kw):
  2128. rArgs = [repr(x)+', ' for x in args] + \
  2129. [ x + ' = ' + '%s, ' % repr(y) for x,y in kw.items()]
  2130. if not rArgs:
  2131. rArgs = '()'
  2132. else:
  2133. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2134. line = '%s%s' % (funcName, rArgs)
  2135. self.appendFunctionCall(line)
  2136. self.indent += 1
  2137. return line
  2138. def exitFunction(self):
  2139. self.indent -= 1
  2140. return self.indent
  2141. def appendFunctionCall(self, line):
  2142. self.lines.append(' '*(self.indent*2) + line)
  2143. return line
  2144. def appendLine(self, line):
  2145. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  2146. return line
  2147. def flush(self):
  2148. outStr = str(self)
  2149. self.indent = 0
  2150. self.lines = []
  2151. return outStr
  2152. class MiniLogSentry:
  2153. def __init__(self, log, funcName, *args, **kw):
  2154. self.log = log
  2155. if self.log:
  2156. self.log.enterFunction(funcName, *args, **kw)
  2157. def __del__(self):
  2158. if self.log:
  2159. self.log.exitFunction()
  2160. del self.log
  2161. def logBlock(id, msg):
  2162. print('<< LOGBLOCK(%03d)' % id)
  2163. print(str(msg))
  2164. print('/LOGBLOCK(%03d) >>' % id)
  2165. class HierarchyException(Exception):
  2166. JOSWILSO = 0
  2167. def __init__(self, owner, description):
  2168. self.owner = owner
  2169. self.desc = description
  2170. def __str__(self):
  2171. return '(%s): %s' % (self.owner, self.desc)
  2172. def __repr__(self):
  2173. return 'HierarchyException(%s)' % (self.owner, )
  2174. def formatTimeCompact(seconds):
  2175. # returns string in format '1d3h22m43s'
  2176. result = ''
  2177. a = int(seconds)
  2178. seconds = a % 60
  2179. a //= 60
  2180. if a > 0:
  2181. minutes = a % 60
  2182. a //= 60
  2183. if a > 0:
  2184. hours = a % 24
  2185. a //= 24
  2186. if a > 0:
  2187. days = a
  2188. result += '%sd' % days
  2189. result += '%sh' % hours
  2190. result += '%sm' % minutes
  2191. result += '%ss' % seconds
  2192. return result
  2193. if __debug__ and __name__ == '__main__':
  2194. ftc = formatTimeCompact
  2195. assert ftc(0) == '0s'
  2196. assert ftc(1) == '1s'
  2197. assert ftc(60) == '1m0s'
  2198. assert ftc(64) == '1m4s'
  2199. assert ftc(60*60) == '1h0m0s'
  2200. assert ftc(24*60*60) == '1d0h0m0s'
  2201. assert ftc(24*60*60 + 2*60*60 + 34*60 + 12) == '1d2h34m12s'
  2202. del ftc
  2203. def formatTimeExact(seconds):
  2204. # like formatTimeCompact but leaves off '0 seconds', '0 minutes' etc. for
  2205. # times that are e.g. 1 hour, 3 days etc.
  2206. # returns string in format '1d3h22m43s'
  2207. result = ''
  2208. a = int(seconds)
  2209. seconds = a % 60
  2210. a //= 60
  2211. if a > 0:
  2212. minutes = a % 60
  2213. a //= 60
  2214. if a > 0:
  2215. hours = a % 24
  2216. a //= 24
  2217. if a > 0:
  2218. days = a
  2219. result += '%sd' % days
  2220. if hours or minutes or seconds:
  2221. result += '%sh' % hours
  2222. if minutes or seconds:
  2223. result += '%sm' % minutes
  2224. if seconds or result == '':
  2225. result += '%ss' % seconds
  2226. return result
  2227. if __debug__ and __name__ == '__main__':
  2228. fte = formatTimeExact
  2229. assert fte(0) == '0s'
  2230. assert fte(1) == '1s'
  2231. assert fte(2) == '2s'
  2232. assert fte(61) == '1m1s'
  2233. assert fte(60) == '1m'
  2234. assert fte(60*60) == '1h'
  2235. assert fte(24*60*60) == '1d'
  2236. assert fte((24*60*60) + (2 * 60)) == '1d0h2m'
  2237. del fte
  2238. class AlphabetCounter:
  2239. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  2240. def __init__(self):
  2241. self._curCounter = ['A']
  2242. def next(self):
  2243. result = ''.join([c for c in self._curCounter])
  2244. index = -1
  2245. while True:
  2246. curChar = self._curCounter[index]
  2247. if curChar is 'Z':
  2248. nextChar = 'A'
  2249. carry = True
  2250. else:
  2251. nextChar = chr(ord(self._curCounter[index])+1)
  2252. carry = False
  2253. self._curCounter[index] = nextChar
  2254. if carry:
  2255. if (-index) == len(self._curCounter):
  2256. self._curCounter = ['A',] + self._curCounter
  2257. break
  2258. else:
  2259. index -= 1
  2260. carry = False
  2261. else:
  2262. break
  2263. return result
  2264. if __debug__ and __name__ == '__main__':
  2265. def testAlphabetCounter():
  2266. tempList = []
  2267. ac = AlphabetCounter()
  2268. for i in xrange(26*3):
  2269. tempList.append(ac.next())
  2270. assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  2271. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
  2272. 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',]
  2273. ac = AlphabetCounter()
  2274. num = 26 # A-Z
  2275. num += (26*26) # AA-ZZ
  2276. num += 26 # AAZ
  2277. num += 1 # ABA
  2278. num += 2 # ABC
  2279. for i in xrange(num):
  2280. x = ac.next()
  2281. assert x == 'ABC'
  2282. testAlphabetCounter()
  2283. del testAlphabetCounter
  2284. class Default:
  2285. # represents 'use the default value'
  2286. # useful for keyword arguments to virtual methods
  2287. pass
  2288. superLogFile = None
  2289. def startSuperLog(customFunction = None):
  2290. global superLogFile
  2291. if(not superLogFile):
  2292. superLogFile = open("c:\\temp\\superLog.txt", "w")
  2293. def trace_dispatch(a,b,c):
  2294. if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0):
  2295. vars = dict(a.f_locals)
  2296. if 'self' in vars:
  2297. del vars['self']
  2298. if '__builtins__' in vars:
  2299. del vars['__builtins__']
  2300. for i in vars:
  2301. vars[i] = safeReprTypeOnFail(vars[i])
  2302. if customFunction:
  2303. superLogFile.write( "before = %s\n"%customFunction())
  2304. superLogFile.write( "%s(%s):%s:%s\n"%(a.f_code.co_filename.split("\\")[-1],a.f_code.co_firstlineno, a.f_code.co_name, vars))
  2305. if customFunction:
  2306. superLogFile.write( "after = %s\n"%customFunction())
  2307. return trace_dispatch
  2308. sys.settrace(trace_dispatch)
  2309. def endSuperLog():
  2310. global superLogFile
  2311. if(superLogFile):
  2312. sys.settrace(None)
  2313. superLogFile.close()
  2314. superLogFile = None
  2315. def configIsToday(configName):
  2316. # TODO: replace usage of strptime with something else
  2317. # returns true if config string is a valid representation of today's date
  2318. today = time.localtime()
  2319. confStr = config.GetString(configName, '')
  2320. for format in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
  2321. try:
  2322. confDate = time.strptime(confStr, format)
  2323. except ValueError:
  2324. pass
  2325. else:
  2326. if (confDate.tm_year == today.tm_year and
  2327. confDate.tm_mon == today.tm_mon and
  2328. confDate.tm_mday == today.tm_mday):
  2329. return True
  2330. return False
  2331. def typeName(o):
  2332. if hasattr(o, '__class__'):
  2333. return o.__class__.__name__
  2334. else:
  2335. return o.__name__
  2336. def safeTypeName(o):
  2337. try:
  2338. return typeName(o)
  2339. except:
  2340. pass
  2341. try:
  2342. return type(o)
  2343. except:
  2344. pass
  2345. return '<failed safeTypeName()>'
  2346. def histogramDict(l):
  2347. d = {}
  2348. for e in l:
  2349. d.setdefault(e, 0)
  2350. d[e] += 1
  2351. return d
  2352. def unescapeHtmlString(s):
  2353. # converts %## to corresponding character
  2354. # replaces '+' with ' '
  2355. result = ''
  2356. i = 0
  2357. while i < len(s):
  2358. char = s[i]
  2359. if char == '+':
  2360. char = ' '
  2361. elif char == '%':
  2362. if i < (len(s)-2):
  2363. num = int(s[i+1:i+3], 16)
  2364. char = chr(num)
  2365. i += 2
  2366. i += 1
  2367. result += char
  2368. return result
  2369. if __debug__ and __name__ == '__main__':
  2370. assert unescapeHtmlString('asdf') == 'asdf'
  2371. assert unescapeHtmlString('as+df') == 'as df'
  2372. assert unescapeHtmlString('as%32df') == 'as2df'
  2373. assert unescapeHtmlString('asdf%32') == 'asdf2'
  2374. builtins.Functor = Functor
  2375. builtins.Stack = Stack
  2376. builtins.Queue = Queue
  2377. builtins.Enum = Enum
  2378. builtins.SerialNumGen = SerialNumGen
  2379. builtins.SerialMaskedGen = SerialMaskedGen
  2380. builtins.ScratchPad = ScratchPad
  2381. builtins.uniqueName = uniqueName
  2382. builtins.serialNum = serialNum
  2383. if __debug__:
  2384. builtins.profiled = profiled
  2385. builtins.exceptionLogged = exceptionLogged
  2386. builtins.itype = itype
  2387. builtins.appendStr = appendStr
  2388. builtins.bound = bound
  2389. builtins.clamp = clamp
  2390. builtins.lerp = lerp
  2391. builtins.makeList = makeList
  2392. builtins.makeTuple = makeTuple
  2393. if __debug__:
  2394. builtins.printStack = printStack
  2395. builtins.printReverseStack = printReverseStack
  2396. builtins.printVerboseStack = printVerboseStack
  2397. builtins.DelayedCall = DelayedCall
  2398. builtins.DelayedFunctor = DelayedFunctor
  2399. builtins.FrameDelayedCall = FrameDelayedCall
  2400. builtins.SubframeCall = SubframeCall
  2401. builtins.invertDict = invertDict
  2402. builtins.invertDictLossless = invertDictLossless
  2403. builtins.getBase = getBase
  2404. builtins.getRepository = getRepository
  2405. builtins.safeRepr = safeRepr
  2406. builtins.fastRepr = fastRepr
  2407. builtins.nullGen = nullGen
  2408. builtins.flywheel = flywheel
  2409. builtins.loopGen = loopGen
  2410. if __debug__:
  2411. builtins.StackTrace = StackTrace
  2412. builtins.report = report
  2413. builtins.pstatcollect = pstatcollect
  2414. builtins.MiniLog = MiniLog
  2415. builtins.MiniLogSentry = MiniLogSentry
  2416. builtins.logBlock = logBlock
  2417. builtins.HierarchyException = HierarchyException
  2418. builtins.deeptype = deeptype
  2419. builtins.Default = Default
  2420. builtins.configIsToday = configIsToday
  2421. builtins.typeName = typeName
  2422. builtins.safeTypeName = safeTypeName
  2423. builtins.histogramDict = histogramDict