ZTWHHH commited on
Commit
3b666bc
·
verified ·
1 Parent(s): f541f47

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_cambrian/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_spec.cpython-310.pyc +0 -0
  2. evalkit_cambrian/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  3. infer_4_47_1/lib/python3.10/importlib/__init__.py +176 -0
  4. infer_4_47_1/lib/python3.10/logging/handlers.py +1587 -0
  5. infer_4_47_1/lib/python3.10/turtledemo/__init__.py +14 -0
  6. infer_4_47_1/lib/python3.10/turtledemo/__main__.py +398 -0
  7. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/__init__.cpython-310.pyc +0 -0
  8. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc +0 -0
  9. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc +0 -0
  10. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc +0 -0
  11. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc +0 -0
  12. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc +0 -0
  13. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc +0 -0
  14. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc +0 -0
  15. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc +0 -0
  16. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc +0 -0
  17. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc +0 -0
  18. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc +0 -0
  19. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc +0 -0
  20. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc +0 -0
  21. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc +0 -0
  22. infer_4_47_1/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc +0 -0
  23. infer_4_47_1/lib/python3.10/turtledemo/bytedesign.py +161 -0
  24. infer_4_47_1/lib/python3.10/turtledemo/chaos.py +59 -0
  25. infer_4_47_1/lib/python3.10/turtledemo/clock.py +131 -0
  26. infer_4_47_1/lib/python3.10/turtledemo/colormixer.py +58 -0
  27. infer_4_47_1/lib/python3.10/turtledemo/forest.py +108 -0
  28. infer_4_47_1/lib/python3.10/turtledemo/fractalcurves.py +138 -0
  29. infer_4_47_1/lib/python3.10/turtledemo/minimal_hanoi.py +79 -0
  30. infer_4_47_1/lib/python3.10/turtledemo/nim.py +226 -0
  31. infer_4_47_1/lib/python3.10/turtledemo/paint.py +54 -0
  32. infer_4_47_1/lib/python3.10/turtledemo/peace.py +61 -0
  33. infer_4_47_1/lib/python3.10/turtledemo/planet_and_moon.py +111 -0
  34. infer_4_47_1/lib/python3.10/turtledemo/rosette.py +65 -0
  35. infer_4_47_1/lib/python3.10/turtledemo/round_dance.py +86 -0
  36. infer_4_47_1/lib/python3.10/turtledemo/sorting_animate.py +204 -0
  37. infer_4_47_1/lib/python3.10/turtledemo/yinyang.py +49 -0
  38. infer_4_47_1/lib/python3.10/xml/__init__.py +20 -0
  39. infer_4_47_1/lib/python3.10/xml/dom/NodeFilter.py +27 -0
  40. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/NodeFilter.cpython-310.pyc +0 -0
  41. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/__init__.cpython-310.pyc +0 -0
  42. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/domreg.cpython-310.pyc +0 -0
  43. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/expatbuilder.cpython-310.pyc +0 -0
  44. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/minicompat.cpython-310.pyc +0 -0
  45. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/minidom.cpython-310.pyc +0 -0
  46. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/pulldom.cpython-310.pyc +0 -0
  47. infer_4_47_1/lib/python3.10/xml/dom/__pycache__/xmlbuilder.cpython-310.pyc +0 -0
  48. infer_4_47_1/lib/python3.10/xml/dom/domreg.py +99 -0
  49. infer_4_47_1/lib/python3.10/xml/dom/expatbuilder.py +965 -0
  50. infer_4_47_1/lib/python3.10/xml/dom/minidom.py +2013 -0
evalkit_cambrian/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_spec.cpython-310.pyc ADDED
Binary file (16.4 kB). View file
 
evalkit_cambrian/lib/python3.10/site-packages/wandb/vendor/promise-2.3.0/tests/test_extra.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This exercises some capabilities above and beyond
2
+ # the Promises/A+ test suite
3
+ from time import sleep
4
+ from pytest import raises, fixture
5
+
6
+ from threading import Event
7
+ from promise import (
8
+ Promise,
9
+ is_thenable,
10
+ promisify,
11
+ promise_for_dict as free_promise_for_dict,
12
+ )
13
+ from concurrent.futures import Future
14
+ from threading import Thread
15
+
16
+ from .utils import assert_exception
17
+
18
+
19
+ class DelayedFulfill(Thread):
20
+ def __init__(self, d, p, v):
21
+ self.delay = d
22
+ self.promise = p
23
+ self.value = v
24
+ Thread.__init__(self)
25
+
26
+ def run(self):
27
+ sleep(self.delay)
28
+ self.promise.do_resolve(self.value)
29
+
30
+
31
+ class DelayedRejection(Thread):
32
+ def __init__(self, d, p, r):
33
+ self.delay = d
34
+ self.promise = p
35
+ self.reason = r
36
+ Thread.__init__(self)
37
+
38
+ def run(self):
39
+ sleep(self.delay)
40
+ self.promise.do_reject(self.reason)
41
+
42
+
43
+ class FakeThenPromise:
44
+ def __init__(self, raises=True):
45
+ self.raises = raises
46
+
47
+ def then(self, s=None, f=None):
48
+ if self.raises:
49
+ raise Exception("FakeThenPromise raises in 'then'")
50
+
51
+
52
+ def df(value, dtime):
53
+ p = Promise()
54
+ t = DelayedFulfill(dtime, p, value)
55
+ t.start()
56
+
57
+ return p
58
+
59
+
60
+ def dr(reason, dtime):
61
+ p = Promise()
62
+ t = DelayedRejection(dtime, p, reason)
63
+ t.start()
64
+
65
+ return p
66
+
67
+
68
+ # Static methods
69
+ def test_fulfilled():
70
+ p = Promise.fulfilled(4)
71
+ assert p.is_fulfilled
72
+ assert p.get() == 4
73
+
74
+
75
+ def test_rejected():
76
+ p = Promise.rejected(Exception("Static rejected"))
77
+ assert p.is_rejected
78
+ with raises(Exception) as exc_info:
79
+ p.get()
80
+ assert str(exc_info.value) == "Static rejected"
81
+
82
+
83
+ # Fulfill
84
+ def test_fulfill_self():
85
+ p = Promise()
86
+ with raises(TypeError) as excinfo:
87
+ p.do_resolve(p)
88
+ p.get()
89
+
90
+
91
+ # Exceptions
92
+ def test_exceptions():
93
+ def throws(v):
94
+ assert False
95
+
96
+ p1 = Promise()
97
+ p1.then(throws)
98
+ p1.do_resolve(5)
99
+
100
+ p2 = Promise()
101
+ p2.catch(throws)
102
+ p2.do_reject(Exception())
103
+
104
+ with raises(Exception) as excinfo:
105
+ p2.get()
106
+
107
+
108
+ def test_thrown_exceptions_have_stacktrace():
109
+ def throws(v):
110
+ assert False
111
+
112
+ p3 = Promise.resolve("a").then(throws)
113
+ with raises(AssertionError) as assert_exc:
114
+ p3.get()
115
+
116
+ assert assert_exc.traceback[-1].path.strpath == __file__
117
+
118
+
119
+ def test_thrown_exceptions_preserve_stacktrace():
120
+ def throws(v):
121
+ assert False
122
+
123
+ def after_throws(v):
124
+ pass
125
+
126
+ p3 = Promise.resolve("a").then(throws).then(after_throws)
127
+ with raises(AssertionError) as assert_exc:
128
+ p3.get()
129
+
130
+ assert assert_exc.traceback[-1].path.strpath == __file__
131
+
132
+
133
+ # WAIT
134
+ # def test_wait_when():
135
+ # p1 = df(5, 0.01)
136
+ # assert p1.is_pending
137
+ # p1._wait()
138
+ # assert p1.is_fulfilled
139
+
140
+
141
+ def test_wait_if():
142
+ p1 = Promise()
143
+ p1.do_resolve(5)
144
+ p1._wait()
145
+ assert p1.is_fulfilled
146
+
147
+
148
+ # def test_wait_timeout():
149
+ # p1 = df(5, 0.1)
150
+ # assert p1.is_pending
151
+ # with raises(Exception) as exc_info:
152
+ # p1._wait(timeout=0.05)
153
+ # assert str(exc_info.value) == "Timeout"
154
+ # assert p1.is_pending
155
+ # p1._wait()
156
+ # assert p1.is_fulfilled
157
+
158
+
159
+ # # GET
160
+ # def test_get_when():
161
+ # p1 = df(5, 0.01)
162
+ # assert p1.is_pending
163
+ # v = p1.get()
164
+ # assert p1.is_fulfilled
165
+ # assert 5 == v
166
+
167
+
168
+ def test_get_if():
169
+ p1 = Promise()
170
+ p1.do_resolve(5)
171
+ v = p1.get()
172
+ assert p1.is_fulfilled
173
+ assert 5 == v
174
+
175
+
176
+ # def test_get_timeout():
177
+ # p1 = df(5, 0.1)
178
+ # assert p1.is_pending
179
+ # with raises(Exception) as exc_info:
180
+ # p1._wait(timeout=0.05)
181
+ # assert str(exc_info.value) == "Timeout"
182
+ # assert p1.is_pending
183
+ # v = p1.get()
184
+ # assert p1.is_fulfilled
185
+ # assert 5 == v
186
+
187
+
188
+ # Promise.all
189
+ def test_promise_all_when():
190
+ p1 = Promise()
191
+ p2 = Promise()
192
+ pl = Promise.all([p1, p2])
193
+ assert p1.is_pending
194
+ assert p2.is_pending
195
+ assert pl.is_pending
196
+ p1.do_resolve(5)
197
+ p1._wait()
198
+ assert p1.is_fulfilled
199
+ assert p2.is_pending
200
+ assert pl.is_pending
201
+ p2.do_resolve(10)
202
+ p2._wait()
203
+ pl._wait()
204
+ assert p1.is_fulfilled
205
+ assert p2.is_fulfilled
206
+ assert pl.is_fulfilled
207
+ assert 5 == p1.get()
208
+ assert 10 == p2.get()
209
+ assert 5 == pl.get()[0]
210
+ assert 10 == pl.get()[1]
211
+
212
+
213
+ def test_promise_all_when_mixed_promises():
214
+ p1 = Promise()
215
+ p2 = Promise()
216
+ pl = Promise.all([p1, 32, p2, False, True])
217
+ assert p1.is_pending
218
+ assert p2.is_pending
219
+ assert pl.is_pending
220
+ p1.do_resolve(5)
221
+ p1._wait()
222
+ assert p1.is_fulfilled
223
+ assert p2.is_pending
224
+ assert pl.is_pending
225
+ p2.do_resolve(10)
226
+ p2._wait()
227
+ pl._wait()
228
+ assert p1.is_fulfilled
229
+ assert p2.is_fulfilled
230
+ assert pl.is_fulfilled
231
+ assert 5 == p1.get()
232
+ assert 10 == p2.get()
233
+ assert pl.get() == [5, 32, 10, False, True]
234
+
235
+
236
+ def test_promise_all_when_if_no_promises():
237
+ pl = Promise.all([10, 32, False, True])
238
+ assert pl.get() == [10, 32, False, True]
239
+
240
+
241
+ def test_promise_all_if():
242
+ p1 = Promise()
243
+ p2 = Promise()
244
+ pd1 = Promise.all([p1, p2])
245
+ pd2 = Promise.all([p1])
246
+ pd3 = Promise.all([])
247
+ pd3._wait()
248
+ assert p1.is_pending
249
+ assert p2.is_pending
250
+ assert pd1.is_pending
251
+ assert pd2.is_pending
252
+ assert pd3.is_fulfilled
253
+ p1.do_resolve(5)
254
+ p1._wait()
255
+ pd2._wait()
256
+ assert p1.is_fulfilled
257
+ assert p2.is_pending
258
+ assert pd1.is_pending
259
+ assert pd2.is_fulfilled
260
+ p2.do_resolve(10)
261
+ p2._wait()
262
+ pd1._wait()
263
+ pd2._wait()
264
+ assert p1.is_fulfilled
265
+ assert p2.is_fulfilled
266
+ assert pd1.is_fulfilled
267
+ assert pd2.is_fulfilled
268
+ assert 5 == p1.get()
269
+ assert 10 == p2.get()
270
+ assert 5 == pd1.get()[0]
271
+ assert 5 == pd2.get()[0]
272
+ assert 10 == pd1.get()[1]
273
+ assert [] == pd3.get()
274
+
275
+
276
+ # promise_for_dict
277
+ @fixture(params=[Promise.for_dict, free_promise_for_dict])
278
+ def promise_for_dict(request):
279
+ return request.param
280
+
281
+
282
+ def test_dict_promise_when(promise_for_dict):
283
+ p1 = Promise()
284
+ p2 = Promise()
285
+ d = {"a": p1, "b": p2}
286
+ pd1 = promise_for_dict(d)
287
+ pd2 = promise_for_dict({"a": p1})
288
+ pd3 = promise_for_dict({})
289
+ assert p1.is_pending
290
+ assert p2.is_pending
291
+ assert pd1.is_pending
292
+ assert pd2.is_pending
293
+ pd3._wait()
294
+ assert pd3.is_fulfilled
295
+ p1.do_resolve(5)
296
+ p1._wait()
297
+ pd2._wait()
298
+ assert p1.is_fulfilled
299
+ assert p2.is_pending
300
+ assert pd1.is_pending
301
+ assert pd2.is_fulfilled
302
+ p2.do_resolve(10)
303
+ p2._wait()
304
+ pd1._wait()
305
+ assert p1.is_fulfilled
306
+ assert p2.is_fulfilled
307
+ assert pd1.is_fulfilled
308
+ assert pd2.is_fulfilled
309
+ assert 5 == p1.get()
310
+ assert 10 == p2.get()
311
+ assert 5 == pd1.get()["a"]
312
+ assert 5 == pd2.get()["a"]
313
+ assert 10 == pd1.get()["b"]
314
+ assert {} == pd3.get()
315
+
316
+
317
+ def test_dict_promise_if(promise_for_dict):
318
+ p1 = Promise()
319
+ p2 = Promise()
320
+ d = {"a": p1, "b": p2}
321
+ pd = promise_for_dict(d)
322
+ assert p1.is_pending
323
+ assert p2.is_pending
324
+ assert pd.is_pending
325
+ p1.do_resolve(5)
326
+ p1._wait()
327
+ assert p1.is_fulfilled
328
+ assert p2.is_pending
329
+ assert pd.is_pending
330
+ p2.do_resolve(10)
331
+ p2._wait()
332
+ assert p1.is_fulfilled
333
+ assert p2.is_fulfilled
334
+ # pd._wait()
335
+ # assert pd.is_fulfilled
336
+ # assert 5 == p1.get()
337
+ # assert 10 == p2.get()
338
+ # assert 5 == pd.get()["a"]
339
+ # assert 10 == pd.get()["b"]
340
+
341
+
342
+ def test_done():
343
+ counter = [0]
344
+ r = Promise()
345
+
346
+ def inc(_):
347
+ counter[0] += 1
348
+
349
+ def dec(_):
350
+ counter[0] -= 1
351
+
352
+ def end(_):
353
+ r.do_resolve(None)
354
+
355
+ p = Promise()
356
+ p.done(inc, dec)
357
+ p.done(inc, dec)
358
+ p.done(end)
359
+ p.do_resolve(4)
360
+
361
+ Promise.wait(r)
362
+ assert counter[0] == 2
363
+
364
+ r = Promise()
365
+
366
+ counter = [0]
367
+ p = Promise()
368
+ p.done(inc, dec)
369
+ p.done(inc, dec)
370
+ p.done(None, end)
371
+ p.do_reject(Exception())
372
+
373
+ Promise.wait(r)
374
+ assert counter[0] == -2
375
+
376
+
377
+ def test_done_all():
378
+ counter = [0]
379
+
380
+ def inc(_):
381
+ counter[0] += 1
382
+
383
+ def dec(_):
384
+ counter[0] -= 1
385
+
386
+ p = Promise()
387
+ r = Promise()
388
+ p.done_all()
389
+ p.done_all([(inc, dec)])
390
+ p.done_all(
391
+ [
392
+ (inc, dec),
393
+ (inc, dec),
394
+ {"success": inc, "failure": dec},
395
+ lambda _: r.do_resolve(None),
396
+ ]
397
+ )
398
+ p.do_resolve(4)
399
+ Promise.wait(r)
400
+ assert counter[0] == 4
401
+
402
+ p = Promise()
403
+ r = Promise()
404
+ p.done_all()
405
+ p.done_all([inc])
406
+ p.done_all([(inc, dec)])
407
+ p.done_all(
408
+ [
409
+ (inc, dec),
410
+ {"success": inc, "failure": dec},
411
+ (None, lambda _: r.do_resolve(None)),
412
+ ]
413
+ )
414
+ p.do_reject(Exception("Uh oh!"))
415
+ Promise.wait(r)
416
+ assert counter[0] == 1
417
+
418
+
419
+ def test_then_all():
420
+ p = Promise()
421
+
422
+ handlers = [
423
+ ((lambda x: x * x), (lambda r: 1)),
424
+ {"success": (lambda x: x + x), "failure": (lambda r: 2)},
425
+ ]
426
+
427
+ results = (
428
+ p.then_all()
429
+ + p.then_all([lambda x: x])
430
+ + p.then_all([(lambda x: x * x, lambda r: 1)])
431
+ + p.then_all(handlers)
432
+ )
433
+
434
+ p.do_resolve(4)
435
+
436
+ assert [r.get() for r in results] == [4, 16, 16, 8]
437
+
438
+ p = Promise()
439
+
440
+ handlers = [
441
+ ((lambda x: x * x), (lambda r: 1)),
442
+ {"success": (lambda x: x + x), "failure": (lambda r: 2)},
443
+ ]
444
+
445
+ results = (
446
+ p.then_all()
447
+ + p.then_all([(lambda x: x * x, lambda r: 1)])
448
+ + p.then_all(handlers)
449
+ )
450
+
451
+ p.do_reject(Exception())
452
+
453
+ assert [r.get() for r in results] == [1, 1, 2]
454
+
455
+
456
+ def test_do_resolve():
457
+ p1 = Promise(lambda resolve, reject: resolve(0))
458
+ assert p1.get() == 0
459
+ assert p1.is_fulfilled
460
+
461
+
462
+ def test_do_resolve_fail_on_call():
463
+ def raises(resolve, reject):
464
+ raise Exception("Fails")
465
+
466
+ p1 = Promise(raises)
467
+ assert not p1.is_fulfilled
468
+ assert str(p1.reason) == "Fails"
469
+
470
+
471
+ def test_catch():
472
+ p1 = Promise(lambda resolve, reject: resolve(0))
473
+ p2 = p1.then(lambda value: 1 / value).catch(lambda e: e).then(lambda e: type(e))
474
+ assert p2.get() == ZeroDivisionError
475
+ assert p2.is_fulfilled
476
+
477
+
478
+ def test_is_thenable_promise():
479
+ promise = Promise()
480
+ assert is_thenable(promise)
481
+
482
+
483
+ def test_is_thenable_then_object():
484
+ promise = FakeThenPromise()
485
+ assert not is_thenable(promise)
486
+
487
+
488
+ def test_is_thenable_future():
489
+ promise = Future()
490
+ assert is_thenable(promise)
491
+
492
+
493
+ def test_is_thenable_simple_object():
494
+ assert not is_thenable(object())
495
+
496
+
497
+ @fixture(params=[Promise.resolve])
498
+ def resolve(request):
499
+ return request.param
500
+
501
+
502
+ def test_resolve_promise(resolve):
503
+ promise = Promise()
504
+ assert resolve(promise) == promise
505
+
506
+
507
+ def test_resolve_then_object(resolve):
508
+ promise = FakeThenPromise(raises=False)
509
+ p = resolve(promise)
510
+ assert isinstance(p, Promise)
511
+
512
+
513
+ def test_resolve_future(resolve):
514
+ future = Future()
515
+ promise = resolve(future)
516
+ assert promise.is_pending
517
+ future.set_result(1)
518
+ assert promise.get() == 1
519
+ assert promise.is_fulfilled
520
+
521
+
522
+ def test_resolve_future_rejected(resolve):
523
+ future = Future()
524
+ promise = resolve(future)
525
+ assert promise.is_pending
526
+ future.set_exception(Exception("Future rejected"))
527
+ assert promise.is_rejected
528
+ assert_exception(promise.reason, Exception, "Future rejected")
529
+
530
+
531
+ def test_resolve_object(resolve):
532
+ val = object()
533
+ promised = resolve(val)
534
+ assert isinstance(promised, Promise)
535
+ assert promised.get() == val
536
+
537
+
538
+ def test_resolve_promise_subclass():
539
+ class MyPromise(Promise):
540
+ pass
541
+
542
+ p = Promise()
543
+ p.do_resolve(10)
544
+ m_p = MyPromise.resolve(p)
545
+
546
+ assert isinstance(m_p, MyPromise)
547
+ assert m_p.get() == p.get()
548
+
549
+
550
+ def test_promise_repr_pending():
551
+ promise = Promise()
552
+ assert repr(promise) == "<Promise at {} pending>".format(hex(id(promise)))
553
+
554
+
555
+ def test_promise_repr_pending():
556
+ val = {1: 2}
557
+ promise = Promise.fulfilled(val)
558
+ promise._wait()
559
+ assert repr(promise) == "<Promise at {} fulfilled with {}>".format(
560
+ hex(id(promise)), repr(val)
561
+ )
562
+
563
+
564
+ def test_promise_repr_fulfilled():
565
+ val = {1: 2}
566
+ promise = Promise.fulfilled(val)
567
+ promise._wait()
568
+ assert repr(promise) == "<Promise at {} fulfilled with {}>".format(
569
+ hex(id(promise)), repr(val)
570
+ )
571
+
572
+
573
+ def test_promise_repr_rejected():
574
+ err = Exception("Error!")
575
+ promise = Promise.rejected(err)
576
+ promise._wait()
577
+ assert repr(promise) == "<Promise at {} rejected with {}>".format(
578
+ hex(id(promise)), repr(err)
579
+ )
580
+
581
+
582
+ def test_promise_loop():
583
+ def by_two(result):
584
+ return result * 2
585
+
586
+ def executor(resolve, reject):
587
+ resolve(Promise.resolve(1).then(lambda v: Promise.resolve(v).then(by_two)))
588
+
589
+ p = Promise(executor)
590
+ assert p.get(.1) == 2
591
+
592
+
593
+ def test_resolve_future_like(resolve):
594
+ class CustomThenable(object):
595
+ def add_done_callback(self, f):
596
+ f(True)
597
+
598
+ def done(self):
599
+ return True
600
+
601
+ def exception(self):
602
+ pass
603
+
604
+ def result(self):
605
+ return True
606
+
607
+ instance = CustomThenable()
608
+
609
+ promise = resolve(instance)
610
+ assert promise.get() == True
611
+
612
+
613
+ def sum_function(a, b):
614
+ return a + b
615
+
616
+
617
+ def test_promisify_function_resolved(resolve):
618
+ promisified_func = promisify(sum_function)
619
+
620
+ result = promisified_func(1, 2)
621
+ assert isinstance(result, Promise)
622
+ assert result.get() == 3
623
+
624
+
625
+ def test_promisify_function_rejected(resolve):
626
+ promisified_func = promisify(sum_function)
627
+
628
+ result = promisified_func(None, None)
629
+ assert isinstance(result, Promise)
630
+ with raises(Exception) as exc_info_promise:
631
+ result.get()
632
+
633
+ with raises(Exception) as exc_info:
634
+ sum_function(None, None)
635
+
636
+ assert str(exc_info_promise.value) == str(exc_info.value)
637
+
638
+
639
+ def test_promises_with_only_then():
640
+ context = {"success": False}
641
+ error = RuntimeError("Ooops!")
642
+ promise1 = Promise(
643
+ lambda resolve, reject: context.update({"promise1_reject": reject})
644
+ )
645
+ promise2 = promise1.then(lambda x: None)
646
+ promise3 = promise1.then(lambda x: None)
647
+ context["promise1_reject"](error)
648
+
649
+ promise2._wait()
650
+ promise3._wait()
651
+ assert promise2.reason == error
652
+ assert promise3.reason == error
653
+
654
+
655
+ def test_promises_promisify_still_works_but_deprecated_for_non_callables():
656
+ x = promisify(1)
657
+ assert isinstance(x, Promise)
658
+ assert x.get() == 1
659
+
660
+
661
+ # def test_promise_loop():
662
+ # values = Promise.resolve([1, None, 2])
663
+ # def on_error(error):
664
+ # error
665
+
666
+ # def executor(resolve, reject):
667
+ # resolve(Promise.resolve(values).then(lambda values: Promise.all([Promise.resolve(values[0])]).catch(on_error)))
668
+
669
+ # p = Promise(executor)
670
+ # assert p.get(.1) == 2
infer_4_47_1/lib/python3.10/importlib/__init__.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A pure Python implementation of import."""
2
+ __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
3
+
4
+ # Bootstrap help #####################################################
5
+
6
+ # Until bootstrapping is complete, DO NOT import any modules that attempt
7
+ # to import importlib._bootstrap (directly or indirectly). Since this
8
+ # partially initialised package would be present in sys.modules, those
9
+ # modules would get an uninitialised copy of the source version, instead
10
+ # of a fully initialised version (either the frozen one or the one
11
+ # initialised below if the frozen one is not available).
12
+ import _imp # Just the builtin component, NOT the full Python module
13
+ import sys
14
+
15
+ try:
16
+ import _frozen_importlib as _bootstrap
17
+ except ImportError:
18
+ from . import _bootstrap
19
+ _bootstrap._setup(sys, _imp)
20
+ else:
21
+ # importlib._bootstrap is the built-in import, ensure we don't create
22
+ # a second copy of the module.
23
+ _bootstrap.__name__ = 'importlib._bootstrap'
24
+ _bootstrap.__package__ = 'importlib'
25
+ try:
26
+ _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
27
+ except NameError:
28
+ # __file__ is not guaranteed to be defined, e.g. if this code gets
29
+ # frozen by a tool like cx_Freeze.
30
+ pass
31
+ sys.modules['importlib._bootstrap'] = _bootstrap
32
+
33
+ try:
34
+ import _frozen_importlib_external as _bootstrap_external
35
+ except ImportError:
36
+ from . import _bootstrap_external
37
+ _bootstrap_external._set_bootstrap_module(_bootstrap)
38
+ _bootstrap._bootstrap_external = _bootstrap_external
39
+ else:
40
+ _bootstrap_external.__name__ = 'importlib._bootstrap_external'
41
+ _bootstrap_external.__package__ = 'importlib'
42
+ try:
43
+ _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
44
+ except NameError:
45
+ # __file__ is not guaranteed to be defined, e.g. if this code gets
46
+ # frozen by a tool like cx_Freeze.
47
+ pass
48
+ sys.modules['importlib._bootstrap_external'] = _bootstrap_external
49
+
50
+ # To simplify imports in test code
51
+ _pack_uint32 = _bootstrap_external._pack_uint32
52
+ _unpack_uint32 = _bootstrap_external._unpack_uint32
53
+
54
+ # Fully bootstrapped at this point, import whatever you like, circular
55
+ # dependencies and startup overhead minimisation permitting :)
56
+
57
+ import warnings
58
+
59
+
60
+ # Public API #########################################################
61
+
62
+ from ._bootstrap import __import__
63
+
64
+
65
+ def invalidate_caches():
66
+ """Call the invalidate_caches() method on all meta path finders stored in
67
+ sys.meta_path (where implemented)."""
68
+ for finder in sys.meta_path:
69
+ if hasattr(finder, 'invalidate_caches'):
70
+ finder.invalidate_caches()
71
+
72
+
73
+ def find_loader(name, path=None):
74
+ """Return the loader for the specified module.
75
+
76
+ This is a backward-compatible wrapper around find_spec().
77
+
78
+ This function is deprecated in favor of importlib.util.find_spec().
79
+
80
+ """
81
+ warnings.warn('Deprecated since Python 3.4 and slated for removal in '
82
+ 'Python 3.12; use importlib.util.find_spec() instead',
83
+ DeprecationWarning, stacklevel=2)
84
+ try:
85
+ loader = sys.modules[name].__loader__
86
+ if loader is None:
87
+ raise ValueError('{}.__loader__ is None'.format(name))
88
+ else:
89
+ return loader
90
+ except KeyError:
91
+ pass
92
+ except AttributeError:
93
+ raise ValueError('{}.__loader__ is not set'.format(name)) from None
94
+
95
+ spec = _bootstrap._find_spec(name, path)
96
+ # We won't worry about malformed specs (missing attributes).
97
+ if spec is None:
98
+ return None
99
+ if spec.loader is None:
100
+ if spec.submodule_search_locations is None:
101
+ raise ImportError('spec for {} missing loader'.format(name),
102
+ name=name)
103
+ raise ImportError('namespace packages do not have loaders',
104
+ name=name)
105
+ return spec.loader
106
+
107
+
108
+ def import_module(name, package=None):
109
+ """Import a module.
110
+
111
+ The 'package' argument is required when performing a relative import. It
112
+ specifies the package to use as the anchor point from which to resolve the
113
+ relative import to an absolute import.
114
+
115
+ """
116
+ level = 0
117
+ if name.startswith('.'):
118
+ if not package:
119
+ msg = ("the 'package' argument is required to perform a relative "
120
+ "import for {!r}")
121
+ raise TypeError(msg.format(name))
122
+ for character in name:
123
+ if character != '.':
124
+ break
125
+ level += 1
126
+ return _bootstrap._gcd_import(name[level:], package, level)
127
+
128
+
129
+ _RELOADING = {}
130
+
131
+
132
+ def reload(module):
133
+ """Reload the module and return it.
134
+
135
+ The module must have been successfully imported before.
136
+
137
+ """
138
+ try:
139
+ name = module.__spec__.name
140
+ except AttributeError:
141
+ try:
142
+ name = module.__name__
143
+ except AttributeError:
144
+ raise TypeError("reload() argument must be a module")
145
+
146
+ if sys.modules.get(name) is not module:
147
+ msg = "module {} not in sys.modules"
148
+ raise ImportError(msg.format(name), name=name)
149
+ if name in _RELOADING:
150
+ return _RELOADING[name]
151
+ _RELOADING[name] = module
152
+ try:
153
+ parent_name = name.rpartition('.')[0]
154
+ if parent_name:
155
+ try:
156
+ parent = sys.modules[parent_name]
157
+ except KeyError:
158
+ msg = "parent {!r} not in sys.modules"
159
+ raise ImportError(msg.format(parent_name),
160
+ name=parent_name) from None
161
+ else:
162
+ pkgpath = parent.__path__
163
+ else:
164
+ pkgpath = None
165
+ target = module
166
+ spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
167
+ if spec is None:
168
+ raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
169
+ _bootstrap._exec(spec, module)
170
+ # The module may have replaced itself in sys.modules!
171
+ return sys.modules[name]
172
+ finally:
173
+ try:
174
+ del _RELOADING[name]
175
+ except KeyError:
176
+ pass
infer_4_47_1/lib/python3.10/logging/handlers.py ADDED
@@ -0,0 +1,1587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2001-2021 by Vinay Sajip. All Rights Reserved.
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software and its
4
+ # documentation for any purpose and without fee is hereby granted,
5
+ # provided that the above copyright notice appear in all copies and that
6
+ # both that copyright notice and this permission notice appear in
7
+ # supporting documentation, and that the name of Vinay Sajip
8
+ # not be used in advertising or publicity pertaining to distribution
9
+ # of the software without specific, written prior permission.
10
+ # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11
+ # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12
+ # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13
+ # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14
+ # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15
+ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ """
18
+ Additional handlers for the logging package for Python. The core package is
19
+ based on PEP 282 and comments thereto in comp.lang.python.
20
+
21
+ Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved.
22
+
23
+ To use, simply 'import logging.handlers' and log away!
24
+ """
25
+
26
+ import io, logging, socket, os, pickle, struct, time, re
27
+ from stat import ST_DEV, ST_INO, ST_MTIME
28
+ import queue
29
+ import threading
30
+ import copy
31
+
32
+ #
33
+ # Some constants...
34
+ #
35
+
36
+ DEFAULT_TCP_LOGGING_PORT = 9020
37
+ DEFAULT_UDP_LOGGING_PORT = 9021
38
+ DEFAULT_HTTP_LOGGING_PORT = 9022
39
+ DEFAULT_SOAP_LOGGING_PORT = 9023
40
+ SYSLOG_UDP_PORT = 514
41
+ SYSLOG_TCP_PORT = 514
42
+
43
+ _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
44
+
45
+ class BaseRotatingHandler(logging.FileHandler):
46
+ """
47
+ Base class for handlers that rotate log files at a certain point.
48
+ Not meant to be instantiated directly. Instead, use RotatingFileHandler
49
+ or TimedRotatingFileHandler.
50
+ """
51
+ namer = None
52
+ rotator = None
53
+
54
+ def __init__(self, filename, mode, encoding=None, delay=False, errors=None):
55
+ """
56
+ Use the specified filename for streamed logging
57
+ """
58
+ logging.FileHandler.__init__(self, filename, mode=mode,
59
+ encoding=encoding, delay=delay,
60
+ errors=errors)
61
+ self.mode = mode
62
+ self.encoding = encoding
63
+ self.errors = errors
64
+
65
+ def emit(self, record):
66
+ """
67
+ Emit a record.
68
+
69
+ Output the record to the file, catering for rollover as described
70
+ in doRollover().
71
+ """
72
+ try:
73
+ if self.shouldRollover(record):
74
+ self.doRollover()
75
+ logging.FileHandler.emit(self, record)
76
+ except Exception:
77
+ self.handleError(record)
78
+
79
+ def rotation_filename(self, default_name):
80
+ """
81
+ Modify the filename of a log file when rotating.
82
+
83
+ This is provided so that a custom filename can be provided.
84
+
85
+ The default implementation calls the 'namer' attribute of the
86
+ handler, if it's callable, passing the default name to
87
+ it. If the attribute isn't callable (the default is None), the name
88
+ is returned unchanged.
89
+
90
+ :param default_name: The default name for the log file.
91
+ """
92
+ if not callable(self.namer):
93
+ result = default_name
94
+ else:
95
+ result = self.namer(default_name)
96
+ return result
97
+
98
+ def rotate(self, source, dest):
99
+ """
100
+ When rotating, rotate the current log.
101
+
102
+ The default implementation calls the 'rotator' attribute of the
103
+ handler, if it's callable, passing the source and dest arguments to
104
+ it. If the attribute isn't callable (the default is None), the source
105
+ is simply renamed to the destination.
106
+
107
+ :param source: The source filename. This is normally the base
108
+ filename, e.g. 'test.log'
109
+ :param dest: The destination filename. This is normally
110
+ what the source is rotated to, e.g. 'test.log.1'.
111
+ """
112
+ if not callable(self.rotator):
113
+ # Issue 18940: A file may not have been created if delay is True.
114
+ if os.path.exists(source):
115
+ os.rename(source, dest)
116
+ else:
117
+ self.rotator(source, dest)
118
+
119
+ class RotatingFileHandler(BaseRotatingHandler):
120
+ """
121
+ Handler for logging to a set of files, which switches from one file
122
+ to the next when the current file reaches a certain size.
123
+ """
124
+ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
125
+ encoding=None, delay=False, errors=None):
126
+ """
127
+ Open the specified file and use it as the stream for logging.
128
+
129
+ By default, the file grows indefinitely. You can specify particular
130
+ values of maxBytes and backupCount to allow the file to rollover at
131
+ a predetermined size.
132
+
133
+ Rollover occurs whenever the current log file is nearly maxBytes in
134
+ length. If backupCount is >= 1, the system will successively create
135
+ new files with the same pathname as the base file, but with extensions
136
+ ".1", ".2" etc. appended to it. For example, with a backupCount of 5
137
+ and a base file name of "app.log", you would get "app.log",
138
+ "app.log.1", "app.log.2", ... through to "app.log.5". The file being
139
+ written to is always "app.log" - when it gets filled up, it is closed
140
+ and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
141
+ exist, then they are renamed to "app.log.2", "app.log.3" etc.
142
+ respectively.
143
+
144
+ If maxBytes is zero, rollover never occurs.
145
+ """
146
+ # If rotation/rollover is wanted, it doesn't make sense to use another
147
+ # mode. If for example 'w' were specified, then if there were multiple
148
+ # runs of the calling application, the logs from previous runs would be
149
+ # lost if the 'w' is respected, because the log file would be truncated
150
+ # on each run.
151
+ if maxBytes > 0:
152
+ mode = 'a'
153
+ if "b" not in mode:
154
+ encoding = io.text_encoding(encoding)
155
+ BaseRotatingHandler.__init__(self, filename, mode, encoding=encoding,
156
+ delay=delay, errors=errors)
157
+ self.maxBytes = maxBytes
158
+ self.backupCount = backupCount
159
+
160
+ def doRollover(self):
161
+ """
162
+ Do a rollover, as described in __init__().
163
+ """
164
+ if self.stream:
165
+ self.stream.close()
166
+ self.stream = None
167
+ if self.backupCount > 0:
168
+ for i in range(self.backupCount - 1, 0, -1):
169
+ sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
170
+ dfn = self.rotation_filename("%s.%d" % (self.baseFilename,
171
+ i + 1))
172
+ if os.path.exists(sfn):
173
+ if os.path.exists(dfn):
174
+ os.remove(dfn)
175
+ os.rename(sfn, dfn)
176
+ dfn = self.rotation_filename(self.baseFilename + ".1")
177
+ if os.path.exists(dfn):
178
+ os.remove(dfn)
179
+ self.rotate(self.baseFilename, dfn)
180
+ if not self.delay:
181
+ self.stream = self._open()
182
+
183
+ def shouldRollover(self, record):
184
+ """
185
+ Determine if rollover should occur.
186
+
187
+ Basically, see if the supplied record would cause the file to exceed
188
+ the size limit we have.
189
+ """
190
+ # See bpo-45401: Never rollover anything other than regular files
191
+ if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
192
+ return False
193
+ if self.stream is None: # delay was set...
194
+ self.stream = self._open()
195
+ if self.maxBytes > 0: # are we rolling over?
196
+ msg = "%s\n" % self.format(record)
197
+ self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
198
+ if self.stream.tell() + len(msg) >= self.maxBytes:
199
+ return True
200
+ return False
201
+
202
+ class TimedRotatingFileHandler(BaseRotatingHandler):
203
+ """
204
+ Handler for logging to a file, rotating the log file at certain timed
205
+ intervals.
206
+
207
+ If backupCount is > 0, when rollover is done, no more than backupCount
208
+ files are kept - the oldest ones are deleted.
209
+ """
210
+ def __init__(self, filename, when='h', interval=1, backupCount=0,
211
+ encoding=None, delay=False, utc=False, atTime=None,
212
+ errors=None):
213
+ encoding = io.text_encoding(encoding)
214
+ BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding,
215
+ delay=delay, errors=errors)
216
+ self.when = when.upper()
217
+ self.backupCount = backupCount
218
+ self.utc = utc
219
+ self.atTime = atTime
220
+ # Calculate the real rollover interval, which is just the number of
221
+ # seconds between rollovers. Also set the filename suffix used when
222
+ # a rollover occurs. Current 'when' events supported:
223
+ # S - Seconds
224
+ # M - Minutes
225
+ # H - Hours
226
+ # D - Days
227
+ # midnight - roll over at midnight
228
+ # W{0-6} - roll over on a certain day; 0 - Monday
229
+ #
230
+ # Case of the 'when' specifier is not important; lower or upper case
231
+ # will work.
232
+ if self.when == 'S':
233
+ self.interval = 1 # one second
234
+ self.suffix = "%Y-%m-%d_%H-%M-%S"
235
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$"
236
+ elif self.when == 'M':
237
+ self.interval = 60 # one minute
238
+ self.suffix = "%Y-%m-%d_%H-%M"
239
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$"
240
+ elif self.when == 'H':
241
+ self.interval = 60 * 60 # one hour
242
+ self.suffix = "%Y-%m-%d_%H"
243
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$"
244
+ elif self.when == 'D' or self.when == 'MIDNIGHT':
245
+ self.interval = 60 * 60 * 24 # one day
246
+ self.suffix = "%Y-%m-%d"
247
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
248
+ elif self.when.startswith('W'):
249
+ self.interval = 60 * 60 * 24 * 7 # one week
250
+ if len(self.when) != 2:
251
+ raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
252
+ if self.when[1] < '0' or self.when[1] > '6':
253
+ raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
254
+ self.dayOfWeek = int(self.when[1])
255
+ self.suffix = "%Y-%m-%d"
256
+ self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
257
+ else:
258
+ raise ValueError("Invalid rollover interval specified: %s" % self.when)
259
+
260
+ self.extMatch = re.compile(self.extMatch, re.ASCII)
261
+ self.interval = self.interval * interval # multiply by units requested
262
+ # The following line added because the filename passed in could be a
263
+ # path object (see Issue #27493), but self.baseFilename will be a string
264
+ filename = self.baseFilename
265
+ if os.path.exists(filename):
266
+ t = os.stat(filename)[ST_MTIME]
267
+ else:
268
+ t = int(time.time())
269
+ self.rolloverAt = self.computeRollover(t)
270
+
271
+ def computeRollover(self, currentTime):
272
+ """
273
+ Work out the rollover time based on the specified time.
274
+ """
275
+ result = currentTime + self.interval
276
+ # If we are rolling over at midnight or weekly, then the interval is already known.
277
+ # What we need to figure out is WHEN the next interval is. In other words,
278
+ # if you are rolling over at midnight, then your base interval is 1 day,
279
+ # but you want to start that one day clock at midnight, not now. So, we
280
+ # have to fudge the rolloverAt value in order to trigger the first rollover
281
+ # at the right time. After that, the regular interval will take care of
282
+ # the rest. Note that this code doesn't care about leap seconds. :)
283
+ if self.when == 'MIDNIGHT' or self.when.startswith('W'):
284
+ # This could be done with less code, but I wanted it to be clear
285
+ if self.utc:
286
+ t = time.gmtime(currentTime)
287
+ else:
288
+ t = time.localtime(currentTime)
289
+ currentHour = t[3]
290
+ currentMinute = t[4]
291
+ currentSecond = t[5]
292
+ currentDay = t[6]
293
+ # r is the number of seconds left between now and the next rotation
294
+ if self.atTime is None:
295
+ rotate_ts = _MIDNIGHT
296
+ else:
297
+ rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 +
298
+ self.atTime.second)
299
+
300
+ r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 +
301
+ currentSecond)
302
+ if r < 0:
303
+ # Rotate time is before the current time (for example when
304
+ # self.rotateAt is 13:45 and it now 14:15), rotation is
305
+ # tomorrow.
306
+ r += _MIDNIGHT
307
+ currentDay = (currentDay + 1) % 7
308
+ result = currentTime + r
309
+ # If we are rolling over on a certain day, add in the number of days until
310
+ # the next rollover, but offset by 1 since we just calculated the time
311
+ # until the next day starts. There are three cases:
312
+ # Case 1) The day to rollover is today; in this case, do nothing
313
+ # Case 2) The day to rollover is further in the interval (i.e., today is
314
+ # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
315
+ # next rollover is simply 6 - 2 - 1, or 3.
316
+ # Case 3) The day to rollover is behind us in the interval (i.e., today
317
+ # is day 5 (Saturday) and rollover is on day 3 (Thursday).
318
+ # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
319
+ # number of days left in the current week (1) plus the number
320
+ # of days in the next week until the rollover day (3).
321
+ # The calculations described in 2) and 3) above need to have a day added.
322
+ # This is because the above time calculation takes us to midnight on this
323
+ # day, i.e. the start of the next day.
324
+ if self.when.startswith('W'):
325
+ day = currentDay # 0 is Monday
326
+ if day != self.dayOfWeek:
327
+ if day < self.dayOfWeek:
328
+ daysToWait = self.dayOfWeek - day
329
+ else:
330
+ daysToWait = 6 - day + self.dayOfWeek + 1
331
+ newRolloverAt = result + (daysToWait * (60 * 60 * 24))
332
+ if not self.utc:
333
+ dstNow = t[-1]
334
+ dstAtRollover = time.localtime(newRolloverAt)[-1]
335
+ if dstNow != dstAtRollover:
336
+ if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
337
+ addend = -3600
338
+ else: # DST bows out before next rollover, so we need to add an hour
339
+ addend = 3600
340
+ newRolloverAt += addend
341
+ result = newRolloverAt
342
+ return result
343
+
344
+ def shouldRollover(self, record):
345
+ """
346
+ Determine if rollover should occur.
347
+
348
+ record is not used, as we are just comparing times, but it is needed so
349
+ the method signatures are the same
350
+ """
351
+ t = int(time.time())
352
+ if t >= self.rolloverAt:
353
+ # See #89564: Never rollover anything other than regular files
354
+ if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
355
+ # The file is not a regular file, so do not rollover, but do
356
+ # set the next rollover time to avoid repeated checks.
357
+ self.rolloverAt = self.computeRollover(t)
358
+ return False
359
+
360
+ return True
361
+ return False
362
+
363
+ def getFilesToDelete(self):
364
+ """
365
+ Determine the files to delete when rolling over.
366
+
367
+ More specific than the earlier method, which just used glob.glob().
368
+ """
369
+ dirName, baseName = os.path.split(self.baseFilename)
370
+ fileNames = os.listdir(dirName)
371
+ result = []
372
+ # See bpo-44753: Don't use the extension when computing the prefix.
373
+ n, e = os.path.splitext(baseName)
374
+ prefix = n + '.'
375
+ plen = len(prefix)
376
+ for fileName in fileNames:
377
+ if self.namer is None:
378
+ # Our files will always start with baseName
379
+ if not fileName.startswith(baseName):
380
+ continue
381
+ else:
382
+ # Our files could be just about anything after custom naming, but
383
+ # likely candidates are of the form
384
+ # foo.log.DATETIME_SUFFIX or foo.DATETIME_SUFFIX.log
385
+ if (not fileName.startswith(baseName) and fileName.endswith(e) and
386
+ len(fileName) > (plen + 1) and not fileName[plen+1].isdigit()):
387
+ continue
388
+
389
+ if fileName[:plen] == prefix:
390
+ suffix = fileName[plen:]
391
+ # See bpo-45628: The date/time suffix could be anywhere in the
392
+ # filename
393
+ parts = suffix.split('.')
394
+ for part in parts:
395
+ if self.extMatch.match(part):
396
+ result.append(os.path.join(dirName, fileName))
397
+ break
398
+ if len(result) < self.backupCount:
399
+ result = []
400
+ else:
401
+ result.sort()
402
+ result = result[:len(result) - self.backupCount]
403
+ return result
404
+
405
+ def doRollover(self):
406
+ """
407
+ do a rollover; in this case, a date/time stamp is appended to the filename
408
+ when the rollover happens. However, you want the file to be named for the
409
+ start of the interval, not the current time. If there is a backup count,
410
+ then we have to get a list of matching filenames, sort them and remove
411
+ the one with the oldest suffix.
412
+ """
413
+ if self.stream:
414
+ self.stream.close()
415
+ self.stream = None
416
+ # get the time that this sequence started at and make it a TimeTuple
417
+ currentTime = int(time.time())
418
+ dstNow = time.localtime(currentTime)[-1]
419
+ t = self.rolloverAt - self.interval
420
+ if self.utc:
421
+ timeTuple = time.gmtime(t)
422
+ else:
423
+ timeTuple = time.localtime(t)
424
+ dstThen = timeTuple[-1]
425
+ if dstNow != dstThen:
426
+ if dstNow:
427
+ addend = 3600
428
+ else:
429
+ addend = -3600
430
+ timeTuple = time.localtime(t + addend)
431
+ dfn = self.rotation_filename(self.baseFilename + "." +
432
+ time.strftime(self.suffix, timeTuple))
433
+ if os.path.exists(dfn):
434
+ os.remove(dfn)
435
+ self.rotate(self.baseFilename, dfn)
436
+ if self.backupCount > 0:
437
+ for s in self.getFilesToDelete():
438
+ os.remove(s)
439
+ if not self.delay:
440
+ self.stream = self._open()
441
+ newRolloverAt = self.computeRollover(currentTime)
442
+ while newRolloverAt <= currentTime:
443
+ newRolloverAt = newRolloverAt + self.interval
444
+ #If DST changes and midnight or weekly rollover, adjust for this.
445
+ if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
446
+ dstAtRollover = time.localtime(newRolloverAt)[-1]
447
+ if dstNow != dstAtRollover:
448
+ if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
449
+ addend = -3600
450
+ else: # DST bows out before next rollover, so we need to add an hour
451
+ addend = 3600
452
+ newRolloverAt += addend
453
+ self.rolloverAt = newRolloverAt
454
+
455
+ class WatchedFileHandler(logging.FileHandler):
456
+ """
457
+ A handler for logging to a file, which watches the file
458
+ to see if it has changed while in use. This can happen because of
459
+ usage of programs such as newsyslog and logrotate which perform
460
+ log file rotation. This handler, intended for use under Unix,
461
+ watches the file to see if it has changed since the last emit.
462
+ (A file has changed if its device or inode have changed.)
463
+ If it has changed, the old file stream is closed, and the file
464
+ opened to get a new stream.
465
+
466
+ This handler is not appropriate for use under Windows, because
467
+ under Windows open files cannot be moved or renamed - logging
468
+ opens the files with exclusive locks - and so there is no need
469
+ for such a handler. Furthermore, ST_INO is not supported under
470
+ Windows; stat always returns zero for this value.
471
+
472
+ This handler is based on a suggestion and patch by Chad J.
473
+ Schroeder.
474
+ """
475
+ def __init__(self, filename, mode='a', encoding=None, delay=False,
476
+ errors=None):
477
+ if "b" not in mode:
478
+ encoding = io.text_encoding(encoding)
479
+ logging.FileHandler.__init__(self, filename, mode=mode,
480
+ encoding=encoding, delay=delay,
481
+ errors=errors)
482
+ self.dev, self.ino = -1, -1
483
+ self._statstream()
484
+
485
+ def _statstream(self):
486
+ if self.stream:
487
+ sres = os.fstat(self.stream.fileno())
488
+ self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
489
+
490
+ def reopenIfNeeded(self):
491
+ """
492
+ Reopen log file if needed.
493
+
494
+ Checks if the underlying file has changed, and if it
495
+ has, close the old stream and reopen the file to get the
496
+ current stream.
497
+ """
498
+ # Reduce the chance of race conditions by stat'ing by path only
499
+ # once and then fstat'ing our new fd if we opened a new log stream.
500
+ # See issue #14632: Thanks to John Mulligan for the problem report
501
+ # and patch.
502
+ try:
503
+ # stat the file by path, checking for existence
504
+ sres = os.stat(self.baseFilename)
505
+ except FileNotFoundError:
506
+ sres = None
507
+ # compare file system stat with that of our stream file handle
508
+ if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
509
+ if self.stream is not None:
510
+ # we have an open file handle, clean it up
511
+ self.stream.flush()
512
+ self.stream.close()
513
+ self.stream = None # See Issue #21742: _open () might fail.
514
+ # open a new file handle and get new stat info from that fd
515
+ self.stream = self._open()
516
+ self._statstream()
517
+
518
+ def emit(self, record):
519
+ """
520
+ Emit a record.
521
+
522
+ If underlying file has changed, reopen the file before emitting the
523
+ record to it.
524
+ """
525
+ self.reopenIfNeeded()
526
+ logging.FileHandler.emit(self, record)
527
+
528
+
529
+ class SocketHandler(logging.Handler):
530
+ """
531
+ A handler class which writes logging records, in pickle format, to
532
+ a streaming socket. The socket is kept open across logging calls.
533
+ If the peer resets it, an attempt is made to reconnect on the next call.
534
+ The pickle which is sent is that of the LogRecord's attribute dictionary
535
+ (__dict__), so that the receiver does not need to have the logging module
536
+ installed in order to process the logging event.
537
+
538
+ To unpickle the record at the receiving end into a LogRecord, use the
539
+ makeLogRecord function.
540
+ """
541
+
542
+ def __init__(self, host, port):
543
+ """
544
+ Initializes the handler with a specific host address and port.
545
+
546
+ When the attribute *closeOnError* is set to True - if a socket error
547
+ occurs, the socket is silently closed and then reopened on the next
548
+ logging call.
549
+ """
550
+ logging.Handler.__init__(self)
551
+ self.host = host
552
+ self.port = port
553
+ if port is None:
554
+ self.address = host
555
+ else:
556
+ self.address = (host, port)
557
+ self.sock = None
558
+ self.closeOnError = False
559
+ self.retryTime = None
560
+ #
561
+ # Exponential backoff parameters.
562
+ #
563
+ self.retryStart = 1.0
564
+ self.retryMax = 30.0
565
+ self.retryFactor = 2.0
566
+
567
+ def makeSocket(self, timeout=1):
568
+ """
569
+ A factory method which allows subclasses to define the precise
570
+ type of socket they want.
571
+ """
572
+ if self.port is not None:
573
+ result = socket.create_connection(self.address, timeout=timeout)
574
+ else:
575
+ result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
576
+ result.settimeout(timeout)
577
+ try:
578
+ result.connect(self.address)
579
+ except OSError:
580
+ result.close() # Issue 19182
581
+ raise
582
+ return result
583
+
584
+ def createSocket(self):
585
+ """
586
+ Try to create a socket, using an exponential backoff with
587
+ a max retry time. Thanks to Robert Olson for the original patch
588
+ (SF #815911) which has been slightly refactored.
589
+ """
590
+ now = time.time()
591
+ # Either retryTime is None, in which case this
592
+ # is the first time back after a disconnect, or
593
+ # we've waited long enough.
594
+ if self.retryTime is None:
595
+ attempt = True
596
+ else:
597
+ attempt = (now >= self.retryTime)
598
+ if attempt:
599
+ try:
600
+ self.sock = self.makeSocket()
601
+ self.retryTime = None # next time, no delay before trying
602
+ except OSError:
603
+ #Creation failed, so set the retry time and return.
604
+ if self.retryTime is None:
605
+ self.retryPeriod = self.retryStart
606
+ else:
607
+ self.retryPeriod = self.retryPeriod * self.retryFactor
608
+ if self.retryPeriod > self.retryMax:
609
+ self.retryPeriod = self.retryMax
610
+ self.retryTime = now + self.retryPeriod
611
+
612
+ def send(self, s):
613
+ """
614
+ Send a pickled string to the socket.
615
+
616
+ This function allows for partial sends which can happen when the
617
+ network is busy.
618
+ """
619
+ if self.sock is None:
620
+ self.createSocket()
621
+ #self.sock can be None either because we haven't reached the retry
622
+ #time yet, or because we have reached the retry time and retried,
623
+ #but are still unable to connect.
624
+ if self.sock:
625
+ try:
626
+ self.sock.sendall(s)
627
+ except OSError: #pragma: no cover
628
+ self.sock.close()
629
+ self.sock = None # so we can call createSocket next time
630
+
631
+ def makePickle(self, record):
632
+ """
633
+ Pickles the record in binary format with a length prefix, and
634
+ returns it ready for transmission across the socket.
635
+ """
636
+ ei = record.exc_info
637
+ if ei:
638
+ # just to get traceback text into record.exc_text ...
639
+ dummy = self.format(record)
640
+ # See issue #14436: If msg or args are objects, they may not be
641
+ # available on the receiving end. So we convert the msg % args
642
+ # to a string, save it as msg and zap the args.
643
+ d = dict(record.__dict__)
644
+ d['msg'] = record.getMessage()
645
+ d['args'] = None
646
+ d['exc_info'] = None
647
+ # Issue #25685: delete 'message' if present: redundant with 'msg'
648
+ d.pop('message', None)
649
+ s = pickle.dumps(d, 1)
650
+ slen = struct.pack(">L", len(s))
651
+ return slen + s
652
+
653
+ def handleError(self, record):
654
+ """
655
+ Handle an error during logging.
656
+
657
+ An error has occurred during logging. Most likely cause -
658
+ connection lost. Close the socket so that we can retry on the
659
+ next event.
660
+ """
661
+ if self.closeOnError and self.sock:
662
+ self.sock.close()
663
+ self.sock = None #try to reconnect next time
664
+ else:
665
+ logging.Handler.handleError(self, record)
666
+
667
+ def emit(self, record):
668
+ """
669
+ Emit a record.
670
+
671
+ Pickles the record and writes it to the socket in binary format.
672
+ If there is an error with the socket, silently drop the packet.
673
+ If there was a problem with the socket, re-establishes the
674
+ socket.
675
+ """
676
+ try:
677
+ s = self.makePickle(record)
678
+ self.send(s)
679
+ except Exception:
680
+ self.handleError(record)
681
+
682
+ def close(self):
683
+ """
684
+ Closes the socket.
685
+ """
686
+ self.acquire()
687
+ try:
688
+ sock = self.sock
689
+ if sock:
690
+ self.sock = None
691
+ sock.close()
692
+ logging.Handler.close(self)
693
+ finally:
694
+ self.release()
695
+
696
+ class DatagramHandler(SocketHandler):
697
+ """
698
+ A handler class which writes logging records, in pickle format, to
699
+ a datagram socket. The pickle which is sent is that of the LogRecord's
700
+ attribute dictionary (__dict__), so that the receiver does not need to
701
+ have the logging module installed in order to process the logging event.
702
+
703
+ To unpickle the record at the receiving end into a LogRecord, use the
704
+ makeLogRecord function.
705
+
706
+ """
707
+ def __init__(self, host, port):
708
+ """
709
+ Initializes the handler with a specific host address and port.
710
+ """
711
+ SocketHandler.__init__(self, host, port)
712
+ self.closeOnError = False
713
+
714
+ def makeSocket(self):
715
+ """
716
+ The factory method of SocketHandler is here overridden to create
717
+ a UDP socket (SOCK_DGRAM).
718
+ """
719
+ if self.port is None:
720
+ family = socket.AF_UNIX
721
+ else:
722
+ family = socket.AF_INET
723
+ s = socket.socket(family, socket.SOCK_DGRAM)
724
+ return s
725
+
726
+ def send(self, s):
727
+ """
728
+ Send a pickled string to a socket.
729
+
730
+ This function no longer allows for partial sends which can happen
731
+ when the network is busy - UDP does not guarantee delivery and
732
+ can deliver packets out of sequence.
733
+ """
734
+ if self.sock is None:
735
+ self.createSocket()
736
+ self.sock.sendto(s, self.address)
737
+
738
+ class SysLogHandler(logging.Handler):
739
+ """
740
+ A handler class which sends formatted logging records to a syslog
741
+ server. Based on Sam Rushing's syslog module:
742
+ http://www.nightmare.com/squirl/python-ext/misc/syslog.py
743
+ Contributed by Nicolas Untz (after which minor refactoring changes
744
+ have been made).
745
+ """
746
+
747
+ # from <linux/sys/syslog.h>:
748
+ # ======================================================================
749
+ # priorities/facilities are encoded into a single 32-bit quantity, where
750
+ # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
751
+ # facility (0-big number). Both the priorities and the facilities map
752
+ # roughly one-to-one to strings in the syslogd(8) source code. This
753
+ # mapping is included in this file.
754
+ #
755
+ # priorities (these are ordered)
756
+
757
+ LOG_EMERG = 0 # system is unusable
758
+ LOG_ALERT = 1 # action must be taken immediately
759
+ LOG_CRIT = 2 # critical conditions
760
+ LOG_ERR = 3 # error conditions
761
+ LOG_WARNING = 4 # warning conditions
762
+ LOG_NOTICE = 5 # normal but significant condition
763
+ LOG_INFO = 6 # informational
764
+ LOG_DEBUG = 7 # debug-level messages
765
+
766
+ # facility codes
767
+ LOG_KERN = 0 # kernel messages
768
+ LOG_USER = 1 # random user-level messages
769
+ LOG_MAIL = 2 # mail system
770
+ LOG_DAEMON = 3 # system daemons
771
+ LOG_AUTH = 4 # security/authorization messages
772
+ LOG_SYSLOG = 5 # messages generated internally by syslogd
773
+ LOG_LPR = 6 # line printer subsystem
774
+ LOG_NEWS = 7 # network news subsystem
775
+ LOG_UUCP = 8 # UUCP subsystem
776
+ LOG_CRON = 9 # clock daemon
777
+ LOG_AUTHPRIV = 10 # security/authorization messages (private)
778
+ LOG_FTP = 11 # FTP daemon
779
+ LOG_NTP = 12 # NTP subsystem
780
+ LOG_SECURITY = 13 # Log audit
781
+ LOG_CONSOLE = 14 # Log alert
782
+ LOG_SOLCRON = 15 # Scheduling daemon (Solaris)
783
+
784
+ # other codes through 15 reserved for system use
785
+ LOG_LOCAL0 = 16 # reserved for local use
786
+ LOG_LOCAL1 = 17 # reserved for local use
787
+ LOG_LOCAL2 = 18 # reserved for local use
788
+ LOG_LOCAL3 = 19 # reserved for local use
789
+ LOG_LOCAL4 = 20 # reserved for local use
790
+ LOG_LOCAL5 = 21 # reserved for local use
791
+ LOG_LOCAL6 = 22 # reserved for local use
792
+ LOG_LOCAL7 = 23 # reserved for local use
793
+
794
+ priority_names = {
795
+ "alert": LOG_ALERT,
796
+ "crit": LOG_CRIT,
797
+ "critical": LOG_CRIT,
798
+ "debug": LOG_DEBUG,
799
+ "emerg": LOG_EMERG,
800
+ "err": LOG_ERR,
801
+ "error": LOG_ERR, # DEPRECATED
802
+ "info": LOG_INFO,
803
+ "notice": LOG_NOTICE,
804
+ "panic": LOG_EMERG, # DEPRECATED
805
+ "warn": LOG_WARNING, # DEPRECATED
806
+ "warning": LOG_WARNING,
807
+ }
808
+
809
+ facility_names = {
810
+ "auth": LOG_AUTH,
811
+ "authpriv": LOG_AUTHPRIV,
812
+ "console": LOG_CONSOLE,
813
+ "cron": LOG_CRON,
814
+ "daemon": LOG_DAEMON,
815
+ "ftp": LOG_FTP,
816
+ "kern": LOG_KERN,
817
+ "lpr": LOG_LPR,
818
+ "mail": LOG_MAIL,
819
+ "news": LOG_NEWS,
820
+ "ntp": LOG_NTP,
821
+ "security": LOG_SECURITY,
822
+ "solaris-cron": LOG_SOLCRON,
823
+ "syslog": LOG_SYSLOG,
824
+ "user": LOG_USER,
825
+ "uucp": LOG_UUCP,
826
+ "local0": LOG_LOCAL0,
827
+ "local1": LOG_LOCAL1,
828
+ "local2": LOG_LOCAL2,
829
+ "local3": LOG_LOCAL3,
830
+ "local4": LOG_LOCAL4,
831
+ "local5": LOG_LOCAL5,
832
+ "local6": LOG_LOCAL6,
833
+ "local7": LOG_LOCAL7,
834
+ }
835
+
836
+ #The map below appears to be trivially lowercasing the key. However,
837
+ #there's more to it than meets the eye - in some locales, lowercasing
838
+ #gives unexpected results. See SF #1524081: in the Turkish locale,
839
+ #"INFO".lower() != "info"
840
+ priority_map = {
841
+ "DEBUG" : "debug",
842
+ "INFO" : "info",
843
+ "WARNING" : "warning",
844
+ "ERROR" : "error",
845
+ "CRITICAL" : "critical"
846
+ }
847
+
848
+ def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
849
+ facility=LOG_USER, socktype=None):
850
+ """
851
+ Initialize a handler.
852
+
853
+ If address is specified as a string, a UNIX socket is used. To log to a
854
+ local syslogd, "SysLogHandler(address="/dev/log")" can be used.
855
+ If facility is not specified, LOG_USER is used. If socktype is
856
+ specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
857
+ socket type will be used. For Unix sockets, you can also specify a
858
+ socktype of None, in which case socket.SOCK_DGRAM will be used, falling
859
+ back to socket.SOCK_STREAM.
860
+ """
861
+ logging.Handler.__init__(self)
862
+
863
+ self.address = address
864
+ self.facility = facility
865
+ self.socktype = socktype
866
+
867
+ if isinstance(address, str):
868
+ self.unixsocket = True
869
+ # Syslog server may be unavailable during handler initialisation.
870
+ # C's openlog() function also ignores connection errors.
871
+ # Moreover, we ignore these errors while logging, so it not worse
872
+ # to ignore it also here.
873
+ try:
874
+ self._connect_unixsocket(address)
875
+ except OSError:
876
+ pass
877
+ else:
878
+ self.unixsocket = False
879
+ if socktype is None:
880
+ socktype = socket.SOCK_DGRAM
881
+ host, port = address
882
+ ress = socket.getaddrinfo(host, port, 0, socktype)
883
+ if not ress:
884
+ raise OSError("getaddrinfo returns an empty list")
885
+ for res in ress:
886
+ af, socktype, proto, _, sa = res
887
+ err = sock = None
888
+ try:
889
+ sock = socket.socket(af, socktype, proto)
890
+ if socktype == socket.SOCK_STREAM:
891
+ sock.connect(sa)
892
+ break
893
+ except OSError as exc:
894
+ err = exc
895
+ if sock is not None:
896
+ sock.close()
897
+ if err is not None:
898
+ raise err
899
+ self.socket = sock
900
+ self.socktype = socktype
901
+
902
+ def _connect_unixsocket(self, address):
903
+ use_socktype = self.socktype
904
+ if use_socktype is None:
905
+ use_socktype = socket.SOCK_DGRAM
906
+ self.socket = socket.socket(socket.AF_UNIX, use_socktype)
907
+ try:
908
+ self.socket.connect(address)
909
+ # it worked, so set self.socktype to the used type
910
+ self.socktype = use_socktype
911
+ except OSError:
912
+ self.socket.close()
913
+ if self.socktype is not None:
914
+ # user didn't specify falling back, so fail
915
+ raise
916
+ use_socktype = socket.SOCK_STREAM
917
+ self.socket = socket.socket(socket.AF_UNIX, use_socktype)
918
+ try:
919
+ self.socket.connect(address)
920
+ # it worked, so set self.socktype to the used type
921
+ self.socktype = use_socktype
922
+ except OSError:
923
+ self.socket.close()
924
+ raise
925
+
926
+ def encodePriority(self, facility, priority):
927
+ """
928
+ Encode the facility and priority. You can pass in strings or
929
+ integers - if strings are passed, the facility_names and
930
+ priority_names mapping dictionaries are used to convert them to
931
+ integers.
932
+ """
933
+ if isinstance(facility, str):
934
+ facility = self.facility_names[facility]
935
+ if isinstance(priority, str):
936
+ priority = self.priority_names[priority]
937
+ return (facility << 3) | priority
938
+
939
+ def close(self):
940
+ """
941
+ Closes the socket.
942
+ """
943
+ self.acquire()
944
+ try:
945
+ self.socket.close()
946
+ logging.Handler.close(self)
947
+ finally:
948
+ self.release()
949
+
950
+ def mapPriority(self, levelName):
951
+ """
952
+ Map a logging level name to a key in the priority_names map.
953
+ This is useful in two scenarios: when custom levels are being
954
+ used, and in the case where you can't do a straightforward
955
+ mapping by lowercasing the logging level name because of locale-
956
+ specific issues (see SF #1524081).
957
+ """
958
+ return self.priority_map.get(levelName, "warning")
959
+
960
+ ident = '' # prepended to all messages
961
+ append_nul = True # some old syslog daemons expect a NUL terminator
962
+
963
+ def emit(self, record):
964
+ """
965
+ Emit a record.
966
+
967
+ The record is formatted, and then sent to the syslog server. If
968
+ exception information is present, it is NOT sent to the server.
969
+ """
970
+ try:
971
+ msg = self.format(record)
972
+ if self.ident:
973
+ msg = self.ident + msg
974
+ if self.append_nul:
975
+ msg += '\000'
976
+
977
+ # We need to convert record level to lowercase, maybe this will
978
+ # change in the future.
979
+ prio = '<%d>' % self.encodePriority(self.facility,
980
+ self.mapPriority(record.levelname))
981
+ prio = prio.encode('utf-8')
982
+ # Message is a string. Convert to bytes as required by RFC 5424
983
+ msg = msg.encode('utf-8')
984
+ msg = prio + msg
985
+ if self.unixsocket:
986
+ try:
987
+ self.socket.send(msg)
988
+ except OSError:
989
+ self.socket.close()
990
+ self._connect_unixsocket(self.address)
991
+ self.socket.send(msg)
992
+ elif self.socktype == socket.SOCK_DGRAM:
993
+ self.socket.sendto(msg, self.address)
994
+ else:
995
+ self.socket.sendall(msg)
996
+ except Exception:
997
+ self.handleError(record)
998
+
999
+ class SMTPHandler(logging.Handler):
1000
+ """
1001
+ A handler class which sends an SMTP email for each logging event.
1002
+ """
1003
+ def __init__(self, mailhost, fromaddr, toaddrs, subject,
1004
+ credentials=None, secure=None, timeout=5.0):
1005
+ """
1006
+ Initialize the handler.
1007
+
1008
+ Initialize the instance with the from and to addresses and subject
1009
+ line of the email. To specify a non-standard SMTP port, use the
1010
+ (host, port) tuple format for the mailhost argument. To specify
1011
+ authentication credentials, supply a (username, password) tuple
1012
+ for the credentials argument. To specify the use of a secure
1013
+ protocol (TLS), pass in a tuple for the secure argument. This will
1014
+ only be used when authentication credentials are supplied. The tuple
1015
+ will be either an empty tuple, or a single-value tuple with the name
1016
+ of a keyfile, or a 2-value tuple with the names of the keyfile and
1017
+ certificate file. (This tuple is passed to the `starttls` method).
1018
+ A timeout in seconds can be specified for the SMTP connection (the
1019
+ default is one second).
1020
+ """
1021
+ logging.Handler.__init__(self)
1022
+ if isinstance(mailhost, (list, tuple)):
1023
+ self.mailhost, self.mailport = mailhost
1024
+ else:
1025
+ self.mailhost, self.mailport = mailhost, None
1026
+ if isinstance(credentials, (list, tuple)):
1027
+ self.username, self.password = credentials
1028
+ else:
1029
+ self.username = None
1030
+ self.fromaddr = fromaddr
1031
+ if isinstance(toaddrs, str):
1032
+ toaddrs = [toaddrs]
1033
+ self.toaddrs = toaddrs
1034
+ self.subject = subject
1035
+ self.secure = secure
1036
+ self.timeout = timeout
1037
+
1038
+ def getSubject(self, record):
1039
+ """
1040
+ Determine the subject for the email.
1041
+
1042
+ If you want to specify a subject line which is record-dependent,
1043
+ override this method.
1044
+ """
1045
+ return self.subject
1046
+
1047
+ def emit(self, record):
1048
+ """
1049
+ Emit a record.
1050
+
1051
+ Format the record and send it to the specified addressees.
1052
+ """
1053
+ try:
1054
+ import smtplib
1055
+ from email.message import EmailMessage
1056
+ import email.utils
1057
+
1058
+ port = self.mailport
1059
+ if not port:
1060
+ port = smtplib.SMTP_PORT
1061
+ smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
1062
+ msg = EmailMessage()
1063
+ msg['From'] = self.fromaddr
1064
+ msg['To'] = ','.join(self.toaddrs)
1065
+ msg['Subject'] = self.getSubject(record)
1066
+ msg['Date'] = email.utils.localtime()
1067
+ msg.set_content(self.format(record))
1068
+ if self.username:
1069
+ if self.secure is not None:
1070
+ smtp.ehlo()
1071
+ smtp.starttls(*self.secure)
1072
+ smtp.ehlo()
1073
+ smtp.login(self.username, self.password)
1074
+ smtp.send_message(msg)
1075
+ smtp.quit()
1076
+ except Exception:
1077
+ self.handleError(record)
1078
+
1079
+ class NTEventLogHandler(logging.Handler):
1080
+ """
1081
+ A handler class which sends events to the NT Event Log. Adds a
1082
+ registry entry for the specified application name. If no dllname is
1083
+ provided, win32service.pyd (which contains some basic message
1084
+ placeholders) is used. Note that use of these placeholders will make
1085
+ your event logs big, as the entire message source is held in the log.
1086
+ If you want slimmer logs, you have to pass in the name of your own DLL
1087
+ which contains the message definitions you want to use in the event log.
1088
+ """
1089
+ def __init__(self, appname, dllname=None, logtype="Application"):
1090
+ logging.Handler.__init__(self)
1091
+ try:
1092
+ import win32evtlogutil, win32evtlog
1093
+ self.appname = appname
1094
+ self._welu = win32evtlogutil
1095
+ if not dllname:
1096
+ dllname = os.path.split(self._welu.__file__)
1097
+ dllname = os.path.split(dllname[0])
1098
+ dllname = os.path.join(dllname[0], r'win32service.pyd')
1099
+ self.dllname = dllname
1100
+ self.logtype = logtype
1101
+ # Administrative privileges are required to add a source to the registry.
1102
+ # This may not be available for a user that just wants to add to an
1103
+ # existing source - handle this specific case.
1104
+ try:
1105
+ self._welu.AddSourceToRegistry(appname, dllname, logtype)
1106
+ except Exception as e:
1107
+ # This will probably be a pywintypes.error. Only raise if it's not
1108
+ # an "access denied" error, else let it pass
1109
+ if getattr(e, 'winerror', None) != 5: # not access denied
1110
+ raise
1111
+ self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
1112
+ self.typemap = {
1113
+ logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
1114
+ logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
1115
+ logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
1116
+ logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
1117
+ logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
1118
+ }
1119
+ except ImportError:
1120
+ print("The Python Win32 extensions for NT (service, event "\
1121
+ "logging) appear not to be available.")
1122
+ self._welu = None
1123
+
1124
+ def getMessageID(self, record):
1125
+ """
1126
+ Return the message ID for the event record. If you are using your
1127
+ own messages, you could do this by having the msg passed to the
1128
+ logger being an ID rather than a formatting string. Then, in here,
1129
+ you could use a dictionary lookup to get the message ID. This
1130
+ version returns 1, which is the base message ID in win32service.pyd.
1131
+ """
1132
+ return 1
1133
+
1134
+ def getEventCategory(self, record):
1135
+ """
1136
+ Return the event category for the record.
1137
+
1138
+ Override this if you want to specify your own categories. This version
1139
+ returns 0.
1140
+ """
1141
+ return 0
1142
+
1143
+ def getEventType(self, record):
1144
+ """
1145
+ Return the event type for the record.
1146
+
1147
+ Override this if you want to specify your own types. This version does
1148
+ a mapping using the handler's typemap attribute, which is set up in
1149
+ __init__() to a dictionary which contains mappings for DEBUG, INFO,
1150
+ WARNING, ERROR and CRITICAL. If you are using your own levels you will
1151
+ either need to override this method or place a suitable dictionary in
1152
+ the handler's typemap attribute.
1153
+ """
1154
+ return self.typemap.get(record.levelno, self.deftype)
1155
+
1156
+ def emit(self, record):
1157
+ """
1158
+ Emit a record.
1159
+
1160
+ Determine the message ID, event category and event type. Then
1161
+ log the message in the NT event log.
1162
+ """
1163
+ if self._welu:
1164
+ try:
1165
+ id = self.getMessageID(record)
1166
+ cat = self.getEventCategory(record)
1167
+ type = self.getEventType(record)
1168
+ msg = self.format(record)
1169
+ self._welu.ReportEvent(self.appname, id, cat, type, [msg])
1170
+ except Exception:
1171
+ self.handleError(record)
1172
+
1173
+ def close(self):
1174
+ """
1175
+ Clean up this handler.
1176
+
1177
+ You can remove the application name from the registry as a
1178
+ source of event log entries. However, if you do this, you will
1179
+ not be able to see the events as you intended in the Event Log
1180
+ Viewer - it needs to be able to access the registry to get the
1181
+ DLL name.
1182
+ """
1183
+ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
1184
+ logging.Handler.close(self)
1185
+
1186
+ class HTTPHandler(logging.Handler):
1187
+ """
1188
+ A class which sends records to a web server, using either GET or
1189
+ POST semantics.
1190
+ """
1191
+ def __init__(self, host, url, method="GET", secure=False, credentials=None,
1192
+ context=None):
1193
+ """
1194
+ Initialize the instance with the host, the request URL, and the method
1195
+ ("GET" or "POST")
1196
+ """
1197
+ logging.Handler.__init__(self)
1198
+ method = method.upper()
1199
+ if method not in ["GET", "POST"]:
1200
+ raise ValueError("method must be GET or POST")
1201
+ if not secure and context is not None:
1202
+ raise ValueError("context parameter only makes sense "
1203
+ "with secure=True")
1204
+ self.host = host
1205
+ self.url = url
1206
+ self.method = method
1207
+ self.secure = secure
1208
+ self.credentials = credentials
1209
+ self.context = context
1210
+
1211
+ def mapLogRecord(self, record):
1212
+ """
1213
+ Default implementation of mapping the log record into a dict
1214
+ that is sent as the CGI data. Overwrite in your class.
1215
+ Contributed by Franz Glasner.
1216
+ """
1217
+ return record.__dict__
1218
+
1219
+ def getConnection(self, host, secure):
1220
+ """
1221
+ get a HTTP[S]Connection.
1222
+
1223
+ Override when a custom connection is required, for example if
1224
+ there is a proxy.
1225
+ """
1226
+ import http.client
1227
+ if secure:
1228
+ connection = http.client.HTTPSConnection(host, context=self.context)
1229
+ else:
1230
+ connection = http.client.HTTPConnection(host)
1231
+ return connection
1232
+
1233
+ def emit(self, record):
1234
+ """
1235
+ Emit a record.
1236
+
1237
+ Send the record to the web server as a percent-encoded dictionary
1238
+ """
1239
+ try:
1240
+ import urllib.parse
1241
+ host = self.host
1242
+ h = self.getConnection(host, self.secure)
1243
+ url = self.url
1244
+ data = urllib.parse.urlencode(self.mapLogRecord(record))
1245
+ if self.method == "GET":
1246
+ if (url.find('?') >= 0):
1247
+ sep = '&'
1248
+ else:
1249
+ sep = '?'
1250
+ url = url + "%c%s" % (sep, data)
1251
+ h.putrequest(self.method, url)
1252
+ # support multiple hosts on one IP address...
1253
+ # need to strip optional :port from host, if present
1254
+ i = host.find(":")
1255
+ if i >= 0:
1256
+ host = host[:i]
1257
+ # See issue #30904: putrequest call above already adds this header
1258
+ # on Python 3.x.
1259
+ # h.putheader("Host", host)
1260
+ if self.method == "POST":
1261
+ h.putheader("Content-type",
1262
+ "application/x-www-form-urlencoded")
1263
+ h.putheader("Content-length", str(len(data)))
1264
+ if self.credentials:
1265
+ import base64
1266
+ s = ('%s:%s' % self.credentials).encode('utf-8')
1267
+ s = 'Basic ' + base64.b64encode(s).strip().decode('ascii')
1268
+ h.putheader('Authorization', s)
1269
+ h.endheaders()
1270
+ if self.method == "POST":
1271
+ h.send(data.encode('utf-8'))
1272
+ h.getresponse() #can't do anything with the result
1273
+ except Exception:
1274
+ self.handleError(record)
1275
+
1276
+ class BufferingHandler(logging.Handler):
1277
+ """
1278
+ A handler class which buffers logging records in memory. Whenever each
1279
+ record is added to the buffer, a check is made to see if the buffer should
1280
+ be flushed. If it should, then flush() is expected to do what's needed.
1281
+ """
1282
+ def __init__(self, capacity):
1283
+ """
1284
+ Initialize the handler with the buffer size.
1285
+ """
1286
+ logging.Handler.__init__(self)
1287
+ self.capacity = capacity
1288
+ self.buffer = []
1289
+
1290
+ def shouldFlush(self, record):
1291
+ """
1292
+ Should the handler flush its buffer?
1293
+
1294
+ Returns true if the buffer is up to capacity. This method can be
1295
+ overridden to implement custom flushing strategies.
1296
+ """
1297
+ return (len(self.buffer) >= self.capacity)
1298
+
1299
+ def emit(self, record):
1300
+ """
1301
+ Emit a record.
1302
+
1303
+ Append the record. If shouldFlush() tells us to, call flush() to process
1304
+ the buffer.
1305
+ """
1306
+ self.buffer.append(record)
1307
+ if self.shouldFlush(record):
1308
+ self.flush()
1309
+
1310
+ def flush(self):
1311
+ """
1312
+ Override to implement custom flushing behaviour.
1313
+
1314
+ This version just zaps the buffer to empty.
1315
+ """
1316
+ self.acquire()
1317
+ try:
1318
+ self.buffer.clear()
1319
+ finally:
1320
+ self.release()
1321
+
1322
+ def close(self):
1323
+ """
1324
+ Close the handler.
1325
+
1326
+ This version just flushes and chains to the parent class' close().
1327
+ """
1328
+ try:
1329
+ self.flush()
1330
+ finally:
1331
+ logging.Handler.close(self)
1332
+
1333
+ class MemoryHandler(BufferingHandler):
1334
+ """
1335
+ A handler class which buffers logging records in memory, periodically
1336
+ flushing them to a target handler. Flushing occurs whenever the buffer
1337
+ is full, or when an event of a certain severity or greater is seen.
1338
+ """
1339
+ def __init__(self, capacity, flushLevel=logging.ERROR, target=None,
1340
+ flushOnClose=True):
1341
+ """
1342
+ Initialize the handler with the buffer size, the level at which
1343
+ flushing should occur and an optional target.
1344
+
1345
+ Note that without a target being set either here or via setTarget(),
1346
+ a MemoryHandler is no use to anyone!
1347
+
1348
+ The ``flushOnClose`` argument is ``True`` for backward compatibility
1349
+ reasons - the old behaviour is that when the handler is closed, the
1350
+ buffer is flushed, even if the flush level hasn't been exceeded nor the
1351
+ capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``.
1352
+ """
1353
+ BufferingHandler.__init__(self, capacity)
1354
+ self.flushLevel = flushLevel
1355
+ self.target = target
1356
+ # See Issue #26559 for why this has been added
1357
+ self.flushOnClose = flushOnClose
1358
+
1359
+ def shouldFlush(self, record):
1360
+ """
1361
+ Check for buffer full or a record at the flushLevel or higher.
1362
+ """
1363
+ return (len(self.buffer) >= self.capacity) or \
1364
+ (record.levelno >= self.flushLevel)
1365
+
1366
+ def setTarget(self, target):
1367
+ """
1368
+ Set the target handler for this handler.
1369
+ """
1370
+ self.acquire()
1371
+ try:
1372
+ self.target = target
1373
+ finally:
1374
+ self.release()
1375
+
1376
+ def flush(self):
1377
+ """
1378
+ For a MemoryHandler, flushing means just sending the buffered
1379
+ records to the target, if there is one. Override if you want
1380
+ different behaviour.
1381
+
1382
+ The record buffer is also cleared by this operation.
1383
+ """
1384
+ self.acquire()
1385
+ try:
1386
+ if self.target:
1387
+ for record in self.buffer:
1388
+ self.target.handle(record)
1389
+ self.buffer.clear()
1390
+ finally:
1391
+ self.release()
1392
+
1393
+ def close(self):
1394
+ """
1395
+ Flush, if appropriately configured, set the target to None and lose the
1396
+ buffer.
1397
+ """
1398
+ try:
1399
+ if self.flushOnClose:
1400
+ self.flush()
1401
+ finally:
1402
+ self.acquire()
1403
+ try:
1404
+ self.target = None
1405
+ BufferingHandler.close(self)
1406
+ finally:
1407
+ self.release()
1408
+
1409
+
1410
+ class QueueHandler(logging.Handler):
1411
+ """
1412
+ This handler sends events to a queue. Typically, it would be used together
1413
+ with a multiprocessing Queue to centralise logging to file in one process
1414
+ (in a multi-process application), so as to avoid file write contention
1415
+ between processes.
1416
+
1417
+ This code is new in Python 3.2, but this class can be copy pasted into
1418
+ user code for use with earlier Python versions.
1419
+ """
1420
+
1421
+ def __init__(self, queue):
1422
+ """
1423
+ Initialise an instance, using the passed queue.
1424
+ """
1425
+ logging.Handler.__init__(self)
1426
+ self.queue = queue
1427
+
1428
+ def enqueue(self, record):
1429
+ """
1430
+ Enqueue a record.
1431
+
1432
+ The base implementation uses put_nowait. You may want to override
1433
+ this method if you want to use blocking, timeouts or custom queue
1434
+ implementations.
1435
+ """
1436
+ self.queue.put_nowait(record)
1437
+
1438
+ def prepare(self, record):
1439
+ """
1440
+ Prepares a record for queuing. The object returned by this method is
1441
+ enqueued.
1442
+
1443
+ The base implementation formats the record to merge the message
1444
+ and arguments, and removes unpickleable items from the record
1445
+ in-place.
1446
+
1447
+ You might want to override this method if you want to convert
1448
+ the record to a dict or JSON string, or send a modified copy
1449
+ of the record while leaving the original intact.
1450
+ """
1451
+ # The format operation gets traceback text into record.exc_text
1452
+ # (if there's exception data), and also returns the formatted
1453
+ # message. We can then use this to replace the original
1454
+ # msg + args, as these might be unpickleable. We also zap the
1455
+ # exc_info, exc_text and stack_info attributes, as they are no longer
1456
+ # needed and, if not None, will typically not be pickleable.
1457
+ msg = self.format(record)
1458
+ # bpo-35726: make copy of record to avoid affecting other handlers in the chain.
1459
+ record = copy.copy(record)
1460
+ record.message = msg
1461
+ record.msg = msg
1462
+ record.args = None
1463
+ record.exc_info = None
1464
+ record.exc_text = None
1465
+ record.stack_info = None
1466
+ return record
1467
+
1468
+ def emit(self, record):
1469
+ """
1470
+ Emit a record.
1471
+
1472
+ Writes the LogRecord to the queue, preparing it for pickling first.
1473
+ """
1474
+ try:
1475
+ self.enqueue(self.prepare(record))
1476
+ except Exception:
1477
+ self.handleError(record)
1478
+
1479
+
1480
+ class QueueListener(object):
1481
+ """
1482
+ This class implements an internal threaded listener which watches for
1483
+ LogRecords being added to a queue, removes them and passes them to a
1484
+ list of handlers for processing.
1485
+ """
1486
+ _sentinel = None
1487
+
1488
+ def __init__(self, queue, *handlers, respect_handler_level=False):
1489
+ """
1490
+ Initialise an instance with the specified queue and
1491
+ handlers.
1492
+ """
1493
+ self.queue = queue
1494
+ self.handlers = handlers
1495
+ self._thread = None
1496
+ self.respect_handler_level = respect_handler_level
1497
+
1498
+ def dequeue(self, block):
1499
+ """
1500
+ Dequeue a record and return it, optionally blocking.
1501
+
1502
+ The base implementation uses get. You may want to override this method
1503
+ if you want to use timeouts or work with custom queue implementations.
1504
+ """
1505
+ return self.queue.get(block)
1506
+
1507
+ def start(self):
1508
+ """
1509
+ Start the listener.
1510
+
1511
+ This starts up a background thread to monitor the queue for
1512
+ LogRecords to process.
1513
+ """
1514
+ self._thread = t = threading.Thread(target=self._monitor)
1515
+ t.daemon = True
1516
+ t.start()
1517
+
1518
+ def prepare(self, record):
1519
+ """
1520
+ Prepare a record for handling.
1521
+
1522
+ This method just returns the passed-in record. You may want to
1523
+ override this method if you need to do any custom marshalling or
1524
+ manipulation of the record before passing it to the handlers.
1525
+ """
1526
+ return record
1527
+
1528
+ def handle(self, record):
1529
+ """
1530
+ Handle a record.
1531
+
1532
+ This just loops through the handlers offering them the record
1533
+ to handle.
1534
+ """
1535
+ record = self.prepare(record)
1536
+ for handler in self.handlers:
1537
+ if not self.respect_handler_level:
1538
+ process = True
1539
+ else:
1540
+ process = record.levelno >= handler.level
1541
+ if process:
1542
+ handler.handle(record)
1543
+
1544
+ def _monitor(self):
1545
+ """
1546
+ Monitor the queue for records, and ask the handler
1547
+ to deal with them.
1548
+
1549
+ This method runs on a separate, internal thread.
1550
+ The thread will terminate if it sees a sentinel object in the queue.
1551
+ """
1552
+ q = self.queue
1553
+ has_task_done = hasattr(q, 'task_done')
1554
+ while True:
1555
+ try:
1556
+ record = self.dequeue(True)
1557
+ if record is self._sentinel:
1558
+ if has_task_done:
1559
+ q.task_done()
1560
+ break
1561
+ self.handle(record)
1562
+ if has_task_done:
1563
+ q.task_done()
1564
+ except queue.Empty:
1565
+ break
1566
+
1567
+ def enqueue_sentinel(self):
1568
+ """
1569
+ This is used to enqueue the sentinel record.
1570
+
1571
+ The base implementation uses put_nowait. You may want to override this
1572
+ method if you want to use timeouts or work with custom queue
1573
+ implementations.
1574
+ """
1575
+ self.queue.put_nowait(self._sentinel)
1576
+
1577
+ def stop(self):
1578
+ """
1579
+ Stop the listener.
1580
+
1581
+ This asks the thread to terminate, and then waits for it to do so.
1582
+ Note that if you don't call this before your application exits, there
1583
+ may be some records still left on the queue, which won't be processed.
1584
+ """
1585
+ self.enqueue_sentinel()
1586
+ self._thread.join()
1587
+ self._thread = None
infer_4_47_1/lib/python3.10/turtledemo/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ --------------------------------------
3
+ About this viewer
4
+ --------------------------------------
5
+
6
+ Tiny demo viewer to view turtle graphics example scripts.
7
+
8
+ Quickly and dirtyly assembled by Gregor Lingl.
9
+ June, 2006
10
+
11
+ For more information see: turtledemo - Help
12
+
13
+ Have fun!
14
+ """
infer_4_47_1/lib/python3.10/turtledemo/__main__.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ ----------------------------------------------
5
+ turtleDemo - Help
6
+ ----------------------------------------------
7
+
8
+ This document has two sections:
9
+
10
+ (1) How to use the demo viewer
11
+ (2) How to add your own demos to the demo repository
12
+
13
+
14
+ (1) How to use the demo viewer.
15
+
16
+ Select a demoscript from the example menu.
17
+ The (syntax colored) source code appears in the left
18
+ source code window. IT CANNOT BE EDITED, but ONLY VIEWED!
19
+
20
+ The demo viewer windows can be resized. The divider between text
21
+ and canvas can be moved by grabbing it with the mouse. The text font
22
+ size can be changed from the menu and with Control/Command '-'/'+'.
23
+ It can also be changed on most systems with Control-mousewheel
24
+ when the mouse is over the text.
25
+
26
+ Press START button to start the demo.
27
+ Stop execution by pressing the STOP button.
28
+ Clear screen by pressing the CLEAR button.
29
+ Restart by pressing the START button again.
30
+
31
+ SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.
32
+
33
+ Press START button to start the demo.
34
+
35
+ - Until the EVENTLOOP is entered everything works
36
+ as in an ordinary demo script.
37
+
38
+ - When the EVENTLOOP is entered, you control the
39
+ application by using the mouse and/or keys (or it's
40
+ controlled by some timer events)
41
+ To stop it you can and must press the STOP button.
42
+
43
+ While the EVENTLOOP is running, the examples menu is disabled.
44
+
45
+ - Only after having pressed the STOP button, you may
46
+ restart it or choose another example script.
47
+
48
+ * * * * * * * *
49
+ In some rare situations there may occur interferences/conflicts
50
+ between events concerning the demo script and those concerning the
51
+ demo-viewer. (They run in the same process.) Strange behaviour may be
52
+ the consequence and in the worst case you must close and restart the
53
+ viewer.
54
+ * * * * * * * *
55
+
56
+
57
+ (2) How to add your own demos to the demo repository
58
+
59
+ - Place the file in the same directory as turtledemo/__main__.py
60
+ IMPORTANT! When imported, the demo should not modify the system
61
+ by calling functions in other modules, such as sys, tkinter, or
62
+ turtle. Global variables should be initialized in main().
63
+
64
+ - The code must contain a main() function which will
65
+ be executed by the viewer (see provided example scripts).
66
+ It may return a string which will be displayed in the Label below
67
+ the source code window (when execution has finished.)
68
+
69
+ - In order to run mydemo.py by itself, such as during development,
70
+ add the following at the end of the file:
71
+
72
+ if __name__ == '__main__':
73
+ main()
74
+ mainloop() # keep window open
75
+
76
+ python -m turtledemo.mydemo # will then run it
77
+
78
+ - If the demo is EVENT DRIVEN, main must return the string
79
+ "EVENTLOOP". This informs the demo viewer that the script is
80
+ still running and must be stopped by the user!
81
+
82
+ If an "EVENTLOOP" demo runs by itself, as with clock, which uses
83
+ ontimer, or minimal_hanoi, which loops by recursion, then the
84
+ code should catch the turtle.Terminator exception that will be
85
+ raised when the user presses the STOP button. (Paint is not such
86
+ a demo; it only acts in response to mouse clicks and movements.)
87
+ """
88
+ import sys
89
+ import os
90
+
91
+ from tkinter import *
92
+ from idlelib.colorizer import ColorDelegator, color_config
93
+ from idlelib.percolator import Percolator
94
+ from idlelib.textview import view_text
95
+ from turtledemo import __doc__ as about_turtledemo
96
+
97
+ import turtle
98
+
99
+ demo_dir = os.path.dirname(os.path.abspath(__file__))
100
+ darwin = sys.platform == 'darwin'
101
+
102
+ STARTUP = 1
103
+ READY = 2
104
+ RUNNING = 3
105
+ DONE = 4
106
+ EVENTDRIVEN = 5
107
+
108
+ menufont = ("Arial", 12, NORMAL)
109
+ btnfont = ("Arial", 12, 'bold')
110
+ txtfont = ['Lucida Console', 10, 'normal']
111
+
112
+ MINIMUM_FONT_SIZE = 6
113
+ MAXIMUM_FONT_SIZE = 100
114
+ font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]
115
+
116
+ def getExampleEntries():
117
+ return [entry[:-3] for entry in os.listdir(demo_dir) if
118
+ entry.endswith(".py") and entry[0] != '_']
119
+
120
+ help_entries = ( # (help_label, help_doc)
121
+ ('Turtledemo help', __doc__),
122
+ ('About turtledemo', about_turtledemo),
123
+ ('About turtle module', turtle.__doc__),
124
+ )
125
+
126
+
127
+ class DemoWindow(object):
128
+
129
+ def __init__(self, filename=None):
130
+ self.root = root = turtle._root = Tk()
131
+ root.title('Python turtle-graphics examples')
132
+ root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
133
+
134
+ if darwin:
135
+ import subprocess
136
+ # Make sure we are the currently activated OS X application
137
+ # so that our menu bar appears.
138
+ subprocess.run(
139
+ [
140
+ 'osascript',
141
+ '-e', 'tell application "System Events"',
142
+ '-e', 'set frontmost of the first process whose '
143
+ 'unix id is {} to true'.format(os.getpid()),
144
+ '-e', 'end tell',
145
+ ],
146
+ stderr=subprocess.DEVNULL,
147
+ stdout=subprocess.DEVNULL,)
148
+
149
+ root.grid_rowconfigure(0, weight=1)
150
+ root.grid_columnconfigure(0, weight=1)
151
+ root.grid_columnconfigure(1, minsize=90, weight=1)
152
+ root.grid_columnconfigure(2, minsize=90, weight=1)
153
+ root.grid_columnconfigure(3, minsize=90, weight=1)
154
+
155
+ self.mBar = Menu(root, relief=RAISED, borderwidth=2)
156
+ self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
157
+ label='Examples', underline=0)
158
+ self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
159
+ label='Fontsize', underline=0)
160
+ self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
161
+ label='Help', underline=0)
162
+ root['menu'] = self.mBar
163
+
164
+ pane = PanedWindow(orient=HORIZONTAL, sashwidth=5,
165
+ sashrelief=SOLID, bg='#ddd')
166
+ pane.add(self.makeTextFrame(pane))
167
+ pane.add(self.makeGraphFrame(pane))
168
+ pane.grid(row=0, columnspan=4, sticky='news')
169
+
170
+ self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
171
+ font=("Arial", 16, 'normal'), borderwidth=2,
172
+ relief=RIDGE)
173
+ if darwin: # Leave Mac button colors alone - #44254.
174
+ self.start_btn = Button(root, text=" START ", font=btnfont,
175
+ fg='#00cc22', command=self.startDemo)
176
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
177
+ fg='#00cc22', command=self.stopIt)
178
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
179
+ fg='#00cc22', command = self.clearCanvas)
180
+ else:
181
+ self.start_btn = Button(root, text=" START ", font=btnfont,
182
+ fg="white", disabledforeground = "#fed",
183
+ command=self.startDemo)
184
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
185
+ fg="white", disabledforeground = "#fed",
186
+ command=self.stopIt)
187
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
188
+ fg="white", disabledforeground="#fed",
189
+ command = self.clearCanvas)
190
+ self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
191
+ self.start_btn.grid(row=1, column=1, sticky='ew')
192
+ self.stop_btn.grid(row=1, column=2, sticky='ew')
193
+ self.clear_btn.grid(row=1, column=3, sticky='ew')
194
+
195
+ Percolator(self.text).insertfilter(ColorDelegator())
196
+ self.dirty = False
197
+ self.exitflag = False
198
+ if filename:
199
+ self.loadfile(filename)
200
+ self.configGUI(DISABLED, DISABLED, DISABLED,
201
+ "Choose example from menu", "black")
202
+ self.state = STARTUP
203
+
204
+
205
+ def onResize(self, event):
206
+ cwidth = self._canvas.winfo_width()
207
+ cheight = self._canvas.winfo_height()
208
+ self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
209
+ self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
210
+
211
+ def makeTextFrame(self, root):
212
+ self.text_frame = text_frame = Frame(root)
213
+ self.text = text = Text(text_frame, name='text', padx=5,
214
+ wrap='none', width=45)
215
+ color_config(text)
216
+
217
+ self.vbar = vbar = Scrollbar(text_frame, name='vbar')
218
+ vbar['command'] = text.yview
219
+ vbar.pack(side=LEFT, fill=Y)
220
+ self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
221
+ hbar['command'] = text.xview
222
+ hbar.pack(side=BOTTOM, fill=X)
223
+ text['yscrollcommand'] = vbar.set
224
+ text['xscrollcommand'] = hbar.set
225
+
226
+ text['font'] = tuple(txtfont)
227
+ shortcut = 'Command' if darwin else 'Control'
228
+ text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
229
+ text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
230
+ text.bind_all('<%s-equal>' % shortcut, self.increase_size)
231
+ text.bind_all('<%s-plus>' % shortcut, self.increase_size)
232
+ text.bind('<Control-MouseWheel>', self.update_mousewheel)
233
+ text.bind('<Control-Button-4>', self.increase_size)
234
+ text.bind('<Control-Button-5>', self.decrease_size)
235
+
236
+ text.pack(side=LEFT, fill=BOTH, expand=1)
237
+ return text_frame
238
+
239
+ def makeGraphFrame(self, root):
240
+ turtle._Screen._root = root
241
+ self.canvwidth = 1000
242
+ self.canvheight = 800
243
+ turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas(
244
+ root, 800, 600, self.canvwidth, self.canvheight)
245
+ canvas.adjustScrolls()
246
+ canvas._rootwindow.bind('<Configure>', self.onResize)
247
+ canvas._canvas['borderwidth'] = 0
248
+
249
+ self.screen = _s_ = turtle.Screen()
250
+ turtle.TurtleScreen.__init__(_s_, _s_._canvas)
251
+ self.scanvas = _s_._canvas
252
+ turtle.RawTurtle.screens = [_s_]
253
+ return canvas
254
+
255
+ def set_txtsize(self, size):
256
+ txtfont[1] = size
257
+ self.text['font'] = tuple(txtfont)
258
+ self.output_lbl['text'] = 'Font size %d' % size
259
+
260
+ def decrease_size(self, dummy=None):
261
+ self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
262
+ return 'break'
263
+
264
+ def increase_size(self, dummy=None):
265
+ self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
266
+ return 'break'
267
+
268
+ def update_mousewheel(self, event):
269
+ # For wheel up, event.delta = 120 on Windows, -1 on darwin.
270
+ # X-11 sends Control-Button-4 event instead.
271
+ if (event.delta < 0) == (not darwin):
272
+ return self.decrease_size()
273
+ else:
274
+ return self.increase_size()
275
+
276
+ def configGUI(self, start, stop, clear, txt="", color="blue"):
277
+ if darwin: # Leave Mac button colors alone - #44254.
278
+ self.start_btn.config(state=start)
279
+ self.stop_btn.config(state=stop)
280
+ self.clear_btn.config(state=clear)
281
+ else:
282
+ self.start_btn.config(state=start,
283
+ bg="#d00" if start == NORMAL else "#fca")
284
+ self.stop_btn.config(state=stop,
285
+ bg="#d00" if stop == NORMAL else "#fca")
286
+ self.clear_btn.config(state=clear,
287
+ bg="#d00" if clear == NORMAL else "#fca")
288
+ self.output_lbl.config(text=txt, fg=color)
289
+
290
+ def makeLoadDemoMenu(self, master):
291
+ menu = Menu(master)
292
+
293
+ for entry in getExampleEntries():
294
+ def load(entry=entry):
295
+ self.loadfile(entry)
296
+ menu.add_command(label=entry, underline=0,
297
+ font=menufont, command=load)
298
+ return menu
299
+
300
+ def makeFontMenu(self, master):
301
+ menu = Menu(master)
302
+ menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
303
+ font=menufont)
304
+ menu.add_command(label="Increase (C-'+')", command=self.increase_size,
305
+ font=menufont)
306
+ menu.add_separator()
307
+
308
+ for size in font_sizes:
309
+ def resize(size=size):
310
+ self.set_txtsize(size)
311
+ menu.add_command(label=str(size), underline=0,
312
+ font=menufont, command=resize)
313
+ return menu
314
+
315
+ def makeHelpMenu(self, master):
316
+ menu = Menu(master)
317
+
318
+ for help_label, help_file in help_entries:
319
+ def show(help_label=help_label, help_file=help_file):
320
+ view_text(self.root, help_label, help_file)
321
+ menu.add_command(label=help_label, font=menufont, command=show)
322
+ return menu
323
+
324
+ def refreshCanvas(self):
325
+ if self.dirty:
326
+ self.screen.clear()
327
+ self.dirty=False
328
+
329
+ def loadfile(self, filename):
330
+ self.clearCanvas()
331
+ turtle.TurtleScreen._RUNNING = False
332
+ modname = 'turtledemo.' + filename
333
+ __import__(modname)
334
+ self.module = sys.modules[modname]
335
+ with open(self.module.__file__, 'r') as f:
336
+ chars = f.read()
337
+ self.text.delete("1.0", "end")
338
+ self.text.insert("1.0", chars)
339
+ self.root.title(filename + " - a Python turtle graphics example")
340
+ self.configGUI(NORMAL, DISABLED, DISABLED,
341
+ "Press start button", "red")
342
+ self.state = READY
343
+
344
+ def startDemo(self):
345
+ self.refreshCanvas()
346
+ self.dirty = True
347
+ turtle.TurtleScreen._RUNNING = True
348
+ self.configGUI(DISABLED, NORMAL, DISABLED,
349
+ "demo running...", "black")
350
+ self.screen.clear()
351
+ self.screen.mode("standard")
352
+ self.state = RUNNING
353
+
354
+ try:
355
+ result = self.module.main()
356
+ if result == "EVENTLOOP":
357
+ self.state = EVENTDRIVEN
358
+ else:
359
+ self.state = DONE
360
+ except turtle.Terminator:
361
+ if self.root is None:
362
+ return
363
+ self.state = DONE
364
+ result = "stopped!"
365
+ if self.state == DONE:
366
+ self.configGUI(NORMAL, DISABLED, NORMAL,
367
+ result)
368
+ elif self.state == EVENTDRIVEN:
369
+ self.exitflag = True
370
+ self.configGUI(DISABLED, NORMAL, DISABLED,
371
+ "use mouse/keys or STOP", "red")
372
+
373
+ def clearCanvas(self):
374
+ self.refreshCanvas()
375
+ self.screen._delete("all")
376
+ self.scanvas.config(cursor="")
377
+ self.configGUI(NORMAL, DISABLED, DISABLED)
378
+
379
+ def stopIt(self):
380
+ if self.exitflag:
381
+ self.clearCanvas()
382
+ self.exitflag = False
383
+ self.configGUI(NORMAL, DISABLED, DISABLED,
384
+ "STOPPED!", "red")
385
+ turtle.TurtleScreen._RUNNING = False
386
+
387
+ def _destroy(self):
388
+ turtle.TurtleScreen._RUNNING = False
389
+ self.root.destroy()
390
+ self.root = None
391
+
392
+
393
+ def main():
394
+ demo = DemoWindow()
395
+ demo.root.mainloop()
396
+
397
+ if __name__ == '__main__':
398
+ main()
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (711 Bytes). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc ADDED
Binary file (3.15 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
infer_4_47_1/lib/python3.10/turtledemo/bytedesign.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_bytedesign.py
5
+
6
+ An example adapted from the example-suite
7
+ of PythonCard's turtle graphics.
8
+
9
+ It's based on an article in BYTE magazine
10
+ Problem Solving with Logo: Using Turtle
11
+ Graphics to Redraw a Design
12
+ November 1982, p. 118 - 134
13
+
14
+ -------------------------------------------
15
+
16
+ Due to the statement
17
+
18
+ t.delay(0)
19
+
20
+ in line 152, which sets the animation delay
21
+ to 0, this animation runs in "line per line"
22
+ mode as fast as possible.
23
+ """
24
+
25
+ from turtle import Turtle, mainloop
26
+ from time import perf_counter as clock
27
+
28
+ # wrapper for any additional drawing routines
29
+ # that need to know about each other
30
+ class Designer(Turtle):
31
+
32
+ def design(self, homePos, scale):
33
+ self.up()
34
+ for i in range(5):
35
+ self.forward(64.65 * scale)
36
+ self.down()
37
+ self.wheel(self.position(), scale)
38
+ self.up()
39
+ self.backward(64.65 * scale)
40
+ self.right(72)
41
+ self.up()
42
+ self.goto(homePos)
43
+ self.right(36)
44
+ self.forward(24.5 * scale)
45
+ self.right(198)
46
+ self.down()
47
+ self.centerpiece(46 * scale, 143.4, scale)
48
+ self.getscreen().tracer(True)
49
+
50
+ def wheel(self, initpos, scale):
51
+ self.right(54)
52
+ for i in range(4):
53
+ self.pentpiece(initpos, scale)
54
+ self.down()
55
+ self.left(36)
56
+ for i in range(5):
57
+ self.tripiece(initpos, scale)
58
+ self.left(36)
59
+ for i in range(5):
60
+ self.down()
61
+ self.right(72)
62
+ self.forward(28 * scale)
63
+ self.up()
64
+ self.backward(28 * scale)
65
+ self.left(54)
66
+ self.getscreen().update()
67
+
68
+ def tripiece(self, initpos, scale):
69
+ oldh = self.heading()
70
+ self.down()
71
+ self.backward(2.5 * scale)
72
+ self.tripolyr(31.5 * scale, scale)
73
+ self.up()
74
+ self.goto(initpos)
75
+ self.setheading(oldh)
76
+ self.down()
77
+ self.backward(2.5 * scale)
78
+ self.tripolyl(31.5 * scale, scale)
79
+ self.up()
80
+ self.goto(initpos)
81
+ self.setheading(oldh)
82
+ self.left(72)
83
+ self.getscreen().update()
84
+
85
+ def pentpiece(self, initpos, scale):
86
+ oldh = self.heading()
87
+ self.up()
88
+ self.forward(29 * scale)
89
+ self.down()
90
+ for i in range(5):
91
+ self.forward(18 * scale)
92
+ self.right(72)
93
+ self.pentr(18 * scale, 75, scale)
94
+ self.up()
95
+ self.goto(initpos)
96
+ self.setheading(oldh)
97
+ self.forward(29 * scale)
98
+ self.down()
99
+ for i in range(5):
100
+ self.forward(18 * scale)
101
+ self.right(72)
102
+ self.pentl(18 * scale, 75, scale)
103
+ self.up()
104
+ self.goto(initpos)
105
+ self.setheading(oldh)
106
+ self.left(72)
107
+ self.getscreen().update()
108
+
109
+ def pentl(self, side, ang, scale):
110
+ if side < (2 * scale): return
111
+ self.forward(side)
112
+ self.left(ang)
113
+ self.pentl(side - (.38 * scale), ang, scale)
114
+
115
+ def pentr(self, side, ang, scale):
116
+ if side < (2 * scale): return
117
+ self.forward(side)
118
+ self.right(ang)
119
+ self.pentr(side - (.38 * scale), ang, scale)
120
+
121
+ def tripolyr(self, side, scale):
122
+ if side < (4 * scale): return
123
+ self.forward(side)
124
+ self.right(111)
125
+ self.forward(side / 1.78)
126
+ self.right(111)
127
+ self.forward(side / 1.3)
128
+ self.right(146)
129
+ self.tripolyr(side * .75, scale)
130
+
131
+ def tripolyl(self, side, scale):
132
+ if side < (4 * scale): return
133
+ self.forward(side)
134
+ self.left(111)
135
+ self.forward(side / 1.78)
136
+ self.left(111)
137
+ self.forward(side / 1.3)
138
+ self.left(146)
139
+ self.tripolyl(side * .75, scale)
140
+
141
+ def centerpiece(self, s, a, scale):
142
+ self.forward(s); self.left(a)
143
+ if s < (7.5 * scale):
144
+ return
145
+ self.centerpiece(s - (1.2 * scale), a, scale)
146
+
147
+ def main():
148
+ t = Designer()
149
+ t.speed(0)
150
+ t.hideturtle()
151
+ t.getscreen().delay(0)
152
+ t.getscreen().tracer(0)
153
+ at = clock()
154
+ t.design(t.position(), 2)
155
+ et = clock()
156
+ return "runtime: %.2f sec." % (et-at)
157
+
158
+ if __name__ == '__main__':
159
+ msg = main()
160
+ print(msg)
161
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/chaos.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: tdemo_chaos.py
2
+ # Author: Gregor Lingl
3
+ # Date: 2009-06-24
4
+
5
+ # A demonstration of chaos
6
+
7
+ from turtle import *
8
+
9
+ N = 80
10
+
11
+ def f(x):
12
+ return 3.9*x*(1-x)
13
+
14
+ def g(x):
15
+ return 3.9*(x-x**2)
16
+
17
+ def h(x):
18
+ return 3.9*x-3.9*x*x
19
+
20
+ def jumpto(x, y):
21
+ penup(); goto(x,y)
22
+
23
+ def line(x1, y1, x2, y2):
24
+ jumpto(x1, y1)
25
+ pendown()
26
+ goto(x2, y2)
27
+
28
+ def coosys():
29
+ line(-1, 0, N+1, 0)
30
+ line(0, -0.1, 0, 1.1)
31
+
32
+ def plot(fun, start, color):
33
+ pencolor(color)
34
+ x = start
35
+ jumpto(0, x)
36
+ pendown()
37
+ dot(5)
38
+ for i in range(N):
39
+ x=fun(x)
40
+ goto(i+1,x)
41
+ dot(5)
42
+
43
+ def main():
44
+ reset()
45
+ setworldcoordinates(-1.0,-0.1, N+1, 1.1)
46
+ speed(0)
47
+ hideturtle()
48
+ coosys()
49
+ plot(f, 0.35, "blue")
50
+ plot(g, 0.35, "green")
51
+ plot(h, 0.35, "red")
52
+ # Now zoom in:
53
+ for s in range(100):
54
+ setworldcoordinates(0.5*s,-0.1, N+1, 1.1)
55
+ return "Done!"
56
+
57
+ if __name__ == "__main__":
58
+ main()
59
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/clock.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: cp1252 -*-
3
+ """ turtle-example-suite:
4
+
5
+ tdemo_clock.py
6
+
7
+ Enhanced clock-program, showing date
8
+ and time
9
+ ------------------------------------
10
+ Press STOP to exit the program!
11
+ ------------------------------------
12
+ """
13
+ from turtle import *
14
+ from datetime import datetime
15
+
16
+ def jump(distanz, winkel=0):
17
+ penup()
18
+ right(winkel)
19
+ forward(distanz)
20
+ left(winkel)
21
+ pendown()
22
+
23
+ def hand(laenge, spitze):
24
+ fd(laenge*1.15)
25
+ rt(90)
26
+ fd(spitze/2.0)
27
+ lt(120)
28
+ fd(spitze)
29
+ lt(120)
30
+ fd(spitze)
31
+ lt(120)
32
+ fd(spitze/2.0)
33
+
34
+ def make_hand_shape(name, laenge, spitze):
35
+ reset()
36
+ jump(-laenge*0.15)
37
+ begin_poly()
38
+ hand(laenge, spitze)
39
+ end_poly()
40
+ hand_form = get_poly()
41
+ register_shape(name, hand_form)
42
+
43
+ def clockface(radius):
44
+ reset()
45
+ pensize(7)
46
+ for i in range(60):
47
+ jump(radius)
48
+ if i % 5 == 0:
49
+ fd(25)
50
+ jump(-radius-25)
51
+ else:
52
+ dot(3)
53
+ jump(-radius)
54
+ rt(6)
55
+
56
+ def setup():
57
+ global second_hand, minute_hand, hour_hand, writer
58
+ mode("logo")
59
+ make_hand_shape("second_hand", 125, 25)
60
+ make_hand_shape("minute_hand", 130, 25)
61
+ make_hand_shape("hour_hand", 90, 25)
62
+ clockface(160)
63
+ second_hand = Turtle()
64
+ second_hand.shape("second_hand")
65
+ second_hand.color("gray20", "gray80")
66
+ minute_hand = Turtle()
67
+ minute_hand.shape("minute_hand")
68
+ minute_hand.color("blue1", "red1")
69
+ hour_hand = Turtle()
70
+ hour_hand.shape("hour_hand")
71
+ hour_hand.color("blue3", "red3")
72
+ for hand in second_hand, minute_hand, hour_hand:
73
+ hand.resizemode("user")
74
+ hand.shapesize(1, 1, 3)
75
+ hand.speed(0)
76
+ ht()
77
+ writer = Turtle()
78
+ #writer.mode("logo")
79
+ writer.ht()
80
+ writer.pu()
81
+ writer.bk(85)
82
+
83
+ def wochentag(t):
84
+ wochentag = ["Monday", "Tuesday", "Wednesday",
85
+ "Thursday", "Friday", "Saturday", "Sunday"]
86
+ return wochentag[t.weekday()]
87
+
88
+ def datum(z):
89
+ monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
90
+ "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
91
+ j = z.year
92
+ m = monat[z.month - 1]
93
+ t = z.day
94
+ return "%s %d %d" % (m, t, j)
95
+
96
+ def tick():
97
+ t = datetime.today()
98
+ sekunde = t.second + t.microsecond*0.000001
99
+ minute = t.minute + sekunde/60.0
100
+ stunde = t.hour + minute/60.0
101
+ try:
102
+ tracer(False) # Terminator can occur here
103
+ writer.clear()
104
+ writer.home()
105
+ writer.forward(65)
106
+ writer.write(wochentag(t),
107
+ align="center", font=("Courier", 14, "bold"))
108
+ writer.back(150)
109
+ writer.write(datum(t),
110
+ align="center", font=("Courier", 14, "bold"))
111
+ writer.forward(85)
112
+ second_hand.setheading(6*sekunde) # or here
113
+ minute_hand.setheading(6*minute)
114
+ hour_hand.setheading(30*stunde)
115
+ tracer(True)
116
+ ontimer(tick, 100)
117
+ except Terminator:
118
+ pass # turtledemo user pressed STOP
119
+
120
+ def main():
121
+ tracer(False)
122
+ setup()
123
+ tracer(True)
124
+ tick()
125
+ return "EVENTLOOP"
126
+
127
+ if __name__ == "__main__":
128
+ mode("logo")
129
+ msg = main()
130
+ print(msg)
131
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/colormixer.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # colormixer
2
+
3
+ from turtle import Screen, Turtle, mainloop
4
+
5
+ class ColorTurtle(Turtle):
6
+
7
+ def __init__(self, x, y):
8
+ Turtle.__init__(self)
9
+ self.shape("turtle")
10
+ self.resizemode("user")
11
+ self.shapesize(3,3,5)
12
+ self.pensize(10)
13
+ self._color = [0,0,0]
14
+ self.x = x
15
+ self._color[x] = y
16
+ self.color(self._color)
17
+ self.speed(0)
18
+ self.left(90)
19
+ self.pu()
20
+ self.goto(x,0)
21
+ self.pd()
22
+ self.sety(1)
23
+ self.pu()
24
+ self.sety(y)
25
+ self.pencolor("gray25")
26
+ self.ondrag(self.shift)
27
+
28
+ def shift(self, x, y):
29
+ self.sety(max(0,min(y,1)))
30
+ self._color[self.x] = self.ycor()
31
+ self.fillcolor(self._color)
32
+ setbgcolor()
33
+
34
+ def setbgcolor():
35
+ screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())
36
+
37
+ def main():
38
+ global screen, red, green, blue
39
+ screen = Screen()
40
+ screen.delay(0)
41
+ screen.setworldcoordinates(-1, -0.3, 3, 1.3)
42
+
43
+ red = ColorTurtle(0, .5)
44
+ green = ColorTurtle(1, .5)
45
+ blue = ColorTurtle(2, .5)
46
+ setbgcolor()
47
+
48
+ writer = Turtle()
49
+ writer.ht()
50
+ writer.pu()
51
+ writer.goto(1,1.15)
52
+ writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
53
+ return "EVENTLOOP"
54
+
55
+ if __name__ == "__main__":
56
+ msg = main()
57
+ print(msg)
58
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/forest.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtlegraphics-example-suite:
3
+
4
+ tdemo_forest.py
5
+
6
+ Displays a 'forest' of 3 breadth-first-trees
7
+ similar to the one in tree.
8
+ For further remarks see tree.py
9
+
10
+ This example is a 'breadth-first'-rewrite of
11
+ a Logo program written by Erich Neuwirth. See
12
+ http://homepage.univie.ac.at/erich.neuwirth/
13
+ """
14
+ from turtle import Turtle, colormode, tracer, mainloop
15
+ from random import randrange
16
+ from time import perf_counter as clock
17
+
18
+ def symRandom(n):
19
+ return randrange(-n,n+1)
20
+
21
+ def randomize( branchlist, angledist, sizedist ):
22
+ return [ (angle+symRandom(angledist),
23
+ sizefactor*1.01**symRandom(sizedist))
24
+ for angle, sizefactor in branchlist ]
25
+
26
+ def randomfd( t, distance, parts, angledist ):
27
+ for i in range(parts):
28
+ t.left(symRandom(angledist))
29
+ t.forward( (1.0 * distance)/parts )
30
+
31
+ def tree(tlist, size, level, widthfactor, branchlists, angledist=10, sizedist=5):
32
+ # benutzt Liste von turtles und Liste von Zweiglisten,
33
+ # fuer jede turtle eine!
34
+ if level > 0:
35
+ lst = []
36
+ brs = []
37
+ for t, branchlist in list(zip(tlist,branchlists)):
38
+ t.pensize( size * widthfactor )
39
+ t.pencolor( 255 - (180 - 11 * level + symRandom(15)),
40
+ 180 - 11 * level + symRandom(15),
41
+ 0 )
42
+ t.pendown()
43
+ randomfd(t, size, level, angledist )
44
+ yield 1
45
+ for angle, sizefactor in branchlist:
46
+ t.left(angle)
47
+ lst.append(t.clone())
48
+ brs.append(randomize(branchlist, angledist, sizedist))
49
+ t.right(angle)
50
+ for x in tree(lst, size*sizefactor, level-1, widthfactor, brs,
51
+ angledist, sizedist):
52
+ yield None
53
+
54
+
55
+ def start(t,x,y):
56
+ colormode(255)
57
+ t.reset()
58
+ t.speed(0)
59
+ t.hideturtle()
60
+ t.left(90)
61
+ t.penup()
62
+ t.setpos(x,y)
63
+ t.pendown()
64
+
65
+ def doit1(level, pen):
66
+ pen.hideturtle()
67
+ start(pen, 20, -208)
68
+ t = tree( [pen], 80, level, 0.1, [[ (45,0.69), (0,0.65), (-45,0.71) ]] )
69
+ return t
70
+
71
+ def doit2(level, pen):
72
+ pen.hideturtle()
73
+ start(pen, -135, -130)
74
+ t = tree( [pen], 120, level, 0.1, [[ (45,0.69), (-45,0.71) ]] )
75
+ return t
76
+
77
+ def doit3(level, pen):
78
+ pen.hideturtle()
79
+ start(pen, 190, -90)
80
+ t = tree( [pen], 100, level, 0.1, [[ (45,0.7), (0,0.72), (-45,0.65) ]] )
81
+ return t
82
+
83
+ # Hier 3 Baumgeneratoren:
84
+ def main():
85
+ p = Turtle()
86
+ p.ht()
87
+ tracer(75,0)
88
+ u = doit1(6, Turtle(undobuffersize=1))
89
+ s = doit2(7, Turtle(undobuffersize=1))
90
+ t = doit3(5, Turtle(undobuffersize=1))
91
+ a = clock()
92
+ while True:
93
+ done = 0
94
+ for b in u,s,t:
95
+ try:
96
+ b.__next__()
97
+ except:
98
+ done += 1
99
+ if done == 3:
100
+ break
101
+
102
+ tracer(1,10)
103
+ b = clock()
104
+ return "runtime: %.2f sec." % (b-a)
105
+
106
+ if __name__ == '__main__':
107
+ main()
108
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/fractalcurves.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_fractalCurves.py
5
+
6
+ This program draws two fractal-curve-designs:
7
+ (1) A hilbert curve (in a box)
8
+ (2) A combination of Koch-curves.
9
+
10
+ The CurvesTurtle class and the fractal-curve-
11
+ methods are taken from the PythonCard example
12
+ scripts for turtle-graphics.
13
+ """
14
+ from turtle import *
15
+ from time import sleep, perf_counter as clock
16
+
17
+ class CurvesTurtle(Pen):
18
+ # example derived from
19
+ # Turtle Geometry: The Computer as a Medium for Exploring Mathematics
20
+ # by Harold Abelson and Andrea diSessa
21
+ # p. 96-98
22
+ def hilbert(self, size, level, parity):
23
+ if level == 0:
24
+ return
25
+ # rotate and draw first subcurve with opposite parity to big curve
26
+ self.left(parity * 90)
27
+ self.hilbert(size, level - 1, -parity)
28
+ # interface to and draw second subcurve with same parity as big curve
29
+ self.forward(size)
30
+ self.right(parity * 90)
31
+ self.hilbert(size, level - 1, parity)
32
+ # third subcurve
33
+ self.forward(size)
34
+ self.hilbert(size, level - 1, parity)
35
+ # fourth subcurve
36
+ self.right(parity * 90)
37
+ self.forward(size)
38
+ self.hilbert(size, level - 1, -parity)
39
+ # a final turn is needed to make the turtle
40
+ # end up facing outward from the large square
41
+ self.left(parity * 90)
42
+
43
+ # Visual Modeling with Logo: A Structural Approach to Seeing
44
+ # by James Clayson
45
+ # Koch curve, after Helge von Koch who introduced this geometric figure in 1904
46
+ # p. 146
47
+ def fractalgon(self, n, rad, lev, dir):
48
+ import math
49
+
50
+ # if dir = 1 turn outward
51
+ # if dir = -1 turn inward
52
+ edge = 2 * rad * math.sin(math.pi / n)
53
+ self.pu()
54
+ self.fd(rad)
55
+ self.pd()
56
+ self.rt(180 - (90 * (n - 2) / n))
57
+ for i in range(n):
58
+ self.fractal(edge, lev, dir)
59
+ self.rt(360 / n)
60
+ self.lt(180 - (90 * (n - 2) / n))
61
+ self.pu()
62
+ self.bk(rad)
63
+ self.pd()
64
+
65
+ # p. 146
66
+ def fractal(self, dist, depth, dir):
67
+ if depth < 1:
68
+ self.fd(dist)
69
+ return
70
+ self.fractal(dist / 3, depth - 1, dir)
71
+ self.lt(60 * dir)
72
+ self.fractal(dist / 3, depth - 1, dir)
73
+ self.rt(120 * dir)
74
+ self.fractal(dist / 3, depth - 1, dir)
75
+ self.lt(60 * dir)
76
+ self.fractal(dist / 3, depth - 1, dir)
77
+
78
+ def main():
79
+ ft = CurvesTurtle()
80
+
81
+ ft.reset()
82
+ ft.speed(0)
83
+ ft.ht()
84
+ ft.getscreen().tracer(1,0)
85
+ ft.pu()
86
+
87
+ size = 6
88
+ ft.setpos(-33*size, -32*size)
89
+ ft.pd()
90
+
91
+ ta=clock()
92
+ ft.fillcolor("red")
93
+ ft.begin_fill()
94
+ ft.fd(size)
95
+
96
+ ft.hilbert(size, 6, 1)
97
+
98
+ # frame
99
+ ft.fd(size)
100
+ for i in range(3):
101
+ ft.lt(90)
102
+ ft.fd(size*(64+i%2))
103
+ ft.pu()
104
+ for i in range(2):
105
+ ft.fd(size)
106
+ ft.rt(90)
107
+ ft.pd()
108
+ for i in range(4):
109
+ ft.fd(size*(66+i%2))
110
+ ft.rt(90)
111
+ ft.end_fill()
112
+ tb=clock()
113
+ res = "Hilbert: %.2fsec. " % (tb-ta)
114
+
115
+ sleep(3)
116
+
117
+ ft.reset()
118
+ ft.speed(0)
119
+ ft.ht()
120
+ ft.getscreen().tracer(1,0)
121
+
122
+ ta=clock()
123
+ ft.color("black", "blue")
124
+ ft.begin_fill()
125
+ ft.fractalgon(3, 250, 4, 1)
126
+ ft.end_fill()
127
+ ft.begin_fill()
128
+ ft.color("red")
129
+ ft.fractalgon(3, 200, 4, -1)
130
+ ft.end_fill()
131
+ tb=clock()
132
+ res += "Koch: %.2fsec." % (tb-ta)
133
+ return res
134
+
135
+ if __name__ == '__main__':
136
+ msg = main()
137
+ print(msg)
138
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/minimal_hanoi.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_minimal_hanoi.py
5
+
6
+ A minimal 'Towers of Hanoi' animation:
7
+ A tower of 6 discs is transferred from the
8
+ left to the right peg.
9
+
10
+ An imho quite elegant and concise
11
+ implementation using a tower class, which
12
+ is derived from the built-in type list.
13
+
14
+ Discs are turtles with shape "square", but
15
+ stretched to rectangles by shapesize()
16
+ ---------------------------------------
17
+ To exit press STOP button
18
+ ---------------------------------------
19
+ """
20
+ from turtle import *
21
+
22
+ class Disc(Turtle):
23
+ def __init__(self, n):
24
+ Turtle.__init__(self, shape="square", visible=False)
25
+ self.pu()
26
+ self.shapesize(1.5, n*1.5, 2) # square-->rectangle
27
+ self.fillcolor(n/6., 0, 1-n/6.)
28
+ self.st()
29
+
30
+ class Tower(list):
31
+ "Hanoi tower, a subclass of built-in type list"
32
+ def __init__(self, x):
33
+ "create an empty tower. x is x-position of peg"
34
+ self.x = x
35
+ def push(self, d):
36
+ d.setx(self.x)
37
+ d.sety(-150+34*len(self))
38
+ self.append(d)
39
+ def pop(self):
40
+ d = list.pop(self)
41
+ d.sety(150)
42
+ return d
43
+
44
+ def hanoi(n, from_, with_, to_):
45
+ if n > 0:
46
+ hanoi(n-1, from_, to_, with_)
47
+ to_.push(from_.pop())
48
+ hanoi(n-1, with_, from_, to_)
49
+
50
+ def play():
51
+ onkey(None,"space")
52
+ clear()
53
+ try:
54
+ hanoi(6, t1, t2, t3)
55
+ write("press STOP button to exit",
56
+ align="center", font=("Courier", 16, "bold"))
57
+ except Terminator:
58
+ pass # turtledemo user pressed STOP
59
+
60
+ def main():
61
+ global t1, t2, t3
62
+ ht(); penup(); goto(0, -225) # writer turtle
63
+ t1 = Tower(-250)
64
+ t2 = Tower(0)
65
+ t3 = Tower(250)
66
+ # make tower of 6 discs
67
+ for i in range(6,0,-1):
68
+ t1.push(Disc(i))
69
+ # prepare spartanic user interface ;-)
70
+ write("press spacebar to start game",
71
+ align="center", font=("Courier", 16, "bold"))
72
+ onkey(play, "space")
73
+ listen()
74
+ return "EVENTLOOP"
75
+
76
+ if __name__=="__main__":
77
+ msg = main()
78
+ print(msg)
79
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/nim.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_nim.py
4
+
5
+ Play nim against the computer. The player
6
+ who takes the last stick is the winner.
7
+
8
+ Implements the model-view-controller
9
+ design pattern.
10
+ """
11
+
12
+
13
+ import turtle
14
+ import random
15
+ import time
16
+
17
+ SCREENWIDTH = 640
18
+ SCREENHEIGHT = 480
19
+
20
+ MINSTICKS = 7
21
+ MAXSTICKS = 31
22
+
23
+ HUNIT = SCREENHEIGHT // 12
24
+ WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2)
25
+
26
+ SCOLOR = (63, 63, 31)
27
+ HCOLOR = (255, 204, 204)
28
+ COLOR = (204, 204, 255)
29
+
30
+ def randomrow():
31
+ return random.randint(MINSTICKS, MAXSTICKS)
32
+
33
+ def computerzug(state):
34
+ xored = state[0] ^ state[1] ^ state[2]
35
+ if xored == 0:
36
+ return randommove(state)
37
+ for z in range(3):
38
+ s = state[z] ^ xored
39
+ if s <= state[z]:
40
+ move = (z, s)
41
+ return move
42
+
43
+ def randommove(state):
44
+ m = max(state)
45
+ while True:
46
+ z = random.randint(0,2)
47
+ if state[z] > (m > 1):
48
+ break
49
+ rand = random.randint(m > 1, state[z]-1)
50
+ return z, rand
51
+
52
+
53
+ class NimModel(object):
54
+ def __init__(self, game):
55
+ self.game = game
56
+
57
+ def setup(self):
58
+ if self.game.state not in [Nim.CREATED, Nim.OVER]:
59
+ return
60
+ self.sticks = [randomrow(), randomrow(), randomrow()]
61
+ self.player = 0
62
+ self.winner = None
63
+ self.game.view.setup()
64
+ self.game.state = Nim.RUNNING
65
+
66
+ def move(self, row, col):
67
+ maxspalte = self.sticks[row]
68
+ self.sticks[row] = col
69
+ self.game.view.notify_move(row, col, maxspalte, self.player)
70
+ if self.game_over():
71
+ self.game.state = Nim.OVER
72
+ self.winner = self.player
73
+ self.game.view.notify_over()
74
+ elif self.player == 0:
75
+ self.player = 1
76
+ row, col = computerzug(self.sticks)
77
+ self.move(row, col)
78
+ self.player = 0
79
+
80
+ def game_over(self):
81
+ return self.sticks == [0, 0, 0]
82
+
83
+ def notify_move(self, row, col):
84
+ if self.sticks[row] <= col:
85
+ return
86
+ self.move(row, col)
87
+
88
+
89
+ class Stick(turtle.Turtle):
90
+ def __init__(self, row, col, game):
91
+ turtle.Turtle.__init__(self, visible=False)
92
+ self.row = row
93
+ self.col = col
94
+ self.game = game
95
+ x, y = self.coords(row, col)
96
+ self.shape("square")
97
+ self.shapesize(HUNIT/10.0, WUNIT/20.0)
98
+ self.speed(0)
99
+ self.pu()
100
+ self.goto(x,y)
101
+ self.color("white")
102
+ self.showturtle()
103
+
104
+ def coords(self, row, col):
105
+ packet, remainder = divmod(col, 5)
106
+ x = (3 + 11 * packet + 2 * remainder) * WUNIT
107
+ y = (2 + 3 * row) * HUNIT
108
+ return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2
109
+
110
+ def makemove(self, x, y):
111
+ if self.game.state != Nim.RUNNING:
112
+ return
113
+ self.game.controller.notify_move(self.row, self.col)
114
+
115
+
116
+ class NimView(object):
117
+ def __init__(self, game):
118
+ self.game = game
119
+ self.screen = game.screen
120
+ self.model = game.model
121
+ self.screen.colormode(255)
122
+ self.screen.tracer(False)
123
+ self.screen.bgcolor((240, 240, 255))
124
+ self.writer = turtle.Turtle(visible=False)
125
+ self.writer.pu()
126
+ self.writer.speed(0)
127
+ self.sticks = {}
128
+ for row in range(3):
129
+ for col in range(MAXSTICKS):
130
+ self.sticks[(row, col)] = Stick(row, col, game)
131
+ self.display("... a moment please ...")
132
+ self.screen.tracer(True)
133
+
134
+ def display(self, msg1, msg2=None):
135
+ self.screen.tracer(False)
136
+ self.writer.clear()
137
+ if msg2 is not None:
138
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 48)
139
+ self.writer.pencolor("red")
140
+ self.writer.write(msg2, align="center", font=("Courier",18,"bold"))
141
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 20)
142
+ self.writer.pencolor("black")
143
+ self.writer.write(msg1, align="center", font=("Courier",14,"bold"))
144
+ self.screen.tracer(True)
145
+
146
+ def setup(self):
147
+ self.screen.tracer(False)
148
+ for row in range(3):
149
+ for col in range(self.model.sticks[row]):
150
+ self.sticks[(row, col)].color(SCOLOR)
151
+ for row in range(3):
152
+ for col in range(self.model.sticks[row], MAXSTICKS):
153
+ self.sticks[(row, col)].color("white")
154
+ self.display("Your turn! Click leftmost stick to remove.")
155
+ self.screen.tracer(True)
156
+
157
+ def notify_move(self, row, col, maxspalte, player):
158
+ if player == 0:
159
+ farbe = HCOLOR
160
+ for s in range(col, maxspalte):
161
+ self.sticks[(row, s)].color(farbe)
162
+ else:
163
+ self.display(" ... thinking ... ")
164
+ time.sleep(0.5)
165
+ self.display(" ... thinking ... aaah ...")
166
+ farbe = COLOR
167
+ for s in range(maxspalte-1, col-1, -1):
168
+ time.sleep(0.2)
169
+ self.sticks[(row, s)].color(farbe)
170
+ self.display("Your turn! Click leftmost stick to remove.")
171
+
172
+ def notify_over(self):
173
+ if self.game.model.winner == 0:
174
+ msg2 = "Congrats. You're the winner!!!"
175
+ else:
176
+ msg2 = "Sorry, the computer is the winner."
177
+ self.display("To play again press space bar. To leave press ESC.", msg2)
178
+
179
+ def clear(self):
180
+ if self.game.state == Nim.OVER:
181
+ self.screen.clear()
182
+
183
+
184
+ class NimController(object):
185
+
186
+ def __init__(self, game):
187
+ self.game = game
188
+ self.sticks = game.view.sticks
189
+ self.BUSY = False
190
+ for stick in self.sticks.values():
191
+ stick.onclick(stick.makemove)
192
+ self.game.screen.onkey(self.game.model.setup, "space")
193
+ self.game.screen.onkey(self.game.view.clear, "Escape")
194
+ self.game.view.display("Press space bar to start game")
195
+ self.game.screen.listen()
196
+
197
+ def notify_move(self, row, col):
198
+ if self.BUSY:
199
+ return
200
+ self.BUSY = True
201
+ self.game.model.notify_move(row, col)
202
+ self.BUSY = False
203
+
204
+
205
+ class Nim(object):
206
+ CREATED = 0
207
+ RUNNING = 1
208
+ OVER = 2
209
+ def __init__(self, screen):
210
+ self.state = Nim.CREATED
211
+ self.screen = screen
212
+ self.model = NimModel(self)
213
+ self.view = NimView(self)
214
+ self.controller = NimController(self)
215
+
216
+
217
+ def main():
218
+ mainscreen = turtle.Screen()
219
+ mainscreen.mode("standard")
220
+ mainscreen.setup(SCREENWIDTH, SCREENHEIGHT)
221
+ nim = Nim(mainscreen)
222
+ return "EVENTLOOP"
223
+
224
+ if __name__ == "__main__":
225
+ main()
226
+ turtle.mainloop()
infer_4_47_1/lib/python3.10/turtledemo/paint.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_paint.py
5
+
6
+ A simple event-driven paint program
7
+
8
+ - left mouse button moves turtle
9
+ - middle mouse button changes color
10
+ - right mouse button toggles between pen up
11
+ (no line drawn when the turtle moves) and
12
+ pen down (line is drawn). If pen up follows
13
+ at least two pen-down moves, the polygon that
14
+ includes the starting point is filled.
15
+ -------------------------------------------
16
+ Play around by clicking into the canvas
17
+ using all three mouse buttons.
18
+ -------------------------------------------
19
+ To exit press STOP button
20
+ -------------------------------------------
21
+ """
22
+ from turtle import *
23
+
24
+ def switchupdown(x=0, y=0):
25
+ if pen()["pendown"]:
26
+ end_fill()
27
+ up()
28
+ else:
29
+ down()
30
+ begin_fill()
31
+
32
+ def changecolor(x=0, y=0):
33
+ global colors
34
+ colors = colors[1:]+colors[:1]
35
+ color(colors[0])
36
+
37
+ def main():
38
+ global colors
39
+ shape("circle")
40
+ resizemode("user")
41
+ shapesize(.5)
42
+ width(3)
43
+ colors=["red", "green", "blue", "yellow"]
44
+ color(colors[0])
45
+ switchupdown()
46
+ onscreenclick(goto,1)
47
+ onscreenclick(changecolor,2)
48
+ onscreenclick(switchupdown,3)
49
+ return "EVENTLOOP"
50
+
51
+ if __name__ == "__main__":
52
+ msg = main()
53
+ print(msg)
54
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/peace.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_peace.py
5
+
6
+ A simple drawing suitable as a beginner's
7
+ programming example. Aside from the
8
+ peacecolors assignment and the for loop,
9
+ it only uses turtle commands.
10
+ """
11
+
12
+ from turtle import *
13
+
14
+ def main():
15
+ peacecolors = ("red3", "orange", "yellow",
16
+ "seagreen4", "orchid4",
17
+ "royalblue1", "dodgerblue4")
18
+
19
+ reset()
20
+ Screen()
21
+ up()
22
+ goto(-320,-195)
23
+ width(70)
24
+
25
+ for pcolor in peacecolors:
26
+ color(pcolor)
27
+ down()
28
+ forward(640)
29
+ up()
30
+ backward(640)
31
+ left(90)
32
+ forward(66)
33
+ right(90)
34
+
35
+ width(25)
36
+ color("white")
37
+ goto(0,-170)
38
+ down()
39
+
40
+ circle(170)
41
+ left(90)
42
+ forward(340)
43
+ up()
44
+ left(180)
45
+ forward(170)
46
+ right(45)
47
+ down()
48
+ forward(170)
49
+ up()
50
+ backward(170)
51
+ left(90)
52
+ down()
53
+ forward(170)
54
+ up()
55
+
56
+ goto(0,300) # vanish if hideturtle() is not available ;-)
57
+ return "Done!"
58
+
59
+ if __name__ == "__main__":
60
+ main()
61
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/planet_and_moon.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_planets_and_moon.py
5
+
6
+ Gravitational system simulation using the
7
+ approximation method from Feynman-lectures,
8
+ p.9-8, using turtlegraphics.
9
+
10
+ Example: heavy central body, light planet,
11
+ very light moon!
12
+ Planet has a circular orbit, moon a stable
13
+ orbit around the planet.
14
+
15
+ You can hold the movement temporarily by
16
+ pressing the left mouse button with the
17
+ mouse over the scrollbar of the canvas.
18
+
19
+ """
20
+ from turtle import Shape, Turtle, mainloop, Vec2D as Vec
21
+
22
+ G = 8
23
+
24
+ class GravSys(object):
25
+ def __init__(self):
26
+ self.planets = []
27
+ self.t = 0
28
+ self.dt = 0.01
29
+ def init(self):
30
+ for p in self.planets:
31
+ p.init()
32
+ def start(self):
33
+ for i in range(10000):
34
+ self.t += self.dt
35
+ for p in self.planets:
36
+ p.step()
37
+
38
+ class Star(Turtle):
39
+ def __init__(self, m, x, v, gravSys, shape):
40
+ Turtle.__init__(self, shape=shape)
41
+ self.penup()
42
+ self.m = m
43
+ self.setpos(x)
44
+ self.v = v
45
+ gravSys.planets.append(self)
46
+ self.gravSys = gravSys
47
+ self.resizemode("user")
48
+ self.pendown()
49
+ def init(self):
50
+ dt = self.gravSys.dt
51
+ self.a = self.acc()
52
+ self.v = self.v + 0.5*dt*self.a
53
+ def acc(self):
54
+ a = Vec(0,0)
55
+ for planet in self.gravSys.planets:
56
+ if planet != self:
57
+ v = planet.pos()-self.pos()
58
+ a += (G*planet.m/abs(v)**3)*v
59
+ return a
60
+ def step(self):
61
+ dt = self.gravSys.dt
62
+ self.setpos(self.pos() + dt*self.v)
63
+ if self.gravSys.planets.index(self) != 0:
64
+ self.setheading(self.towards(self.gravSys.planets[0]))
65
+ self.a = self.acc()
66
+ self.v = self.v + dt*self.a
67
+
68
+ ## create compound yellow/blue turtleshape for planets
69
+
70
+ def main():
71
+ s = Turtle()
72
+ s.reset()
73
+ s.getscreen().tracer(0,0)
74
+ s.ht()
75
+ s.pu()
76
+ s.fd(6)
77
+ s.lt(90)
78
+ s.begin_poly()
79
+ s.circle(6, 180)
80
+ s.end_poly()
81
+ m1 = s.get_poly()
82
+ s.begin_poly()
83
+ s.circle(6,180)
84
+ s.end_poly()
85
+ m2 = s.get_poly()
86
+
87
+ planetshape = Shape("compound")
88
+ planetshape.addcomponent(m1,"orange")
89
+ planetshape.addcomponent(m2,"blue")
90
+ s.getscreen().register_shape("planet", planetshape)
91
+ s.getscreen().tracer(1,0)
92
+
93
+ ## setup gravitational system
94
+ gs = GravSys()
95
+ sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle")
96
+ sun.color("yellow")
97
+ sun.shapesize(1.8)
98
+ sun.pu()
99
+ earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet")
100
+ earth.pencolor("green")
101
+ earth.shapesize(0.8)
102
+ moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet")
103
+ moon.pencolor("blue")
104
+ moon.shapesize(0.5)
105
+ gs.init()
106
+ gs.start()
107
+ return "Done!"
108
+
109
+ if __name__ == '__main__':
110
+ main()
111
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/rosette.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_wikipedia3.py
4
+
5
+ This example is
6
+ inspired by the Wikipedia article on turtle
7
+ graphics. (See example wikipedia1 for URLs)
8
+
9
+ First we create (ne-1) (i.e. 35 in this
10
+ example) copies of our first turtle p.
11
+ Then we let them perform their steps in
12
+ parallel.
13
+
14
+ Followed by a complete undo().
15
+ """
16
+ from turtle import Screen, Turtle, mainloop
17
+ from time import perf_counter as clock, sleep
18
+
19
+ def mn_eck(p, ne,sz):
20
+ turtlelist = [p]
21
+ #create ne-1 additional turtles
22
+ for i in range(1,ne):
23
+ q = p.clone()
24
+ q.rt(360.0/ne)
25
+ turtlelist.append(q)
26
+ p = q
27
+ for i in range(ne):
28
+ c = abs(ne/2.0-i)/(ne*.7)
29
+ # let those ne turtles make a step
30
+ # in parallel:
31
+ for t in turtlelist:
32
+ t.rt(360./ne)
33
+ t.pencolor(1-c,0,c)
34
+ t.fd(sz)
35
+
36
+ def main():
37
+ s = Screen()
38
+ s.bgcolor("black")
39
+ p=Turtle()
40
+ p.speed(0)
41
+ p.hideturtle()
42
+ p.pencolor("red")
43
+ p.pensize(3)
44
+
45
+ s.tracer(36,0)
46
+
47
+ at = clock()
48
+ mn_eck(p, 36, 19)
49
+ et = clock()
50
+ z1 = et-at
51
+
52
+ sleep(1)
53
+
54
+ at = clock()
55
+ while any(t.undobufferentries() for t in s.turtles()):
56
+ for t in s.turtles():
57
+ t.undo()
58
+ et = clock()
59
+ return "runtime: %.3f sec" % (z1+et-at)
60
+
61
+
62
+ if __name__ == '__main__':
63
+ msg = main()
64
+ print(msg)
65
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/round_dance.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_round_dance.py
4
+
5
+ (Needs version 1.1 of the turtle module that
6
+ comes with Python 3.1)
7
+
8
+ Dancing turtles have a compound shape
9
+ consisting of a series of triangles of
10
+ decreasing size.
11
+
12
+ Turtles march along a circle while rotating
13
+ pairwise in opposite direction, with one
14
+ exception. Does that breaking of symmetry
15
+ enhance the attractiveness of the example?
16
+
17
+ Press any key to stop the animation.
18
+
19
+ Technically: demonstrates use of compound
20
+ shapes, transformation of shapes as well as
21
+ cloning turtles. The animation is
22
+ controlled through update().
23
+ """
24
+
25
+ from turtle import *
26
+
27
+ def stop():
28
+ global running
29
+ running = False
30
+
31
+ def main():
32
+ global running
33
+ clearscreen()
34
+ bgcolor("gray10")
35
+ tracer(False)
36
+ shape("triangle")
37
+ f = 0.793402
38
+ phi = 9.064678
39
+ s = 5
40
+ c = 1
41
+ # create compound shape
42
+ sh = Shape("compound")
43
+ for i in range(10):
44
+ shapesize(s)
45
+ p =get_shapepoly()
46
+ s *= f
47
+ c *= f
48
+ tilt(-phi)
49
+ sh.addcomponent(p, (c, 0.25, 1-c), "black")
50
+ register_shape("multitri", sh)
51
+ # create dancers
52
+ shapesize(1)
53
+ shape("multitri")
54
+ pu()
55
+ setpos(0, -200)
56
+ dancers = []
57
+ for i in range(180):
58
+ fd(7)
59
+ tilt(-4)
60
+ lt(2)
61
+ update()
62
+ if i % 12 == 0:
63
+ dancers.append(clone())
64
+ home()
65
+ # dance
66
+ running = True
67
+ onkeypress(stop)
68
+ listen()
69
+ cs = 1
70
+ while running:
71
+ ta = -4
72
+ for dancer in dancers:
73
+ dancer.fd(7)
74
+ dancer.lt(2)
75
+ dancer.tilt(ta)
76
+ ta = -4 if ta > 0 else 2
77
+ if cs < 180:
78
+ right(4)
79
+ shapesize(cs)
80
+ cs *= 1.005
81
+ update()
82
+ return "DONE!"
83
+
84
+ if __name__=='__main__':
85
+ print(main())
86
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/sorting_animate.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+
4
+ sorting_animation.py
5
+
6
+ A minimal sorting algorithm animation:
7
+ Sorts a shelf of 10 blocks using insertion
8
+ sort, selection sort and quicksort.
9
+
10
+ Shelfs are implemented using builtin lists.
11
+
12
+ Blocks are turtles with shape "square", but
13
+ stretched to rectangles by shapesize()
14
+ ---------------------------------------
15
+ To exit press space button
16
+ ---------------------------------------
17
+ """
18
+ from turtle import *
19
+ import random
20
+
21
+
22
+ class Block(Turtle):
23
+
24
+ def __init__(self, size):
25
+ self.size = size
26
+ Turtle.__init__(self, shape="square", visible=False)
27
+ self.pu()
28
+ self.shapesize(size * 1.5, 1.5, 2) # square-->rectangle
29
+ self.fillcolor("black")
30
+ self.st()
31
+
32
+ def glow(self):
33
+ self.fillcolor("red")
34
+
35
+ def unglow(self):
36
+ self.fillcolor("black")
37
+
38
+ def __repr__(self):
39
+ return "Block size: {0}".format(self.size)
40
+
41
+
42
+ class Shelf(list):
43
+
44
+ def __init__(self, y):
45
+ "create a shelf. y is y-position of first block"
46
+ self.y = y
47
+ self.x = -150
48
+
49
+ def push(self, d):
50
+ width, _, _ = d.shapesize()
51
+ # align blocks by the bottom edge
52
+ y_offset = width / 2 * 20
53
+ d.sety(self.y + y_offset)
54
+ d.setx(self.x + 34 * len(self))
55
+ self.append(d)
56
+
57
+ def _close_gap_from_i(self, i):
58
+ for b in self[i:]:
59
+ xpos, _ = b.pos()
60
+ b.setx(xpos - 34)
61
+
62
+ def _open_gap_from_i(self, i):
63
+ for b in self[i:]:
64
+ xpos, _ = b.pos()
65
+ b.setx(xpos + 34)
66
+
67
+ def pop(self, key):
68
+ b = list.pop(self, key)
69
+ b.glow()
70
+ b.sety(200)
71
+ self._close_gap_from_i(key)
72
+ return b
73
+
74
+ def insert(self, key, b):
75
+ self._open_gap_from_i(key)
76
+ list.insert(self, key, b)
77
+ b.setx(self.x + 34 * key)
78
+ width, _, _ = b.shapesize()
79
+ # align blocks by the bottom edge
80
+ y_offset = width / 2 * 20
81
+ b.sety(self.y + y_offset)
82
+ b.unglow()
83
+
84
+ def isort(shelf):
85
+ length = len(shelf)
86
+ for i in range(1, length):
87
+ hole = i
88
+ while hole > 0 and shelf[i].size < shelf[hole - 1].size:
89
+ hole = hole - 1
90
+ shelf.insert(hole, shelf.pop(i))
91
+ return
92
+
93
+ def ssort(shelf):
94
+ length = len(shelf)
95
+ for j in range(0, length - 1):
96
+ imin = j
97
+ for i in range(j + 1, length):
98
+ if shelf[i].size < shelf[imin].size:
99
+ imin = i
100
+ if imin != j:
101
+ shelf.insert(j, shelf.pop(imin))
102
+
103
+ def partition(shelf, left, right, pivot_index):
104
+ pivot = shelf[pivot_index]
105
+ shelf.insert(right, shelf.pop(pivot_index))
106
+ store_index = left
107
+ for i in range(left, right): # range is non-inclusive of ending value
108
+ if shelf[i].size < pivot.size:
109
+ shelf.insert(store_index, shelf.pop(i))
110
+ store_index = store_index + 1
111
+ shelf.insert(store_index, shelf.pop(right)) # move pivot to correct position
112
+ return store_index
113
+
114
+ def qsort(shelf, left, right):
115
+ if left < right:
116
+ pivot_index = left
117
+ pivot_new_index = partition(shelf, left, right, pivot_index)
118
+ qsort(shelf, left, pivot_new_index - 1)
119
+ qsort(shelf, pivot_new_index + 1, right)
120
+
121
+ def randomize():
122
+ disable_keys()
123
+ clear()
124
+ target = list(range(10))
125
+ random.shuffle(target)
126
+ for i, t in enumerate(target):
127
+ for j in range(i, len(s)):
128
+ if s[j].size == t + 1:
129
+ s.insert(i, s.pop(j))
130
+ show_text(instructions1)
131
+ show_text(instructions2, line=1)
132
+ enable_keys()
133
+
134
+ def show_text(text, line=0):
135
+ line = 20 * line
136
+ goto(0,-250 - line)
137
+ write(text, align="center", font=("Courier", 16, "bold"))
138
+
139
+ def start_ssort():
140
+ disable_keys()
141
+ clear()
142
+ show_text("Selection Sort")
143
+ ssort(s)
144
+ clear()
145
+ show_text(instructions1)
146
+ show_text(instructions2, line=1)
147
+ enable_keys()
148
+
149
+ def start_isort():
150
+ disable_keys()
151
+ clear()
152
+ show_text("Insertion Sort")
153
+ isort(s)
154
+ clear()
155
+ show_text(instructions1)
156
+ show_text(instructions2, line=1)
157
+ enable_keys()
158
+
159
+ def start_qsort():
160
+ disable_keys()
161
+ clear()
162
+ show_text("Quicksort")
163
+ qsort(s, 0, len(s) - 1)
164
+ clear()
165
+ show_text(instructions1)
166
+ show_text(instructions2, line=1)
167
+ enable_keys()
168
+
169
+ def init_shelf():
170
+ global s
171
+ s = Shelf(-200)
172
+ vals = (4, 2, 8, 9, 1, 5, 10, 3, 7, 6)
173
+ for i in vals:
174
+ s.push(Block(i))
175
+
176
+ def disable_keys():
177
+ onkey(None, "s")
178
+ onkey(None, "i")
179
+ onkey(None, "q")
180
+ onkey(None, "r")
181
+
182
+ def enable_keys():
183
+ onkey(start_isort, "i")
184
+ onkey(start_ssort, "s")
185
+ onkey(start_qsort, "q")
186
+ onkey(randomize, "r")
187
+ onkey(bye, "space")
188
+
189
+ def main():
190
+ getscreen().clearscreen()
191
+ ht(); penup()
192
+ init_shelf()
193
+ show_text(instructions1)
194
+ show_text(instructions2, line=1)
195
+ enable_keys()
196
+ listen()
197
+ return "EVENTLOOP"
198
+
199
+ instructions1 = "press i for insertion sort, s for selection sort, q for quicksort"
200
+ instructions2 = "spacebar to quit, r to randomize"
201
+
202
+ if __name__=="__main__":
203
+ msg = main()
204
+ mainloop()
infer_4_47_1/lib/python3.10/turtledemo/yinyang.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_yinyang.py
5
+
6
+ Another drawing suitable as a beginner's
7
+ programming example.
8
+
9
+ The small circles are drawn by the circle
10
+ command.
11
+
12
+ """
13
+
14
+ from turtle import *
15
+
16
+ def yin(radius, color1, color2):
17
+ width(3)
18
+ color("black", color1)
19
+ begin_fill()
20
+ circle(radius/2., 180)
21
+ circle(radius, 180)
22
+ left(180)
23
+ circle(-radius/2., 180)
24
+ end_fill()
25
+ left(90)
26
+ up()
27
+ forward(radius*0.35)
28
+ right(90)
29
+ down()
30
+ color(color1, color2)
31
+ begin_fill()
32
+ circle(radius*0.15)
33
+ end_fill()
34
+ left(90)
35
+ up()
36
+ backward(radius*0.35)
37
+ down()
38
+ left(90)
39
+
40
+ def main():
41
+ reset()
42
+ yin(200, "black", "white")
43
+ yin(200, "white", "black")
44
+ ht()
45
+ return "Done!"
46
+
47
+ if __name__ == '__main__':
48
+ main()
49
+ mainloop()
infer_4_47_1/lib/python3.10/xml/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core XML support for Python.
2
+
3
+ This package contains four sub-packages:
4
+
5
+ dom -- The W3C Document Object Model. This supports DOM Level 1 +
6
+ Namespaces.
7
+
8
+ parsers -- Python wrappers for XML parsers (currently only supports Expat).
9
+
10
+ sax -- The Simple API for XML, developed by XML-Dev, led by David
11
+ Megginson and ported to Python by Lars Marius Garshol. This
12
+ supports the SAX 2 API.
13
+
14
+ etree -- The ElementTree XML library. This is a subset of the full
15
+ ElementTree XML release.
16
+
17
+ """
18
+
19
+
20
+ __all__ = ["dom", "parsers", "sax", "etree"]
infer_4_47_1/lib/python3.10/xml/dom/NodeFilter.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is the Python mapping for interface NodeFilter from
2
+ # DOM2-Traversal-Range. It contains only constants.
3
+
4
+ class NodeFilter:
5
+ """
6
+ This is the DOM2 NodeFilter interface. It contains only constants.
7
+ """
8
+ FILTER_ACCEPT = 1
9
+ FILTER_REJECT = 2
10
+ FILTER_SKIP = 3
11
+
12
+ SHOW_ALL = 0xFFFFFFFF
13
+ SHOW_ELEMENT = 0x00000001
14
+ SHOW_ATTRIBUTE = 0x00000002
15
+ SHOW_TEXT = 0x00000004
16
+ SHOW_CDATA_SECTION = 0x00000008
17
+ SHOW_ENTITY_REFERENCE = 0x00000010
18
+ SHOW_ENTITY = 0x00000020
19
+ SHOW_PROCESSING_INSTRUCTION = 0x00000040
20
+ SHOW_COMMENT = 0x00000080
21
+ SHOW_DOCUMENT = 0x00000100
22
+ SHOW_DOCUMENT_TYPE = 0x00000200
23
+ SHOW_DOCUMENT_FRAGMENT = 0x00000400
24
+ SHOW_NOTATION = 0x00000800
25
+
26
+ def acceptNode(self, node):
27
+ raise NotImplementedError
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/NodeFilter.cpython-310.pyc ADDED
Binary file (1.22 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.53 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/domreg.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/expatbuilder.cpython-310.pyc ADDED
Binary file (27.3 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/minicompat.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/minidom.cpython-310.pyc ADDED
Binary file (55.6 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/pulldom.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/__pycache__/xmlbuilder.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
infer_4_47_1/lib/python3.10/xml/dom/domreg.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Registration facilities for DOM. This module should not be used
2
+ directly. Instead, the functions getDOMImplementation and
3
+ registerDOMImplementation should be imported from xml.dom."""
4
+
5
+ # This is a list of well-known implementations. Well-known names
6
+ # should be published by posting to [email protected], and are
7
+ # subsequently recorded in this file.
8
+
9
+ import sys
10
+
11
+ well_known_implementations = {
12
+ 'minidom':'xml.dom.minidom',
13
+ '4DOM': 'xml.dom.DOMImplementation',
14
+ }
15
+
16
+ # DOM implementations not officially registered should register
17
+ # themselves with their
18
+
19
+ registered = {}
20
+
21
+ def registerDOMImplementation(name, factory):
22
+ """registerDOMImplementation(name, factory)
23
+
24
+ Register the factory function with the name. The factory function
25
+ should return an object which implements the DOMImplementation
26
+ interface. The factory function can either return the same object,
27
+ or a new one (e.g. if that implementation supports some
28
+ customization)."""
29
+
30
+ registered[name] = factory
31
+
32
+ def _good_enough(dom, features):
33
+ "_good_enough(dom, features) -> Return 1 if the dom offers the features"
34
+ for f,v in features:
35
+ if not dom.hasFeature(f,v):
36
+ return 0
37
+ return 1
38
+
39
+ def getDOMImplementation(name=None, features=()):
40
+ """getDOMImplementation(name = None, features = ()) -> DOM implementation.
41
+
42
+ Return a suitable DOM implementation. The name is either
43
+ well-known, the module name of a DOM implementation, or None. If
44
+ it is not None, imports the corresponding module and returns
45
+ DOMImplementation object if the import succeeds.
46
+
47
+ If name is not given, consider the available implementations to
48
+ find one with the required feature set. If no implementation can
49
+ be found, raise an ImportError. The features list must be a sequence
50
+ of (feature, version) pairs which are passed to hasFeature."""
51
+
52
+ import os
53
+ creator = None
54
+ mod = well_known_implementations.get(name)
55
+ if mod:
56
+ mod = __import__(mod, {}, {}, ['getDOMImplementation'])
57
+ return mod.getDOMImplementation()
58
+ elif name:
59
+ return registered[name]()
60
+ elif not sys.flags.ignore_environment and "PYTHON_DOM" in os.environ:
61
+ return getDOMImplementation(name = os.environ["PYTHON_DOM"])
62
+
63
+ # User did not specify a name, try implementations in arbitrary
64
+ # order, returning the one that has the required features
65
+ if isinstance(features, str):
66
+ features = _parse_feature_string(features)
67
+ for creator in registered.values():
68
+ dom = creator()
69
+ if _good_enough(dom, features):
70
+ return dom
71
+
72
+ for creator in well_known_implementations.keys():
73
+ try:
74
+ dom = getDOMImplementation(name = creator)
75
+ except Exception: # typically ImportError, or AttributeError
76
+ continue
77
+ if _good_enough(dom, features):
78
+ return dom
79
+
80
+ raise ImportError("no suitable DOM implementation found")
81
+
82
+ def _parse_feature_string(s):
83
+ features = []
84
+ parts = s.split()
85
+ i = 0
86
+ length = len(parts)
87
+ while i < length:
88
+ feature = parts[i]
89
+ if feature[0] in "0123456789":
90
+ raise ValueError("bad feature name: %r" % (feature,))
91
+ i = i + 1
92
+ version = None
93
+ if i < length:
94
+ v = parts[i]
95
+ if v[0] in "0123456789":
96
+ i = i + 1
97
+ version = v
98
+ features.append((feature, version))
99
+ return tuple(features)
infer_4_47_1/lib/python3.10/xml/dom/expatbuilder.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Facility to use the Expat parser to load a minidom instance
2
+ from a string or file.
3
+
4
+ This avoids all the overhead of SAX and pulldom to gain performance.
5
+ """
6
+
7
+ # Warning!
8
+ #
9
+ # This module is tightly bound to the implementation details of the
10
+ # minidom DOM and can't be used with other DOM implementations. This
11
+ # is due, in part, to a lack of appropriate methods in the DOM (there is
12
+ # no way to create Entity and Notation nodes via the DOM Level 2
13
+ # interface), and for performance. The latter is the cause of some fairly
14
+ # cryptic code.
15
+ #
16
+ # Performance hacks:
17
+ #
18
+ # - .character_data_handler() has an extra case in which continuing
19
+ # data is appended to an existing Text node; this can be a
20
+ # speedup since pyexpat can break up character data into multiple
21
+ # callbacks even though we set the buffer_text attribute on the
22
+ # parser. This also gives us the advantage that we don't need a
23
+ # separate normalization pass.
24
+ #
25
+ # - Determining that a node exists is done using an identity comparison
26
+ # with None rather than a truth test; this avoids searching for and
27
+ # calling any methods on the node object if it exists. (A rather
28
+ # nice speedup is achieved this way as well!)
29
+
30
+ from xml.dom import xmlbuilder, minidom, Node
31
+ from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE
32
+ from xml.parsers import expat
33
+ from xml.dom.minidom import _append_child, _set_attribute_node
34
+ from xml.dom.NodeFilter import NodeFilter
35
+
36
+ TEXT_NODE = Node.TEXT_NODE
37
+ CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE
38
+ DOCUMENT_NODE = Node.DOCUMENT_NODE
39
+
40
+ FILTER_ACCEPT = xmlbuilder.DOMBuilderFilter.FILTER_ACCEPT
41
+ FILTER_REJECT = xmlbuilder.DOMBuilderFilter.FILTER_REJECT
42
+ FILTER_SKIP = xmlbuilder.DOMBuilderFilter.FILTER_SKIP
43
+ FILTER_INTERRUPT = xmlbuilder.DOMBuilderFilter.FILTER_INTERRUPT
44
+
45
+ theDOMImplementation = minidom.getDOMImplementation()
46
+
47
+ # Expat typename -> TypeInfo
48
+ _typeinfo_map = {
49
+ "CDATA": minidom.TypeInfo(None, "cdata"),
50
+ "ENUM": minidom.TypeInfo(None, "enumeration"),
51
+ "ENTITY": minidom.TypeInfo(None, "entity"),
52
+ "ENTITIES": minidom.TypeInfo(None, "entities"),
53
+ "ID": minidom.TypeInfo(None, "id"),
54
+ "IDREF": minidom.TypeInfo(None, "idref"),
55
+ "IDREFS": minidom.TypeInfo(None, "idrefs"),
56
+ "NMTOKEN": minidom.TypeInfo(None, "nmtoken"),
57
+ "NMTOKENS": minidom.TypeInfo(None, "nmtokens"),
58
+ }
59
+
60
+ class ElementInfo(object):
61
+ __slots__ = '_attr_info', '_model', 'tagName'
62
+
63
+ def __init__(self, tagName, model=None):
64
+ self.tagName = tagName
65
+ self._attr_info = []
66
+ self._model = model
67
+
68
+ def __getstate__(self):
69
+ return self._attr_info, self._model, self.tagName
70
+
71
+ def __setstate__(self, state):
72
+ self._attr_info, self._model, self.tagName = state
73
+
74
+ def getAttributeType(self, aname):
75
+ for info in self._attr_info:
76
+ if info[1] == aname:
77
+ t = info[-2]
78
+ if t[0] == "(":
79
+ return _typeinfo_map["ENUM"]
80
+ else:
81
+ return _typeinfo_map[info[-2]]
82
+ return minidom._no_type
83
+
84
+ def getAttributeTypeNS(self, namespaceURI, localName):
85
+ return minidom._no_type
86
+
87
+ def isElementContent(self):
88
+ if self._model:
89
+ type = self._model[0]
90
+ return type not in (expat.model.XML_CTYPE_ANY,
91
+ expat.model.XML_CTYPE_MIXED)
92
+ else:
93
+ return False
94
+
95
+ def isEmpty(self):
96
+ if self._model:
97
+ return self._model[0] == expat.model.XML_CTYPE_EMPTY
98
+ else:
99
+ return False
100
+
101
+ def isId(self, aname):
102
+ for info in self._attr_info:
103
+ if info[1] == aname:
104
+ return info[-2] == "ID"
105
+ return False
106
+
107
+ def isIdNS(self, euri, ename, auri, aname):
108
+ # not sure this is meaningful
109
+ return self.isId((auri, aname))
110
+
111
+ def _intern(builder, s):
112
+ return builder._intern_setdefault(s, s)
113
+
114
+ def _parse_ns_name(builder, name):
115
+ assert ' ' in name
116
+ parts = name.split(' ')
117
+ intern = builder._intern_setdefault
118
+ if len(parts) == 3:
119
+ uri, localname, prefix = parts
120
+ prefix = intern(prefix, prefix)
121
+ qname = "%s:%s" % (prefix, localname)
122
+ qname = intern(qname, qname)
123
+ localname = intern(localname, localname)
124
+ elif len(parts) == 2:
125
+ uri, localname = parts
126
+ prefix = EMPTY_PREFIX
127
+ qname = localname = intern(localname, localname)
128
+ else:
129
+ raise ValueError("Unsupported syntax: spaces in URIs not supported: %r" % name)
130
+ return intern(uri, uri), localname, prefix, qname
131
+
132
+
133
+ class ExpatBuilder:
134
+ """Document builder that uses Expat to build a ParsedXML.DOM document
135
+ instance."""
136
+
137
+ def __init__(self, options=None):
138
+ if options is None:
139
+ options = xmlbuilder.Options()
140
+ self._options = options
141
+ if self._options.filter is not None:
142
+ self._filter = FilterVisibilityController(self._options.filter)
143
+ else:
144
+ self._filter = None
145
+ # This *really* doesn't do anything in this case, so
146
+ # override it with something fast & minimal.
147
+ self._finish_start_element = id
148
+ self._parser = None
149
+ self.reset()
150
+
151
+ def createParser(self):
152
+ """Create a new parser object."""
153
+ return expat.ParserCreate()
154
+
155
+ def getParser(self):
156
+ """Return the parser object, creating a new one if needed."""
157
+ if not self._parser:
158
+ self._parser = self.createParser()
159
+ self._intern_setdefault = self._parser.intern.setdefault
160
+ self._parser.buffer_text = True
161
+ self._parser.ordered_attributes = True
162
+ self._parser.specified_attributes = True
163
+ self.install(self._parser)
164
+ return self._parser
165
+
166
+ def reset(self):
167
+ """Free all data structures used during DOM construction."""
168
+ self.document = theDOMImplementation.createDocument(
169
+ EMPTY_NAMESPACE, None, None)
170
+ self.curNode = self.document
171
+ self._elem_info = self.document._elem_info
172
+ self._cdata = False
173
+
174
+ def install(self, parser):
175
+ """Install the callbacks needed to build the DOM into the parser."""
176
+ # This creates circular references!
177
+ parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler
178
+ parser.StartElementHandler = self.first_element_handler
179
+ parser.EndElementHandler = self.end_element_handler
180
+ parser.ProcessingInstructionHandler = self.pi_handler
181
+ if self._options.entities:
182
+ parser.EntityDeclHandler = self.entity_decl_handler
183
+ parser.NotationDeclHandler = self.notation_decl_handler
184
+ if self._options.comments:
185
+ parser.CommentHandler = self.comment_handler
186
+ if self._options.cdata_sections:
187
+ parser.StartCdataSectionHandler = self.start_cdata_section_handler
188
+ parser.EndCdataSectionHandler = self.end_cdata_section_handler
189
+ parser.CharacterDataHandler = self.character_data_handler_cdata
190
+ else:
191
+ parser.CharacterDataHandler = self.character_data_handler
192
+ parser.ExternalEntityRefHandler = self.external_entity_ref_handler
193
+ parser.XmlDeclHandler = self.xml_decl_handler
194
+ parser.ElementDeclHandler = self.element_decl_handler
195
+ parser.AttlistDeclHandler = self.attlist_decl_handler
196
+
197
+ def parseFile(self, file):
198
+ """Parse a document from a file object, returning the document
199
+ node."""
200
+ parser = self.getParser()
201
+ first_buffer = True
202
+ try:
203
+ while 1:
204
+ buffer = file.read(16*1024)
205
+ if not buffer:
206
+ break
207
+ parser.Parse(buffer, False)
208
+ if first_buffer and self.document.documentElement:
209
+ self._setup_subset(buffer)
210
+ first_buffer = False
211
+ parser.Parse(b"", True)
212
+ except ParseEscape:
213
+ pass
214
+ doc = self.document
215
+ self.reset()
216
+ self._parser = None
217
+ return doc
218
+
219
+ def parseString(self, string):
220
+ """Parse a document from a string, returning the document node."""
221
+ parser = self.getParser()
222
+ try:
223
+ parser.Parse(string, True)
224
+ self._setup_subset(string)
225
+ except ParseEscape:
226
+ pass
227
+ doc = self.document
228
+ self.reset()
229
+ self._parser = None
230
+ return doc
231
+
232
+ def _setup_subset(self, buffer):
233
+ """Load the internal subset if there might be one."""
234
+ if self.document.doctype:
235
+ extractor = InternalSubsetExtractor()
236
+ extractor.parseString(buffer)
237
+ subset = extractor.getSubset()
238
+ self.document.doctype.internalSubset = subset
239
+
240
+ def start_doctype_decl_handler(self, doctypeName, systemId, publicId,
241
+ has_internal_subset):
242
+ doctype = self.document.implementation.createDocumentType(
243
+ doctypeName, publicId, systemId)
244
+ doctype.ownerDocument = self.document
245
+ _append_child(self.document, doctype)
246
+ self.document.doctype = doctype
247
+ if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT:
248
+ self.document.doctype = None
249
+ del self.document.childNodes[-1]
250
+ doctype = None
251
+ self._parser.EntityDeclHandler = None
252
+ self._parser.NotationDeclHandler = None
253
+ if has_internal_subset:
254
+ if doctype is not None:
255
+ doctype.entities._seq = []
256
+ doctype.notations._seq = []
257
+ self._parser.CommentHandler = None
258
+ self._parser.ProcessingInstructionHandler = None
259
+ self._parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler
260
+
261
+ def end_doctype_decl_handler(self):
262
+ if self._options.comments:
263
+ self._parser.CommentHandler = self.comment_handler
264
+ self._parser.ProcessingInstructionHandler = self.pi_handler
265
+ if not (self._elem_info or self._filter):
266
+ self._finish_end_element = id
267
+
268
+ def pi_handler(self, target, data):
269
+ node = self.document.createProcessingInstruction(target, data)
270
+ _append_child(self.curNode, node)
271
+ if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
272
+ self.curNode.removeChild(node)
273
+
274
+ def character_data_handler_cdata(self, data):
275
+ childNodes = self.curNode.childNodes
276
+ if self._cdata:
277
+ if ( self._cdata_continue
278
+ and childNodes[-1].nodeType == CDATA_SECTION_NODE):
279
+ childNodes[-1].appendData(data)
280
+ return
281
+ node = self.document.createCDATASection(data)
282
+ self._cdata_continue = True
283
+ elif childNodes and childNodes[-1].nodeType == TEXT_NODE:
284
+ node = childNodes[-1]
285
+ value = node.data + data
286
+ node.data = value
287
+ return
288
+ else:
289
+ node = minidom.Text()
290
+ node.data = data
291
+ node.ownerDocument = self.document
292
+ _append_child(self.curNode, node)
293
+
294
+ def character_data_handler(self, data):
295
+ childNodes = self.curNode.childNodes
296
+ if childNodes and childNodes[-1].nodeType == TEXT_NODE:
297
+ node = childNodes[-1]
298
+ node.data = node.data + data
299
+ return
300
+ node = minidom.Text()
301
+ node.data = node.data + data
302
+ node.ownerDocument = self.document
303
+ _append_child(self.curNode, node)
304
+
305
+ def entity_decl_handler(self, entityName, is_parameter_entity, value,
306
+ base, systemId, publicId, notationName):
307
+ if is_parameter_entity:
308
+ # we don't care about parameter entities for the DOM
309
+ return
310
+ if not self._options.entities:
311
+ return
312
+ node = self.document._create_entity(entityName, publicId,
313
+ systemId, notationName)
314
+ if value is not None:
315
+ # internal entity
316
+ # node *should* be readonly, but we'll cheat
317
+ child = self.document.createTextNode(value)
318
+ node.childNodes.append(child)
319
+ self.document.doctype.entities._seq.append(node)
320
+ if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
321
+ del self.document.doctype.entities._seq[-1]
322
+
323
+ def notation_decl_handler(self, notationName, base, systemId, publicId):
324
+ node = self.document._create_notation(notationName, publicId, systemId)
325
+ self.document.doctype.notations._seq.append(node)
326
+ if self._filter and self._filter.acceptNode(node) == FILTER_ACCEPT:
327
+ del self.document.doctype.notations._seq[-1]
328
+
329
+ def comment_handler(self, data):
330
+ node = self.document.createComment(data)
331
+ _append_child(self.curNode, node)
332
+ if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
333
+ self.curNode.removeChild(node)
334
+
335
+ def start_cdata_section_handler(self):
336
+ self._cdata = True
337
+ self._cdata_continue = False
338
+
339
+ def end_cdata_section_handler(self):
340
+ self._cdata = False
341
+ self._cdata_continue = False
342
+
343
+ def external_entity_ref_handler(self, context, base, systemId, publicId):
344
+ return 1
345
+
346
+ def first_element_handler(self, name, attributes):
347
+ if self._filter is None and not self._elem_info:
348
+ self._finish_end_element = id
349
+ self.getParser().StartElementHandler = self.start_element_handler
350
+ self.start_element_handler(name, attributes)
351
+
352
+ def start_element_handler(self, name, attributes):
353
+ node = self.document.createElement(name)
354
+ _append_child(self.curNode, node)
355
+ self.curNode = node
356
+
357
+ if attributes:
358
+ for i in range(0, len(attributes), 2):
359
+ a = minidom.Attr(attributes[i], EMPTY_NAMESPACE,
360
+ None, EMPTY_PREFIX)
361
+ value = attributes[i+1]
362
+ a.value = value
363
+ a.ownerDocument = self.document
364
+ _set_attribute_node(node, a)
365
+
366
+ if node is not self.document.documentElement:
367
+ self._finish_start_element(node)
368
+
369
+ def _finish_start_element(self, node):
370
+ if self._filter:
371
+ # To be general, we'd have to call isSameNode(), but this
372
+ # is sufficient for minidom:
373
+ if node is self.document.documentElement:
374
+ return
375
+ filt = self._filter.startContainer(node)
376
+ if filt == FILTER_REJECT:
377
+ # ignore this node & all descendents
378
+ Rejecter(self)
379
+ elif filt == FILTER_SKIP:
380
+ # ignore this node, but make it's children become
381
+ # children of the parent node
382
+ Skipper(self)
383
+ else:
384
+ return
385
+ self.curNode = node.parentNode
386
+ node.parentNode.removeChild(node)
387
+ node.unlink()
388
+
389
+ # If this ever changes, Namespaces.end_element_handler() needs to
390
+ # be changed to match.
391
+ #
392
+ def end_element_handler(self, name):
393
+ curNode = self.curNode
394
+ self.curNode = curNode.parentNode
395
+ self._finish_end_element(curNode)
396
+
397
+ def _finish_end_element(self, curNode):
398
+ info = self._elem_info.get(curNode.tagName)
399
+ if info:
400
+ self._handle_white_text_nodes(curNode, info)
401
+ if self._filter:
402
+ if curNode is self.document.documentElement:
403
+ return
404
+ if self._filter.acceptNode(curNode) == FILTER_REJECT:
405
+ self.curNode.removeChild(curNode)
406
+ curNode.unlink()
407
+
408
+ def _handle_white_text_nodes(self, node, info):
409
+ if (self._options.whitespace_in_element_content
410
+ or not info.isElementContent()):
411
+ return
412
+
413
+ # We have element type information and should remove ignorable
414
+ # whitespace; identify for text nodes which contain only
415
+ # whitespace.
416
+ L = []
417
+ for child in node.childNodes:
418
+ if child.nodeType == TEXT_NODE and not child.data.strip():
419
+ L.append(child)
420
+
421
+ # Remove ignorable whitespace from the tree.
422
+ for child in L:
423
+ node.removeChild(child)
424
+
425
+ def element_decl_handler(self, name, model):
426
+ info = self._elem_info.get(name)
427
+ if info is None:
428
+ self._elem_info[name] = ElementInfo(name, model)
429
+ else:
430
+ assert info._model is None
431
+ info._model = model
432
+
433
+ def attlist_decl_handler(self, elem, name, type, default, required):
434
+ info = self._elem_info.get(elem)
435
+ if info is None:
436
+ info = ElementInfo(elem)
437
+ self._elem_info[elem] = info
438
+ info._attr_info.append(
439
+ [None, name, None, None, default, 0, type, required])
440
+
441
+ def xml_decl_handler(self, version, encoding, standalone):
442
+ self.document.version = version
443
+ self.document.encoding = encoding
444
+ # This is still a little ugly, thanks to the pyexpat API. ;-(
445
+ if standalone >= 0:
446
+ if standalone:
447
+ self.document.standalone = True
448
+ else:
449
+ self.document.standalone = False
450
+
451
+
452
+ # Don't include FILTER_INTERRUPT, since that's checked separately
453
+ # where allowed.
454
+ _ALLOWED_FILTER_RETURNS = (FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP)
455
+
456
+ class FilterVisibilityController(object):
457
+ """Wrapper around a DOMBuilderFilter which implements the checks
458
+ to make the whatToShow filter attribute work."""
459
+
460
+ __slots__ = 'filter',
461
+
462
+ def __init__(self, filter):
463
+ self.filter = filter
464
+
465
+ def startContainer(self, node):
466
+ mask = self._nodetype_mask[node.nodeType]
467
+ if self.filter.whatToShow & mask:
468
+ val = self.filter.startContainer(node)
469
+ if val == FILTER_INTERRUPT:
470
+ raise ParseEscape
471
+ if val not in _ALLOWED_FILTER_RETURNS:
472
+ raise ValueError(
473
+ "startContainer() returned illegal value: " + repr(val))
474
+ return val
475
+ else:
476
+ return FILTER_ACCEPT
477
+
478
+ def acceptNode(self, node):
479
+ mask = self._nodetype_mask[node.nodeType]
480
+ if self.filter.whatToShow & mask:
481
+ val = self.filter.acceptNode(node)
482
+ if val == FILTER_INTERRUPT:
483
+ raise ParseEscape
484
+ if val == FILTER_SKIP:
485
+ # move all child nodes to the parent, and remove this node
486
+ parent = node.parentNode
487
+ for child in node.childNodes[:]:
488
+ parent.appendChild(child)
489
+ # node is handled by the caller
490
+ return FILTER_REJECT
491
+ if val not in _ALLOWED_FILTER_RETURNS:
492
+ raise ValueError(
493
+ "acceptNode() returned illegal value: " + repr(val))
494
+ return val
495
+ else:
496
+ return FILTER_ACCEPT
497
+
498
+ _nodetype_mask = {
499
+ Node.ELEMENT_NODE: NodeFilter.SHOW_ELEMENT,
500
+ Node.ATTRIBUTE_NODE: NodeFilter.SHOW_ATTRIBUTE,
501
+ Node.TEXT_NODE: NodeFilter.SHOW_TEXT,
502
+ Node.CDATA_SECTION_NODE: NodeFilter.SHOW_CDATA_SECTION,
503
+ Node.ENTITY_REFERENCE_NODE: NodeFilter.SHOW_ENTITY_REFERENCE,
504
+ Node.ENTITY_NODE: NodeFilter.SHOW_ENTITY,
505
+ Node.PROCESSING_INSTRUCTION_NODE: NodeFilter.SHOW_PROCESSING_INSTRUCTION,
506
+ Node.COMMENT_NODE: NodeFilter.SHOW_COMMENT,
507
+ Node.DOCUMENT_NODE: NodeFilter.SHOW_DOCUMENT,
508
+ Node.DOCUMENT_TYPE_NODE: NodeFilter.SHOW_DOCUMENT_TYPE,
509
+ Node.DOCUMENT_FRAGMENT_NODE: NodeFilter.SHOW_DOCUMENT_FRAGMENT,
510
+ Node.NOTATION_NODE: NodeFilter.SHOW_NOTATION,
511
+ }
512
+
513
+
514
+ class FilterCrutch(object):
515
+ __slots__ = '_builder', '_level', '_old_start', '_old_end'
516
+
517
+ def __init__(self, builder):
518
+ self._level = 0
519
+ self._builder = builder
520
+ parser = builder._parser
521
+ self._old_start = parser.StartElementHandler
522
+ self._old_end = parser.EndElementHandler
523
+ parser.StartElementHandler = self.start_element_handler
524
+ parser.EndElementHandler = self.end_element_handler
525
+
526
+ class Rejecter(FilterCrutch):
527
+ __slots__ = ()
528
+
529
+ def __init__(self, builder):
530
+ FilterCrutch.__init__(self, builder)
531
+ parser = builder._parser
532
+ for name in ("ProcessingInstructionHandler",
533
+ "CommentHandler",
534
+ "CharacterDataHandler",
535
+ "StartCdataSectionHandler",
536
+ "EndCdataSectionHandler",
537
+ "ExternalEntityRefHandler",
538
+ ):
539
+ setattr(parser, name, None)
540
+
541
+ def start_element_handler(self, *args):
542
+ self._level = self._level + 1
543
+
544
+ def end_element_handler(self, *args):
545
+ if self._level == 0:
546
+ # restore the old handlers
547
+ parser = self._builder._parser
548
+ self._builder.install(parser)
549
+ parser.StartElementHandler = self._old_start
550
+ parser.EndElementHandler = self._old_end
551
+ else:
552
+ self._level = self._level - 1
553
+
554
+ class Skipper(FilterCrutch):
555
+ __slots__ = ()
556
+
557
+ def start_element_handler(self, *args):
558
+ node = self._builder.curNode
559
+ self._old_start(*args)
560
+ if self._builder.curNode is not node:
561
+ self._level = self._level + 1
562
+
563
+ def end_element_handler(self, *args):
564
+ if self._level == 0:
565
+ # We're popping back out of the node we're skipping, so we
566
+ # shouldn't need to do anything but reset the handlers.
567
+ self._builder._parser.StartElementHandler = self._old_start
568
+ self._builder._parser.EndElementHandler = self._old_end
569
+ self._builder = None
570
+ else:
571
+ self._level = self._level - 1
572
+ self._old_end(*args)
573
+
574
+
575
+ # framework document used by the fragment builder.
576
+ # Takes a string for the doctype, subset string, and namespace attrs string.
577
+
578
+ _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID = \
579
+ "http://xml.python.org/entities/fragment-builder/internal"
580
+
581
+ _FRAGMENT_BUILDER_TEMPLATE = (
582
+ '''\
583
+ <!DOCTYPE wrapper
584
+ %%s [
585
+ <!ENTITY fragment-builder-internal
586
+ SYSTEM "%s">
587
+ %%s
588
+ ]>
589
+ <wrapper %%s
590
+ >&fragment-builder-internal;</wrapper>'''
591
+ % _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID)
592
+
593
+
594
+ class FragmentBuilder(ExpatBuilder):
595
+ """Builder which constructs document fragments given XML source
596
+ text and a context node.
597
+
598
+ The context node is expected to provide information about the
599
+ namespace declarations which are in scope at the start of the
600
+ fragment.
601
+ """
602
+
603
+ def __init__(self, context, options=None):
604
+ if context.nodeType == DOCUMENT_NODE:
605
+ self.originalDocument = context
606
+ self.context = context
607
+ else:
608
+ self.originalDocument = context.ownerDocument
609
+ self.context = context
610
+ ExpatBuilder.__init__(self, options)
611
+
612
+ def reset(self):
613
+ ExpatBuilder.reset(self)
614
+ self.fragment = None
615
+
616
+ def parseFile(self, file):
617
+ """Parse a document fragment from a file object, returning the
618
+ fragment node."""
619
+ return self.parseString(file.read())
620
+
621
+ def parseString(self, string):
622
+ """Parse a document fragment from a string, returning the
623
+ fragment node."""
624
+ self._source = string
625
+ parser = self.getParser()
626
+ doctype = self.originalDocument.doctype
627
+ ident = ""
628
+ if doctype:
629
+ subset = doctype.internalSubset or self._getDeclarations()
630
+ if doctype.publicId:
631
+ ident = ('PUBLIC "%s" "%s"'
632
+ % (doctype.publicId, doctype.systemId))
633
+ elif doctype.systemId:
634
+ ident = 'SYSTEM "%s"' % doctype.systemId
635
+ else:
636
+ subset = ""
637
+ nsattrs = self._getNSattrs() # get ns decls from node's ancestors
638
+ document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs)
639
+ try:
640
+ parser.Parse(document, True)
641
+ except:
642
+ self.reset()
643
+ raise
644
+ fragment = self.fragment
645
+ self.reset()
646
+ ## self._parser = None
647
+ return fragment
648
+
649
+ def _getDeclarations(self):
650
+ """Re-create the internal subset from the DocumentType node.
651
+
652
+ This is only needed if we don't already have the
653
+ internalSubset as a string.
654
+ """
655
+ doctype = self.context.ownerDocument.doctype
656
+ s = ""
657
+ if doctype:
658
+ for i in range(doctype.notations.length):
659
+ notation = doctype.notations.item(i)
660
+ if s:
661
+ s = s + "\n "
662
+ s = "%s<!NOTATION %s" % (s, notation.nodeName)
663
+ if notation.publicId:
664
+ s = '%s PUBLIC "%s"\n "%s">' \
665
+ % (s, notation.publicId, notation.systemId)
666
+ else:
667
+ s = '%s SYSTEM "%s">' % (s, notation.systemId)
668
+ for i in range(doctype.entities.length):
669
+ entity = doctype.entities.item(i)
670
+ if s:
671
+ s = s + "\n "
672
+ s = "%s<!ENTITY %s" % (s, entity.nodeName)
673
+ if entity.publicId:
674
+ s = '%s PUBLIC "%s"\n "%s"' \
675
+ % (s, entity.publicId, entity.systemId)
676
+ elif entity.systemId:
677
+ s = '%s SYSTEM "%s"' % (s, entity.systemId)
678
+ else:
679
+ s = '%s "%s"' % (s, entity.firstChild.data)
680
+ if entity.notationName:
681
+ s = "%s NOTATION %s" % (s, entity.notationName)
682
+ s = s + ">"
683
+ return s
684
+
685
+ def _getNSattrs(self):
686
+ return ""
687
+
688
+ def external_entity_ref_handler(self, context, base, systemId, publicId):
689
+ if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID:
690
+ # this entref is the one that we made to put the subtree
691
+ # in; all of our given input is parsed in here.
692
+ old_document = self.document
693
+ old_cur_node = self.curNode
694
+ parser = self._parser.ExternalEntityParserCreate(context)
695
+ # put the real document back, parse into the fragment to return
696
+ self.document = self.originalDocument
697
+ self.fragment = self.document.createDocumentFragment()
698
+ self.curNode = self.fragment
699
+ try:
700
+ parser.Parse(self._source, True)
701
+ finally:
702
+ self.curNode = old_cur_node
703
+ self.document = old_document
704
+ self._source = None
705
+ return -1
706
+ else:
707
+ return ExpatBuilder.external_entity_ref_handler(
708
+ self, context, base, systemId, publicId)
709
+
710
+
711
+ class Namespaces:
712
+ """Mix-in class for builders; adds support for namespaces."""
713
+
714
+ def _initNamespaces(self):
715
+ # list of (prefix, uri) ns declarations. Namespace attrs are
716
+ # constructed from this and added to the element's attrs.
717
+ self._ns_ordered_prefixes = []
718
+
719
+ def createParser(self):
720
+ """Create a new namespace-handling parser."""
721
+ parser = expat.ParserCreate(namespace_separator=" ")
722
+ parser.namespace_prefixes = True
723
+ return parser
724
+
725
+ def install(self, parser):
726
+ """Insert the namespace-handlers onto the parser."""
727
+ ExpatBuilder.install(self, parser)
728
+ if self._options.namespace_declarations:
729
+ parser.StartNamespaceDeclHandler = (
730
+ self.start_namespace_decl_handler)
731
+
732
+ def start_namespace_decl_handler(self, prefix, uri):
733
+ """Push this namespace declaration on our storage."""
734
+ self._ns_ordered_prefixes.append((prefix, uri))
735
+
736
+ def start_element_handler(self, name, attributes):
737
+ if ' ' in name:
738
+ uri, localname, prefix, qname = _parse_ns_name(self, name)
739
+ else:
740
+ uri = EMPTY_NAMESPACE
741
+ qname = name
742
+ localname = None
743
+ prefix = EMPTY_PREFIX
744
+ node = minidom.Element(qname, uri, prefix, localname)
745
+ node.ownerDocument = self.document
746
+ _append_child(self.curNode, node)
747
+ self.curNode = node
748
+
749
+ if self._ns_ordered_prefixes:
750
+ for prefix, uri in self._ns_ordered_prefixes:
751
+ if prefix:
752
+ a = minidom.Attr(_intern(self, 'xmlns:' + prefix),
753
+ XMLNS_NAMESPACE, prefix, "xmlns")
754
+ else:
755
+ a = minidom.Attr("xmlns", XMLNS_NAMESPACE,
756
+ "xmlns", EMPTY_PREFIX)
757
+ a.value = uri
758
+ a.ownerDocument = self.document
759
+ _set_attribute_node(node, a)
760
+ del self._ns_ordered_prefixes[:]
761
+
762
+ if attributes:
763
+ node._ensure_attributes()
764
+ _attrs = node._attrs
765
+ _attrsNS = node._attrsNS
766
+ for i in range(0, len(attributes), 2):
767
+ aname = attributes[i]
768
+ value = attributes[i+1]
769
+ if ' ' in aname:
770
+ uri, localname, prefix, qname = _parse_ns_name(self, aname)
771
+ a = minidom.Attr(qname, uri, localname, prefix)
772
+ _attrs[qname] = a
773
+ _attrsNS[(uri, localname)] = a
774
+ else:
775
+ a = minidom.Attr(aname, EMPTY_NAMESPACE,
776
+ aname, EMPTY_PREFIX)
777
+ _attrs[aname] = a
778
+ _attrsNS[(EMPTY_NAMESPACE, aname)] = a
779
+ a.ownerDocument = self.document
780
+ a.value = value
781
+ a.ownerElement = node
782
+
783
+ if __debug__:
784
+ # This only adds some asserts to the original
785
+ # end_element_handler(), so we only define this when -O is not
786
+ # used. If changing one, be sure to check the other to see if
787
+ # it needs to be changed as well.
788
+ #
789
+ def end_element_handler(self, name):
790
+ curNode = self.curNode
791
+ if ' ' in name:
792
+ uri, localname, prefix, qname = _parse_ns_name(self, name)
793
+ assert (curNode.namespaceURI == uri
794
+ and curNode.localName == localname
795
+ and curNode.prefix == prefix), \
796
+ "element stack messed up! (namespace)"
797
+ else:
798
+ assert curNode.nodeName == name, \
799
+ "element stack messed up - bad nodeName"
800
+ assert curNode.namespaceURI == EMPTY_NAMESPACE, \
801
+ "element stack messed up - bad namespaceURI"
802
+ self.curNode = curNode.parentNode
803
+ self._finish_end_element(curNode)
804
+
805
+
806
+ class ExpatBuilderNS(Namespaces, ExpatBuilder):
807
+ """Document builder that supports namespaces."""
808
+
809
+ def reset(self):
810
+ ExpatBuilder.reset(self)
811
+ self._initNamespaces()
812
+
813
+
814
+ class FragmentBuilderNS(Namespaces, FragmentBuilder):
815
+ """Fragment builder that supports namespaces."""
816
+
817
+ def reset(self):
818
+ FragmentBuilder.reset(self)
819
+ self._initNamespaces()
820
+
821
+ def _getNSattrs(self):
822
+ """Return string of namespace attributes from this element and
823
+ ancestors."""
824
+ # XXX This needs to be re-written to walk the ancestors of the
825
+ # context to build up the namespace information from
826
+ # declarations, elements, and attributes found in context.
827
+ # Otherwise we have to store a bunch more data on the DOM
828
+ # (though that *might* be more reliable -- not clear).
829
+ attrs = ""
830
+ context = self.context
831
+ L = []
832
+ while context:
833
+ if hasattr(context, '_ns_prefix_uri'):
834
+ for prefix, uri in context._ns_prefix_uri.items():
835
+ # add every new NS decl from context to L and attrs string
836
+ if prefix in L:
837
+ continue
838
+ L.append(prefix)
839
+ if prefix:
840
+ declname = "xmlns:" + prefix
841
+ else:
842
+ declname = "xmlns"
843
+ if attrs:
844
+ attrs = "%s\n %s='%s'" % (attrs, declname, uri)
845
+ else:
846
+ attrs = " %s='%s'" % (declname, uri)
847
+ context = context.parentNode
848
+ return attrs
849
+
850
+
851
+ class ParseEscape(Exception):
852
+ """Exception raised to short-circuit parsing in InternalSubsetExtractor."""
853
+ pass
854
+
855
+ class InternalSubsetExtractor(ExpatBuilder):
856
+ """XML processor which can rip out the internal document type subset."""
857
+
858
+ subset = None
859
+
860
+ def getSubset(self):
861
+ """Return the internal subset as a string."""
862
+ return self.subset
863
+
864
+ def parseFile(self, file):
865
+ try:
866
+ ExpatBuilder.parseFile(self, file)
867
+ except ParseEscape:
868
+ pass
869
+
870
+ def parseString(self, string):
871
+ try:
872
+ ExpatBuilder.parseString(self, string)
873
+ except ParseEscape:
874
+ pass
875
+
876
+ def install(self, parser):
877
+ parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler
878
+ parser.StartElementHandler = self.start_element_handler
879
+
880
+ def start_doctype_decl_handler(self, name, publicId, systemId,
881
+ has_internal_subset):
882
+ if has_internal_subset:
883
+ parser = self.getParser()
884
+ self.subset = []
885
+ parser.DefaultHandler = self.subset.append
886
+ parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler
887
+ else:
888
+ raise ParseEscape()
889
+
890
+ def end_doctype_decl_handler(self):
891
+ s = ''.join(self.subset).replace('\r\n', '\n').replace('\r', '\n')
892
+ self.subset = s
893
+ raise ParseEscape()
894
+
895
+ def start_element_handler(self, name, attrs):
896
+ raise ParseEscape()
897
+
898
+
899
+ def parse(file, namespaces=True):
900
+ """Parse a document, returning the resulting Document node.
901
+
902
+ 'file' may be either a file name or an open file object.
903
+ """
904
+ if namespaces:
905
+ builder = ExpatBuilderNS()
906
+ else:
907
+ builder = ExpatBuilder()
908
+
909
+ if isinstance(file, str):
910
+ with open(file, 'rb') as fp:
911
+ result = builder.parseFile(fp)
912
+ else:
913
+ result = builder.parseFile(file)
914
+ return result
915
+
916
+
917
+ def parseString(string, namespaces=True):
918
+ """Parse a document from a string, returning the resulting
919
+ Document node.
920
+ """
921
+ if namespaces:
922
+ builder = ExpatBuilderNS()
923
+ else:
924
+ builder = ExpatBuilder()
925
+ return builder.parseString(string)
926
+
927
+
928
+ def parseFragment(file, context, namespaces=True):
929
+ """Parse a fragment of a document, given the context from which it
930
+ was originally extracted. context should be the parent of the
931
+ node(s) which are in the fragment.
932
+
933
+ 'file' may be either a file name or an open file object.
934
+ """
935
+ if namespaces:
936
+ builder = FragmentBuilderNS(context)
937
+ else:
938
+ builder = FragmentBuilder(context)
939
+
940
+ if isinstance(file, str):
941
+ with open(file, 'rb') as fp:
942
+ result = builder.parseFile(fp)
943
+ else:
944
+ result = builder.parseFile(file)
945
+ return result
946
+
947
+
948
+ def parseFragmentString(string, context, namespaces=True):
949
+ """Parse a fragment of a document from a string, given the context
950
+ from which it was originally extracted. context should be the
951
+ parent of the node(s) which are in the fragment.
952
+ """
953
+ if namespaces:
954
+ builder = FragmentBuilderNS(context)
955
+ else:
956
+ builder = FragmentBuilder(context)
957
+ return builder.parseString(string)
958
+
959
+
960
+ def makeBuilder(options):
961
+ """Create a builder based on an Options object."""
962
+ if options.namespaces:
963
+ return ExpatBuilderNS(options)
964
+ else:
965
+ return ExpatBuilder(options)
infer_4_47_1/lib/python3.10/xml/dom/minidom.py ADDED
@@ -0,0 +1,2013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple implementation of the Level 1 DOM.
2
+
3
+ Namespaces and other minor Level 2 features are also supported.
4
+
5
+ parse("foo.xml")
6
+
7
+ parseString("<foo><bar/></foo>")
8
+
9
+ Todo:
10
+ =====
11
+ * convenience methods for getting elements and text.
12
+ * more testing
13
+ * bring some of the writer and linearizer code into conformance with this
14
+ interface
15
+ * SAX 2 namespaces
16
+ """
17
+
18
+ import io
19
+ import xml.dom
20
+
21
+ from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
22
+ from xml.dom.minicompat import *
23
+ from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
24
+
25
+ # This is used by the ID-cache invalidation checks; the list isn't
26
+ # actually complete, since the nodes being checked will never be the
27
+ # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
28
+ # the node being added or removed, not the node being modified.)
29
+ #
30
+ _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
31
+ xml.dom.Node.ENTITY_REFERENCE_NODE)
32
+
33
+
34
+ class Node(xml.dom.Node):
35
+ namespaceURI = None # this is non-null only for elements and attributes
36
+ parentNode = None
37
+ ownerDocument = None
38
+ nextSibling = None
39
+ previousSibling = None
40
+
41
+ prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
42
+
43
+ def __bool__(self):
44
+ return True
45
+
46
+ def toxml(self, encoding=None, standalone=None):
47
+ return self.toprettyxml("", "", encoding, standalone)
48
+
49
+ def toprettyxml(self, indent="\t", newl="\n", encoding=None,
50
+ standalone=None):
51
+ if encoding is None:
52
+ writer = io.StringIO()
53
+ else:
54
+ writer = io.TextIOWrapper(io.BytesIO(),
55
+ encoding=encoding,
56
+ errors="xmlcharrefreplace",
57
+ newline='\n')
58
+ if self.nodeType == Node.DOCUMENT_NODE:
59
+ # Can pass encoding only to document, to put it into XML header
60
+ self.writexml(writer, "", indent, newl, encoding, standalone)
61
+ else:
62
+ self.writexml(writer, "", indent, newl)
63
+ if encoding is None:
64
+ return writer.getvalue()
65
+ else:
66
+ return writer.detach().getvalue()
67
+
68
+ def hasChildNodes(self):
69
+ return bool(self.childNodes)
70
+
71
+ def _get_childNodes(self):
72
+ return self.childNodes
73
+
74
+ def _get_firstChild(self):
75
+ if self.childNodes:
76
+ return self.childNodes[0]
77
+
78
+ def _get_lastChild(self):
79
+ if self.childNodes:
80
+ return self.childNodes[-1]
81
+
82
+ def insertBefore(self, newChild, refChild):
83
+ if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
84
+ for c in tuple(newChild.childNodes):
85
+ self.insertBefore(c, refChild)
86
+ ### The DOM does not clearly specify what to return in this case
87
+ return newChild
88
+ if newChild.nodeType not in self._child_node_types:
89
+ raise xml.dom.HierarchyRequestErr(
90
+ "%s cannot be child of %s" % (repr(newChild), repr(self)))
91
+ if newChild.parentNode is not None:
92
+ newChild.parentNode.removeChild(newChild)
93
+ if refChild is None:
94
+ self.appendChild(newChild)
95
+ else:
96
+ try:
97
+ index = self.childNodes.index(refChild)
98
+ except ValueError:
99
+ raise xml.dom.NotFoundErr()
100
+ if newChild.nodeType in _nodeTypes_with_children:
101
+ _clear_id_cache(self)
102
+ self.childNodes.insert(index, newChild)
103
+ newChild.nextSibling = refChild
104
+ refChild.previousSibling = newChild
105
+ if index:
106
+ node = self.childNodes[index-1]
107
+ node.nextSibling = newChild
108
+ newChild.previousSibling = node
109
+ else:
110
+ newChild.previousSibling = None
111
+ newChild.parentNode = self
112
+ return newChild
113
+
114
+ def appendChild(self, node):
115
+ if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
116
+ for c in tuple(node.childNodes):
117
+ self.appendChild(c)
118
+ ### The DOM does not clearly specify what to return in this case
119
+ return node
120
+ if node.nodeType not in self._child_node_types:
121
+ raise xml.dom.HierarchyRequestErr(
122
+ "%s cannot be child of %s" % (repr(node), repr(self)))
123
+ elif node.nodeType in _nodeTypes_with_children:
124
+ _clear_id_cache(self)
125
+ if node.parentNode is not None:
126
+ node.parentNode.removeChild(node)
127
+ _append_child(self, node)
128
+ node.nextSibling = None
129
+ return node
130
+
131
+ def replaceChild(self, newChild, oldChild):
132
+ if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
133
+ refChild = oldChild.nextSibling
134
+ self.removeChild(oldChild)
135
+ return self.insertBefore(newChild, refChild)
136
+ if newChild.nodeType not in self._child_node_types:
137
+ raise xml.dom.HierarchyRequestErr(
138
+ "%s cannot be child of %s" % (repr(newChild), repr(self)))
139
+ if newChild is oldChild:
140
+ return
141
+ if newChild.parentNode is not None:
142
+ newChild.parentNode.removeChild(newChild)
143
+ try:
144
+ index = self.childNodes.index(oldChild)
145
+ except ValueError:
146
+ raise xml.dom.NotFoundErr()
147
+ self.childNodes[index] = newChild
148
+ newChild.parentNode = self
149
+ oldChild.parentNode = None
150
+ if (newChild.nodeType in _nodeTypes_with_children
151
+ or oldChild.nodeType in _nodeTypes_with_children):
152
+ _clear_id_cache(self)
153
+ newChild.nextSibling = oldChild.nextSibling
154
+ newChild.previousSibling = oldChild.previousSibling
155
+ oldChild.nextSibling = None
156
+ oldChild.previousSibling = None
157
+ if newChild.previousSibling:
158
+ newChild.previousSibling.nextSibling = newChild
159
+ if newChild.nextSibling:
160
+ newChild.nextSibling.previousSibling = newChild
161
+ return oldChild
162
+
163
+ def removeChild(self, oldChild):
164
+ try:
165
+ self.childNodes.remove(oldChild)
166
+ except ValueError:
167
+ raise xml.dom.NotFoundErr()
168
+ if oldChild.nextSibling is not None:
169
+ oldChild.nextSibling.previousSibling = oldChild.previousSibling
170
+ if oldChild.previousSibling is not None:
171
+ oldChild.previousSibling.nextSibling = oldChild.nextSibling
172
+ oldChild.nextSibling = oldChild.previousSibling = None
173
+ if oldChild.nodeType in _nodeTypes_with_children:
174
+ _clear_id_cache(self)
175
+
176
+ oldChild.parentNode = None
177
+ return oldChild
178
+
179
+ def normalize(self):
180
+ L = []
181
+ for child in self.childNodes:
182
+ if child.nodeType == Node.TEXT_NODE:
183
+ if not child.data:
184
+ # empty text node; discard
185
+ if L:
186
+ L[-1].nextSibling = child.nextSibling
187
+ if child.nextSibling:
188
+ child.nextSibling.previousSibling = child.previousSibling
189
+ child.unlink()
190
+ elif L and L[-1].nodeType == child.nodeType:
191
+ # collapse text node
192
+ node = L[-1]
193
+ node.data = node.data + child.data
194
+ node.nextSibling = child.nextSibling
195
+ if child.nextSibling:
196
+ child.nextSibling.previousSibling = node
197
+ child.unlink()
198
+ else:
199
+ L.append(child)
200
+ else:
201
+ L.append(child)
202
+ if child.nodeType == Node.ELEMENT_NODE:
203
+ child.normalize()
204
+ self.childNodes[:] = L
205
+
206
+ def cloneNode(self, deep):
207
+ return _clone_node(self, deep, self.ownerDocument or self)
208
+
209
+ def isSupported(self, feature, version):
210
+ return self.ownerDocument.implementation.hasFeature(feature, version)
211
+
212
+ def _get_localName(self):
213
+ # Overridden in Element and Attr where localName can be Non-Null
214
+ return None
215
+
216
+ # Node interfaces from Level 3 (WD 9 April 2002)
217
+
218
+ def isSameNode(self, other):
219
+ return self is other
220
+
221
+ def getInterface(self, feature):
222
+ if self.isSupported(feature, None):
223
+ return self
224
+ else:
225
+ return None
226
+
227
+ # The "user data" functions use a dictionary that is only present
228
+ # if some user data has been set, so be careful not to assume it
229
+ # exists.
230
+
231
+ def getUserData(self, key):
232
+ try:
233
+ return self._user_data[key][0]
234
+ except (AttributeError, KeyError):
235
+ return None
236
+
237
+ def setUserData(self, key, data, handler):
238
+ old = None
239
+ try:
240
+ d = self._user_data
241
+ except AttributeError:
242
+ d = {}
243
+ self._user_data = d
244
+ if key in d:
245
+ old = d[key][0]
246
+ if data is None:
247
+ # ignore handlers passed for None
248
+ handler = None
249
+ if old is not None:
250
+ del d[key]
251
+ else:
252
+ d[key] = (data, handler)
253
+ return old
254
+
255
+ def _call_user_data_handler(self, operation, src, dst):
256
+ if hasattr(self, "_user_data"):
257
+ for key, (data, handler) in list(self._user_data.items()):
258
+ if handler is not None:
259
+ handler.handle(operation, key, data, src, dst)
260
+
261
+ # minidom-specific API:
262
+
263
+ def unlink(self):
264
+ self.parentNode = self.ownerDocument = None
265
+ if self.childNodes:
266
+ for child in self.childNodes:
267
+ child.unlink()
268
+ self.childNodes = NodeList()
269
+ self.previousSibling = None
270
+ self.nextSibling = None
271
+
272
+ # A Node is its own context manager, to ensure that an unlink() call occurs.
273
+ # This is similar to how a file object works.
274
+ def __enter__(self):
275
+ return self
276
+
277
+ def __exit__(self, et, ev, tb):
278
+ self.unlink()
279
+
280
+ defproperty(Node, "firstChild", doc="First child node, or None.")
281
+ defproperty(Node, "lastChild", doc="Last child node, or None.")
282
+ defproperty(Node, "localName", doc="Namespace-local name of this node.")
283
+
284
+
285
+ def _append_child(self, node):
286
+ # fast path with less checks; usable by DOM builders if careful
287
+ childNodes = self.childNodes
288
+ if childNodes:
289
+ last = childNodes[-1]
290
+ node.previousSibling = last
291
+ last.nextSibling = node
292
+ childNodes.append(node)
293
+ node.parentNode = self
294
+
295
+ def _in_document(node):
296
+ # return True iff node is part of a document tree
297
+ while node is not None:
298
+ if node.nodeType == Node.DOCUMENT_NODE:
299
+ return True
300
+ node = node.parentNode
301
+ return False
302
+
303
+ def _write_data(writer, data):
304
+ "Writes datachars to writer."
305
+ if data:
306
+ data = data.replace("&", "&amp;").replace("<", "&lt;"). \
307
+ replace("\"", "&quot;").replace(">", "&gt;")
308
+ writer.write(data)
309
+
310
+ def _get_elements_by_tagName_helper(parent, name, rc):
311
+ for node in parent.childNodes:
312
+ if node.nodeType == Node.ELEMENT_NODE and \
313
+ (name == "*" or node.tagName == name):
314
+ rc.append(node)
315
+ _get_elements_by_tagName_helper(node, name, rc)
316
+ return rc
317
+
318
+ def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
319
+ for node in parent.childNodes:
320
+ if node.nodeType == Node.ELEMENT_NODE:
321
+ if ((localName == "*" or node.localName == localName) and
322
+ (nsURI == "*" or node.namespaceURI == nsURI)):
323
+ rc.append(node)
324
+ _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
325
+ return rc
326
+
327
+ class DocumentFragment(Node):
328
+ nodeType = Node.DOCUMENT_FRAGMENT_NODE
329
+ nodeName = "#document-fragment"
330
+ nodeValue = None
331
+ attributes = None
332
+ parentNode = None
333
+ _child_node_types = (Node.ELEMENT_NODE,
334
+ Node.TEXT_NODE,
335
+ Node.CDATA_SECTION_NODE,
336
+ Node.ENTITY_REFERENCE_NODE,
337
+ Node.PROCESSING_INSTRUCTION_NODE,
338
+ Node.COMMENT_NODE,
339
+ Node.NOTATION_NODE)
340
+
341
+ def __init__(self):
342
+ self.childNodes = NodeList()
343
+
344
+
345
+ class Attr(Node):
346
+ __slots__=('_name', '_value', 'namespaceURI',
347
+ '_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement')
348
+ nodeType = Node.ATTRIBUTE_NODE
349
+ attributes = None
350
+ specified = False
351
+ _is_id = False
352
+
353
+ _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
354
+
355
+ def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
356
+ prefix=None):
357
+ self.ownerElement = None
358
+ self._name = qName
359
+ self.namespaceURI = namespaceURI
360
+ self._prefix = prefix
361
+ if localName is not None:
362
+ self._localName = localName
363
+ self.childNodes = NodeList()
364
+
365
+ # Add the single child node that represents the value of the attr
366
+ self.childNodes.append(Text())
367
+
368
+ # nodeValue and value are set elsewhere
369
+
370
+ def _get_localName(self):
371
+ try:
372
+ return self._localName
373
+ except AttributeError:
374
+ return self.nodeName.split(":", 1)[-1]
375
+
376
+ def _get_specified(self):
377
+ return self.specified
378
+
379
+ def _get_name(self):
380
+ return self._name
381
+
382
+ def _set_name(self, value):
383
+ self._name = value
384
+ if self.ownerElement is not None:
385
+ _clear_id_cache(self.ownerElement)
386
+
387
+ nodeName = name = property(_get_name, _set_name)
388
+
389
+ def _get_value(self):
390
+ return self._value
391
+
392
+ def _set_value(self, value):
393
+ self._value = value
394
+ self.childNodes[0].data = value
395
+ if self.ownerElement is not None:
396
+ _clear_id_cache(self.ownerElement)
397
+ self.childNodes[0].data = value
398
+
399
+ nodeValue = value = property(_get_value, _set_value)
400
+
401
+ def _get_prefix(self):
402
+ return self._prefix
403
+
404
+ def _set_prefix(self, prefix):
405
+ nsuri = self.namespaceURI
406
+ if prefix == "xmlns":
407
+ if nsuri and nsuri != XMLNS_NAMESPACE:
408
+ raise xml.dom.NamespaceErr(
409
+ "illegal use of 'xmlns' prefix for the wrong namespace")
410
+ self._prefix = prefix
411
+ if prefix is None:
412
+ newName = self.localName
413
+ else:
414
+ newName = "%s:%s" % (prefix, self.localName)
415
+ if self.ownerElement:
416
+ _clear_id_cache(self.ownerElement)
417
+ self.name = newName
418
+
419
+ prefix = property(_get_prefix, _set_prefix)
420
+
421
+ def unlink(self):
422
+ # This implementation does not call the base implementation
423
+ # since most of that is not needed, and the expense of the
424
+ # method call is not warranted. We duplicate the removal of
425
+ # children, but that's all we needed from the base class.
426
+ elem = self.ownerElement
427
+ if elem is not None:
428
+ del elem._attrs[self.nodeName]
429
+ del elem._attrsNS[(self.namespaceURI, self.localName)]
430
+ if self._is_id:
431
+ self._is_id = False
432
+ elem._magic_id_nodes -= 1
433
+ self.ownerDocument._magic_id_count -= 1
434
+ for child in self.childNodes:
435
+ child.unlink()
436
+ del self.childNodes[:]
437
+
438
+ def _get_isId(self):
439
+ if self._is_id:
440
+ return True
441
+ doc = self.ownerDocument
442
+ elem = self.ownerElement
443
+ if doc is None or elem is None:
444
+ return False
445
+
446
+ info = doc._get_elem_info(elem)
447
+ if info is None:
448
+ return False
449
+ if self.namespaceURI:
450
+ return info.isIdNS(self.namespaceURI, self.localName)
451
+ else:
452
+ return info.isId(self.nodeName)
453
+
454
+ def _get_schemaType(self):
455
+ doc = self.ownerDocument
456
+ elem = self.ownerElement
457
+ if doc is None or elem is None:
458
+ return _no_type
459
+
460
+ info = doc._get_elem_info(elem)
461
+ if info is None:
462
+ return _no_type
463
+ if self.namespaceURI:
464
+ return info.getAttributeTypeNS(self.namespaceURI, self.localName)
465
+ else:
466
+ return info.getAttributeType(self.nodeName)
467
+
468
+ defproperty(Attr, "isId", doc="True if this attribute is an ID.")
469
+ defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
470
+ defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
471
+
472
+
473
+ class NamedNodeMap(object):
474
+ """The attribute list is a transient interface to the underlying
475
+ dictionaries. Mutations here will change the underlying element's
476
+ dictionary.
477
+
478
+ Ordering is imposed artificially and does not reflect the order of
479
+ attributes as found in an input document.
480
+ """
481
+
482
+ __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
483
+
484
+ def __init__(self, attrs, attrsNS, ownerElement):
485
+ self._attrs = attrs
486
+ self._attrsNS = attrsNS
487
+ self._ownerElement = ownerElement
488
+
489
+ def _get_length(self):
490
+ return len(self._attrs)
491
+
492
+ def item(self, index):
493
+ try:
494
+ return self[list(self._attrs.keys())[index]]
495
+ except IndexError:
496
+ return None
497
+
498
+ def items(self):
499
+ L = []
500
+ for node in self._attrs.values():
501
+ L.append((node.nodeName, node.value))
502
+ return L
503
+
504
+ def itemsNS(self):
505
+ L = []
506
+ for node in self._attrs.values():
507
+ L.append(((node.namespaceURI, node.localName), node.value))
508
+ return L
509
+
510
+ def __contains__(self, key):
511
+ if isinstance(key, str):
512
+ return key in self._attrs
513
+ else:
514
+ return key in self._attrsNS
515
+
516
+ def keys(self):
517
+ return self._attrs.keys()
518
+
519
+ def keysNS(self):
520
+ return self._attrsNS.keys()
521
+
522
+ def values(self):
523
+ return self._attrs.values()
524
+
525
+ def get(self, name, value=None):
526
+ return self._attrs.get(name, value)
527
+
528
+ __len__ = _get_length
529
+
530
+ def _cmp(self, other):
531
+ if self._attrs is getattr(other, "_attrs", None):
532
+ return 0
533
+ else:
534
+ return (id(self) > id(other)) - (id(self) < id(other))
535
+
536
+ def __eq__(self, other):
537
+ return self._cmp(other) == 0
538
+
539
+ def __ge__(self, other):
540
+ return self._cmp(other) >= 0
541
+
542
+ def __gt__(self, other):
543
+ return self._cmp(other) > 0
544
+
545
+ def __le__(self, other):
546
+ return self._cmp(other) <= 0
547
+
548
+ def __lt__(self, other):
549
+ return self._cmp(other) < 0
550
+
551
+ def __getitem__(self, attname_or_tuple):
552
+ if isinstance(attname_or_tuple, tuple):
553
+ return self._attrsNS[attname_or_tuple]
554
+ else:
555
+ return self._attrs[attname_or_tuple]
556
+
557
+ # same as set
558
+ def __setitem__(self, attname, value):
559
+ if isinstance(value, str):
560
+ try:
561
+ node = self._attrs[attname]
562
+ except KeyError:
563
+ node = Attr(attname)
564
+ node.ownerDocument = self._ownerElement.ownerDocument
565
+ self.setNamedItem(node)
566
+ node.value = value
567
+ else:
568
+ if not isinstance(value, Attr):
569
+ raise TypeError("value must be a string or Attr object")
570
+ node = value
571
+ self.setNamedItem(node)
572
+
573
+ def getNamedItem(self, name):
574
+ try:
575
+ return self._attrs[name]
576
+ except KeyError:
577
+ return None
578
+
579
+ def getNamedItemNS(self, namespaceURI, localName):
580
+ try:
581
+ return self._attrsNS[(namespaceURI, localName)]
582
+ except KeyError:
583
+ return None
584
+
585
+ def removeNamedItem(self, name):
586
+ n = self.getNamedItem(name)
587
+ if n is not None:
588
+ _clear_id_cache(self._ownerElement)
589
+ del self._attrs[n.nodeName]
590
+ del self._attrsNS[(n.namespaceURI, n.localName)]
591
+ if hasattr(n, 'ownerElement'):
592
+ n.ownerElement = None
593
+ return n
594
+ else:
595
+ raise xml.dom.NotFoundErr()
596
+
597
+ def removeNamedItemNS(self, namespaceURI, localName):
598
+ n = self.getNamedItemNS(namespaceURI, localName)
599
+ if n is not None:
600
+ _clear_id_cache(self._ownerElement)
601
+ del self._attrsNS[(n.namespaceURI, n.localName)]
602
+ del self._attrs[n.nodeName]
603
+ if hasattr(n, 'ownerElement'):
604
+ n.ownerElement = None
605
+ return n
606
+ else:
607
+ raise xml.dom.NotFoundErr()
608
+
609
+ def setNamedItem(self, node):
610
+ if not isinstance(node, Attr):
611
+ raise xml.dom.HierarchyRequestErr(
612
+ "%s cannot be child of %s" % (repr(node), repr(self)))
613
+ old = self._attrs.get(node.name)
614
+ if old:
615
+ old.unlink()
616
+ self._attrs[node.name] = node
617
+ self._attrsNS[(node.namespaceURI, node.localName)] = node
618
+ node.ownerElement = self._ownerElement
619
+ _clear_id_cache(node.ownerElement)
620
+ return old
621
+
622
+ def setNamedItemNS(self, node):
623
+ return self.setNamedItem(node)
624
+
625
+ def __delitem__(self, attname_or_tuple):
626
+ node = self[attname_or_tuple]
627
+ _clear_id_cache(node.ownerElement)
628
+ node.unlink()
629
+
630
+ def __getstate__(self):
631
+ return self._attrs, self._attrsNS, self._ownerElement
632
+
633
+ def __setstate__(self, state):
634
+ self._attrs, self._attrsNS, self._ownerElement = state
635
+
636
+ defproperty(NamedNodeMap, "length",
637
+ doc="Number of nodes in the NamedNodeMap.")
638
+
639
+ AttributeList = NamedNodeMap
640
+
641
+
642
+ class TypeInfo(object):
643
+ __slots__ = 'namespace', 'name'
644
+
645
+ def __init__(self, namespace, name):
646
+ self.namespace = namespace
647
+ self.name = name
648
+
649
+ def __repr__(self):
650
+ if self.namespace:
651
+ return "<%s %r (from %r)>" % (self.__class__.__name__, self.name,
652
+ self.namespace)
653
+ else:
654
+ return "<%s %r>" % (self.__class__.__name__, self.name)
655
+
656
+ def _get_name(self):
657
+ return self.name
658
+
659
+ def _get_namespace(self):
660
+ return self.namespace
661
+
662
+ _no_type = TypeInfo(None, None)
663
+
664
+ class Element(Node):
665
+ __slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix',
666
+ 'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS',
667
+ 'nextSibling', 'previousSibling')
668
+ nodeType = Node.ELEMENT_NODE
669
+ nodeValue = None
670
+ schemaType = _no_type
671
+
672
+ _magic_id_nodes = 0
673
+
674
+ _child_node_types = (Node.ELEMENT_NODE,
675
+ Node.PROCESSING_INSTRUCTION_NODE,
676
+ Node.COMMENT_NODE,
677
+ Node.TEXT_NODE,
678
+ Node.CDATA_SECTION_NODE,
679
+ Node.ENTITY_REFERENCE_NODE)
680
+
681
+ def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
682
+ localName=None):
683
+ self.parentNode = None
684
+ self.tagName = self.nodeName = tagName
685
+ self.prefix = prefix
686
+ self.namespaceURI = namespaceURI
687
+ self.childNodes = NodeList()
688
+ self.nextSibling = self.previousSibling = None
689
+
690
+ # Attribute dictionaries are lazily created
691
+ # attributes are double-indexed:
692
+ # tagName -> Attribute
693
+ # URI,localName -> Attribute
694
+ # in the future: consider lazy generation
695
+ # of attribute objects this is too tricky
696
+ # for now because of headaches with
697
+ # namespaces.
698
+ self._attrs = None
699
+ self._attrsNS = None
700
+
701
+ def _ensure_attributes(self):
702
+ if self._attrs is None:
703
+ self._attrs = {}
704
+ self._attrsNS = {}
705
+
706
+ def _get_localName(self):
707
+ try:
708
+ return self._localName
709
+ except AttributeError:
710
+ return self.tagName.split(":", 1)[-1]
711
+
712
+ def _get_tagName(self):
713
+ return self.tagName
714
+
715
+ def unlink(self):
716
+ if self._attrs is not None:
717
+ for attr in list(self._attrs.values()):
718
+ attr.unlink()
719
+ self._attrs = None
720
+ self._attrsNS = None
721
+ Node.unlink(self)
722
+
723
+ def getAttribute(self, attname):
724
+ """Returns the value of the specified attribute.
725
+
726
+ Returns the value of the element's attribute named attname as
727
+ a string. An empty string is returned if the element does not
728
+ have such an attribute. Note that an empty string may also be
729
+ returned as an explicitly given attribute value, use the
730
+ hasAttribute method to distinguish these two cases.
731
+ """
732
+ if self._attrs is None:
733
+ return ""
734
+ try:
735
+ return self._attrs[attname].value
736
+ except KeyError:
737
+ return ""
738
+
739
+ def getAttributeNS(self, namespaceURI, localName):
740
+ if self._attrsNS is None:
741
+ return ""
742
+ try:
743
+ return self._attrsNS[(namespaceURI, localName)].value
744
+ except KeyError:
745
+ return ""
746
+
747
+ def setAttribute(self, attname, value):
748
+ attr = self.getAttributeNode(attname)
749
+ if attr is None:
750
+ attr = Attr(attname)
751
+ attr.value = value # also sets nodeValue
752
+ attr.ownerDocument = self.ownerDocument
753
+ self.setAttributeNode(attr)
754
+ elif value != attr.value:
755
+ attr.value = value
756
+ if attr.isId:
757
+ _clear_id_cache(self)
758
+
759
+ def setAttributeNS(self, namespaceURI, qualifiedName, value):
760
+ prefix, localname = _nssplit(qualifiedName)
761
+ attr = self.getAttributeNodeNS(namespaceURI, localname)
762
+ if attr is None:
763
+ attr = Attr(qualifiedName, namespaceURI, localname, prefix)
764
+ attr.value = value
765
+ attr.ownerDocument = self.ownerDocument
766
+ self.setAttributeNode(attr)
767
+ else:
768
+ if value != attr.value:
769
+ attr.value = value
770
+ if attr.isId:
771
+ _clear_id_cache(self)
772
+ if attr.prefix != prefix:
773
+ attr.prefix = prefix
774
+ attr.nodeName = qualifiedName
775
+
776
+ def getAttributeNode(self, attrname):
777
+ if self._attrs is None:
778
+ return None
779
+ return self._attrs.get(attrname)
780
+
781
+ def getAttributeNodeNS(self, namespaceURI, localName):
782
+ if self._attrsNS is None:
783
+ return None
784
+ return self._attrsNS.get((namespaceURI, localName))
785
+
786
+ def setAttributeNode(self, attr):
787
+ if attr.ownerElement not in (None, self):
788
+ raise xml.dom.InuseAttributeErr("attribute node already owned")
789
+ self._ensure_attributes()
790
+ old1 = self._attrs.get(attr.name, None)
791
+ if old1 is not None:
792
+ self.removeAttributeNode(old1)
793
+ old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
794
+ if old2 is not None and old2 is not old1:
795
+ self.removeAttributeNode(old2)
796
+ _set_attribute_node(self, attr)
797
+
798
+ if old1 is not attr:
799
+ # It might have already been part of this node, in which case
800
+ # it doesn't represent a change, and should not be returned.
801
+ return old1
802
+ if old2 is not attr:
803
+ return old2
804
+
805
+ setAttributeNodeNS = setAttributeNode
806
+
807
+ def removeAttribute(self, name):
808
+ if self._attrsNS is None:
809
+ raise xml.dom.NotFoundErr()
810
+ try:
811
+ attr = self._attrs[name]
812
+ except KeyError:
813
+ raise xml.dom.NotFoundErr()
814
+ self.removeAttributeNode(attr)
815
+
816
+ def removeAttributeNS(self, namespaceURI, localName):
817
+ if self._attrsNS is None:
818
+ raise xml.dom.NotFoundErr()
819
+ try:
820
+ attr = self._attrsNS[(namespaceURI, localName)]
821
+ except KeyError:
822
+ raise xml.dom.NotFoundErr()
823
+ self.removeAttributeNode(attr)
824
+
825
+ def removeAttributeNode(self, node):
826
+ if node is None:
827
+ raise xml.dom.NotFoundErr()
828
+ try:
829
+ self._attrs[node.name]
830
+ except KeyError:
831
+ raise xml.dom.NotFoundErr()
832
+ _clear_id_cache(self)
833
+ node.unlink()
834
+ # Restore this since the node is still useful and otherwise
835
+ # unlinked
836
+ node.ownerDocument = self.ownerDocument
837
+ return node
838
+
839
+ removeAttributeNodeNS = removeAttributeNode
840
+
841
+ def hasAttribute(self, name):
842
+ """Checks whether the element has an attribute with the specified name.
843
+
844
+ Returns True if the element has an attribute with the specified name.
845
+ Otherwise, returns False.
846
+ """
847
+ if self._attrs is None:
848
+ return False
849
+ return name in self._attrs
850
+
851
+ def hasAttributeNS(self, namespaceURI, localName):
852
+ if self._attrsNS is None:
853
+ return False
854
+ return (namespaceURI, localName) in self._attrsNS
855
+
856
+ def getElementsByTagName(self, name):
857
+ """Returns all descendant elements with the given tag name.
858
+
859
+ Returns the list of all descendant elements (not direct children
860
+ only) with the specified tag name.
861
+ """
862
+ return _get_elements_by_tagName_helper(self, name, NodeList())
863
+
864
+ def getElementsByTagNameNS(self, namespaceURI, localName):
865
+ return _get_elements_by_tagName_ns_helper(
866
+ self, namespaceURI, localName, NodeList())
867
+
868
+ def __repr__(self):
869
+ return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
870
+
871
+ def writexml(self, writer, indent="", addindent="", newl=""):
872
+ """Write an XML element to a file-like object
873
+
874
+ Write the element to the writer object that must provide
875
+ a write method (e.g. a file or StringIO object).
876
+ """
877
+ # indent = current indentation
878
+ # addindent = indentation to add to higher levels
879
+ # newl = newline string
880
+ writer.write(indent+"<" + self.tagName)
881
+
882
+ attrs = self._get_attributes()
883
+
884
+ for a_name in attrs.keys():
885
+ writer.write(" %s=\"" % a_name)
886
+ _write_data(writer, attrs[a_name].value)
887
+ writer.write("\"")
888
+ if self.childNodes:
889
+ writer.write(">")
890
+ if (len(self.childNodes) == 1 and
891
+ self.childNodes[0].nodeType in (
892
+ Node.TEXT_NODE, Node.CDATA_SECTION_NODE)):
893
+ self.childNodes[0].writexml(writer, '', '', '')
894
+ else:
895
+ writer.write(newl)
896
+ for node in self.childNodes:
897
+ node.writexml(writer, indent+addindent, addindent, newl)
898
+ writer.write(indent)
899
+ writer.write("</%s>%s" % (self.tagName, newl))
900
+ else:
901
+ writer.write("/>%s"%(newl))
902
+
903
+ def _get_attributes(self):
904
+ self._ensure_attributes()
905
+ return NamedNodeMap(self._attrs, self._attrsNS, self)
906
+
907
+ def hasAttributes(self):
908
+ if self._attrs:
909
+ return True
910
+ else:
911
+ return False
912
+
913
+ # DOM Level 3 attributes, based on the 22 Oct 2002 draft
914
+
915
+ def setIdAttribute(self, name):
916
+ idAttr = self.getAttributeNode(name)
917
+ self.setIdAttributeNode(idAttr)
918
+
919
+ def setIdAttributeNS(self, namespaceURI, localName):
920
+ idAttr = self.getAttributeNodeNS(namespaceURI, localName)
921
+ self.setIdAttributeNode(idAttr)
922
+
923
+ def setIdAttributeNode(self, idAttr):
924
+ if idAttr is None or not self.isSameNode(idAttr.ownerElement):
925
+ raise xml.dom.NotFoundErr()
926
+ if _get_containing_entref(self) is not None:
927
+ raise xml.dom.NoModificationAllowedErr()
928
+ if not idAttr._is_id:
929
+ idAttr._is_id = True
930
+ self._magic_id_nodes += 1
931
+ self.ownerDocument._magic_id_count += 1
932
+ _clear_id_cache(self)
933
+
934
+ defproperty(Element, "attributes",
935
+ doc="NamedNodeMap of attributes on the element.")
936
+ defproperty(Element, "localName",
937
+ doc="Namespace-local name of this element.")
938
+
939
+
940
+ def _set_attribute_node(element, attr):
941
+ _clear_id_cache(element)
942
+ element._ensure_attributes()
943
+ element._attrs[attr.name] = attr
944
+ element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
945
+
946
+ # This creates a circular reference, but Element.unlink()
947
+ # breaks the cycle since the references to the attribute
948
+ # dictionaries are tossed.
949
+ attr.ownerElement = element
950
+
951
+ class Childless:
952
+ """Mixin that makes childless-ness easy to implement and avoids
953
+ the complexity of the Node methods that deal with children.
954
+ """
955
+ __slots__ = ()
956
+
957
+ attributes = None
958
+ childNodes = EmptyNodeList()
959
+ firstChild = None
960
+ lastChild = None
961
+
962
+ def _get_firstChild(self):
963
+ return None
964
+
965
+ def _get_lastChild(self):
966
+ return None
967
+
968
+ def appendChild(self, node):
969
+ raise xml.dom.HierarchyRequestErr(
970
+ self.nodeName + " nodes cannot have children")
971
+
972
+ def hasChildNodes(self):
973
+ return False
974
+
975
+ def insertBefore(self, newChild, refChild):
976
+ raise xml.dom.HierarchyRequestErr(
977
+ self.nodeName + " nodes do not have children")
978
+
979
+ def removeChild(self, oldChild):
980
+ raise xml.dom.NotFoundErr(
981
+ self.nodeName + " nodes do not have children")
982
+
983
+ def normalize(self):
984
+ # For childless nodes, normalize() has nothing to do.
985
+ pass
986
+
987
+ def replaceChild(self, newChild, oldChild):
988
+ raise xml.dom.HierarchyRequestErr(
989
+ self.nodeName + " nodes do not have children")
990
+
991
+
992
+ class ProcessingInstruction(Childless, Node):
993
+ nodeType = Node.PROCESSING_INSTRUCTION_NODE
994
+ __slots__ = ('target', 'data')
995
+
996
+ def __init__(self, target, data):
997
+ self.target = target
998
+ self.data = data
999
+
1000
+ # nodeValue is an alias for data
1001
+ def _get_nodeValue(self):
1002
+ return self.data
1003
+ def _set_nodeValue(self, value):
1004
+ self.data = value
1005
+ nodeValue = property(_get_nodeValue, _set_nodeValue)
1006
+
1007
+ # nodeName is an alias for target
1008
+ def _get_nodeName(self):
1009
+ return self.target
1010
+ def _set_nodeName(self, value):
1011
+ self.target = value
1012
+ nodeName = property(_get_nodeName, _set_nodeName)
1013
+
1014
+ def writexml(self, writer, indent="", addindent="", newl=""):
1015
+ writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
1016
+
1017
+
1018
+ class CharacterData(Childless, Node):
1019
+ __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling')
1020
+
1021
+ def __init__(self):
1022
+ self.ownerDocument = self.parentNode = None
1023
+ self.previousSibling = self.nextSibling = None
1024
+ self._data = ''
1025
+ Node.__init__(self)
1026
+
1027
+ def _get_length(self):
1028
+ return len(self.data)
1029
+ __len__ = _get_length
1030
+
1031
+ def _get_data(self):
1032
+ return self._data
1033
+ def _set_data(self, data):
1034
+ self._data = data
1035
+
1036
+ data = nodeValue = property(_get_data, _set_data)
1037
+
1038
+ def __repr__(self):
1039
+ data = self.data
1040
+ if len(data) > 10:
1041
+ dotdotdot = "..."
1042
+ else:
1043
+ dotdotdot = ""
1044
+ return '<DOM %s node "%r%s">' % (
1045
+ self.__class__.__name__, data[0:10], dotdotdot)
1046
+
1047
+ def substringData(self, offset, count):
1048
+ if offset < 0:
1049
+ raise xml.dom.IndexSizeErr("offset cannot be negative")
1050
+ if offset >= len(self.data):
1051
+ raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
1052
+ if count < 0:
1053
+ raise xml.dom.IndexSizeErr("count cannot be negative")
1054
+ return self.data[offset:offset+count]
1055
+
1056
+ def appendData(self, arg):
1057
+ self.data = self.data + arg
1058
+
1059
+ def insertData(self, offset, arg):
1060
+ if offset < 0:
1061
+ raise xml.dom.IndexSizeErr("offset cannot be negative")
1062
+ if offset >= len(self.data):
1063
+ raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
1064
+ if arg:
1065
+ self.data = "%s%s%s" % (
1066
+ self.data[:offset], arg, self.data[offset:])
1067
+
1068
+ def deleteData(self, offset, count):
1069
+ if offset < 0:
1070
+ raise xml.dom.IndexSizeErr("offset cannot be negative")
1071
+ if offset >= len(self.data):
1072
+ raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
1073
+ if count < 0:
1074
+ raise xml.dom.IndexSizeErr("count cannot be negative")
1075
+ if count:
1076
+ self.data = self.data[:offset] + self.data[offset+count:]
1077
+
1078
+ def replaceData(self, offset, count, arg):
1079
+ if offset < 0:
1080
+ raise xml.dom.IndexSizeErr("offset cannot be negative")
1081
+ if offset >= len(self.data):
1082
+ raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
1083
+ if count < 0:
1084
+ raise xml.dom.IndexSizeErr("count cannot be negative")
1085
+ if count:
1086
+ self.data = "%s%s%s" % (
1087
+ self.data[:offset], arg, self.data[offset+count:])
1088
+
1089
+ defproperty(CharacterData, "length", doc="Length of the string data.")
1090
+
1091
+
1092
+ class Text(CharacterData):
1093
+ __slots__ = ()
1094
+
1095
+ nodeType = Node.TEXT_NODE
1096
+ nodeName = "#text"
1097
+ attributes = None
1098
+
1099
+ def splitText(self, offset):
1100
+ if offset < 0 or offset > len(self.data):
1101
+ raise xml.dom.IndexSizeErr("illegal offset value")
1102
+ newText = self.__class__()
1103
+ newText.data = self.data[offset:]
1104
+ newText.ownerDocument = self.ownerDocument
1105
+ next = self.nextSibling
1106
+ if self.parentNode and self in self.parentNode.childNodes:
1107
+ if next is None:
1108
+ self.parentNode.appendChild(newText)
1109
+ else:
1110
+ self.parentNode.insertBefore(newText, next)
1111
+ self.data = self.data[:offset]
1112
+ return newText
1113
+
1114
+ def writexml(self, writer, indent="", addindent="", newl=""):
1115
+ _write_data(writer, "%s%s%s" % (indent, self.data, newl))
1116
+
1117
+ # DOM Level 3 (WD 9 April 2002)
1118
+
1119
+ def _get_wholeText(self):
1120
+ L = [self.data]
1121
+ n = self.previousSibling
1122
+ while n is not None:
1123
+ if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1124
+ L.insert(0, n.data)
1125
+ n = n.previousSibling
1126
+ else:
1127
+ break
1128
+ n = self.nextSibling
1129
+ while n is not None:
1130
+ if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1131
+ L.append(n.data)
1132
+ n = n.nextSibling
1133
+ else:
1134
+ break
1135
+ return ''.join(L)
1136
+
1137
+ def replaceWholeText(self, content):
1138
+ # XXX This needs to be seriously changed if minidom ever
1139
+ # supports EntityReference nodes.
1140
+ parent = self.parentNode
1141
+ n = self.previousSibling
1142
+ while n is not None:
1143
+ if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1144
+ next = n.previousSibling
1145
+ parent.removeChild(n)
1146
+ n = next
1147
+ else:
1148
+ break
1149
+ n = self.nextSibling
1150
+ if not content:
1151
+ parent.removeChild(self)
1152
+ while n is not None:
1153
+ if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1154
+ next = n.nextSibling
1155
+ parent.removeChild(n)
1156
+ n = next
1157
+ else:
1158
+ break
1159
+ if content:
1160
+ self.data = content
1161
+ return self
1162
+ else:
1163
+ return None
1164
+
1165
+ def _get_isWhitespaceInElementContent(self):
1166
+ if self.data.strip():
1167
+ return False
1168
+ elem = _get_containing_element(self)
1169
+ if elem is None:
1170
+ return False
1171
+ info = self.ownerDocument._get_elem_info(elem)
1172
+ if info is None:
1173
+ return False
1174
+ else:
1175
+ return info.isElementContent()
1176
+
1177
+ defproperty(Text, "isWhitespaceInElementContent",
1178
+ doc="True iff this text node contains only whitespace"
1179
+ " and is in element content.")
1180
+ defproperty(Text, "wholeText",
1181
+ doc="The text of all logically-adjacent text nodes.")
1182
+
1183
+
1184
+ def _get_containing_element(node):
1185
+ c = node.parentNode
1186
+ while c is not None:
1187
+ if c.nodeType == Node.ELEMENT_NODE:
1188
+ return c
1189
+ c = c.parentNode
1190
+ return None
1191
+
1192
+ def _get_containing_entref(node):
1193
+ c = node.parentNode
1194
+ while c is not None:
1195
+ if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1196
+ return c
1197
+ c = c.parentNode
1198
+ return None
1199
+
1200
+
1201
+ class Comment(CharacterData):
1202
+ nodeType = Node.COMMENT_NODE
1203
+ nodeName = "#comment"
1204
+
1205
+ def __init__(self, data):
1206
+ CharacterData.__init__(self)
1207
+ self._data = data
1208
+
1209
+ def writexml(self, writer, indent="", addindent="", newl=""):
1210
+ if "--" in self.data:
1211
+ raise ValueError("'--' is not allowed in a comment node")
1212
+ writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1213
+
1214
+
1215
+ class CDATASection(Text):
1216
+ __slots__ = ()
1217
+
1218
+ nodeType = Node.CDATA_SECTION_NODE
1219
+ nodeName = "#cdata-section"
1220
+
1221
+ def writexml(self, writer, indent="", addindent="", newl=""):
1222
+ if self.data.find("]]>") >= 0:
1223
+ raise ValueError("']]>' not allowed in a CDATA section")
1224
+ writer.write("<![CDATA[%s]]>" % self.data)
1225
+
1226
+
1227
+ class ReadOnlySequentialNamedNodeMap(object):
1228
+ __slots__ = '_seq',
1229
+
1230
+ def __init__(self, seq=()):
1231
+ # seq should be a list or tuple
1232
+ self._seq = seq
1233
+
1234
+ def __len__(self):
1235
+ return len(self._seq)
1236
+
1237
+ def _get_length(self):
1238
+ return len(self._seq)
1239
+
1240
+ def getNamedItem(self, name):
1241
+ for n in self._seq:
1242
+ if n.nodeName == name:
1243
+ return n
1244
+
1245
+ def getNamedItemNS(self, namespaceURI, localName):
1246
+ for n in self._seq:
1247
+ if n.namespaceURI == namespaceURI and n.localName == localName:
1248
+ return n
1249
+
1250
+ def __getitem__(self, name_or_tuple):
1251
+ if isinstance(name_or_tuple, tuple):
1252
+ node = self.getNamedItemNS(*name_or_tuple)
1253
+ else:
1254
+ node = self.getNamedItem(name_or_tuple)
1255
+ if node is None:
1256
+ raise KeyError(name_or_tuple)
1257
+ return node
1258
+
1259
+ def item(self, index):
1260
+ if index < 0:
1261
+ return None
1262
+ try:
1263
+ return self._seq[index]
1264
+ except IndexError:
1265
+ return None
1266
+
1267
+ def removeNamedItem(self, name):
1268
+ raise xml.dom.NoModificationAllowedErr(
1269
+ "NamedNodeMap instance is read-only")
1270
+
1271
+ def removeNamedItemNS(self, namespaceURI, localName):
1272
+ raise xml.dom.NoModificationAllowedErr(
1273
+ "NamedNodeMap instance is read-only")
1274
+
1275
+ def setNamedItem(self, node):
1276
+ raise xml.dom.NoModificationAllowedErr(
1277
+ "NamedNodeMap instance is read-only")
1278
+
1279
+ def setNamedItemNS(self, node):
1280
+ raise xml.dom.NoModificationAllowedErr(
1281
+ "NamedNodeMap instance is read-only")
1282
+
1283
+ def __getstate__(self):
1284
+ return [self._seq]
1285
+
1286
+ def __setstate__(self, state):
1287
+ self._seq = state[0]
1288
+
1289
+ defproperty(ReadOnlySequentialNamedNodeMap, "length",
1290
+ doc="Number of entries in the NamedNodeMap.")
1291
+
1292
+
1293
+ class Identified:
1294
+ """Mix-in class that supports the publicId and systemId attributes."""
1295
+
1296
+ __slots__ = 'publicId', 'systemId'
1297
+
1298
+ def _identified_mixin_init(self, publicId, systemId):
1299
+ self.publicId = publicId
1300
+ self.systemId = systemId
1301
+
1302
+ def _get_publicId(self):
1303
+ return self.publicId
1304
+
1305
+ def _get_systemId(self):
1306
+ return self.systemId
1307
+
1308
+ class DocumentType(Identified, Childless, Node):
1309
+ nodeType = Node.DOCUMENT_TYPE_NODE
1310
+ nodeValue = None
1311
+ name = None
1312
+ publicId = None
1313
+ systemId = None
1314
+ internalSubset = None
1315
+
1316
+ def __init__(self, qualifiedName):
1317
+ self.entities = ReadOnlySequentialNamedNodeMap()
1318
+ self.notations = ReadOnlySequentialNamedNodeMap()
1319
+ if qualifiedName:
1320
+ prefix, localname = _nssplit(qualifiedName)
1321
+ self.name = localname
1322
+ self.nodeName = self.name
1323
+
1324
+ def _get_internalSubset(self):
1325
+ return self.internalSubset
1326
+
1327
+ def cloneNode(self, deep):
1328
+ if self.ownerDocument is None:
1329
+ # it's ok
1330
+ clone = DocumentType(None)
1331
+ clone.name = self.name
1332
+ clone.nodeName = self.name
1333
+ operation = xml.dom.UserDataHandler.NODE_CLONED
1334
+ if deep:
1335
+ clone.entities._seq = []
1336
+ clone.notations._seq = []
1337
+ for n in self.notations._seq:
1338
+ notation = Notation(n.nodeName, n.publicId, n.systemId)
1339
+ clone.notations._seq.append(notation)
1340
+ n._call_user_data_handler(operation, n, notation)
1341
+ for e in self.entities._seq:
1342
+ entity = Entity(e.nodeName, e.publicId, e.systemId,
1343
+ e.notationName)
1344
+ entity.actualEncoding = e.actualEncoding
1345
+ entity.encoding = e.encoding
1346
+ entity.version = e.version
1347
+ clone.entities._seq.append(entity)
1348
+ e._call_user_data_handler(operation, e, entity)
1349
+ self._call_user_data_handler(operation, self, clone)
1350
+ return clone
1351
+ else:
1352
+ return None
1353
+
1354
+ def writexml(self, writer, indent="", addindent="", newl=""):
1355
+ writer.write("<!DOCTYPE ")
1356
+ writer.write(self.name)
1357
+ if self.publicId:
1358
+ writer.write("%s PUBLIC '%s'%s '%s'"
1359
+ % (newl, self.publicId, newl, self.systemId))
1360
+ elif self.systemId:
1361
+ writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
1362
+ if self.internalSubset is not None:
1363
+ writer.write(" [")
1364
+ writer.write(self.internalSubset)
1365
+ writer.write("]")
1366
+ writer.write(">"+newl)
1367
+
1368
+ class Entity(Identified, Node):
1369
+ attributes = None
1370
+ nodeType = Node.ENTITY_NODE
1371
+ nodeValue = None
1372
+
1373
+ actualEncoding = None
1374
+ encoding = None
1375
+ version = None
1376
+
1377
+ def __init__(self, name, publicId, systemId, notation):
1378
+ self.nodeName = name
1379
+ self.notationName = notation
1380
+ self.childNodes = NodeList()
1381
+ self._identified_mixin_init(publicId, systemId)
1382
+
1383
+ def _get_actualEncoding(self):
1384
+ return self.actualEncoding
1385
+
1386
+ def _get_encoding(self):
1387
+ return self.encoding
1388
+
1389
+ def _get_version(self):
1390
+ return self.version
1391
+
1392
+ def appendChild(self, newChild):
1393
+ raise xml.dom.HierarchyRequestErr(
1394
+ "cannot append children to an entity node")
1395
+
1396
+ def insertBefore(self, newChild, refChild):
1397
+ raise xml.dom.HierarchyRequestErr(
1398
+ "cannot insert children below an entity node")
1399
+
1400
+ def removeChild(self, oldChild):
1401
+ raise xml.dom.HierarchyRequestErr(
1402
+ "cannot remove children from an entity node")
1403
+
1404
+ def replaceChild(self, newChild, oldChild):
1405
+ raise xml.dom.HierarchyRequestErr(
1406
+ "cannot replace children of an entity node")
1407
+
1408
+ class Notation(Identified, Childless, Node):
1409
+ nodeType = Node.NOTATION_NODE
1410
+ nodeValue = None
1411
+
1412
+ def __init__(self, name, publicId, systemId):
1413
+ self.nodeName = name
1414
+ self._identified_mixin_init(publicId, systemId)
1415
+
1416
+
1417
+ class DOMImplementation(DOMImplementationLS):
1418
+ _features = [("core", "1.0"),
1419
+ ("core", "2.0"),
1420
+ ("core", None),
1421
+ ("xml", "1.0"),
1422
+ ("xml", "2.0"),
1423
+ ("xml", None),
1424
+ ("ls-load", "3.0"),
1425
+ ("ls-load", None),
1426
+ ]
1427
+
1428
+ def hasFeature(self, feature, version):
1429
+ if version == "":
1430
+ version = None
1431
+ return (feature.lower(), version) in self._features
1432
+
1433
+ def createDocument(self, namespaceURI, qualifiedName, doctype):
1434
+ if doctype and doctype.parentNode is not None:
1435
+ raise xml.dom.WrongDocumentErr(
1436
+ "doctype object owned by another DOM tree")
1437
+ doc = self._create_document()
1438
+
1439
+ add_root_element = not (namespaceURI is None
1440
+ and qualifiedName is None
1441
+ and doctype is None)
1442
+
1443
+ if not qualifiedName and add_root_element:
1444
+ # The spec is unclear what to raise here; SyntaxErr
1445
+ # would be the other obvious candidate. Since Xerces raises
1446
+ # InvalidCharacterErr, and since SyntaxErr is not listed
1447
+ # for createDocument, that seems to be the better choice.
1448
+ # XXX: need to check for illegal characters here and in
1449
+ # createElement.
1450
+
1451
+ # DOM Level III clears this up when talking about the return value
1452
+ # of this function. If namespaceURI, qName and DocType are
1453
+ # Null the document is returned without a document element
1454
+ # Otherwise if doctype or namespaceURI are not None
1455
+ # Then we go back to the above problem
1456
+ raise xml.dom.InvalidCharacterErr("Element with no name")
1457
+
1458
+ if add_root_element:
1459
+ prefix, localname = _nssplit(qualifiedName)
1460
+ if prefix == "xml" \
1461
+ and namespaceURI != "http://www.w3.org/XML/1998/namespace":
1462
+ raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
1463
+ if prefix and not namespaceURI:
1464
+ raise xml.dom.NamespaceErr(
1465
+ "illegal use of prefix without namespaces")
1466
+ element = doc.createElementNS(namespaceURI, qualifiedName)
1467
+ if doctype:
1468
+ doc.appendChild(doctype)
1469
+ doc.appendChild(element)
1470
+
1471
+ if doctype:
1472
+ doctype.parentNode = doctype.ownerDocument = doc
1473
+
1474
+ doc.doctype = doctype
1475
+ doc.implementation = self
1476
+ return doc
1477
+
1478
+ def createDocumentType(self, qualifiedName, publicId, systemId):
1479
+ doctype = DocumentType(qualifiedName)
1480
+ doctype.publicId = publicId
1481
+ doctype.systemId = systemId
1482
+ return doctype
1483
+
1484
+ # DOM Level 3 (WD 9 April 2002)
1485
+
1486
+ def getInterface(self, feature):
1487
+ if self.hasFeature(feature, None):
1488
+ return self
1489
+ else:
1490
+ return None
1491
+
1492
+ # internal
1493
+ def _create_document(self):
1494
+ return Document()
1495
+
1496
+ class ElementInfo(object):
1497
+ """Object that represents content-model information for an element.
1498
+
1499
+ This implementation is not expected to be used in practice; DOM
1500
+ builders should provide implementations which do the right thing
1501
+ using information available to it.
1502
+
1503
+ """
1504
+
1505
+ __slots__ = 'tagName',
1506
+
1507
+ def __init__(self, name):
1508
+ self.tagName = name
1509
+
1510
+ def getAttributeType(self, aname):
1511
+ return _no_type
1512
+
1513
+ def getAttributeTypeNS(self, namespaceURI, localName):
1514
+ return _no_type
1515
+
1516
+ def isElementContent(self):
1517
+ return False
1518
+
1519
+ def isEmpty(self):
1520
+ """Returns true iff this element is declared to have an EMPTY
1521
+ content model."""
1522
+ return False
1523
+
1524
+ def isId(self, aname):
1525
+ """Returns true iff the named attribute is a DTD-style ID."""
1526
+ return False
1527
+
1528
+ def isIdNS(self, namespaceURI, localName):
1529
+ """Returns true iff the identified attribute is a DTD-style ID."""
1530
+ return False
1531
+
1532
+ def __getstate__(self):
1533
+ return self.tagName
1534
+
1535
+ def __setstate__(self, state):
1536
+ self.tagName = state
1537
+
1538
+ def _clear_id_cache(node):
1539
+ if node.nodeType == Node.DOCUMENT_NODE:
1540
+ node._id_cache.clear()
1541
+ node._id_search_stack = None
1542
+ elif _in_document(node):
1543
+ node.ownerDocument._id_cache.clear()
1544
+ node.ownerDocument._id_search_stack= None
1545
+
1546
+ class Document(Node, DocumentLS):
1547
+ __slots__ = ('_elem_info', 'doctype',
1548
+ '_id_search_stack', 'childNodes', '_id_cache')
1549
+ _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1550
+ Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1551
+
1552
+ implementation = DOMImplementation()
1553
+ nodeType = Node.DOCUMENT_NODE
1554
+ nodeName = "#document"
1555
+ nodeValue = None
1556
+ attributes = None
1557
+ parentNode = None
1558
+ previousSibling = nextSibling = None
1559
+
1560
+
1561
+ # Document attributes from Level 3 (WD 9 April 2002)
1562
+
1563
+ actualEncoding = None
1564
+ encoding = None
1565
+ standalone = None
1566
+ version = None
1567
+ strictErrorChecking = False
1568
+ errorHandler = None
1569
+ documentURI = None
1570
+
1571
+ _magic_id_count = 0
1572
+
1573
+ def __init__(self):
1574
+ self.doctype = None
1575
+ self.childNodes = NodeList()
1576
+ # mapping of (namespaceURI, localName) -> ElementInfo
1577
+ # and tagName -> ElementInfo
1578
+ self._elem_info = {}
1579
+ self._id_cache = {}
1580
+ self._id_search_stack = None
1581
+
1582
+ def _get_elem_info(self, element):
1583
+ if element.namespaceURI:
1584
+ key = element.namespaceURI, element.localName
1585
+ else:
1586
+ key = element.tagName
1587
+ return self._elem_info.get(key)
1588
+
1589
+ def _get_actualEncoding(self):
1590
+ return self.actualEncoding
1591
+
1592
+ def _get_doctype(self):
1593
+ return self.doctype
1594
+
1595
+ def _get_documentURI(self):
1596
+ return self.documentURI
1597
+
1598
+ def _get_encoding(self):
1599
+ return self.encoding
1600
+
1601
+ def _get_errorHandler(self):
1602
+ return self.errorHandler
1603
+
1604
+ def _get_standalone(self):
1605
+ return self.standalone
1606
+
1607
+ def _get_strictErrorChecking(self):
1608
+ return self.strictErrorChecking
1609
+
1610
+ def _get_version(self):
1611
+ return self.version
1612
+
1613
+ def appendChild(self, node):
1614
+ if node.nodeType not in self._child_node_types:
1615
+ raise xml.dom.HierarchyRequestErr(
1616
+ "%s cannot be child of %s" % (repr(node), repr(self)))
1617
+ if node.parentNode is not None:
1618
+ # This needs to be done before the next test since this
1619
+ # may *be* the document element, in which case it should
1620
+ # end up re-ordered to the end.
1621
+ node.parentNode.removeChild(node)
1622
+
1623
+ if node.nodeType == Node.ELEMENT_NODE \
1624
+ and self._get_documentElement():
1625
+ raise xml.dom.HierarchyRequestErr(
1626
+ "two document elements disallowed")
1627
+ return Node.appendChild(self, node)
1628
+
1629
+ def removeChild(self, oldChild):
1630
+ try:
1631
+ self.childNodes.remove(oldChild)
1632
+ except ValueError:
1633
+ raise xml.dom.NotFoundErr()
1634
+ oldChild.nextSibling = oldChild.previousSibling = None
1635
+ oldChild.parentNode = None
1636
+ if self.documentElement is oldChild:
1637
+ self.documentElement = None
1638
+
1639
+ return oldChild
1640
+
1641
+ def _get_documentElement(self):
1642
+ for node in self.childNodes:
1643
+ if node.nodeType == Node.ELEMENT_NODE:
1644
+ return node
1645
+
1646
+ def unlink(self):
1647
+ if self.doctype is not None:
1648
+ self.doctype.unlink()
1649
+ self.doctype = None
1650
+ Node.unlink(self)
1651
+
1652
+ def cloneNode(self, deep):
1653
+ if not deep:
1654
+ return None
1655
+ clone = self.implementation.createDocument(None, None, None)
1656
+ clone.encoding = self.encoding
1657
+ clone.standalone = self.standalone
1658
+ clone.version = self.version
1659
+ for n in self.childNodes:
1660
+ childclone = _clone_node(n, deep, clone)
1661
+ assert childclone.ownerDocument.isSameNode(clone)
1662
+ clone.childNodes.append(childclone)
1663
+ if childclone.nodeType == Node.DOCUMENT_NODE:
1664
+ assert clone.documentElement is None
1665
+ elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1666
+ assert clone.doctype is None
1667
+ clone.doctype = childclone
1668
+ childclone.parentNode = clone
1669
+ self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
1670
+ self, clone)
1671
+ return clone
1672
+
1673
+ def createDocumentFragment(self):
1674
+ d = DocumentFragment()
1675
+ d.ownerDocument = self
1676
+ return d
1677
+
1678
+ def createElement(self, tagName):
1679
+ e = Element(tagName)
1680
+ e.ownerDocument = self
1681
+ return e
1682
+
1683
+ def createTextNode(self, data):
1684
+ if not isinstance(data, str):
1685
+ raise TypeError("node contents must be a string")
1686
+ t = Text()
1687
+ t.data = data
1688
+ t.ownerDocument = self
1689
+ return t
1690
+
1691
+ def createCDATASection(self, data):
1692
+ if not isinstance(data, str):
1693
+ raise TypeError("node contents must be a string")
1694
+ c = CDATASection()
1695
+ c.data = data
1696
+ c.ownerDocument = self
1697
+ return c
1698
+
1699
+ def createComment(self, data):
1700
+ c = Comment(data)
1701
+ c.ownerDocument = self
1702
+ return c
1703
+
1704
+ def createProcessingInstruction(self, target, data):
1705
+ p = ProcessingInstruction(target, data)
1706
+ p.ownerDocument = self
1707
+ return p
1708
+
1709
+ def createAttribute(self, qName):
1710
+ a = Attr(qName)
1711
+ a.ownerDocument = self
1712
+ a.value = ""
1713
+ return a
1714
+
1715
+ def createElementNS(self, namespaceURI, qualifiedName):
1716
+ prefix, localName = _nssplit(qualifiedName)
1717
+ e = Element(qualifiedName, namespaceURI, prefix)
1718
+ e.ownerDocument = self
1719
+ return e
1720
+
1721
+ def createAttributeNS(self, namespaceURI, qualifiedName):
1722
+ prefix, localName = _nssplit(qualifiedName)
1723
+ a = Attr(qualifiedName, namespaceURI, localName, prefix)
1724
+ a.ownerDocument = self
1725
+ a.value = ""
1726
+ return a
1727
+
1728
+ # A couple of implementation-specific helpers to create node types
1729
+ # not supported by the W3C DOM specs:
1730
+
1731
+ def _create_entity(self, name, publicId, systemId, notationName):
1732
+ e = Entity(name, publicId, systemId, notationName)
1733
+ e.ownerDocument = self
1734
+ return e
1735
+
1736
+ def _create_notation(self, name, publicId, systemId):
1737
+ n = Notation(name, publicId, systemId)
1738
+ n.ownerDocument = self
1739
+ return n
1740
+
1741
+ def getElementById(self, id):
1742
+ if id in self._id_cache:
1743
+ return self._id_cache[id]
1744
+ if not (self._elem_info or self._magic_id_count):
1745
+ return None
1746
+
1747
+ stack = self._id_search_stack
1748
+ if stack is None:
1749
+ # we never searched before, or the cache has been cleared
1750
+ stack = [self.documentElement]
1751
+ self._id_search_stack = stack
1752
+ elif not stack:
1753
+ # Previous search was completed and cache is still valid;
1754
+ # no matching node.
1755
+ return None
1756
+
1757
+ result = None
1758
+ while stack:
1759
+ node = stack.pop()
1760
+ # add child elements to stack for continued searching
1761
+ stack.extend([child for child in node.childNodes
1762
+ if child.nodeType in _nodeTypes_with_children])
1763
+ # check this node
1764
+ info = self._get_elem_info(node)
1765
+ if info:
1766
+ # We have to process all ID attributes before
1767
+ # returning in order to get all the attributes set to
1768
+ # be IDs using Element.setIdAttribute*().
1769
+ for attr in node.attributes.values():
1770
+ if attr.namespaceURI:
1771
+ if info.isIdNS(attr.namespaceURI, attr.localName):
1772
+ self._id_cache[attr.value] = node
1773
+ if attr.value == id:
1774
+ result = node
1775
+ elif not node._magic_id_nodes:
1776
+ break
1777
+ elif info.isId(attr.name):
1778
+ self._id_cache[attr.value] = node
1779
+ if attr.value == id:
1780
+ result = node
1781
+ elif not node._magic_id_nodes:
1782
+ break
1783
+ elif attr._is_id:
1784
+ self._id_cache[attr.value] = node
1785
+ if attr.value == id:
1786
+ result = node
1787
+ elif node._magic_id_nodes == 1:
1788
+ break
1789
+ elif node._magic_id_nodes:
1790
+ for attr in node.attributes.values():
1791
+ if attr._is_id:
1792
+ self._id_cache[attr.value] = node
1793
+ if attr.value == id:
1794
+ result = node
1795
+ if result is not None:
1796
+ break
1797
+ return result
1798
+
1799
+ def getElementsByTagName(self, name):
1800
+ return _get_elements_by_tagName_helper(self, name, NodeList())
1801
+
1802
+ def getElementsByTagNameNS(self, namespaceURI, localName):
1803
+ return _get_elements_by_tagName_ns_helper(
1804
+ self, namespaceURI, localName, NodeList())
1805
+
1806
+ def isSupported(self, feature, version):
1807
+ return self.implementation.hasFeature(feature, version)
1808
+
1809
+ def importNode(self, node, deep):
1810
+ if node.nodeType == Node.DOCUMENT_NODE:
1811
+ raise xml.dom.NotSupportedErr("cannot import document nodes")
1812
+ elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1813
+ raise xml.dom.NotSupportedErr("cannot import document type nodes")
1814
+ return _clone_node(node, deep, self)
1815
+
1816
+ def writexml(self, writer, indent="", addindent="", newl="", encoding=None,
1817
+ standalone=None):
1818
+ declarations = []
1819
+
1820
+ if encoding:
1821
+ declarations.append(f'encoding="{encoding}"')
1822
+ if standalone is not None:
1823
+ declarations.append(f'standalone="{"yes" if standalone else "no"}"')
1824
+
1825
+ writer.write(f'<?xml version="1.0" {" ".join(declarations)}?>{newl}')
1826
+
1827
+ for node in self.childNodes:
1828
+ node.writexml(writer, indent, addindent, newl)
1829
+
1830
+ # DOM Level 3 (WD 9 April 2002)
1831
+
1832
+ def renameNode(self, n, namespaceURI, name):
1833
+ if n.ownerDocument is not self:
1834
+ raise xml.dom.WrongDocumentErr(
1835
+ "cannot rename nodes from other documents;\n"
1836
+ "expected %s,\nfound %s" % (self, n.ownerDocument))
1837
+ if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
1838
+ raise xml.dom.NotSupportedErr(
1839
+ "renameNode() only applies to element and attribute nodes")
1840
+ if namespaceURI != EMPTY_NAMESPACE:
1841
+ if ':' in name:
1842
+ prefix, localName = name.split(':', 1)
1843
+ if ( prefix == "xmlns"
1844
+ and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1845
+ raise xml.dom.NamespaceErr(
1846
+ "illegal use of 'xmlns' prefix")
1847
+ else:
1848
+ if ( name == "xmlns"
1849
+ and namespaceURI != xml.dom.XMLNS_NAMESPACE
1850
+ and n.nodeType == Node.ATTRIBUTE_NODE):
1851
+ raise xml.dom.NamespaceErr(
1852
+ "illegal use of the 'xmlns' attribute")
1853
+ prefix = None
1854
+ localName = name
1855
+ else:
1856
+ prefix = None
1857
+ localName = None
1858
+ if n.nodeType == Node.ATTRIBUTE_NODE:
1859
+ element = n.ownerElement
1860
+ if element is not None:
1861
+ is_id = n._is_id
1862
+ element.removeAttributeNode(n)
1863
+ else:
1864
+ element = None
1865
+ n.prefix = prefix
1866
+ n._localName = localName
1867
+ n.namespaceURI = namespaceURI
1868
+ n.nodeName = name
1869
+ if n.nodeType == Node.ELEMENT_NODE:
1870
+ n.tagName = name
1871
+ else:
1872
+ # attribute node
1873
+ n.name = name
1874
+ if element is not None:
1875
+ element.setAttributeNode(n)
1876
+ if is_id:
1877
+ element.setIdAttributeNode(n)
1878
+ # It's not clear from a semantic perspective whether we should
1879
+ # call the user data handlers for the NODE_RENAMED event since
1880
+ # we're re-using the existing node. The draft spec has been
1881
+ # interpreted as meaning "no, don't call the handler unless a
1882
+ # new node is created."
1883
+ return n
1884
+
1885
+ defproperty(Document, "documentElement",
1886
+ doc="Top-level element of this document.")
1887
+
1888
+
1889
+ def _clone_node(node, deep, newOwnerDocument):
1890
+ """
1891
+ Clone a node and give it the new owner document.
1892
+ Called by Node.cloneNode and Document.importNode
1893
+ """
1894
+ if node.ownerDocument.isSameNode(newOwnerDocument):
1895
+ operation = xml.dom.UserDataHandler.NODE_CLONED
1896
+ else:
1897
+ operation = xml.dom.UserDataHandler.NODE_IMPORTED
1898
+ if node.nodeType == Node.ELEMENT_NODE:
1899
+ clone = newOwnerDocument.createElementNS(node.namespaceURI,
1900
+ node.nodeName)
1901
+ for attr in node.attributes.values():
1902
+ clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1903
+ a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1904
+ a.specified = attr.specified
1905
+
1906
+ if deep:
1907
+ for child in node.childNodes:
1908
+ c = _clone_node(child, deep, newOwnerDocument)
1909
+ clone.appendChild(c)
1910
+
1911
+ elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1912
+ clone = newOwnerDocument.createDocumentFragment()
1913
+ if deep:
1914
+ for child in node.childNodes:
1915
+ c = _clone_node(child, deep, newOwnerDocument)
1916
+ clone.appendChild(c)
1917
+
1918
+ elif node.nodeType == Node.TEXT_NODE:
1919
+ clone = newOwnerDocument.createTextNode(node.data)
1920
+ elif node.nodeType == Node.CDATA_SECTION_NODE:
1921
+ clone = newOwnerDocument.createCDATASection(node.data)
1922
+ elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1923
+ clone = newOwnerDocument.createProcessingInstruction(node.target,
1924
+ node.data)
1925
+ elif node.nodeType == Node.COMMENT_NODE:
1926
+ clone = newOwnerDocument.createComment(node.data)
1927
+ elif node.nodeType == Node.ATTRIBUTE_NODE:
1928
+ clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1929
+ node.nodeName)
1930
+ clone.specified = True
1931
+ clone.value = node.value
1932
+ elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1933
+ assert node.ownerDocument is not newOwnerDocument
1934
+ operation = xml.dom.UserDataHandler.NODE_IMPORTED
1935
+ clone = newOwnerDocument.implementation.createDocumentType(
1936
+ node.name, node.publicId, node.systemId)
1937
+ clone.ownerDocument = newOwnerDocument
1938
+ if deep:
1939
+ clone.entities._seq = []
1940
+ clone.notations._seq = []
1941
+ for n in node.notations._seq:
1942
+ notation = Notation(n.nodeName, n.publicId, n.systemId)
1943
+ notation.ownerDocument = newOwnerDocument
1944
+ clone.notations._seq.append(notation)
1945
+ if hasattr(n, '_call_user_data_handler'):
1946
+ n._call_user_data_handler(operation, n, notation)
1947
+ for e in node.entities._seq:
1948
+ entity = Entity(e.nodeName, e.publicId, e.systemId,
1949
+ e.notationName)
1950
+ entity.actualEncoding = e.actualEncoding
1951
+ entity.encoding = e.encoding
1952
+ entity.version = e.version
1953
+ entity.ownerDocument = newOwnerDocument
1954
+ clone.entities._seq.append(entity)
1955
+ if hasattr(e, '_call_user_data_handler'):
1956
+ e._call_user_data_handler(operation, e, entity)
1957
+ else:
1958
+ # Note the cloning of Document and DocumentType nodes is
1959
+ # implementation specific. minidom handles those cases
1960
+ # directly in the cloneNode() methods.
1961
+ raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
1962
+
1963
+ # Check for _call_user_data_handler() since this could conceivably
1964
+ # used with other DOM implementations (one of the FourThought
1965
+ # DOMs, perhaps?).
1966
+ if hasattr(node, '_call_user_data_handler'):
1967
+ node._call_user_data_handler(operation, node, clone)
1968
+ return clone
1969
+
1970
+
1971
+ def _nssplit(qualifiedName):
1972
+ fields = qualifiedName.split(':', 1)
1973
+ if len(fields) == 2:
1974
+ return fields
1975
+ else:
1976
+ return (None, fields[0])
1977
+
1978
+
1979
+ def _do_pulldom_parse(func, args, kwargs):
1980
+ events = func(*args, **kwargs)
1981
+ toktype, rootNode = events.getEvent()
1982
+ events.expandNode(rootNode)
1983
+ events.clear()
1984
+ return rootNode
1985
+
1986
+ def parse(file, parser=None, bufsize=None):
1987
+ """Parse a file into a DOM by filename or file object."""
1988
+ if parser is None and not bufsize:
1989
+ from xml.dom import expatbuilder
1990
+ return expatbuilder.parse(file)
1991
+ else:
1992
+ from xml.dom import pulldom
1993
+ return _do_pulldom_parse(pulldom.parse, (file,),
1994
+ {'parser': parser, 'bufsize': bufsize})
1995
+
1996
+ def parseString(string, parser=None):
1997
+ """Parse a file into a DOM from a string."""
1998
+ if parser is None:
1999
+ from xml.dom import expatbuilder
2000
+ return expatbuilder.parseString(string)
2001
+ else:
2002
+ from xml.dom import pulldom
2003
+ return _do_pulldom_parse(pulldom.parseString, (string,),
2004
+ {'parser': parser})
2005
+
2006
+ def getDOMImplementation(features=None):
2007
+ if features:
2008
+ if isinstance(features, str):
2009
+ features = domreg._parse_feature_string(features)
2010
+ for f, v in features:
2011
+ if not Document.implementation.hasFeature(f, v):
2012
+ return None
2013
+ return Document.implementation