ZTWHHH commited on
Commit
33b5330
·
verified ·
1 Parent(s): 60b1f35

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_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER +1 -0
  2. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE +21 -0
  3. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA +34 -0
  4. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD +13 -0
  5. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED +0 -0
  6. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL +5 -0
  7. evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt +1 -0
  8. evalkit_tf446/lib/python3.10/site-packages/pyasn1/__pycache__/__init__.cpython-310.pyc +0 -0
  9. evalkit_tf446/lib/python3.10/site-packages/pyasn1/__pycache__/error.cpython-310.pyc +0 -0
  10. evalkit_tf446/lib/python3.10/site-packages/pyasn1/codec/native/__pycache__/decoder.cpython-310.pyc +0 -0
  11. evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__init__.py +4 -0
  12. evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__pycache__/__init__.cpython-310.pyc +0 -0
  13. evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__pycache__/integer.cpython-310.pyc +0 -0
  14. evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/integer.py +13 -0
  15. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__init__.py +1 -0
  16. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/__init__.cpython-310.pyc +0 -0
  17. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/base.cpython-310.pyc +0 -0
  18. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/char.cpython-310.pyc +0 -0
  19. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/constraint.cpython-310.pyc +0 -0
  20. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/error.cpython-310.pyc +0 -0
  21. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/namedtype.cpython-310.pyc +0 -0
  22. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/namedval.cpython-310.pyc +0 -0
  23. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/opentype.cpython-310.pyc +0 -0
  24. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/tag.cpython-310.pyc +0 -0
  25. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/tagmap.cpython-310.pyc +0 -0
  26. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/univ.cpython-310.pyc +0 -0
  27. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/useful.cpython-310.pyc +0 -0
  28. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/base.py +699 -0
  29. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/char.py +288 -0
  30. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/constraint.py +751 -0
  31. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/error.py +11 -0
  32. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/namedtype.py +550 -0
  33. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/namedval.py +192 -0
  34. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/opentype.py +104 -0
  35. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/tag.py +335 -0
  36. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/tagmap.py +96 -0
  37. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/univ.py +0 -0
  38. evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/useful.py +189 -0
  39. evalkit_tf446/lib/python3.10/site-packages/uvicorn/__init__.py +5 -0
  40. evalkit_tf446/lib/python3.10/site-packages/uvicorn/__main__.py +4 -0
  41. evalkit_tf446/lib/python3.10/site-packages/uvicorn/_subprocess.py +84 -0
  42. evalkit_tf446/lib/python3.10/site-packages/uvicorn/_types.py +293 -0
  43. evalkit_tf446/lib/python3.10/site-packages/uvicorn/config.py +529 -0
  44. evalkit_tf446/lib/python3.10/site-packages/uvicorn/importer.py +34 -0
  45. evalkit_tf446/lib/python3.10/site-packages/uvicorn/logging.py +117 -0
  46. evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__init__.py +0 -0
  47. evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/__init__.cpython-310.pyc +0 -0
  48. evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-310.pyc +0 -0
  49. evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/auto.cpython-310.pyc +0 -0
  50. evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-310.pyc +0 -0
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Edinburgh Genome Foundry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/METADATA ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: proglog
3
+ Version: 0.1.10
4
+ Summary: Log and progress bar manager for console, notebooks, web...
5
+ Author: Zulko
6
+ License: MIT
7
+ Keywords: logger log progress bar
8
+ Platform: UNKNOWN
9
+ License-File: LICENSE
10
+ Requires-Dist: tqdm
11
+
12
+ Proglog
13
+ =======
14
+
15
+ Proglog is a progress logging system for Python. It allows to build complex
16
+ libraries while giving the user control on the management of logs, callbacks and progress bars.
17
+
18
+
19
+ Infos
20
+ -----
21
+
22
+ **PIP installation:**
23
+
24
+ .. code:: bash
25
+
26
+ pip install proglog
27
+
28
+ **Github Page**
29
+
30
+ `<https://github.com/Edinburgh-Genome-Foundry/Proglog>`_
31
+
32
+ **License:** MIT, Copyright Edinburgh Genome Foundry
33
+
34
+
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/RECORD ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ proglog-0.1.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ proglog-0.1.10.dist-info/LICENSE,sha256=akVjFR4jDJtNakzf3avomKdfddMyA9WHJ5aVV08efxY,1081
3
+ proglog-0.1.10.dist-info/METADATA,sha256=7HqXAeqQ_WotmBFY28nag6MAHWRdXYCY0x1Xmv49hKI,639
4
+ proglog-0.1.10.dist-info/RECORD,,
5
+ proglog-0.1.10.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ proglog-0.1.10.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
7
+ proglog-0.1.10.dist-info/top_level.txt,sha256=KeCzTcuXoZxru4GWsCpIwgVBfHdDrI0ujnDKu61sFXE,8
8
+ proglog/__init__.py,sha256=m68k-TnqoChy0FjkHWqSfPuEiQgl69Cfs-N4Kp7k-tU,302
9
+ proglog/__pycache__/__init__.cpython-310.pyc,,
10
+ proglog/__pycache__/proglog.cpython-310.pyc,,
11
+ proglog/__pycache__/version.cpython-310.pyc,,
12
+ proglog/proglog.py,sha256=qWQSpWM-pR_pyh5vrrlVBU094bkatfj9prbz5PJpK7U,13250
13
+ proglog/version.py,sha256=z0zCHFTcKSR0tJ6h5qrpNmRVP21QIPP8N0p7quCnnm0,23
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/REQUESTED ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
evalkit_tf446/lib/python3.10/site-packages/proglog-0.1.10.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ proglog
evalkit_tf446/lib/python3.10/site-packages/pyasn1/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/__pycache__/error.cpython-310.pyc ADDED
Binary file (4.1 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/codec/native/__pycache__/decoder.cpython-310.pyc ADDED
Binary file (5.67 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # This file is necessary to make this directory a package.
2
+
3
+ # sentinal for missing argument
4
+ _MISSING = object()
evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/__pycache__/integer.cpython-310.pyc ADDED
Binary file (427 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/compat/integer.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ def to_bytes(value, signed=False, length=0):
8
+ length = max(value.bit_length(), length)
9
+
10
+ if signed and length % 8 == 0:
11
+ length += 1
12
+
13
+ return value.to_bytes(length // 8 + (length % 8 and 1 or 0), 'big', signed=signed)
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is necessary to make this directory a package.
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/base.cpython-310.pyc ADDED
Binary file (21.8 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/char.cpython-310.pyc ADDED
Binary file (5.6 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/constraint.cpython-310.pyc ADDED
Binary file (23.7 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/error.cpython-310.pyc ADDED
Binary file (386 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/namedtype.cpython-310.pyc ADDED
Binary file (18.3 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/namedval.cpython-310.pyc ADDED
Binary file (5.48 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/opentype.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/tag.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/tagmap.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/univ.cpython-310.pyc ADDED
Binary file (93.8 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/__pycache__/useful.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/base.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ import sys
8
+
9
+ from pyasn1 import error
10
+ from pyasn1.type import constraint
11
+ from pyasn1.type import tag
12
+ from pyasn1.type import tagmap
13
+
14
+ __all__ = ['Asn1Item', 'Asn1Type', 'SimpleAsn1Type',
15
+ 'ConstructedAsn1Type']
16
+
17
+
18
+ class Asn1Item(object):
19
+ @classmethod
20
+ def getTypeId(cls, increment=1):
21
+ try:
22
+ Asn1Item._typeCounter += increment
23
+ except AttributeError:
24
+ Asn1Item._typeCounter = increment
25
+ return Asn1Item._typeCounter
26
+
27
+
28
+ class Asn1Type(Asn1Item):
29
+ """Base class for all classes representing ASN.1 types.
30
+
31
+ In the user code, |ASN.1| class is normally used only for telling
32
+ ASN.1 objects from others.
33
+
34
+ Note
35
+ ----
36
+ For as long as ASN.1 is concerned, a way to compare ASN.1 types
37
+ is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods.
38
+ """
39
+ #: Set or return a :py:class:`~pyasn1.type.tag.TagSet` object representing
40
+ #: ASN.1 tag(s) associated with |ASN.1| type.
41
+ tagSet = tag.TagSet()
42
+
43
+ #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
44
+ #: object imposing constraints on initialization values.
45
+ subtypeSpec = constraint.ConstraintsIntersection()
46
+
47
+ # Disambiguation ASN.1 types identification
48
+ typeId = None
49
+
50
+ def __init__(self, **kwargs):
51
+ readOnly = {
52
+ 'tagSet': self.tagSet,
53
+ 'subtypeSpec': self.subtypeSpec
54
+ }
55
+
56
+ readOnly.update(kwargs)
57
+
58
+ self.__dict__.update(readOnly)
59
+
60
+ self._readOnly = readOnly
61
+
62
+ def __setattr__(self, name, value):
63
+ if name[0] != '_' and name in self._readOnly:
64
+ raise error.PyAsn1Error('read-only instance attribute "%s"' % name)
65
+
66
+ self.__dict__[name] = value
67
+
68
+ def __str__(self):
69
+ return self.prettyPrint()
70
+
71
+ @property
72
+ def readOnly(self):
73
+ return self._readOnly
74
+
75
+ @property
76
+ def effectiveTagSet(self):
77
+ """For |ASN.1| type is equivalent to *tagSet*
78
+ """
79
+ return self.tagSet # used by untagged types
80
+
81
+ @property
82
+ def tagMap(self):
83
+ """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object.
84
+ """
85
+ return tagmap.TagMap({self.tagSet: self})
86
+
87
+ def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
88
+ """Examine |ASN.1| type for equality with other ASN.1 type.
89
+
90
+ ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
91
+ (:py:mod:`~pyasn1.type.constraint`) are examined when carrying
92
+ out ASN.1 types comparison.
93
+
94
+ Python class inheritance relationship is NOT considered.
95
+
96
+ Parameters
97
+ ----------
98
+ other: a pyasn1 type object
99
+ Class instance representing ASN.1 type.
100
+
101
+ Returns
102
+ -------
103
+ : :class:`bool`
104
+ :obj:`True` if *other* is |ASN.1| type,
105
+ :obj:`False` otherwise.
106
+ """
107
+ return (self is other or
108
+ (not matchTags or self.tagSet == other.tagSet) and
109
+ (not matchConstraints or self.subtypeSpec == other.subtypeSpec))
110
+
111
+ def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):
112
+ """Examine |ASN.1| type for subtype relationship with other ASN.1 type.
113
+
114
+ ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
115
+ (:py:mod:`~pyasn1.type.constraint`) are examined when carrying
116
+ out ASN.1 types comparison.
117
+
118
+ Python class inheritance relationship is NOT considered.
119
+
120
+ Parameters
121
+ ----------
122
+ other: a pyasn1 type object
123
+ Class instance representing ASN.1 type.
124
+
125
+ Returns
126
+ -------
127
+ : :class:`bool`
128
+ :obj:`True` if *other* is a subtype of |ASN.1| type,
129
+ :obj:`False` otherwise.
130
+ """
131
+ return (not matchTags or
132
+ (self.tagSet.isSuperTagSetOf(other.tagSet)) and
133
+ (not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec)))
134
+
135
+ @staticmethod
136
+ def isNoValue(*values):
137
+ for value in values:
138
+ if value is not noValue:
139
+ return False
140
+ return True
141
+
142
+ def prettyPrint(self, scope=0):
143
+ raise NotImplementedError
144
+
145
+ # backward compatibility
146
+
147
+ def getTagSet(self):
148
+ return self.tagSet
149
+
150
+ def getEffectiveTagSet(self):
151
+ return self.effectiveTagSet
152
+
153
+ def getTagMap(self):
154
+ return self.tagMap
155
+
156
+ def getSubtypeSpec(self):
157
+ return self.subtypeSpec
158
+
159
+ # backward compatibility
160
+ def hasValue(self):
161
+ return self.isValue
162
+
163
+ # Backward compatibility
164
+ Asn1ItemBase = Asn1Type
165
+
166
+
167
+ class NoValue(object):
168
+ """Create a singleton instance of NoValue class.
169
+
170
+ The *NoValue* sentinel object represents an instance of ASN.1 schema
171
+ object as opposed to ASN.1 value object.
172
+
173
+ Only ASN.1 schema-related operations can be performed on ASN.1
174
+ schema objects.
175
+
176
+ Warning
177
+ -------
178
+ Any operation attempted on the *noValue* object will raise the
179
+ *PyAsn1Error* exception.
180
+ """
181
+ skipMethods = {
182
+ '__slots__',
183
+ # attributes
184
+ '__getattribute__',
185
+ '__getattr__',
186
+ '__setattr__',
187
+ '__delattr__',
188
+ # class instance
189
+ '__class__',
190
+ '__init__',
191
+ '__del__',
192
+ '__new__',
193
+ '__repr__',
194
+ '__qualname__',
195
+ '__objclass__',
196
+ 'im_class',
197
+ '__sizeof__',
198
+ # pickle protocol
199
+ '__reduce__',
200
+ '__reduce_ex__',
201
+ '__getnewargs__',
202
+ '__getinitargs__',
203
+ '__getstate__',
204
+ '__setstate__',
205
+ }
206
+
207
+ _instance = None
208
+
209
+ def __new__(cls):
210
+ if cls._instance is None:
211
+ def getPlug(name):
212
+ def plug(self, *args, **kw):
213
+ raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % name)
214
+ return plug
215
+
216
+ op_names = [name
217
+ for typ in (str, int, list, dict)
218
+ for name in dir(typ)
219
+ if (name not in cls.skipMethods and
220
+ name.startswith('__') and
221
+ name.endswith('__') and
222
+ callable(getattr(typ, name)))]
223
+
224
+ for name in set(op_names):
225
+ setattr(cls, name, getPlug(name))
226
+
227
+ cls._instance = object.__new__(cls)
228
+
229
+ return cls._instance
230
+
231
+ def __getattr__(self, attr):
232
+ if attr in self.skipMethods:
233
+ raise AttributeError('Attribute %s not present' % attr)
234
+
235
+ raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
236
+
237
+ def __repr__(self):
238
+ return '<%s object>' % self.__class__.__name__
239
+
240
+
241
+ noValue = NoValue()
242
+
243
+
244
+ class SimpleAsn1Type(Asn1Type):
245
+ """Base class for all simple classes representing ASN.1 types.
246
+
247
+ ASN.1 distinguishes types by their ability to hold other objects.
248
+ Scalar types are known as *simple* in ASN.1.
249
+
250
+ In the user code, |ASN.1| class is normally used only for telling
251
+ ASN.1 objects from others.
252
+
253
+ Note
254
+ ----
255
+ For as long as ASN.1 is concerned, a way to compare ASN.1 types
256
+ is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods.
257
+ """
258
+ #: Default payload value
259
+ defaultValue = noValue
260
+
261
+ def __init__(self, value=noValue, **kwargs):
262
+ Asn1Type.__init__(self, **kwargs)
263
+ if value is noValue:
264
+ value = self.defaultValue
265
+ else:
266
+ value = self.prettyIn(value)
267
+ try:
268
+ self.subtypeSpec(value)
269
+
270
+ except error.PyAsn1Error as exValue:
271
+ raise type(exValue)('%s at %s' % (exValue, self.__class__.__name__))
272
+
273
+ self._value = value
274
+
275
+ def __repr__(self):
276
+ representation = '%s %s object' % (
277
+ self.__class__.__name__, self.isValue and 'value' or 'schema')
278
+
279
+ for attr, value in self.readOnly.items():
280
+ if value:
281
+ representation += ', %s %s' % (attr, value)
282
+
283
+ if self.isValue:
284
+ value = self.prettyPrint()
285
+ if len(value) > 32:
286
+ value = value[:16] + '...' + value[-16:]
287
+ representation += ', payload [%s]' % value
288
+
289
+ return '<%s>' % representation
290
+
291
+ def __eq__(self, other):
292
+ if self is other:
293
+ return True
294
+ return self._value == other
295
+
296
+ def __ne__(self, other):
297
+ return self._value != other
298
+
299
+ def __lt__(self, other):
300
+ return self._value < other
301
+
302
+ def __le__(self, other):
303
+ return self._value <= other
304
+
305
+ def __gt__(self, other):
306
+ return self._value > other
307
+
308
+ def __ge__(self, other):
309
+ return self._value >= other
310
+
311
+ def __bool__(self):
312
+ return bool(self._value)
313
+
314
+ def __hash__(self):
315
+ return hash(self._value)
316
+
317
+ @property
318
+ def isValue(self):
319
+ """Indicate that |ASN.1| object represents ASN.1 value.
320
+
321
+ If *isValue* is :obj:`False` then this object represents just
322
+ ASN.1 schema.
323
+
324
+ If *isValue* is :obj:`True` then, in addition to its ASN.1 schema
325
+ features, this object can also be used like a Python built-in object
326
+ (e.g. :class:`int`, :class:`str`, :class:`dict` etc.).
327
+
328
+ Returns
329
+ -------
330
+ : :class:`bool`
331
+ :obj:`False` if object represents just ASN.1 schema.
332
+ :obj:`True` if object represents ASN.1 schema and can be used as a normal value.
333
+
334
+ Note
335
+ ----
336
+ There is an important distinction between PyASN1 schema and value objects.
337
+ The PyASN1 schema objects can only participate in ASN.1 schema-related
338
+ operations (e.g. defining or testing the structure of the data). Most
339
+ obvious uses of ASN.1 schema is to guide serialisation codecs whilst
340
+ encoding/decoding serialised ASN.1 contents.
341
+
342
+ The PyASN1 value objects can **additionally** participate in many operations
343
+ involving regular Python objects (e.g. arithmetic, comprehension etc).
344
+ """
345
+ return self._value is not noValue
346
+
347
+ def clone(self, value=noValue, **kwargs):
348
+ """Create a modified version of |ASN.1| schema or value object.
349
+
350
+ The `clone()` method accepts the same set arguments as |ASN.1|
351
+ class takes on instantiation except that all arguments
352
+ of the `clone()` method are optional.
353
+
354
+ Whatever arguments are supplied, they are used to create a copy
355
+ of `self` taking precedence over the ones used to instantiate `self`.
356
+
357
+ Note
358
+ ----
359
+ Due to the immutable nature of the |ASN.1| object, if no arguments
360
+ are supplied, no new |ASN.1| object will be created and `self` will
361
+ be returned instead.
362
+ """
363
+ if value is noValue:
364
+ if not kwargs:
365
+ return self
366
+
367
+ value = self._value
368
+
369
+ initializers = self.readOnly.copy()
370
+ initializers.update(kwargs)
371
+
372
+ return self.__class__(value, **initializers)
373
+
374
+ def subtype(self, value=noValue, **kwargs):
375
+ """Create a specialization of |ASN.1| schema or value object.
376
+
377
+ The subtype relationship between ASN.1 types has no correlation with
378
+ subtype relationship between Python types. ASN.1 type is mainly identified
379
+ by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range
380
+ constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`).
381
+ These ASN.1 type properties are implemented as |ASN.1| attributes.
382
+
383
+ The `subtype()` method accepts the same set arguments as |ASN.1|
384
+ class takes on instantiation except that all parameters
385
+ of the `subtype()` method are optional.
386
+
387
+ With the exception of the arguments described below, the rest of
388
+ supplied arguments they are used to create a copy of `self` taking
389
+ precedence over the ones used to instantiate `self`.
390
+
391
+ The following arguments to `subtype()` create a ASN.1 subtype out of
392
+ |ASN.1| type:
393
+
394
+ Other Parameters
395
+ ----------------
396
+ implicitTag: :py:class:`~pyasn1.type.tag.Tag`
397
+ Implicitly apply given ASN.1 tag object to `self`'s
398
+ :py:class:`~pyasn1.type.tag.TagSet`, then use the result as
399
+ new object's ASN.1 tag(s).
400
+
401
+ explicitTag: :py:class:`~pyasn1.type.tag.Tag`
402
+ Explicitly apply given ASN.1 tag object to `self`'s
403
+ :py:class:`~pyasn1.type.tag.TagSet`, then use the result as
404
+ new object's ASN.1 tag(s).
405
+
406
+ subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
407
+ Add ASN.1 constraints object to one of the `self`'s, then
408
+ use the result as new object's ASN.1 constraints.
409
+
410
+ Returns
411
+ -------
412
+ :
413
+ new instance of |ASN.1| schema or value object
414
+
415
+ Note
416
+ ----
417
+ Due to the immutable nature of the |ASN.1| object, if no arguments
418
+ are supplied, no new |ASN.1| object will be created and `self` will
419
+ be returned instead.
420
+ """
421
+ if value is noValue:
422
+ if not kwargs:
423
+ return self
424
+
425
+ value = self._value
426
+
427
+ initializers = self.readOnly.copy()
428
+
429
+ implicitTag = kwargs.pop('implicitTag', None)
430
+ if implicitTag is not None:
431
+ initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
432
+
433
+ explicitTag = kwargs.pop('explicitTag', None)
434
+ if explicitTag is not None:
435
+ initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
436
+
437
+ for arg, option in kwargs.items():
438
+ initializers[arg] += option
439
+
440
+ return self.__class__(value, **initializers)
441
+
442
+ def prettyIn(self, value):
443
+ return value
444
+
445
+ def prettyOut(self, value):
446
+ return str(value)
447
+
448
+ def prettyPrint(self, scope=0):
449
+ return self.prettyOut(self._value)
450
+
451
+ def prettyPrintType(self, scope=0):
452
+ return '%s -> %s' % (self.tagSet, self.__class__.__name__)
453
+
454
+ # Backward compatibility
455
+ AbstractSimpleAsn1Item = SimpleAsn1Type
456
+
457
+ #
458
+ # Constructed types:
459
+ # * There are five of them: Sequence, SequenceOf/SetOf, Set and Choice
460
+ # * ASN1 types and values are represened by Python class instances
461
+ # * Value initialization is made for defaulted components only
462
+ # * Primary method of component addressing is by-position. Data model for base
463
+ # type is Python sequence. Additional type-specific addressing methods
464
+ # may be implemented for particular types.
465
+ # * SequenceOf and SetOf types do not implement any additional methods
466
+ # * Sequence, Set and Choice types also implement by-identifier addressing
467
+ # * Sequence, Set and Choice types also implement by-asn1-type (tag) addressing
468
+ # * Sequence and Set types may include optional and defaulted
469
+ # components
470
+ # * Constructed types hold a reference to component types used for value
471
+ # verification and ordering.
472
+ # * Component type is a scalar type for SequenceOf/SetOf types and a list
473
+ # of types for Sequence/Set/Choice.
474
+ #
475
+
476
+
477
+ class ConstructedAsn1Type(Asn1Type):
478
+ """Base class for all constructed classes representing ASN.1 types.
479
+
480
+ ASN.1 distinguishes types by their ability to hold other objects.
481
+ Those "nesting" types are known as *constructed* in ASN.1.
482
+
483
+ In the user code, |ASN.1| class is normally used only for telling
484
+ ASN.1 objects from others.
485
+
486
+ Note
487
+ ----
488
+ For as long as ASN.1 is concerned, a way to compare ASN.1 types
489
+ is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods.
490
+ """
491
+
492
+ #: If :obj:`True`, requires exact component type matching,
493
+ #: otherwise subtype relation is only enforced
494
+ strictConstraints = False
495
+
496
+ componentType = None
497
+
498
+ # backward compatibility, unused
499
+ sizeSpec = constraint.ConstraintsIntersection()
500
+
501
+ def __init__(self, **kwargs):
502
+ readOnly = {
503
+ 'componentType': self.componentType,
504
+ # backward compatibility, unused
505
+ 'sizeSpec': self.sizeSpec
506
+ }
507
+
508
+ # backward compatibility: preserve legacy sizeSpec support
509
+ kwargs = self._moveSizeSpec(**kwargs)
510
+
511
+ readOnly.update(kwargs)
512
+
513
+ Asn1Type.__init__(self, **readOnly)
514
+
515
+ def _moveSizeSpec(self, **kwargs):
516
+ # backward compatibility, unused
517
+ sizeSpec = kwargs.pop('sizeSpec', self.sizeSpec)
518
+ if sizeSpec:
519
+ subtypeSpec = kwargs.pop('subtypeSpec', self.subtypeSpec)
520
+ if subtypeSpec:
521
+ subtypeSpec = sizeSpec
522
+
523
+ else:
524
+ subtypeSpec += sizeSpec
525
+
526
+ kwargs['subtypeSpec'] = subtypeSpec
527
+
528
+ return kwargs
529
+
530
+ def __repr__(self):
531
+ representation = '%s %s object' % (
532
+ self.__class__.__name__, self.isValue and 'value' or 'schema'
533
+ )
534
+
535
+ for attr, value in self.readOnly.items():
536
+ if value is not noValue:
537
+ representation += ', %s=%r' % (attr, value)
538
+
539
+ if self.isValue and self.components:
540
+ representation += ', payload [%s]' % ', '.join(
541
+ [repr(x) for x in self.components])
542
+
543
+ return '<%s>' % representation
544
+
545
+ def __eq__(self, other):
546
+ return self is other or self.components == other
547
+
548
+ def __ne__(self, other):
549
+ return self.components != other
550
+
551
+ def __lt__(self, other):
552
+ return self.components < other
553
+
554
+ def __le__(self, other):
555
+ return self.components <= other
556
+
557
+ def __gt__(self, other):
558
+ return self.components > other
559
+
560
+ def __ge__(self, other):
561
+ return self.components >= other
562
+
563
+ def __bool__(self):
564
+ return bool(self.components)
565
+
566
+ @property
567
+ def components(self):
568
+ raise error.PyAsn1Error('Method not implemented')
569
+
570
+ def _cloneComponentValues(self, myClone, cloneValueFlag):
571
+ pass
572
+
573
+ def clone(self, **kwargs):
574
+ """Create a modified version of |ASN.1| schema object.
575
+
576
+ The `clone()` method accepts the same set arguments as |ASN.1|
577
+ class takes on instantiation except that all arguments
578
+ of the `clone()` method are optional.
579
+
580
+ Whatever arguments are supplied, they are used to create a copy
581
+ of `self` taking precedence over the ones used to instantiate `self`.
582
+
583
+ Possible values of `self` are never copied over thus `clone()` can
584
+ only create a new schema object.
585
+
586
+ Returns
587
+ -------
588
+ :
589
+ new instance of |ASN.1| type/value
590
+
591
+ Note
592
+ ----
593
+ Due to the mutable nature of the |ASN.1| object, even if no arguments
594
+ are supplied, a new |ASN.1| object will be created and returned.
595
+ """
596
+ cloneValueFlag = kwargs.pop('cloneValueFlag', False)
597
+
598
+ initializers = self.readOnly.copy()
599
+ initializers.update(kwargs)
600
+
601
+ clone = self.__class__(**initializers)
602
+
603
+ if cloneValueFlag:
604
+ self._cloneComponentValues(clone, cloneValueFlag)
605
+
606
+ return clone
607
+
608
+ def subtype(self, **kwargs):
609
+ """Create a specialization of |ASN.1| schema object.
610
+
611
+ The `subtype()` method accepts the same set arguments as |ASN.1|
612
+ class takes on instantiation except that all parameters
613
+ of the `subtype()` method are optional.
614
+
615
+ With the exception of the arguments described below, the rest of
616
+ supplied arguments they are used to create a copy of `self` taking
617
+ precedence over the ones used to instantiate `self`.
618
+
619
+ The following arguments to `subtype()` create a ASN.1 subtype out of
620
+ |ASN.1| type.
621
+
622
+ Other Parameters
623
+ ----------------
624
+ implicitTag: :py:class:`~pyasn1.type.tag.Tag`
625
+ Implicitly apply given ASN.1 tag object to `self`'s
626
+ :py:class:`~pyasn1.type.tag.TagSet`, then use the result as
627
+ new object's ASN.1 tag(s).
628
+
629
+ explicitTag: :py:class:`~pyasn1.type.tag.Tag`
630
+ Explicitly apply given ASN.1 tag object to `self`'s
631
+ :py:class:`~pyasn1.type.tag.TagSet`, then use the result as
632
+ new object's ASN.1 tag(s).
633
+
634
+ subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
635
+ Add ASN.1 constraints object to one of the `self`'s, then
636
+ use the result as new object's ASN.1 constraints.
637
+
638
+
639
+ Returns
640
+ -------
641
+ :
642
+ new instance of |ASN.1| type/value
643
+
644
+ Note
645
+ ----
646
+ Due to the mutable nature of the |ASN.1| object, even if no arguments
647
+ are supplied, a new |ASN.1| object will be created and returned.
648
+ """
649
+
650
+ initializers = self.readOnly.copy()
651
+
652
+ cloneValueFlag = kwargs.pop('cloneValueFlag', False)
653
+
654
+ implicitTag = kwargs.pop('implicitTag', None)
655
+ if implicitTag is not None:
656
+ initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
657
+
658
+ explicitTag = kwargs.pop('explicitTag', None)
659
+ if explicitTag is not None:
660
+ initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
661
+
662
+ for arg, option in kwargs.items():
663
+ initializers[arg] += option
664
+
665
+ clone = self.__class__(**initializers)
666
+
667
+ if cloneValueFlag:
668
+ self._cloneComponentValues(clone, cloneValueFlag)
669
+
670
+ return clone
671
+
672
+ def getComponentByPosition(self, idx):
673
+ raise error.PyAsn1Error('Method not implemented')
674
+
675
+ def setComponentByPosition(self, idx, value, verifyConstraints=True):
676
+ raise error.PyAsn1Error('Method not implemented')
677
+
678
+ def setComponents(self, *args, **kwargs):
679
+ for idx, value in enumerate(args):
680
+ self[idx] = value
681
+ for k in kwargs:
682
+ self[k] = kwargs[k]
683
+ return self
684
+
685
+ # backward compatibility
686
+
687
+ def setDefaultComponents(self):
688
+ pass
689
+
690
+ def getComponentType(self):
691
+ return self.componentType
692
+
693
+ # backward compatibility, unused
694
+ def verifySizeSpec(self):
695
+ self.subtypeSpec(self)
696
+
697
+
698
+ # Backward compatibility
699
+ AbstractConstructedAsn1Item = ConstructedAsn1Type
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/char.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ import sys
8
+
9
+ from pyasn1 import error
10
+ from pyasn1.type import tag
11
+ from pyasn1.type import univ
12
+
13
+ __all__ = ['NumericString', 'PrintableString', 'TeletexString', 'T61String', 'VideotexString',
14
+ 'IA5String', 'GraphicString', 'VisibleString', 'ISO646String',
15
+ 'GeneralString', 'UniversalString', 'BMPString', 'UTF8String']
16
+
17
+ NoValue = univ.NoValue
18
+ noValue = univ.noValue
19
+
20
+
21
+ class AbstractCharacterString(univ.OctetString):
22
+ """Creates |ASN.1| schema or value object.
23
+
24
+ |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`,
25
+ its objects are immutable and duck-type :class:`bytes`.
26
+ When used in octet-stream context, |ASN.1| type assumes
27
+ "|encoding|" encoding.
28
+
29
+ Keyword Args
30
+ ------------
31
+ value: :class:`str`, :class:`bytes` or |ASN.1| object
32
+ :class:`str`, alternatively :class:`bytes`
33
+ representing octet-stream of serialised unicode string
34
+ (note `encoding` parameter) or |ASN.1| class instance.
35
+ If `value` is not given, schema object will be created.
36
+
37
+ tagSet: :py:class:`~pyasn1.type.tag.TagSet`
38
+ Object representing non-default ASN.1 tag(s)
39
+
40
+ subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
41
+ Object representing non-default ASN.1 subtype constraint(s). Constraints
42
+ verification for |ASN.1| type occurs automatically on object
43
+ instantiation.
44
+
45
+ encoding: :py:class:`str`
46
+ Unicode codec ID to encode/decode
47
+ :class:`str` the payload when |ASN.1| object is used
48
+ in octet-stream context.
49
+
50
+ Raises
51
+ ------
52
+ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error
53
+ On constraint violation or bad initializer.
54
+ """
55
+
56
+ def __str__(self):
57
+ return str(self._value)
58
+
59
+ def __bytes__(self):
60
+ try:
61
+ return self._value.encode(self.encoding)
62
+ except UnicodeEncodeError as exc:
63
+ raise error.PyAsn1UnicodeEncodeError(
64
+ "Can't encode string '%s' with codec "
65
+ "%s" % (self._value, self.encoding), exc
66
+ )
67
+
68
+ def prettyIn(self, value):
69
+ try:
70
+ if isinstance(value, str):
71
+ return value
72
+ elif isinstance(value, bytes):
73
+ return value.decode(self.encoding)
74
+ elif isinstance(value, (tuple, list)):
75
+ return self.prettyIn(bytes(value))
76
+ elif isinstance(value, univ.OctetString):
77
+ return value.asOctets().decode(self.encoding)
78
+ else:
79
+ return str(value)
80
+
81
+ except (UnicodeDecodeError, LookupError) as exc:
82
+ raise error.PyAsn1UnicodeDecodeError(
83
+ "Can't decode string '%s' with codec "
84
+ "%s" % (value, self.encoding), exc
85
+ )
86
+
87
+ def asOctets(self, padding=True):
88
+ return bytes(self)
89
+
90
+ def asNumbers(self, padding=True):
91
+ return tuple(bytes(self))
92
+
93
+ #
94
+ # See OctetString.prettyPrint() for the explanation
95
+ #
96
+
97
+ def prettyOut(self, value):
98
+ return value
99
+
100
+ def prettyPrint(self, scope=0):
101
+ # first see if subclass has its own .prettyOut()
102
+ value = self.prettyOut(self._value)
103
+
104
+ if value is not self._value:
105
+ return value
106
+
107
+ return AbstractCharacterString.__str__(self)
108
+
109
+ def __reversed__(self):
110
+ return reversed(self._value)
111
+
112
+
113
+ class NumericString(AbstractCharacterString):
114
+ __doc__ = AbstractCharacterString.__doc__
115
+
116
+ #: Set (on class, not on instance) or return a
117
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
118
+ #: associated with |ASN.1| type.
119
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
120
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 18)
121
+ )
122
+ encoding = 'us-ascii'
123
+
124
+ # Optimization for faster codec lookup
125
+ typeId = AbstractCharacterString.getTypeId()
126
+
127
+
128
+ class PrintableString(AbstractCharacterString):
129
+ __doc__ = AbstractCharacterString.__doc__
130
+
131
+ #: Set (on class, not on instance) or return a
132
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
133
+ #: associated with |ASN.1| type.
134
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
135
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 19)
136
+ )
137
+ encoding = 'us-ascii'
138
+
139
+ # Optimization for faster codec lookup
140
+ typeId = AbstractCharacterString.getTypeId()
141
+
142
+
143
+ class TeletexString(AbstractCharacterString):
144
+ __doc__ = AbstractCharacterString.__doc__
145
+
146
+ #: Set (on class, not on instance) or return a
147
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
148
+ #: associated with |ASN.1| type.
149
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
150
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 20)
151
+ )
152
+ encoding = 'iso-8859-1'
153
+
154
+ # Optimization for faster codec lookup
155
+ typeId = AbstractCharacterString.getTypeId()
156
+
157
+
158
+ class T61String(TeletexString):
159
+ __doc__ = TeletexString.__doc__
160
+
161
+ # Optimization for faster codec lookup
162
+ typeId = AbstractCharacterString.getTypeId()
163
+
164
+
165
+ class VideotexString(AbstractCharacterString):
166
+ __doc__ = AbstractCharacterString.__doc__
167
+
168
+ #: Set (on class, not on instance) or return a
169
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
170
+ #: associated with |ASN.1| type.
171
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
172
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 21)
173
+ )
174
+ encoding = 'iso-8859-1'
175
+
176
+ # Optimization for faster codec lookup
177
+ typeId = AbstractCharacterString.getTypeId()
178
+
179
+
180
+ class IA5String(AbstractCharacterString):
181
+ __doc__ = AbstractCharacterString.__doc__
182
+
183
+ #: Set (on class, not on instance) or return a
184
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
185
+ #: associated with |ASN.1| type.
186
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
187
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 22)
188
+ )
189
+ encoding = 'us-ascii'
190
+
191
+ # Optimization for faster codec lookup
192
+ typeId = AbstractCharacterString.getTypeId()
193
+
194
+
195
+ class GraphicString(AbstractCharacterString):
196
+ __doc__ = AbstractCharacterString.__doc__
197
+
198
+ #: Set (on class, not on instance) or return a
199
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
200
+ #: associated with |ASN.1| type.
201
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
202
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 25)
203
+ )
204
+ encoding = 'iso-8859-1'
205
+
206
+ # Optimization for faster codec lookup
207
+ typeId = AbstractCharacterString.getTypeId()
208
+
209
+
210
+ class VisibleString(AbstractCharacterString):
211
+ __doc__ = AbstractCharacterString.__doc__
212
+
213
+ #: Set (on class, not on instance) or return a
214
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
215
+ #: associated with |ASN.1| type.
216
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
217
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 26)
218
+ )
219
+ encoding = 'us-ascii'
220
+
221
+ # Optimization for faster codec lookup
222
+ typeId = AbstractCharacterString.getTypeId()
223
+
224
+
225
+ class ISO646String(VisibleString):
226
+ __doc__ = VisibleString.__doc__
227
+
228
+ # Optimization for faster codec lookup
229
+ typeId = AbstractCharacterString.getTypeId()
230
+
231
+ class GeneralString(AbstractCharacterString):
232
+ __doc__ = AbstractCharacterString.__doc__
233
+
234
+ #: Set (on class, not on instance) or return a
235
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
236
+ #: associated with |ASN.1| type.
237
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
238
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 27)
239
+ )
240
+ encoding = 'iso-8859-1'
241
+
242
+ # Optimization for faster codec lookup
243
+ typeId = AbstractCharacterString.getTypeId()
244
+
245
+
246
+ class UniversalString(AbstractCharacterString):
247
+ __doc__ = AbstractCharacterString.__doc__
248
+
249
+ #: Set (on class, not on instance) or return a
250
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
251
+ #: associated with |ASN.1| type.
252
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
253
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 28)
254
+ )
255
+ encoding = "utf-32-be"
256
+
257
+ # Optimization for faster codec lookup
258
+ typeId = AbstractCharacterString.getTypeId()
259
+
260
+
261
+ class BMPString(AbstractCharacterString):
262
+ __doc__ = AbstractCharacterString.__doc__
263
+
264
+ #: Set (on class, not on instance) or return a
265
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
266
+ #: associated with |ASN.1| type.
267
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
268
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 30)
269
+ )
270
+ encoding = "utf-16-be"
271
+
272
+ # Optimization for faster codec lookup
273
+ typeId = AbstractCharacterString.getTypeId()
274
+
275
+
276
+ class UTF8String(AbstractCharacterString):
277
+ __doc__ = AbstractCharacterString.__doc__
278
+
279
+ #: Set (on class, not on instance) or return a
280
+ #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
281
+ #: associated with |ASN.1| type.
282
+ tagSet = AbstractCharacterString.tagSet.tagImplicitly(
283
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12)
284
+ )
285
+ encoding = "utf-8"
286
+
287
+ # Optimization for faster codec lookup
288
+ typeId = AbstractCharacterString.getTypeId()
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/constraint.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ # Original concept and code by Mike C. Fletcher.
8
+ #
9
+ import sys
10
+
11
+ from pyasn1.type import error
12
+
13
+ __all__ = ['SingleValueConstraint', 'ContainedSubtypeConstraint',
14
+ 'ValueRangeConstraint', 'ValueSizeConstraint',
15
+ 'PermittedAlphabetConstraint', 'InnerTypeConstraint',
16
+ 'ConstraintsExclusion', 'ConstraintsIntersection',
17
+ 'ConstraintsUnion']
18
+
19
+
20
+ class AbstractConstraint(object):
21
+
22
+ def __init__(self, *values):
23
+ self._valueMap = set()
24
+ self._setValues(values)
25
+ self.__hash = hash((self.__class__.__name__, self._values))
26
+
27
+ def __call__(self, value, idx=None):
28
+ if not self._values:
29
+ return
30
+
31
+ try:
32
+ self._testValue(value, idx)
33
+
34
+ except error.ValueConstraintError as exc:
35
+ raise error.ValueConstraintError(
36
+ '%s failed at: %r' % (self, exc)
37
+ )
38
+
39
+ def __repr__(self):
40
+ representation = '%s object' % (self.__class__.__name__)
41
+
42
+ if self._values:
43
+ representation += ', consts %s' % ', '.join(
44
+ [repr(x) for x in self._values])
45
+
46
+ return '<%s>' % representation
47
+
48
+ def __eq__(self, other):
49
+ if self is other:
50
+ return True
51
+ return self._values == other
52
+
53
+ def __ne__(self, other):
54
+ return self._values != other
55
+
56
+ def __lt__(self, other):
57
+ return self._values < other
58
+
59
+ def __le__(self, other):
60
+ return self._values <= other
61
+
62
+ def __gt__(self, other):
63
+ return self._values > other
64
+
65
+ def __ge__(self, other):
66
+ return self._values >= other
67
+
68
+ def __bool__(self):
69
+ return bool(self._values)
70
+
71
+ def __hash__(self):
72
+ return self.__hash
73
+
74
+ def _setValues(self, values):
75
+ self._values = values
76
+
77
+ def _testValue(self, value, idx):
78
+ raise error.ValueConstraintError(value)
79
+
80
+ # Constraints derivation logic
81
+ def getValueMap(self):
82
+ return self._valueMap
83
+
84
+ def isSuperTypeOf(self, otherConstraint):
85
+ # TODO: fix possible comparison of set vs scalars here
86
+ return (otherConstraint is self or
87
+ not self._values or
88
+ otherConstraint == self or
89
+ self in otherConstraint.getValueMap())
90
+
91
+ def isSubTypeOf(self, otherConstraint):
92
+ return (otherConstraint is self or
93
+ not self or
94
+ otherConstraint == self or
95
+ otherConstraint in self._valueMap)
96
+
97
+
98
+ class SingleValueConstraint(AbstractConstraint):
99
+ """Create a SingleValueConstraint object.
100
+
101
+ The SingleValueConstraint satisfies any value that
102
+ is present in the set of permitted values.
103
+
104
+ Objects of this type are iterable (emitting constraint values) and
105
+ can act as operands for some arithmetic operations e.g. addition
106
+ and subtraction. The latter can be used for combining multiple
107
+ SingleValueConstraint objects into one.
108
+
109
+ The SingleValueConstraint object can be applied to
110
+ any ASN.1 type.
111
+
112
+ Parameters
113
+ ----------
114
+ *values: :class:`int`
115
+ Full set of values permitted by this constraint object.
116
+
117
+ Examples
118
+ --------
119
+ .. code-block:: python
120
+
121
+ class DivisorOfSix(Integer):
122
+ '''
123
+ ASN.1 specification:
124
+
125
+ Divisor-Of-6 ::= INTEGER (1 | 2 | 3 | 6)
126
+ '''
127
+ subtypeSpec = SingleValueConstraint(1, 2, 3, 6)
128
+
129
+ # this will succeed
130
+ divisor_of_six = DivisorOfSix(1)
131
+
132
+ # this will raise ValueConstraintError
133
+ divisor_of_six = DivisorOfSix(7)
134
+ """
135
+ def _setValues(self, values):
136
+ self._values = values
137
+ self._set = set(values)
138
+
139
+ def _testValue(self, value, idx):
140
+ if value not in self._set:
141
+ raise error.ValueConstraintError(value)
142
+
143
+ # Constrains can be merged or reduced
144
+
145
+ def __contains__(self, item):
146
+ return item in self._set
147
+
148
+ def __iter__(self):
149
+ return iter(self._set)
150
+
151
+ def __add__(self, constraint):
152
+ return self.__class__(*(self._set.union(constraint)))
153
+
154
+ def __sub__(self, constraint):
155
+ return self.__class__(*(self._set.difference(constraint)))
156
+
157
+
158
+ class ContainedSubtypeConstraint(AbstractConstraint):
159
+ """Create a ContainedSubtypeConstraint object.
160
+
161
+ The ContainedSubtypeConstraint satisfies any value that
162
+ is present in the set of permitted values and also
163
+ satisfies included constraints.
164
+
165
+ The ContainedSubtypeConstraint object can be applied to
166
+ any ASN.1 type.
167
+
168
+ Parameters
169
+ ----------
170
+ *values:
171
+ Full set of values and constraint objects permitted
172
+ by this constraint object.
173
+
174
+ Examples
175
+ --------
176
+ .. code-block:: python
177
+
178
+ class DivisorOfEighteen(Integer):
179
+ '''
180
+ ASN.1 specification:
181
+
182
+ Divisors-of-18 ::= INTEGER (INCLUDES Divisors-of-6 | 9 | 18)
183
+ '''
184
+ subtypeSpec = ContainedSubtypeConstraint(
185
+ SingleValueConstraint(1, 2, 3, 6), 9, 18
186
+ )
187
+
188
+ # this will succeed
189
+ divisor_of_eighteen = DivisorOfEighteen(9)
190
+
191
+ # this will raise ValueConstraintError
192
+ divisor_of_eighteen = DivisorOfEighteen(10)
193
+ """
194
+ def _testValue(self, value, idx):
195
+ for constraint in self._values:
196
+ if isinstance(constraint, AbstractConstraint):
197
+ constraint(value, idx)
198
+ elif value not in self._set:
199
+ raise error.ValueConstraintError(value)
200
+
201
+
202
+ class ValueRangeConstraint(AbstractConstraint):
203
+ """Create a ValueRangeConstraint object.
204
+
205
+ The ValueRangeConstraint satisfies any value that
206
+ falls in the range of permitted values.
207
+
208
+ The ValueRangeConstraint object can only be applied
209
+ to :class:`~pyasn1.type.univ.Integer` and
210
+ :class:`~pyasn1.type.univ.Real` types.
211
+
212
+ Parameters
213
+ ----------
214
+ start: :class:`int`
215
+ Minimum permitted value in the range (inclusive)
216
+
217
+ end: :class:`int`
218
+ Maximum permitted value in the range (inclusive)
219
+
220
+ Examples
221
+ --------
222
+ .. code-block:: python
223
+
224
+ class TeenAgeYears(Integer):
225
+ '''
226
+ ASN.1 specification:
227
+
228
+ TeenAgeYears ::= INTEGER (13 .. 19)
229
+ '''
230
+ subtypeSpec = ValueRangeConstraint(13, 19)
231
+
232
+ # this will succeed
233
+ teen_year = TeenAgeYears(18)
234
+
235
+ # this will raise ValueConstraintError
236
+ teen_year = TeenAgeYears(20)
237
+ """
238
+ def _testValue(self, value, idx):
239
+ if value < self.start or value > self.stop:
240
+ raise error.ValueConstraintError(value)
241
+
242
+ def _setValues(self, values):
243
+ if len(values) != 2:
244
+ raise error.PyAsn1Error(
245
+ '%s: bad constraint values' % (self.__class__.__name__,)
246
+ )
247
+ self.start, self.stop = values
248
+ if self.start > self.stop:
249
+ raise error.PyAsn1Error(
250
+ '%s: screwed constraint values (start > stop): %s > %s' % (
251
+ self.__class__.__name__,
252
+ self.start, self.stop
253
+ )
254
+ )
255
+ AbstractConstraint._setValues(self, values)
256
+
257
+
258
+ class ValueSizeConstraint(ValueRangeConstraint):
259
+ """Create a ValueSizeConstraint object.
260
+
261
+ The ValueSizeConstraint satisfies any value for
262
+ as long as its size falls within the range of
263
+ permitted sizes.
264
+
265
+ The ValueSizeConstraint object can be applied
266
+ to :class:`~pyasn1.type.univ.BitString`,
267
+ :class:`~pyasn1.type.univ.OctetString` (including
268
+ all :ref:`character ASN.1 types <type.char>`),
269
+ :class:`~pyasn1.type.univ.SequenceOf`
270
+ and :class:`~pyasn1.type.univ.SetOf` types.
271
+
272
+ Parameters
273
+ ----------
274
+ minimum: :class:`int`
275
+ Minimum permitted size of the value (inclusive)
276
+
277
+ maximum: :class:`int`
278
+ Maximum permitted size of the value (inclusive)
279
+
280
+ Examples
281
+ --------
282
+ .. code-block:: python
283
+
284
+ class BaseballTeamRoster(SetOf):
285
+ '''
286
+ ASN.1 specification:
287
+
288
+ BaseballTeamRoster ::= SET SIZE (1..25) OF PlayerNames
289
+ '''
290
+ componentType = PlayerNames()
291
+ subtypeSpec = ValueSizeConstraint(1, 25)
292
+
293
+ # this will succeed
294
+ team = BaseballTeamRoster()
295
+ team.extend(['Jan', 'Matej'])
296
+ encode(team)
297
+
298
+ # this will raise ValueConstraintError
299
+ team = BaseballTeamRoster()
300
+ team.extend(['Jan'] * 26)
301
+ encode(team)
302
+
303
+ Note
304
+ ----
305
+ Whenever ValueSizeConstraint is applied to mutable types
306
+ (e.g. :class:`~pyasn1.type.univ.SequenceOf`,
307
+ :class:`~pyasn1.type.univ.SetOf`), constraint
308
+ validation only happens at the serialisation phase rather
309
+ than schema instantiation phase (as it is with immutable
310
+ types).
311
+ """
312
+ def _testValue(self, value, idx):
313
+ valueSize = len(value)
314
+ if valueSize < self.start or valueSize > self.stop:
315
+ raise error.ValueConstraintError(value)
316
+
317
+
318
+ class PermittedAlphabetConstraint(SingleValueConstraint):
319
+ """Create a PermittedAlphabetConstraint object.
320
+
321
+ The PermittedAlphabetConstraint satisfies any character
322
+ string for as long as all its characters are present in
323
+ the set of permitted characters.
324
+
325
+ Objects of this type are iterable (emitting constraint values) and
326
+ can act as operands for some arithmetic operations e.g. addition
327
+ and subtraction.
328
+
329
+ The PermittedAlphabetConstraint object can only be applied
330
+ to the :ref:`character ASN.1 types <type.char>` such as
331
+ :class:`~pyasn1.type.char.IA5String`.
332
+
333
+ Parameters
334
+ ----------
335
+ *alphabet: :class:`str`
336
+ Full set of characters permitted by this constraint object.
337
+
338
+ Example
339
+ -------
340
+ .. code-block:: python
341
+
342
+ class BooleanValue(IA5String):
343
+ '''
344
+ ASN.1 specification:
345
+
346
+ BooleanValue ::= IA5String (FROM ('T' | 'F'))
347
+ '''
348
+ subtypeSpec = PermittedAlphabetConstraint('T', 'F')
349
+
350
+ # this will succeed
351
+ truth = BooleanValue('T')
352
+ truth = BooleanValue('TF')
353
+
354
+ # this will raise ValueConstraintError
355
+ garbage = BooleanValue('TAF')
356
+
357
+ ASN.1 `FROM ... EXCEPT ...` clause can be modelled by combining multiple
358
+ PermittedAlphabetConstraint objects into one:
359
+
360
+ Example
361
+ -------
362
+ .. code-block:: python
363
+
364
+ class Lipogramme(IA5String):
365
+ '''
366
+ ASN.1 specification:
367
+
368
+ Lipogramme ::=
369
+ IA5String (FROM (ALL EXCEPT ("e"|"E")))
370
+ '''
371
+ subtypeSpec = (
372
+ PermittedAlphabetConstraint(*string.printable) -
373
+ PermittedAlphabetConstraint('e', 'E')
374
+ )
375
+
376
+ # this will succeed
377
+ lipogramme = Lipogramme('A work of fiction?')
378
+
379
+ # this will raise ValueConstraintError
380
+ lipogramme = Lipogramme('Eel')
381
+
382
+ Note
383
+ ----
384
+ Although `ConstraintsExclusion` object could seemingly be used for this
385
+ purpose, practically, for it to work, it needs to represent its operand
386
+ constraints as sets and intersect one with the other. That would require
387
+ the insight into the constraint values (and their types) that are otherwise
388
+ hidden inside the constraint object.
389
+
390
+ Therefore it's more practical to model `EXCEPT` clause at
391
+ `PermittedAlphabetConstraint` level instead.
392
+ """
393
+ def _setValues(self, values):
394
+ self._values = values
395
+ self._set = set(values)
396
+
397
+ def _testValue(self, value, idx):
398
+ if not self._set.issuperset(value):
399
+ raise error.ValueConstraintError(value)
400
+
401
+
402
+ class ComponentPresentConstraint(AbstractConstraint):
403
+ """Create a ComponentPresentConstraint object.
404
+
405
+ The ComponentPresentConstraint is only satisfied when the value
406
+ is not `None`.
407
+
408
+ The ComponentPresentConstraint object is typically used with
409
+ `WithComponentsConstraint`.
410
+
411
+ Examples
412
+ --------
413
+ .. code-block:: python
414
+
415
+ present = ComponentPresentConstraint()
416
+
417
+ # this will succeed
418
+ present('whatever')
419
+
420
+ # this will raise ValueConstraintError
421
+ present(None)
422
+ """
423
+ def _setValues(self, values):
424
+ self._values = ('<must be present>',)
425
+
426
+ if values:
427
+ raise error.PyAsn1Error('No arguments expected')
428
+
429
+ def _testValue(self, value, idx):
430
+ if value is None:
431
+ raise error.ValueConstraintError(
432
+ 'Component is not present:')
433
+
434
+
435
+ class ComponentAbsentConstraint(AbstractConstraint):
436
+ """Create a ComponentAbsentConstraint object.
437
+
438
+ The ComponentAbsentConstraint is only satisfied when the value
439
+ is `None`.
440
+
441
+ The ComponentAbsentConstraint object is typically used with
442
+ `WithComponentsConstraint`.
443
+
444
+ Examples
445
+ --------
446
+ .. code-block:: python
447
+
448
+ absent = ComponentAbsentConstraint()
449
+
450
+ # this will succeed
451
+ absent(None)
452
+
453
+ # this will raise ValueConstraintError
454
+ absent('whatever')
455
+ """
456
+ def _setValues(self, values):
457
+ self._values = ('<must be absent>',)
458
+
459
+ if values:
460
+ raise error.PyAsn1Error('No arguments expected')
461
+
462
+ def _testValue(self, value, idx):
463
+ if value is not None:
464
+ raise error.ValueConstraintError(
465
+ 'Component is not absent: %r' % value)
466
+
467
+
468
+ class WithComponentsConstraint(AbstractConstraint):
469
+ """Create a WithComponentsConstraint object.
470
+
471
+ The `WithComponentsConstraint` satisfies any mapping object that has
472
+ constrained fields present or absent, what is indicated by
473
+ `ComponentPresentConstraint` and `ComponentAbsentConstraint`
474
+ objects respectively.
475
+
476
+ The `WithComponentsConstraint` object is typically applied
477
+ to :class:`~pyasn1.type.univ.Set` or
478
+ :class:`~pyasn1.type.univ.Sequence` types.
479
+
480
+ Parameters
481
+ ----------
482
+ *fields: :class:`tuple`
483
+ Zero or more tuples of (`field`, `constraint`) indicating constrained
484
+ fields.
485
+
486
+ Notes
487
+ -----
488
+ On top of the primary use of `WithComponentsConstraint` (ensuring presence
489
+ or absence of particular components of a :class:`~pyasn1.type.univ.Set` or
490
+ :class:`~pyasn1.type.univ.Sequence`), it is also possible to pass any other
491
+ constraint objects or their combinations. In case of scalar fields, these
492
+ constraints will be verified in addition to the constraints belonging to
493
+ scalar components themselves. However, formally, these additional
494
+ constraints do not change the type of these ASN.1 objects.
495
+
496
+ Examples
497
+ --------
498
+
499
+ .. code-block:: python
500
+
501
+ class Item(Sequence): # Set is similar
502
+ '''
503
+ ASN.1 specification:
504
+
505
+ Item ::= SEQUENCE {
506
+ id INTEGER OPTIONAL,
507
+ name OCTET STRING OPTIONAL
508
+ } WITH COMPONENTS id PRESENT, name ABSENT | id ABSENT, name PRESENT
509
+ '''
510
+ componentType = NamedTypes(
511
+ OptionalNamedType('id', Integer()),
512
+ OptionalNamedType('name', OctetString())
513
+ )
514
+ withComponents = ConstraintsUnion(
515
+ WithComponentsConstraint(
516
+ ('id', ComponentPresentConstraint()),
517
+ ('name', ComponentAbsentConstraint())
518
+ ),
519
+ WithComponentsConstraint(
520
+ ('id', ComponentAbsentConstraint()),
521
+ ('name', ComponentPresentConstraint())
522
+ )
523
+ )
524
+
525
+ item = Item()
526
+
527
+ # This will succeed
528
+ item['id'] = 1
529
+
530
+ # This will succeed
531
+ item.reset()
532
+ item['name'] = 'John'
533
+
534
+ # This will fail (on encoding)
535
+ item.reset()
536
+ descr['id'] = 1
537
+ descr['name'] = 'John'
538
+ """
539
+ def _testValue(self, value, idx):
540
+ for field, constraint in self._values:
541
+ constraint(value.get(field))
542
+
543
+ def _setValues(self, values):
544
+ AbstractConstraint._setValues(self, values)
545
+
546
+
547
+ # This is a bit kludgy, meaning two op modes within a single constraint
548
+ class InnerTypeConstraint(AbstractConstraint):
549
+ """Value must satisfy the type and presence constraints"""
550
+
551
+ def _testValue(self, value, idx):
552
+ if self.__singleTypeConstraint:
553
+ self.__singleTypeConstraint(value)
554
+ elif self.__multipleTypeConstraint:
555
+ if idx not in self.__multipleTypeConstraint:
556
+ raise error.ValueConstraintError(value)
557
+ constraint, status = self.__multipleTypeConstraint[idx]
558
+ if status == 'ABSENT': # XXX presence is not checked!
559
+ raise error.ValueConstraintError(value)
560
+ constraint(value)
561
+
562
+ def _setValues(self, values):
563
+ self.__multipleTypeConstraint = {}
564
+ self.__singleTypeConstraint = None
565
+ for v in values:
566
+ if isinstance(v, tuple):
567
+ self.__multipleTypeConstraint[v[0]] = v[1], v[2]
568
+ else:
569
+ self.__singleTypeConstraint = v
570
+ AbstractConstraint._setValues(self, values)
571
+
572
+
573
+ # Logic operations on constraints
574
+
575
+ class ConstraintsExclusion(AbstractConstraint):
576
+ """Create a ConstraintsExclusion logic operator object.
577
+
578
+ The ConstraintsExclusion logic operator succeeds when the
579
+ value does *not* satisfy the operand constraint.
580
+
581
+ The ConstraintsExclusion object can be applied to
582
+ any constraint and logic operator object.
583
+
584
+ Parameters
585
+ ----------
586
+ *constraints:
587
+ Constraint or logic operator objects.
588
+
589
+ Examples
590
+ --------
591
+ .. code-block:: python
592
+
593
+ class LuckyNumber(Integer):
594
+ subtypeSpec = ConstraintsExclusion(
595
+ SingleValueConstraint(13)
596
+ )
597
+
598
+ # this will succeed
599
+ luckyNumber = LuckyNumber(12)
600
+
601
+ # this will raise ValueConstraintError
602
+ luckyNumber = LuckyNumber(13)
603
+
604
+ Note
605
+ ----
606
+ The `FROM ... EXCEPT ...` ASN.1 clause should be modeled by combining
607
+ constraint objects into one. See `PermittedAlphabetConstraint` for more
608
+ information.
609
+ """
610
+ def _testValue(self, value, idx):
611
+ for constraint in self._values:
612
+ try:
613
+ constraint(value, idx)
614
+
615
+ except error.ValueConstraintError:
616
+ continue
617
+
618
+ raise error.ValueConstraintError(value)
619
+
620
+ def _setValues(self, values):
621
+ AbstractConstraint._setValues(self, values)
622
+
623
+
624
+ class AbstractConstraintSet(AbstractConstraint):
625
+
626
+ def __getitem__(self, idx):
627
+ return self._values[idx]
628
+
629
+ def __iter__(self):
630
+ return iter(self._values)
631
+
632
+ def __add__(self, value):
633
+ return self.__class__(*(self._values + (value,)))
634
+
635
+ def __radd__(self, value):
636
+ return self.__class__(*((value,) + self._values))
637
+
638
+ def __len__(self):
639
+ return len(self._values)
640
+
641
+ # Constraints inclusion in sets
642
+
643
+ def _setValues(self, values):
644
+ self._values = values
645
+ for constraint in values:
646
+ if constraint:
647
+ self._valueMap.add(constraint)
648
+ self._valueMap.update(constraint.getValueMap())
649
+
650
+
651
+ class ConstraintsIntersection(AbstractConstraintSet):
652
+ """Create a ConstraintsIntersection logic operator object.
653
+
654
+ The ConstraintsIntersection logic operator only succeeds
655
+ if *all* its operands succeed.
656
+
657
+ The ConstraintsIntersection object can be applied to
658
+ any constraint and logic operator objects.
659
+
660
+ The ConstraintsIntersection object duck-types the immutable
661
+ container object like Python :py:class:`tuple`.
662
+
663
+ Parameters
664
+ ----------
665
+ *constraints:
666
+ Constraint or logic operator objects.
667
+
668
+ Examples
669
+ --------
670
+ .. code-block:: python
671
+
672
+ class CapitalAndSmall(IA5String):
673
+ '''
674
+ ASN.1 specification:
675
+
676
+ CapitalAndSmall ::=
677
+ IA5String (FROM ("A".."Z"|"a".."z"))
678
+ '''
679
+ subtypeSpec = ConstraintsIntersection(
680
+ PermittedAlphabetConstraint('A', 'Z'),
681
+ PermittedAlphabetConstraint('a', 'z')
682
+ )
683
+
684
+ # this will succeed
685
+ capital_and_small = CapitalAndSmall('Hello')
686
+
687
+ # this will raise ValueConstraintError
688
+ capital_and_small = CapitalAndSmall('hello')
689
+ """
690
+ def _testValue(self, value, idx):
691
+ for constraint in self._values:
692
+ constraint(value, idx)
693
+
694
+
695
+ class ConstraintsUnion(AbstractConstraintSet):
696
+ """Create a ConstraintsUnion logic operator object.
697
+
698
+ The ConstraintsUnion logic operator succeeds if
699
+ *at least* a single operand succeeds.
700
+
701
+ The ConstraintsUnion object can be applied to
702
+ any constraint and logic operator objects.
703
+
704
+ The ConstraintsUnion object duck-types the immutable
705
+ container object like Python :py:class:`tuple`.
706
+
707
+ Parameters
708
+ ----------
709
+ *constraints:
710
+ Constraint or logic operator objects.
711
+
712
+ Examples
713
+ --------
714
+ .. code-block:: python
715
+
716
+ class CapitalOrSmall(IA5String):
717
+ '''
718
+ ASN.1 specification:
719
+
720
+ CapitalOrSmall ::=
721
+ IA5String (FROM ("A".."Z") | FROM ("a".."z"))
722
+ '''
723
+ subtypeSpec = ConstraintsUnion(
724
+ PermittedAlphabetConstraint('A', 'Z'),
725
+ PermittedAlphabetConstraint('a', 'z')
726
+ )
727
+
728
+ # this will succeed
729
+ capital_or_small = CapitalAndSmall('Hello')
730
+
731
+ # this will raise ValueConstraintError
732
+ capital_or_small = CapitalOrSmall('hello!')
733
+ """
734
+ def _testValue(self, value, idx):
735
+ for constraint in self._values:
736
+ try:
737
+ constraint(value, idx)
738
+ except error.ValueConstraintError:
739
+ pass
740
+ else:
741
+ return
742
+
743
+ raise error.ValueConstraintError(
744
+ 'all of %s failed for "%s"' % (self._values, value)
745
+ )
746
+
747
+ # TODO:
748
+ # refactor InnerTypeConstraint
749
+ # add tests for type check
750
+ # implement other constraint types
751
+ # make constraint validation easy to skip
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/error.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ from pyasn1.error import PyAsn1Error
8
+
9
+
10
+ class ValueConstraintError(PyAsn1Error):
11
+ pass
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/namedtype.py ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ import sys
8
+
9
+ from pyasn1 import error
10
+ from pyasn1.type import tag
11
+ from pyasn1.type import tagmap
12
+
13
+ __all__ = ['NamedType', 'OptionalNamedType', 'DefaultedNamedType',
14
+ 'NamedTypes']
15
+
16
+ class NamedType(object):
17
+ """Create named field object for a constructed ASN.1 type.
18
+
19
+ The |NamedType| object represents a single name and ASN.1 type of a constructed ASN.1 type.
20
+
21
+ |NamedType| objects are immutable and duck-type Python :class:`tuple` objects
22
+ holding *name* and *asn1Object* components.
23
+
24
+ Parameters
25
+ ----------
26
+ name: :py:class:`str`
27
+ Field name
28
+
29
+ asn1Object:
30
+ ASN.1 type object
31
+ """
32
+ isOptional = False
33
+ isDefaulted = False
34
+
35
+ def __init__(self, name, asn1Object, openType=None):
36
+ self.__name = name
37
+ self.__type = asn1Object
38
+ self.__nameAndType = name, asn1Object
39
+ self.__openType = openType
40
+
41
+ def __repr__(self):
42
+ representation = '%s=%r' % (self.name, self.asn1Object)
43
+
44
+ if self.openType:
45
+ representation += ', open type %r' % self.openType
46
+
47
+ return '<%s object, type %s>' % (
48
+ self.__class__.__name__, representation)
49
+
50
+ def __eq__(self, other):
51
+ return self.__nameAndType == other
52
+
53
+ def __ne__(self, other):
54
+ return self.__nameAndType != other
55
+
56
+ def __lt__(self, other):
57
+ return self.__nameAndType < other
58
+
59
+ def __le__(self, other):
60
+ return self.__nameAndType <= other
61
+
62
+ def __gt__(self, other):
63
+ return self.__nameAndType > other
64
+
65
+ def __ge__(self, other):
66
+ return self.__nameAndType >= other
67
+
68
+ def __hash__(self):
69
+ return hash(self.__nameAndType)
70
+
71
+ def __getitem__(self, idx):
72
+ return self.__nameAndType[idx]
73
+
74
+ def __iter__(self):
75
+ return iter(self.__nameAndType)
76
+
77
+ @property
78
+ def name(self):
79
+ return self.__name
80
+
81
+ @property
82
+ def asn1Object(self):
83
+ return self.__type
84
+
85
+ @property
86
+ def openType(self):
87
+ return self.__openType
88
+
89
+ # Backward compatibility
90
+
91
+ def getName(self):
92
+ return self.name
93
+
94
+ def getType(self):
95
+ return self.asn1Object
96
+
97
+
98
+ class OptionalNamedType(NamedType):
99
+ __doc__ = NamedType.__doc__
100
+
101
+ isOptional = True
102
+
103
+
104
+ class DefaultedNamedType(NamedType):
105
+ __doc__ = NamedType.__doc__
106
+
107
+ isDefaulted = True
108
+
109
+
110
+ class NamedTypes(object):
111
+ """Create a collection of named fields for a constructed ASN.1 type.
112
+
113
+ The NamedTypes object represents a collection of named fields of a constructed ASN.1 type.
114
+
115
+ *NamedTypes* objects are immutable and duck-type Python :class:`dict` objects
116
+ holding *name* as keys and ASN.1 type object as values.
117
+
118
+ Parameters
119
+ ----------
120
+ *namedTypes: :class:`~pyasn1.type.namedtype.NamedType`
121
+
122
+ Examples
123
+ --------
124
+
125
+ .. code-block:: python
126
+
127
+ class Description(Sequence):
128
+ '''
129
+ ASN.1 specification:
130
+
131
+ Description ::= SEQUENCE {
132
+ surname IA5String,
133
+ first-name IA5String OPTIONAL,
134
+ age INTEGER DEFAULT 40
135
+ }
136
+ '''
137
+ componentType = NamedTypes(
138
+ NamedType('surname', IA5String()),
139
+ OptionalNamedType('first-name', IA5String()),
140
+ DefaultedNamedType('age', Integer(40))
141
+ )
142
+
143
+ descr = Description()
144
+ descr['surname'] = 'Smith'
145
+ descr['first-name'] = 'John'
146
+ """
147
+ def __init__(self, *namedTypes, **kwargs):
148
+ self.__namedTypes = namedTypes
149
+ self.__namedTypesLen = len(self.__namedTypes)
150
+ self.__minTagSet = self.__computeMinTagSet()
151
+ self.__nameToPosMap = self.__computeNameToPosMap()
152
+ self.__tagToPosMap = self.__computeTagToPosMap()
153
+ self.__ambiguousTypes = 'terminal' not in kwargs and self.__computeAmbiguousTypes() or {}
154
+ self.__uniqueTagMap = self.__computeTagMaps(unique=True)
155
+ self.__nonUniqueTagMap = self.__computeTagMaps(unique=False)
156
+ self.__hasOptionalOrDefault = any([True for namedType in self.__namedTypes
157
+ if namedType.isDefaulted or namedType.isOptional])
158
+ self.__hasOpenTypes = any([True for namedType in self.__namedTypes
159
+ if namedType.openType])
160
+
161
+ self.__requiredComponents = frozenset(
162
+ [idx for idx, nt in enumerate(self.__namedTypes) if not nt.isOptional and not nt.isDefaulted]
163
+ )
164
+ self.__keys = frozenset([namedType.name for namedType in self.__namedTypes])
165
+ self.__values = tuple([namedType.asn1Object for namedType in self.__namedTypes])
166
+ self.__items = tuple([(namedType.name, namedType.asn1Object) for namedType in self.__namedTypes])
167
+
168
+ def __repr__(self):
169
+ representation = ', '.join(['%r' % x for x in self.__namedTypes])
170
+ return '<%s object, types %s>' % (
171
+ self.__class__.__name__, representation)
172
+
173
+ def __eq__(self, other):
174
+ return self.__namedTypes == other
175
+
176
+ def __ne__(self, other):
177
+ return self.__namedTypes != other
178
+
179
+ def __lt__(self, other):
180
+ return self.__namedTypes < other
181
+
182
+ def __le__(self, other):
183
+ return self.__namedTypes <= other
184
+
185
+ def __gt__(self, other):
186
+ return self.__namedTypes > other
187
+
188
+ def __ge__(self, other):
189
+ return self.__namedTypes >= other
190
+
191
+ def __hash__(self):
192
+ return hash(self.__namedTypes)
193
+
194
+ def __getitem__(self, idx):
195
+ try:
196
+ return self.__namedTypes[idx]
197
+
198
+ except TypeError:
199
+ return self.__namedTypes[self.__nameToPosMap[idx]]
200
+
201
+ def __contains__(self, key):
202
+ return key in self.__nameToPosMap
203
+
204
+ def __iter__(self):
205
+ return (x[0] for x in self.__namedTypes)
206
+
207
+ def __bool__(self):
208
+ return self.__namedTypesLen > 0
209
+
210
+ def __len__(self):
211
+ return self.__namedTypesLen
212
+
213
+ # Python dict protocol
214
+
215
+ def values(self):
216
+ return self.__values
217
+
218
+ def keys(self):
219
+ return self.__keys
220
+
221
+ def items(self):
222
+ return self.__items
223
+
224
+ def clone(self):
225
+ return self.__class__(*self.__namedTypes)
226
+
227
+ class PostponedError(object):
228
+ def __init__(self, errorMsg):
229
+ self.__errorMsg = errorMsg
230
+
231
+ def __getitem__(self, item):
232
+ raise error.PyAsn1Error(self.__errorMsg)
233
+
234
+ def __computeTagToPosMap(self):
235
+ tagToPosMap = {}
236
+ for idx, namedType in enumerate(self.__namedTypes):
237
+ tagMap = namedType.asn1Object.tagMap
238
+ if isinstance(tagMap, NamedTypes.PostponedError):
239
+ return tagMap
240
+ if not tagMap:
241
+ continue
242
+ for _tagSet in tagMap.presentTypes:
243
+ if _tagSet in tagToPosMap:
244
+ return NamedTypes.PostponedError('Duplicate component tag %s at %s' % (_tagSet, namedType))
245
+ tagToPosMap[_tagSet] = idx
246
+
247
+ return tagToPosMap
248
+
249
+ def __computeNameToPosMap(self):
250
+ nameToPosMap = {}
251
+ for idx, namedType in enumerate(self.__namedTypes):
252
+ if namedType.name in nameToPosMap:
253
+ return NamedTypes.PostponedError('Duplicate component name %s at %s' % (namedType.name, namedType))
254
+ nameToPosMap[namedType.name] = idx
255
+
256
+ return nameToPosMap
257
+
258
+ def __computeAmbiguousTypes(self):
259
+ ambiguousTypes = {}
260
+ partialAmbiguousTypes = ()
261
+ for idx, namedType in reversed(tuple(enumerate(self.__namedTypes))):
262
+ if namedType.isOptional or namedType.isDefaulted:
263
+ partialAmbiguousTypes = (namedType,) + partialAmbiguousTypes
264
+ else:
265
+ partialAmbiguousTypes = (namedType,)
266
+ if len(partialAmbiguousTypes) == len(self.__namedTypes):
267
+ ambiguousTypes[idx] = self
268
+ else:
269
+ ambiguousTypes[idx] = NamedTypes(*partialAmbiguousTypes, **dict(terminal=True))
270
+ return ambiguousTypes
271
+
272
+ def getTypeByPosition(self, idx):
273
+ """Return ASN.1 type object by its position in fields set.
274
+
275
+ Parameters
276
+ ----------
277
+ idx: :py:class:`int`
278
+ Field index
279
+
280
+ Returns
281
+ -------
282
+ :
283
+ ASN.1 type
284
+
285
+ Raises
286
+ ------
287
+ ~pyasn1.error.PyAsn1Error
288
+ If given position is out of fields range
289
+ """
290
+ try:
291
+ return self.__namedTypes[idx].asn1Object
292
+
293
+ except IndexError:
294
+ raise error.PyAsn1Error('Type position out of range')
295
+
296
+ def getPositionByType(self, tagSet):
297
+ """Return field position by its ASN.1 type.
298
+
299
+ Parameters
300
+ ----------
301
+ tagSet: :class:`~pysnmp.type.tag.TagSet`
302
+ ASN.1 tag set distinguishing one ASN.1 type from others.
303
+
304
+ Returns
305
+ -------
306
+ : :py:class:`int`
307
+ ASN.1 type position in fields set
308
+
309
+ Raises
310
+ ------
311
+ ~pyasn1.error.PyAsn1Error
312
+ If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes*
313
+ """
314
+ try:
315
+ return self.__tagToPosMap[tagSet]
316
+
317
+ except KeyError:
318
+ raise error.PyAsn1Error('Type %s not found' % (tagSet,))
319
+
320
+ def getNameByPosition(self, idx):
321
+ """Return field name by its position in fields set.
322
+
323
+ Parameters
324
+ ----------
325
+ idx: :py:class:`idx`
326
+ Field index
327
+
328
+ Returns
329
+ -------
330
+ : :py:class:`str`
331
+ Field name
332
+
333
+ Raises
334
+ ------
335
+ ~pyasn1.error.PyAsn1Error
336
+ If given field name is not present in callee *NamedTypes*
337
+ """
338
+ try:
339
+ return self.__namedTypes[idx].name
340
+
341
+ except IndexError:
342
+ raise error.PyAsn1Error('Type position out of range')
343
+
344
+ def getPositionByName(self, name):
345
+ """Return field position by filed name.
346
+
347
+ Parameters
348
+ ----------
349
+ name: :py:class:`str`
350
+ Field name
351
+
352
+ Returns
353
+ -------
354
+ : :py:class:`int`
355
+ Field position in fields set
356
+
357
+ Raises
358
+ ------
359
+ ~pyasn1.error.PyAsn1Error
360
+ If *name* is not present or not unique within callee *NamedTypes*
361
+ """
362
+ try:
363
+ return self.__nameToPosMap[name]
364
+
365
+ except KeyError:
366
+ raise error.PyAsn1Error('Name %s not found' % (name,))
367
+
368
+ def getTagMapNearPosition(self, idx):
369
+ """Return ASN.1 types that are allowed at or past given field position.
370
+
371
+ Some ASN.1 serialisation allow for skipping optional and defaulted fields.
372
+ Some constructed ASN.1 types allow reordering of the fields. When recovering
373
+ such objects it may be important to know which types can possibly be
374
+ present at any given position in the field sets.
375
+
376
+ Parameters
377
+ ----------
378
+ idx: :py:class:`int`
379
+ Field index
380
+
381
+ Returns
382
+ -------
383
+ : :class:`~pyasn1.type.tagmap.TagMap`
384
+ Map if ASN.1 types allowed at given field position
385
+
386
+ Raises
387
+ ------
388
+ ~pyasn1.error.PyAsn1Error
389
+ If given position is out of fields range
390
+ """
391
+ try:
392
+ return self.__ambiguousTypes[idx].tagMap
393
+
394
+ except KeyError:
395
+ raise error.PyAsn1Error('Type position out of range')
396
+
397
+ def getPositionNearType(self, tagSet, idx):
398
+ """Return the closest field position where given ASN.1 type is allowed.
399
+
400
+ Some ASN.1 serialisation allow for skipping optional and defaulted fields.
401
+ Some constructed ASN.1 types allow reordering of the fields. When recovering
402
+ such objects it may be important to know at which field position, in field set,
403
+ given *tagSet* is allowed at or past *idx* position.
404
+
405
+ Parameters
406
+ ----------
407
+ tagSet: :class:`~pyasn1.type.tag.TagSet`
408
+ ASN.1 type which field position to look up
409
+
410
+ idx: :py:class:`int`
411
+ Field position at or past which to perform ASN.1 type look up
412
+
413
+ Returns
414
+ -------
415
+ : :py:class:`int`
416
+ Field position in fields set
417
+
418
+ Raises
419
+ ------
420
+ ~pyasn1.error.PyAsn1Error
421
+ If *tagSet* is not present or not unique within callee *NamedTypes*
422
+ or *idx* is out of fields range
423
+ """
424
+ try:
425
+ return idx + self.__ambiguousTypes[idx].getPositionByType(tagSet)
426
+
427
+ except KeyError:
428
+ raise error.PyAsn1Error('Type position out of range')
429
+
430
+ def __computeMinTagSet(self):
431
+ minTagSet = None
432
+ for namedType in self.__namedTypes:
433
+ asn1Object = namedType.asn1Object
434
+
435
+ try:
436
+ tagSet = asn1Object.minTagSet
437
+
438
+ except AttributeError:
439
+ tagSet = asn1Object.tagSet
440
+
441
+ if minTagSet is None or tagSet < minTagSet:
442
+ minTagSet = tagSet
443
+
444
+ return minTagSet or tag.TagSet()
445
+
446
+ @property
447
+ def minTagSet(self):
448
+ """Return the minimal TagSet among ASN.1 type in callee *NamedTypes*.
449
+
450
+ Some ASN.1 types/serialisation protocols require ASN.1 types to be
451
+ arranged based on their numerical tag value. The *minTagSet* property
452
+ returns that.
453
+
454
+ Returns
455
+ -------
456
+ : :class:`~pyasn1.type.tagset.TagSet`
457
+ Minimal TagSet among ASN.1 types in callee *NamedTypes*
458
+ """
459
+ return self.__minTagSet
460
+
461
+ def __computeTagMaps(self, unique):
462
+ presentTypes = {}
463
+ skipTypes = {}
464
+ defaultType = None
465
+ for namedType in self.__namedTypes:
466
+ tagMap = namedType.asn1Object.tagMap
467
+ if isinstance(tagMap, NamedTypes.PostponedError):
468
+ return tagMap
469
+ for tagSet in tagMap:
470
+ if unique and tagSet in presentTypes:
471
+ return NamedTypes.PostponedError('Non-unique tagSet %s of %s at %s' % (tagSet, namedType, self))
472
+ presentTypes[tagSet] = namedType.asn1Object
473
+ skipTypes.update(tagMap.skipTypes)
474
+
475
+ if defaultType is None:
476
+ defaultType = tagMap.defaultType
477
+ elif tagMap.defaultType is not None:
478
+ return NamedTypes.PostponedError('Duplicate default ASN.1 type at %s' % (self,))
479
+
480
+ return tagmap.TagMap(presentTypes, skipTypes, defaultType)
481
+
482
+ @property
483
+ def tagMap(self):
484
+ """Return a *TagMap* object from tags and types recursively.
485
+
486
+ Return a :class:`~pyasn1.type.tagmap.TagMap` object by
487
+ combining tags from *TagMap* objects of children types and
488
+ associating them with their immediate child type.
489
+
490
+ Example
491
+ -------
492
+ .. code-block:: python
493
+
494
+ OuterType ::= CHOICE {
495
+ innerType INTEGER
496
+ }
497
+
498
+ Calling *.tagMap* on *OuterType* will yield a map like this:
499
+
500
+ .. code-block:: python
501
+
502
+ Integer.tagSet -> Choice
503
+ """
504
+ return self.__nonUniqueTagMap
505
+
506
+ @property
507
+ def tagMapUnique(self):
508
+ """Return a *TagMap* object from unique tags and types recursively.
509
+
510
+ Return a :class:`~pyasn1.type.tagmap.TagMap` object by
511
+ combining tags from *TagMap* objects of children types and
512
+ associating them with their immediate child type.
513
+
514
+ Example
515
+ -------
516
+ .. code-block:: python
517
+
518
+ OuterType ::= CHOICE {
519
+ innerType INTEGER
520
+ }
521
+
522
+ Calling *.tagMapUnique* on *OuterType* will yield a map like this:
523
+
524
+ .. code-block:: python
525
+
526
+ Integer.tagSet -> Choice
527
+
528
+ Note
529
+ ----
530
+
531
+ Duplicate *TagSet* objects found in the tree of children
532
+ types would cause error.
533
+ """
534
+ return self.__uniqueTagMap
535
+
536
+ @property
537
+ def hasOptionalOrDefault(self):
538
+ return self.__hasOptionalOrDefault
539
+
540
+ @property
541
+ def hasOpenTypes(self):
542
+ return self.__hasOpenTypes
543
+
544
+ @property
545
+ def namedTypes(self):
546
+ return tuple(self.__namedTypes)
547
+
548
+ @property
549
+ def requiredComponents(self):
550
+ return self.__requiredComponents
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/namedval.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ # ASN.1 named integers
8
+ #
9
+ from pyasn1 import error
10
+
11
+ __all__ = ['NamedValues']
12
+
13
+
14
+ class NamedValues(object):
15
+ """Create named values object.
16
+
17
+ The |NamedValues| object represents a collection of string names
18
+ associated with numeric IDs. These objects are used for giving
19
+ names to otherwise numerical values.
20
+
21
+ |NamedValues| objects are immutable and duck-type Python
22
+ :class:`dict` object mapping ID to name and vice-versa.
23
+
24
+ Parameters
25
+ ----------
26
+ *args: variable number of two-element :py:class:`tuple`
27
+
28
+ name: :py:class:`str`
29
+ Value label
30
+
31
+ value: :py:class:`int`
32
+ Numeric value
33
+
34
+ Keyword Args
35
+ ------------
36
+ name: :py:class:`str`
37
+ Value label
38
+
39
+ value: :py:class:`int`
40
+ Numeric value
41
+
42
+ Examples
43
+ --------
44
+
45
+ .. code-block:: pycon
46
+
47
+ >>> nv = NamedValues('a', 'b', ('c', 0), d=1)
48
+ >>> nv
49
+ >>> {'c': 0, 'd': 1, 'a': 2, 'b': 3}
50
+ >>> nv[0]
51
+ 'c'
52
+ >>> nv['a']
53
+ 2
54
+ """
55
+ def __init__(self, *args, **kwargs):
56
+ self.__names = {}
57
+ self.__numbers = {}
58
+
59
+ anonymousNames = []
60
+
61
+ for namedValue in args:
62
+ if isinstance(namedValue, (tuple, list)):
63
+ try:
64
+ name, number = namedValue
65
+
66
+ except ValueError:
67
+ raise error.PyAsn1Error('Not a proper attribute-value pair %r' % (namedValue,))
68
+
69
+ else:
70
+ anonymousNames.append(namedValue)
71
+ continue
72
+
73
+ if name in self.__names:
74
+ raise error.PyAsn1Error('Duplicate name %s' % (name,))
75
+
76
+ if number in self.__numbers:
77
+ raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number))
78
+
79
+ self.__names[name] = number
80
+ self.__numbers[number] = name
81
+
82
+ for name, number in kwargs.items():
83
+ if name in self.__names:
84
+ raise error.PyAsn1Error('Duplicate name %s' % (name,))
85
+
86
+ if number in self.__numbers:
87
+ raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number))
88
+
89
+ self.__names[name] = number
90
+ self.__numbers[number] = name
91
+
92
+ if anonymousNames:
93
+
94
+ number = self.__numbers and max(self.__numbers) + 1 or 0
95
+
96
+ for name in anonymousNames:
97
+
98
+ if name in self.__names:
99
+ raise error.PyAsn1Error('Duplicate name %s' % (name,))
100
+
101
+ self.__names[name] = number
102
+ self.__numbers[number] = name
103
+
104
+ number += 1
105
+
106
+ def __repr__(self):
107
+ representation = ', '.join(['%s=%d' % x for x in self.items()])
108
+
109
+ if len(representation) > 64:
110
+ representation = representation[:32] + '...' + representation[-32:]
111
+
112
+ return '<%s object, enums %s>' % (
113
+ self.__class__.__name__, representation)
114
+
115
+ def __eq__(self, other):
116
+ return dict(self) == other
117
+
118
+ def __ne__(self, other):
119
+ return dict(self) != other
120
+
121
+ def __lt__(self, other):
122
+ return dict(self) < other
123
+
124
+ def __le__(self, other):
125
+ return dict(self) <= other
126
+
127
+ def __gt__(self, other):
128
+ return dict(self) > other
129
+
130
+ def __ge__(self, other):
131
+ return dict(self) >= other
132
+
133
+ def __hash__(self):
134
+ return hash(self.items())
135
+
136
+ # Python dict protocol (read-only)
137
+
138
+ def __getitem__(self, key):
139
+ try:
140
+ return self.__numbers[key]
141
+
142
+ except KeyError:
143
+ return self.__names[key]
144
+
145
+ def __len__(self):
146
+ return len(self.__names)
147
+
148
+ def __contains__(self, key):
149
+ return key in self.__names or key in self.__numbers
150
+
151
+ def __iter__(self):
152
+ return iter(self.__names)
153
+
154
+ def values(self):
155
+ return iter(self.__numbers)
156
+
157
+ def keys(self):
158
+ return iter(self.__names)
159
+
160
+ def items(self):
161
+ for name in self.__names:
162
+ yield name, self.__names[name]
163
+
164
+ # support merging
165
+
166
+ def __add__(self, namedValues):
167
+ return self.__class__(*tuple(self.items()) + tuple(namedValues.items()))
168
+
169
+ # XXX clone/subtype?
170
+
171
+ def clone(self, *args, **kwargs):
172
+ new = self.__class__(*args, **kwargs)
173
+ return self + new
174
+
175
+ # legacy protocol
176
+
177
+ def getName(self, value):
178
+ if value in self.__numbers:
179
+ return self.__numbers[value]
180
+
181
+ def getValue(self, name):
182
+ if name in self.__names:
183
+ return self.__names[name]
184
+
185
+ def getValues(self, *names):
186
+ try:
187
+ return [self.__names[name] for name in names]
188
+
189
+ except KeyError:
190
+ raise error.PyAsn1Error(
191
+ 'Unknown bit identifier(s): %s' % (set(names).difference(self.__names),)
192
+ )
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/opentype.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+
8
+ __all__ = ['OpenType']
9
+
10
+
11
+ class OpenType(object):
12
+ """Create ASN.1 type map indexed by a value
13
+
14
+ The *OpenType* object models an untyped field of a constructed ASN.1
15
+ type. In ASN.1 syntax it is usually represented by the
16
+ `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`,
17
+ `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically
18
+ used together with :class:`~pyasn1.type.univ.Any` object.
19
+
20
+ OpenType objects duck-type a read-only Python :class:`dict` objects,
21
+ however the passed `typeMap` is not copied, but stored by reference.
22
+ That means the user can manipulate `typeMap` at run time having this
23
+ reflected on *OpenType* object behavior.
24
+
25
+ The |OpenType| class models an untyped field of a constructed ASN.1
26
+ type. In ASN.1 syntax it is usually represented by the
27
+ `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`,
28
+ `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically
29
+ used with :class:`~pyasn1.type.univ.Any` type.
30
+
31
+ Parameters
32
+ ----------
33
+ name: :py:class:`str`
34
+ Field name
35
+
36
+ typeMap: :py:class:`dict`
37
+ A map of value->ASN.1 type. It's stored by reference and can be
38
+ mutated later to register new mappings.
39
+
40
+ Examples
41
+ --------
42
+
43
+ For untyped scalars:
44
+
45
+ .. code-block:: python
46
+
47
+ openType = OpenType(
48
+ 'id', {1: Integer(),
49
+ 2: OctetString()}
50
+ )
51
+ Sequence(
52
+ componentType=NamedTypes(
53
+ NamedType('id', Integer()),
54
+ NamedType('blob', Any(), openType=openType)
55
+ )
56
+ )
57
+
58
+ For untyped `SET OF` or `SEQUENCE OF` vectors:
59
+
60
+ .. code-block:: python
61
+
62
+ openType = OpenType(
63
+ 'id', {1: Integer(),
64
+ 2: OctetString()}
65
+ )
66
+ Sequence(
67
+ componentType=NamedTypes(
68
+ NamedType('id', Integer()),
69
+ NamedType('blob', SetOf(componentType=Any()),
70
+ openType=openType)
71
+ )
72
+ )
73
+ """
74
+
75
+ def __init__(self, name, typeMap=None):
76
+ self.__name = name
77
+ if typeMap is None:
78
+ self.__typeMap = {}
79
+ else:
80
+ self.__typeMap = typeMap
81
+
82
+ @property
83
+ def name(self):
84
+ return self.__name
85
+
86
+ # Python dict protocol
87
+
88
+ def values(self):
89
+ return self.__typeMap.values()
90
+
91
+ def keys(self):
92
+ return self.__typeMap.keys()
93
+
94
+ def items(self):
95
+ return self.__typeMap.items()
96
+
97
+ def __contains__(self, key):
98
+ return key in self.__typeMap
99
+
100
+ def __getitem__(self, key):
101
+ return self.__typeMap[key]
102
+
103
+ def __iter__(self):
104
+ return iter(self.__typeMap)
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/tag.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ from pyasn1 import error
8
+
9
+ __all__ = ['tagClassUniversal', 'tagClassApplication', 'tagClassContext',
10
+ 'tagClassPrivate', 'tagFormatSimple', 'tagFormatConstructed',
11
+ 'tagCategoryImplicit', 'tagCategoryExplicit',
12
+ 'tagCategoryUntagged', 'Tag', 'TagSet']
13
+
14
+ #: Identifier for ASN.1 class UNIVERSAL
15
+ tagClassUniversal = 0x00
16
+
17
+ #: Identifier for ASN.1 class APPLICATION
18
+ tagClassApplication = 0x40
19
+
20
+ #: Identifier for ASN.1 class context-specific
21
+ tagClassContext = 0x80
22
+
23
+ #: Identifier for ASN.1 class private
24
+ tagClassPrivate = 0xC0
25
+
26
+ #: Identifier for "simple" ASN.1 structure (e.g. scalar)
27
+ tagFormatSimple = 0x00
28
+
29
+ #: Identifier for "constructed" ASN.1 structure (e.g. may have inner components)
30
+ tagFormatConstructed = 0x20
31
+
32
+ tagCategoryImplicit = 0x01
33
+ tagCategoryExplicit = 0x02
34
+ tagCategoryUntagged = 0x04
35
+
36
+
37
+ class Tag(object):
38
+ """Create ASN.1 tag
39
+
40
+ Represents ASN.1 tag that can be attached to a ASN.1 type to make
41
+ types distinguishable from each other.
42
+
43
+ *Tag* objects are immutable and duck-type Python :class:`tuple` objects
44
+ holding three integer components of a tag.
45
+
46
+ Parameters
47
+ ----------
48
+ tagClass: :py:class:`int`
49
+ Tag *class* value
50
+
51
+ tagFormat: :py:class:`int`
52
+ Tag *format* value
53
+
54
+ tagId: :py:class:`int`
55
+ Tag ID value
56
+ """
57
+ def __init__(self, tagClass, tagFormat, tagId):
58
+ if tagId < 0:
59
+ raise error.PyAsn1Error('Negative tag ID (%s) not allowed' % tagId)
60
+ self.__tagClass = tagClass
61
+ self.__tagFormat = tagFormat
62
+ self.__tagId = tagId
63
+ self.__tagClassId = tagClass, tagId
64
+ self.__hash = hash(self.__tagClassId)
65
+
66
+ def __repr__(self):
67
+ representation = '[%s:%s:%s]' % (
68
+ self.__tagClass, self.__tagFormat, self.__tagId)
69
+ return '<%s object, tag %s>' % (
70
+ self.__class__.__name__, representation)
71
+
72
+ def __eq__(self, other):
73
+ return self.__tagClassId == other
74
+
75
+ def __ne__(self, other):
76
+ return self.__tagClassId != other
77
+
78
+ def __lt__(self, other):
79
+ return self.__tagClassId < other
80
+
81
+ def __le__(self, other):
82
+ return self.__tagClassId <= other
83
+
84
+ def __gt__(self, other):
85
+ return self.__tagClassId > other
86
+
87
+ def __ge__(self, other):
88
+ return self.__tagClassId >= other
89
+
90
+ def __hash__(self):
91
+ return self.__hash
92
+
93
+ def __getitem__(self, idx):
94
+ if idx == 0:
95
+ return self.__tagClass
96
+ elif idx == 1:
97
+ return self.__tagFormat
98
+ elif idx == 2:
99
+ return self.__tagId
100
+ else:
101
+ raise IndexError
102
+
103
+ def __iter__(self):
104
+ yield self.__tagClass
105
+ yield self.__tagFormat
106
+ yield self.__tagId
107
+
108
+ def __and__(self, otherTag):
109
+ return self.__class__(self.__tagClass & otherTag.tagClass,
110
+ self.__tagFormat & otherTag.tagFormat,
111
+ self.__tagId & otherTag.tagId)
112
+
113
+ def __or__(self, otherTag):
114
+ return self.__class__(self.__tagClass | otherTag.tagClass,
115
+ self.__tagFormat | otherTag.tagFormat,
116
+ self.__tagId | otherTag.tagId)
117
+
118
+ @property
119
+ def tagClass(self):
120
+ """ASN.1 tag class
121
+
122
+ Returns
123
+ -------
124
+ : :py:class:`int`
125
+ Tag class
126
+ """
127
+ return self.__tagClass
128
+
129
+ @property
130
+ def tagFormat(self):
131
+ """ASN.1 tag format
132
+
133
+ Returns
134
+ -------
135
+ : :py:class:`int`
136
+ Tag format
137
+ """
138
+ return self.__tagFormat
139
+
140
+ @property
141
+ def tagId(self):
142
+ """ASN.1 tag ID
143
+
144
+ Returns
145
+ -------
146
+ : :py:class:`int`
147
+ Tag ID
148
+ """
149
+ return self.__tagId
150
+
151
+
152
+ class TagSet(object):
153
+ """Create a collection of ASN.1 tags
154
+
155
+ Represents a combination of :class:`~pyasn1.type.tag.Tag` objects
156
+ that can be attached to a ASN.1 type to make types distinguishable
157
+ from each other.
158
+
159
+ *TagSet* objects are immutable and duck-type Python :class:`tuple` objects
160
+ holding arbitrary number of :class:`~pyasn1.type.tag.Tag` objects.
161
+
162
+ Parameters
163
+ ----------
164
+ baseTag: :class:`~pyasn1.type.tag.Tag`
165
+ Base *Tag* object. This tag survives IMPLICIT tagging.
166
+
167
+ *superTags: :class:`~pyasn1.type.tag.Tag`
168
+ Additional *Tag* objects taking part in subtyping.
169
+
170
+ Examples
171
+ --------
172
+ .. code-block:: python
173
+
174
+ class OrderNumber(NumericString):
175
+ '''
176
+ ASN.1 specification
177
+
178
+ Order-number ::=
179
+ [APPLICATION 5] IMPLICIT NumericString
180
+ '''
181
+ tagSet = NumericString.tagSet.tagImplicitly(
182
+ Tag(tagClassApplication, tagFormatSimple, 5)
183
+ )
184
+
185
+ orderNumber = OrderNumber('1234')
186
+ """
187
+ def __init__(self, baseTag=(), *superTags):
188
+ self.__baseTag = baseTag
189
+ self.__superTags = superTags
190
+ self.__superTagsClassId = tuple(
191
+ [(superTag.tagClass, superTag.tagId) for superTag in superTags]
192
+ )
193
+ self.__lenOfSuperTags = len(superTags)
194
+ self.__hash = hash(self.__superTagsClassId)
195
+
196
+ def __repr__(self):
197
+ representation = '-'.join(['%s:%s:%s' % (x.tagClass, x.tagFormat, x.tagId)
198
+ for x in self.__superTags])
199
+ if representation:
200
+ representation = 'tags ' + representation
201
+ else:
202
+ representation = 'untagged'
203
+
204
+ return '<%s object, %s>' % (self.__class__.__name__, representation)
205
+
206
+ def __add__(self, superTag):
207
+ return self.__class__(self.__baseTag, *self.__superTags + (superTag,))
208
+
209
+ def __radd__(self, superTag):
210
+ return self.__class__(self.__baseTag, *(superTag,) + self.__superTags)
211
+
212
+ def __getitem__(self, i):
213
+ if i.__class__ is slice:
214
+ return self.__class__(self.__baseTag, *self.__superTags[i])
215
+ else:
216
+ return self.__superTags[i]
217
+
218
+ def __eq__(self, other):
219
+ return self.__superTagsClassId == other
220
+
221
+ def __ne__(self, other):
222
+ return self.__superTagsClassId != other
223
+
224
+ def __lt__(self, other):
225
+ return self.__superTagsClassId < other
226
+
227
+ def __le__(self, other):
228
+ return self.__superTagsClassId <= other
229
+
230
+ def __gt__(self, other):
231
+ return self.__superTagsClassId > other
232
+
233
+ def __ge__(self, other):
234
+ return self.__superTagsClassId >= other
235
+
236
+ def __hash__(self):
237
+ return self.__hash
238
+
239
+ def __len__(self):
240
+ return self.__lenOfSuperTags
241
+
242
+ @property
243
+ def baseTag(self):
244
+ """Return base ASN.1 tag
245
+
246
+ Returns
247
+ -------
248
+ : :class:`~pyasn1.type.tag.Tag`
249
+ Base tag of this *TagSet*
250
+ """
251
+ return self.__baseTag
252
+
253
+ @property
254
+ def superTags(self):
255
+ """Return ASN.1 tags
256
+
257
+ Returns
258
+ -------
259
+ : :py:class:`tuple`
260
+ Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains
261
+ """
262
+ return self.__superTags
263
+
264
+ def tagExplicitly(self, superTag):
265
+ """Return explicitly tagged *TagSet*
266
+
267
+ Create a new *TagSet* representing callee *TagSet* explicitly tagged
268
+ with passed tag(s). With explicit tagging mode, new tags are appended
269
+ to existing tag(s).
270
+
271
+ Parameters
272
+ ----------
273
+ superTag: :class:`~pyasn1.type.tag.Tag`
274
+ *Tag* object to tag this *TagSet*
275
+
276
+ Returns
277
+ -------
278
+ : :class:`~pyasn1.type.tag.TagSet`
279
+ New *TagSet* object
280
+ """
281
+ if superTag.tagClass == tagClassUniversal:
282
+ raise error.PyAsn1Error("Can't tag with UNIVERSAL class tag")
283
+ if superTag.tagFormat != tagFormatConstructed:
284
+ superTag = Tag(superTag.tagClass, tagFormatConstructed, superTag.tagId)
285
+ return self + superTag
286
+
287
+ def tagImplicitly(self, superTag):
288
+ """Return implicitly tagged *TagSet*
289
+
290
+ Create a new *TagSet* representing callee *TagSet* implicitly tagged
291
+ with passed tag(s). With implicit tagging mode, new tag(s) replace the
292
+ last existing tag.
293
+
294
+ Parameters
295
+ ----------
296
+ superTag: :class:`~pyasn1.type.tag.Tag`
297
+ *Tag* object to tag this *TagSet*
298
+
299
+ Returns
300
+ -------
301
+ : :class:`~pyasn1.type.tag.TagSet`
302
+ New *TagSet* object
303
+ """
304
+ if self.__superTags:
305
+ superTag = Tag(superTag.tagClass, self.__superTags[-1].tagFormat, superTag.tagId)
306
+ return self[:-1] + superTag
307
+
308
+ def isSuperTagSetOf(self, tagSet):
309
+ """Test type relationship against given *TagSet*
310
+
311
+ The callee is considered to be a supertype of given *TagSet*
312
+ tag-wise if all tags in *TagSet* are present in the callee and
313
+ they are in the same order.
314
+
315
+ Parameters
316
+ ----------
317
+ tagSet: :class:`~pyasn1.type.tag.TagSet`
318
+ *TagSet* object to evaluate against the callee
319
+
320
+ Returns
321
+ -------
322
+ : :py:class:`bool`
323
+ :obj:`True` if callee is a supertype of *tagSet*
324
+ """
325
+ if len(tagSet) < self.__lenOfSuperTags:
326
+ return False
327
+ return self.__superTags == tagSet[:self.__lenOfSuperTags]
328
+
329
+ # Backward compatibility
330
+
331
+ def getBaseTag(self):
332
+ return self.__baseTag
333
+
334
+ def initTagSet(tag):
335
+ return TagSet(tag, tag)
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/tagmap.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ from pyasn1 import error
8
+
9
+ __all__ = ['TagMap']
10
+
11
+
12
+ class TagMap(object):
13
+ """Map *TagSet* objects to ASN.1 types
14
+
15
+ Create an object mapping *TagSet* object to ASN.1 type.
16
+
17
+ *TagMap* objects are immutable and duck-type read-only Python
18
+ :class:`dict` objects holding *TagSet* objects as keys and ASN.1
19
+ type objects as values.
20
+
21
+ Parameters
22
+ ----------
23
+ presentTypes: :py:class:`dict`
24
+ Map of :class:`~pyasn1.type.tag.TagSet` to ASN.1 objects considered
25
+ as being unconditionally present in the *TagMap*.
26
+
27
+ skipTypes: :py:class:`dict`
28
+ A collection of :class:`~pyasn1.type.tag.TagSet` objects considered
29
+ as absent in the *TagMap* even when *defaultType* is present.
30
+
31
+ defaultType: ASN.1 type object
32
+ An ASN.1 type object callee *TagMap* returns for any *TagSet* key not present
33
+ in *presentTypes* (unless given key is present in *skipTypes*).
34
+ """
35
+ def __init__(self, presentTypes=None, skipTypes=None, defaultType=None):
36
+ self.__presentTypes = presentTypes or {}
37
+ self.__skipTypes = skipTypes or {}
38
+ self.__defaultType = defaultType
39
+
40
+ def __contains__(self, tagSet):
41
+ return (tagSet in self.__presentTypes or
42
+ self.__defaultType is not None and tagSet not in self.__skipTypes)
43
+
44
+ def __getitem__(self, tagSet):
45
+ try:
46
+ return self.__presentTypes[tagSet]
47
+ except KeyError:
48
+ if self.__defaultType is None:
49
+ raise
50
+ elif tagSet in self.__skipTypes:
51
+ raise error.PyAsn1Error('Key in negative map')
52
+ else:
53
+ return self.__defaultType
54
+
55
+ def __iter__(self):
56
+ return iter(self.__presentTypes)
57
+
58
+ def __repr__(self):
59
+ representation = '%s object' % self.__class__.__name__
60
+
61
+ if self.__presentTypes:
62
+ representation += ', present %s' % repr(self.__presentTypes)
63
+
64
+ if self.__skipTypes:
65
+ representation += ', skip %s' % repr(self.__skipTypes)
66
+
67
+ if self.__defaultType is not None:
68
+ representation += ', default %s' % repr(self.__defaultType)
69
+
70
+ return '<%s>' % representation
71
+
72
+ @property
73
+ def presentTypes(self):
74
+ """Return *TagSet* to ASN.1 type map present in callee *TagMap*"""
75
+ return self.__presentTypes
76
+
77
+ @property
78
+ def skipTypes(self):
79
+ """Return *TagSet* collection unconditionally absent in callee *TagMap*"""
80
+ return self.__skipTypes
81
+
82
+ @property
83
+ def defaultType(self):
84
+ """Return default ASN.1 type being returned for any missing *TagSet*"""
85
+ return self.__defaultType
86
+
87
+ # Backward compatibility
88
+
89
+ def getPosMap(self):
90
+ return self.presentTypes
91
+
92
+ def getNegMap(self):
93
+ return self.skipTypes
94
+
95
+ def getDef(self):
96
+ return self.defaultType
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/univ.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_tf446/lib/python3.10/site-packages/pyasn1/type/useful.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file is part of pyasn1 software.
3
+ #
4
+ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
5
+ # License: https://pyasn1.readthedocs.io/en/latest/license.html
6
+ #
7
+ import datetime
8
+
9
+ from pyasn1 import error
10
+ from pyasn1.type import char
11
+ from pyasn1.type import tag
12
+ from pyasn1.type import univ
13
+
14
+ __all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime']
15
+
16
+ NoValue = univ.NoValue
17
+ noValue = univ.noValue
18
+
19
+
20
+ class ObjectDescriptor(char.GraphicString):
21
+ __doc__ = char.GraphicString.__doc__
22
+
23
+ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
24
+ tagSet = char.GraphicString.tagSet.tagImplicitly(
25
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7)
26
+ )
27
+
28
+ # Optimization for faster codec lookup
29
+ typeId = char.GraphicString.getTypeId()
30
+
31
+
32
+ class TimeMixIn(object):
33
+
34
+ _yearsDigits = 4
35
+ _hasSubsecond = False
36
+ _optionalMinutes = False
37
+ _shortTZ = False
38
+
39
+ class FixedOffset(datetime.tzinfo):
40
+ """Fixed offset in minutes east from UTC."""
41
+
42
+ # defaulted arguments required
43
+ # https: // docs.python.org / 2.3 / lib / datetime - tzinfo.html
44
+ def __init__(self, offset=0, name='UTC'):
45
+ self.__offset = datetime.timedelta(minutes=offset)
46
+ self.__name = name
47
+
48
+ def utcoffset(self, dt):
49
+ return self.__offset
50
+
51
+ def tzname(self, dt):
52
+ return self.__name
53
+
54
+ def dst(self, dt):
55
+ return datetime.timedelta(0)
56
+
57
+ UTC = FixedOffset()
58
+
59
+ @property
60
+ def asDateTime(self):
61
+ """Create :py:class:`datetime.datetime` object from a |ASN.1| object.
62
+
63
+ Returns
64
+ -------
65
+ :
66
+ new instance of :py:class:`datetime.datetime` object
67
+ """
68
+ text = str(self)
69
+ if text.endswith('Z'):
70
+ tzinfo = TimeMixIn.UTC
71
+ text = text[:-1]
72
+
73
+ elif '-' in text or '+' in text:
74
+ if '+' in text:
75
+ text, plusminus, tz = text.partition('+')
76
+ else:
77
+ text, plusminus, tz = text.partition('-')
78
+
79
+ if self._shortTZ and len(tz) == 2:
80
+ tz += '00'
81
+
82
+ if len(tz) != 4:
83
+ raise error.PyAsn1Error('malformed time zone offset %s' % tz)
84
+
85
+ try:
86
+ minutes = int(tz[:2]) * 60 + int(tz[2:])
87
+ if plusminus == '-':
88
+ minutes *= -1
89
+
90
+ except ValueError:
91
+ raise error.PyAsn1Error('unknown time specification %s' % self)
92
+
93
+ tzinfo = TimeMixIn.FixedOffset(minutes, '?')
94
+
95
+ else:
96
+ tzinfo = None
97
+
98
+ if '.' in text or ',' in text:
99
+ if '.' in text:
100
+ text, _, ms = text.partition('.')
101
+ else:
102
+ text, _, ms = text.partition(',')
103
+
104
+ try:
105
+ ms = int(ms) * 1000
106
+
107
+ except ValueError:
108
+ raise error.PyAsn1Error('bad sub-second time specification %s' % self)
109
+
110
+ else:
111
+ ms = 0
112
+
113
+ if self._optionalMinutes and len(text) - self._yearsDigits == 6:
114
+ text += '0000'
115
+ elif len(text) - self._yearsDigits == 8:
116
+ text += '00'
117
+
118
+ try:
119
+ dt = datetime.datetime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')
120
+
121
+ except ValueError:
122
+ raise error.PyAsn1Error('malformed datetime format %s' % self)
123
+
124
+ return dt.replace(microsecond=ms, tzinfo=tzinfo)
125
+
126
+ @classmethod
127
+ def fromDateTime(cls, dt):
128
+ """Create |ASN.1| object from a :py:class:`datetime.datetime` object.
129
+
130
+ Parameters
131
+ ----------
132
+ dt: :py:class:`datetime.datetime` object
133
+ The `datetime.datetime` object to initialize the |ASN.1| object
134
+ from
135
+
136
+ Returns
137
+ -------
138
+ :
139
+ new instance of |ASN.1| value
140
+ """
141
+ text = dt.strftime(cls._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')
142
+ if cls._hasSubsecond:
143
+ text += '.%d' % (dt.microsecond // 1000)
144
+
145
+ if dt.utcoffset():
146
+ seconds = dt.utcoffset().seconds
147
+ if seconds < 0:
148
+ text += '-'
149
+ else:
150
+ text += '+'
151
+ text += '%.2d%.2d' % (seconds // 3600, seconds % 3600)
152
+ else:
153
+ text += 'Z'
154
+
155
+ return cls(text)
156
+
157
+
158
+ class GeneralizedTime(char.VisibleString, TimeMixIn):
159
+ __doc__ = char.VisibleString.__doc__
160
+
161
+ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
162
+ tagSet = char.VisibleString.tagSet.tagImplicitly(
163
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24)
164
+ )
165
+
166
+ # Optimization for faster codec lookup
167
+ typeId = char.VideotexString.getTypeId()
168
+
169
+ _yearsDigits = 4
170
+ _hasSubsecond = True
171
+ _optionalMinutes = True
172
+ _shortTZ = True
173
+
174
+
175
+ class UTCTime(char.VisibleString, TimeMixIn):
176
+ __doc__ = char.VisibleString.__doc__
177
+
178
+ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
179
+ tagSet = char.VisibleString.tagSet.tagImplicitly(
180
+ tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23)
181
+ )
182
+
183
+ # Optimization for faster codec lookup
184
+ typeId = char.VideotexString.getTypeId()
185
+
186
+ _yearsDigits = 2
187
+ _hasSubsecond = False
188
+ _optionalMinutes = False
189
+ _shortTZ = False
evalkit_tf446/lib/python3.10/site-packages/uvicorn/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from uvicorn.config import Config
2
+ from uvicorn.main import Server, main, run
3
+
4
+ __version__ = "0.32.0"
5
+ __all__ = ["main", "run", "Config", "Server"]
evalkit_tf446/lib/python3.10/site-packages/uvicorn/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import uvicorn
2
+
3
+ if __name__ == "__main__":
4
+ uvicorn.main()
evalkit_tf446/lib/python3.10/site-packages/uvicorn/_subprocess.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Some light wrappers around Python's multiprocessing, to deal with cleanly
3
+ starting child processes.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import multiprocessing
9
+ import os
10
+ import sys
11
+ from multiprocessing.context import SpawnProcess
12
+ from socket import socket
13
+ from typing import Callable
14
+
15
+ from uvicorn.config import Config
16
+
17
+ multiprocessing.allow_connection_pickling()
18
+ spawn = multiprocessing.get_context("spawn")
19
+
20
+
21
+ def get_subprocess(
22
+ config: Config,
23
+ target: Callable[..., None],
24
+ sockets: list[socket],
25
+ ) -> SpawnProcess:
26
+ """
27
+ Called in the parent process, to instantiate a new child process instance.
28
+ The child is not yet started at this point.
29
+
30
+ * config - The Uvicorn configuration instance.
31
+ * target - A callable that accepts a list of sockets. In practice this will
32
+ be the `Server.run()` method.
33
+ * sockets - A list of sockets to pass to the server. Sockets are bound once
34
+ by the parent process, and then passed to the child processes.
35
+ """
36
+ # We pass across the stdin fileno, and reopen it in the child process.
37
+ # This is required for some debugging environments.
38
+ try:
39
+ stdin_fileno = sys.stdin.fileno()
40
+ # The `sys.stdin` can be `None`, see https://docs.python.org/3/library/sys.html#sys.__stdin__.
41
+ except (AttributeError, OSError):
42
+ stdin_fileno = None
43
+
44
+ kwargs = {
45
+ "config": config,
46
+ "target": target,
47
+ "sockets": sockets,
48
+ "stdin_fileno": stdin_fileno,
49
+ }
50
+
51
+ return spawn.Process(target=subprocess_started, kwargs=kwargs)
52
+
53
+
54
+ def subprocess_started(
55
+ config: Config,
56
+ target: Callable[..., None],
57
+ sockets: list[socket],
58
+ stdin_fileno: int | None,
59
+ ) -> None:
60
+ """
61
+ Called when the child process starts.
62
+
63
+ * config - The Uvicorn configuration instance.
64
+ * target - A callable that accepts a list of sockets. In practice this will
65
+ be the `Server.run()` method.
66
+ * sockets - A list of sockets to pass to the server. Sockets are bound once
67
+ by the parent process, and then passed to the child processes.
68
+ * stdin_fileno - The file number of sys.stdin, so that it can be reattached
69
+ to the child process.
70
+ """
71
+ # Re-open stdin.
72
+ if stdin_fileno is not None:
73
+ sys.stdin = os.fdopen(stdin_fileno) # pragma: full coverage
74
+
75
+ # Logging needs to be setup again for each child.
76
+ config.configure_logging()
77
+
78
+ try:
79
+ # Now we can call into `Server.run(sockets=sockets)`
80
+ target(sockets=sockets)
81
+ except KeyboardInterrupt: # pragma: no cover
82
+ # supress the exception to avoid a traceback from subprocess.Popen
83
+ # the parent already expects us to end, so no vital information is lost
84
+ pass
evalkit_tf446/lib/python3.10/site-packages/uvicorn/_types.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (c) Django Software Foundation and individual contributors.
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of Django nor the names of its contributors may be used
16
+ to endorse or promote products derived from this software without
17
+ specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
23
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import sys
34
+ import types
35
+ from typing import (
36
+ Any,
37
+ Awaitable,
38
+ Callable,
39
+ Iterable,
40
+ Literal,
41
+ MutableMapping,
42
+ Optional,
43
+ Protocol,
44
+ Tuple,
45
+ Type,
46
+ TypedDict,
47
+ Union,
48
+ )
49
+
50
+ if sys.version_info >= (3, 11): # pragma: py-lt-311
51
+ from typing import NotRequired
52
+ else: # pragma: py-gte-311
53
+ from typing_extensions import NotRequired
54
+
55
+ # WSGI
56
+ Environ = MutableMapping[str, Any]
57
+ ExcInfo = Tuple[Type[BaseException], BaseException, Optional[types.TracebackType]]
58
+ StartResponse = Callable[[str, Iterable[Tuple[str, str]], Optional[ExcInfo]], None]
59
+ WSGIApp = Callable[[Environ, StartResponse], Union[Iterable[bytes], BaseException]]
60
+
61
+
62
+ # ASGI
63
+ class ASGIVersions(TypedDict):
64
+ spec_version: str
65
+ version: Literal["2.0"] | Literal["3.0"]
66
+
67
+
68
+ class HTTPScope(TypedDict):
69
+ type: Literal["http"]
70
+ asgi: ASGIVersions
71
+ http_version: str
72
+ method: str
73
+ scheme: str
74
+ path: str
75
+ raw_path: bytes
76
+ query_string: bytes
77
+ root_path: str
78
+ headers: Iterable[tuple[bytes, bytes]]
79
+ client: tuple[str, int] | None
80
+ server: tuple[str, int | None] | None
81
+ state: NotRequired[dict[str, Any]]
82
+ extensions: NotRequired[dict[str, dict[object, object]]]
83
+
84
+
85
+ class WebSocketScope(TypedDict):
86
+ type: Literal["websocket"]
87
+ asgi: ASGIVersions
88
+ http_version: str
89
+ scheme: str
90
+ path: str
91
+ raw_path: bytes
92
+ query_string: bytes
93
+ root_path: str
94
+ headers: Iterable[tuple[bytes, bytes]]
95
+ client: tuple[str, int] | None
96
+ server: tuple[str, int | None] | None
97
+ subprotocols: Iterable[str]
98
+ state: NotRequired[dict[str, Any]]
99
+ extensions: NotRequired[dict[str, dict[object, object]]]
100
+
101
+
102
+ class LifespanScope(TypedDict):
103
+ type: Literal["lifespan"]
104
+ asgi: ASGIVersions
105
+ state: NotRequired[dict[str, Any]]
106
+
107
+
108
+ WWWScope = Union[HTTPScope, WebSocketScope]
109
+ Scope = Union[HTTPScope, WebSocketScope, LifespanScope]
110
+
111
+
112
+ class HTTPRequestEvent(TypedDict):
113
+ type: Literal["http.request"]
114
+ body: bytes
115
+ more_body: bool
116
+
117
+
118
+ class HTTPResponseDebugEvent(TypedDict):
119
+ type: Literal["http.response.debug"]
120
+ info: dict[str, object]
121
+
122
+
123
+ class HTTPResponseStartEvent(TypedDict):
124
+ type: Literal["http.response.start"]
125
+ status: int
126
+ headers: NotRequired[Iterable[tuple[bytes, bytes]]]
127
+ trailers: NotRequired[bool]
128
+
129
+
130
+ class HTTPResponseBodyEvent(TypedDict):
131
+ type: Literal["http.response.body"]
132
+ body: bytes
133
+ more_body: NotRequired[bool]
134
+
135
+
136
+ class HTTPResponseTrailersEvent(TypedDict):
137
+ type: Literal["http.response.trailers"]
138
+ headers: Iterable[tuple[bytes, bytes]]
139
+ more_trailers: bool
140
+
141
+
142
+ class HTTPServerPushEvent(TypedDict):
143
+ type: Literal["http.response.push"]
144
+ path: str
145
+ headers: Iterable[tuple[bytes, bytes]]
146
+
147
+
148
+ class HTTPDisconnectEvent(TypedDict):
149
+ type: Literal["http.disconnect"]
150
+
151
+
152
+ class WebSocketConnectEvent(TypedDict):
153
+ type: Literal["websocket.connect"]
154
+
155
+
156
+ class WebSocketAcceptEvent(TypedDict):
157
+ type: Literal["websocket.accept"]
158
+ subprotocol: NotRequired[str | None]
159
+ headers: NotRequired[Iterable[tuple[bytes, bytes]]]
160
+
161
+
162
+ class _WebSocketReceiveEventBytes(TypedDict):
163
+ type: Literal["websocket.receive"]
164
+ bytes: bytes
165
+ text: NotRequired[None]
166
+
167
+
168
+ class _WebSocketReceiveEventText(TypedDict):
169
+ type: Literal["websocket.receive"]
170
+ bytes: NotRequired[None]
171
+ text: str
172
+
173
+
174
+ WebSocketReceiveEvent = Union[_WebSocketReceiveEventBytes, _WebSocketReceiveEventText]
175
+
176
+
177
+ class _WebSocketSendEventBytes(TypedDict):
178
+ type: Literal["websocket.send"]
179
+ bytes: bytes
180
+ text: NotRequired[None]
181
+
182
+
183
+ class _WebSocketSendEventText(TypedDict):
184
+ type: Literal["websocket.send"]
185
+ bytes: NotRequired[None]
186
+ text: str
187
+
188
+
189
+ WebSocketSendEvent = Union[_WebSocketSendEventBytes, _WebSocketSendEventText]
190
+
191
+
192
+ class WebSocketResponseStartEvent(TypedDict):
193
+ type: Literal["websocket.http.response.start"]
194
+ status: int
195
+ headers: Iterable[tuple[bytes, bytes]]
196
+
197
+
198
+ class WebSocketResponseBodyEvent(TypedDict):
199
+ type: Literal["websocket.http.response.body"]
200
+ body: bytes
201
+ more_body: NotRequired[bool]
202
+
203
+
204
+ class WebSocketDisconnectEvent(TypedDict):
205
+ type: Literal["websocket.disconnect"]
206
+ code: int
207
+ reason: NotRequired[str | None]
208
+
209
+
210
+ class WebSocketCloseEvent(TypedDict):
211
+ type: Literal["websocket.close"]
212
+ code: NotRequired[int]
213
+ reason: NotRequired[str | None]
214
+
215
+
216
+ class LifespanStartupEvent(TypedDict):
217
+ type: Literal["lifespan.startup"]
218
+
219
+
220
+ class LifespanShutdownEvent(TypedDict):
221
+ type: Literal["lifespan.shutdown"]
222
+
223
+
224
+ class LifespanStartupCompleteEvent(TypedDict):
225
+ type: Literal["lifespan.startup.complete"]
226
+
227
+
228
+ class LifespanStartupFailedEvent(TypedDict):
229
+ type: Literal["lifespan.startup.failed"]
230
+ message: str
231
+
232
+
233
+ class LifespanShutdownCompleteEvent(TypedDict):
234
+ type: Literal["lifespan.shutdown.complete"]
235
+
236
+
237
+ class LifespanShutdownFailedEvent(TypedDict):
238
+ type: Literal["lifespan.shutdown.failed"]
239
+ message: str
240
+
241
+
242
+ WebSocketEvent = Union[WebSocketReceiveEvent, WebSocketDisconnectEvent, WebSocketConnectEvent]
243
+
244
+
245
+ ASGIReceiveEvent = Union[
246
+ HTTPRequestEvent,
247
+ HTTPDisconnectEvent,
248
+ WebSocketConnectEvent,
249
+ WebSocketReceiveEvent,
250
+ WebSocketDisconnectEvent,
251
+ LifespanStartupEvent,
252
+ LifespanShutdownEvent,
253
+ ]
254
+
255
+
256
+ ASGISendEvent = Union[
257
+ HTTPResponseStartEvent,
258
+ HTTPResponseBodyEvent,
259
+ HTTPResponseTrailersEvent,
260
+ HTTPServerPushEvent,
261
+ HTTPDisconnectEvent,
262
+ WebSocketAcceptEvent,
263
+ WebSocketSendEvent,
264
+ WebSocketResponseStartEvent,
265
+ WebSocketResponseBodyEvent,
266
+ WebSocketCloseEvent,
267
+ LifespanStartupCompleteEvent,
268
+ LifespanStartupFailedEvent,
269
+ LifespanShutdownCompleteEvent,
270
+ LifespanShutdownFailedEvent,
271
+ ]
272
+
273
+
274
+ ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
275
+ ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
276
+
277
+
278
+ class ASGI2Protocol(Protocol):
279
+ def __init__(self, scope: Scope) -> None: ... # pragma: no cover
280
+
281
+ async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... # pragma: no cover
282
+
283
+
284
+ ASGI2Application = Type[ASGI2Protocol]
285
+ ASGI3Application = Callable[
286
+ [
287
+ Scope,
288
+ ASGIReceiveCallable,
289
+ ASGISendCallable,
290
+ ],
291
+ Awaitable[None],
292
+ ]
293
+ ASGIApplication = Union[ASGI2Application, ASGI3Application]
evalkit_tf446/lib/python3.10/site-packages/uvicorn/config.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import inspect
5
+ import json
6
+ import logging
7
+ import logging.config
8
+ import os
9
+ import socket
10
+ import ssl
11
+ import sys
12
+ from configparser import RawConfigParser
13
+ from pathlib import Path
14
+ from typing import IO, Any, Awaitable, Callable, Literal
15
+
16
+ import click
17
+
18
+ from uvicorn._types import ASGIApplication
19
+ from uvicorn.importer import ImportFromStringError, import_from_string
20
+ from uvicorn.logging import TRACE_LOG_LEVEL
21
+ from uvicorn.middleware.asgi2 import ASGI2Middleware
22
+ from uvicorn.middleware.message_logger import MessageLoggerMiddleware
23
+ from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
24
+ from uvicorn.middleware.wsgi import WSGIMiddleware
25
+
26
+ HTTPProtocolType = Literal["auto", "h11", "httptools"]
27
+ WSProtocolType = Literal["auto", "none", "websockets", "wsproto"]
28
+ LifespanType = Literal["auto", "on", "off"]
29
+ LoopSetupType = Literal["none", "auto", "asyncio", "uvloop"]
30
+ InterfaceType = Literal["auto", "asgi3", "asgi2", "wsgi"]
31
+
32
+ LOG_LEVELS: dict[str, int] = {
33
+ "critical": logging.CRITICAL,
34
+ "error": logging.ERROR,
35
+ "warning": logging.WARNING,
36
+ "info": logging.INFO,
37
+ "debug": logging.DEBUG,
38
+ "trace": TRACE_LOG_LEVEL,
39
+ }
40
+ HTTP_PROTOCOLS: dict[HTTPProtocolType, str] = {
41
+ "auto": "uvicorn.protocols.http.auto:AutoHTTPProtocol",
42
+ "h11": "uvicorn.protocols.http.h11_impl:H11Protocol",
43
+ "httptools": "uvicorn.protocols.http.httptools_impl:HttpToolsProtocol",
44
+ }
45
+ WS_PROTOCOLS: dict[WSProtocolType, str | None] = {
46
+ "auto": "uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol",
47
+ "none": None,
48
+ "websockets": "uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol",
49
+ "wsproto": "uvicorn.protocols.websockets.wsproto_impl:WSProtocol",
50
+ }
51
+ LIFESPAN: dict[LifespanType, str] = {
52
+ "auto": "uvicorn.lifespan.on:LifespanOn",
53
+ "on": "uvicorn.lifespan.on:LifespanOn",
54
+ "off": "uvicorn.lifespan.off:LifespanOff",
55
+ }
56
+ LOOP_SETUPS: dict[LoopSetupType, str | None] = {
57
+ "none": None,
58
+ "auto": "uvicorn.loops.auto:auto_loop_setup",
59
+ "asyncio": "uvicorn.loops.asyncio:asyncio_setup",
60
+ "uvloop": "uvicorn.loops.uvloop:uvloop_setup",
61
+ }
62
+ INTERFACES: list[InterfaceType] = ["auto", "asgi3", "asgi2", "wsgi"]
63
+
64
+ SSL_PROTOCOL_VERSION: int = ssl.PROTOCOL_TLS_SERVER
65
+
66
+ LOGGING_CONFIG: dict[str, Any] = {
67
+ "version": 1,
68
+ "disable_existing_loggers": False,
69
+ "formatters": {
70
+ "default": {
71
+ "()": "uvicorn.logging.DefaultFormatter",
72
+ "fmt": "%(levelprefix)s %(message)s",
73
+ "use_colors": None,
74
+ },
75
+ "access": {
76
+ "()": "uvicorn.logging.AccessFormatter",
77
+ "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s', # noqa: E501
78
+ },
79
+ },
80
+ "handlers": {
81
+ "default": {
82
+ "formatter": "default",
83
+ "class": "logging.StreamHandler",
84
+ "stream": "ext://sys.stderr",
85
+ },
86
+ "access": {
87
+ "formatter": "access",
88
+ "class": "logging.StreamHandler",
89
+ "stream": "ext://sys.stdout",
90
+ },
91
+ },
92
+ "loggers": {
93
+ "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
94
+ "uvicorn.error": {"level": "INFO"},
95
+ "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
96
+ },
97
+ }
98
+
99
+ logger = logging.getLogger("uvicorn.error")
100
+
101
+
102
+ def create_ssl_context(
103
+ certfile: str | os.PathLike[str],
104
+ keyfile: str | os.PathLike[str] | None,
105
+ password: str | None,
106
+ ssl_version: int,
107
+ cert_reqs: int,
108
+ ca_certs: str | os.PathLike[str] | None,
109
+ ciphers: str | None,
110
+ ) -> ssl.SSLContext:
111
+ ctx = ssl.SSLContext(ssl_version)
112
+ get_password = (lambda: password) if password else None
113
+ ctx.load_cert_chain(certfile, keyfile, get_password)
114
+ ctx.verify_mode = ssl.VerifyMode(cert_reqs)
115
+ if ca_certs:
116
+ ctx.load_verify_locations(ca_certs)
117
+ if ciphers:
118
+ ctx.set_ciphers(ciphers)
119
+ return ctx
120
+
121
+
122
+ def is_dir(path: Path) -> bool:
123
+ try:
124
+ if not path.is_absolute():
125
+ path = path.resolve()
126
+ return path.is_dir()
127
+ except OSError: # pragma: full coverage
128
+ return False
129
+
130
+
131
+ def resolve_reload_patterns(patterns_list: list[str], directories_list: list[str]) -> tuple[list[str], list[Path]]:
132
+ directories: list[Path] = list(set(map(Path, directories_list.copy())))
133
+ patterns: list[str] = patterns_list.copy()
134
+
135
+ current_working_directory = Path.cwd()
136
+ for pattern in patterns_list:
137
+ # Special case for the .* pattern, otherwise this would only match
138
+ # hidden directories which is probably undesired
139
+ if pattern == ".*":
140
+ continue
141
+ patterns.append(pattern)
142
+ if is_dir(Path(pattern)):
143
+ directories.append(Path(pattern))
144
+ else:
145
+ for match in current_working_directory.glob(pattern):
146
+ if is_dir(match):
147
+ directories.append(match)
148
+
149
+ directories = list(set(directories))
150
+ directories = list(map(Path, directories))
151
+ directories = list(map(lambda x: x.resolve(), directories))
152
+ directories = list({reload_path for reload_path in directories if is_dir(reload_path)})
153
+
154
+ children = []
155
+ for j in range(len(directories)):
156
+ for k in range(j + 1, len(directories)): # pragma: full coverage
157
+ if directories[j] in directories[k].parents:
158
+ children.append(directories[k])
159
+ elif directories[k] in directories[j].parents:
160
+ children.append(directories[j])
161
+
162
+ directories = list(set(directories).difference(set(children)))
163
+
164
+ return list(set(patterns)), directories
165
+
166
+
167
+ def _normalize_dirs(dirs: list[str] | str | None) -> list[str]:
168
+ if dirs is None:
169
+ return []
170
+ if isinstance(dirs, str):
171
+ return [dirs]
172
+ return list(set(dirs))
173
+
174
+
175
+ class Config:
176
+ def __init__(
177
+ self,
178
+ app: ASGIApplication | Callable[..., Any] | str,
179
+ host: str = "127.0.0.1",
180
+ port: int = 8000,
181
+ uds: str | None = None,
182
+ fd: int | None = None,
183
+ loop: LoopSetupType = "auto",
184
+ http: type[asyncio.Protocol] | HTTPProtocolType = "auto",
185
+ ws: type[asyncio.Protocol] | WSProtocolType = "auto",
186
+ ws_max_size: int = 16 * 1024 * 1024,
187
+ ws_max_queue: int = 32,
188
+ ws_ping_interval: float | None = 20.0,
189
+ ws_ping_timeout: float | None = 20.0,
190
+ ws_per_message_deflate: bool = True,
191
+ lifespan: LifespanType = "auto",
192
+ env_file: str | os.PathLike[str] | None = None,
193
+ log_config: dict[str, Any] | str | RawConfigParser | IO[Any] | None = LOGGING_CONFIG,
194
+ log_level: str | int | None = None,
195
+ access_log: bool = True,
196
+ use_colors: bool | None = None,
197
+ interface: InterfaceType = "auto",
198
+ reload: bool = False,
199
+ reload_dirs: list[str] | str | None = None,
200
+ reload_delay: float = 0.25,
201
+ reload_includes: list[str] | str | None = None,
202
+ reload_excludes: list[str] | str | None = None,
203
+ workers: int | None = None,
204
+ proxy_headers: bool = True,
205
+ server_header: bool = True,
206
+ date_header: bool = True,
207
+ forwarded_allow_ips: list[str] | str | None = None,
208
+ root_path: str = "",
209
+ limit_concurrency: int | None = None,
210
+ limit_max_requests: int | None = None,
211
+ backlog: int = 2048,
212
+ timeout_keep_alive: int = 5,
213
+ timeout_notify: int = 30,
214
+ timeout_graceful_shutdown: int | None = None,
215
+ callback_notify: Callable[..., Awaitable[None]] | None = None,
216
+ ssl_keyfile: str | os.PathLike[str] | None = None,
217
+ ssl_certfile: str | os.PathLike[str] | None = None,
218
+ ssl_keyfile_password: str | None = None,
219
+ ssl_version: int = SSL_PROTOCOL_VERSION,
220
+ ssl_cert_reqs: int = ssl.CERT_NONE,
221
+ ssl_ca_certs: str | None = None,
222
+ ssl_ciphers: str = "TLSv1",
223
+ headers: list[tuple[str, str]] | None = None,
224
+ factory: bool = False,
225
+ h11_max_incomplete_event_size: int | None = None,
226
+ ):
227
+ self.app = app
228
+ self.host = host
229
+ self.port = port
230
+ self.uds = uds
231
+ self.fd = fd
232
+ self.loop = loop
233
+ self.http = http
234
+ self.ws = ws
235
+ self.ws_max_size = ws_max_size
236
+ self.ws_max_queue = ws_max_queue
237
+ self.ws_ping_interval = ws_ping_interval
238
+ self.ws_ping_timeout = ws_ping_timeout
239
+ self.ws_per_message_deflate = ws_per_message_deflate
240
+ self.lifespan = lifespan
241
+ self.log_config = log_config
242
+ self.log_level = log_level
243
+ self.access_log = access_log
244
+ self.use_colors = use_colors
245
+ self.interface = interface
246
+ self.reload = reload
247
+ self.reload_delay = reload_delay
248
+ self.workers = workers or 1
249
+ self.proxy_headers = proxy_headers
250
+ self.server_header = server_header
251
+ self.date_header = date_header
252
+ self.root_path = root_path
253
+ self.limit_concurrency = limit_concurrency
254
+ self.limit_max_requests = limit_max_requests
255
+ self.backlog = backlog
256
+ self.timeout_keep_alive = timeout_keep_alive
257
+ self.timeout_notify = timeout_notify
258
+ self.timeout_graceful_shutdown = timeout_graceful_shutdown
259
+ self.callback_notify = callback_notify
260
+ self.ssl_keyfile = ssl_keyfile
261
+ self.ssl_certfile = ssl_certfile
262
+ self.ssl_keyfile_password = ssl_keyfile_password
263
+ self.ssl_version = ssl_version
264
+ self.ssl_cert_reqs = ssl_cert_reqs
265
+ self.ssl_ca_certs = ssl_ca_certs
266
+ self.ssl_ciphers = ssl_ciphers
267
+ self.headers: list[tuple[str, str]] = headers or []
268
+ self.encoded_headers: list[tuple[bytes, bytes]] = []
269
+ self.factory = factory
270
+ self.h11_max_incomplete_event_size = h11_max_incomplete_event_size
271
+
272
+ self.loaded = False
273
+ self.configure_logging()
274
+
275
+ self.reload_dirs: list[Path] = []
276
+ self.reload_dirs_excludes: list[Path] = []
277
+ self.reload_includes: list[str] = []
278
+ self.reload_excludes: list[str] = []
279
+
280
+ if (reload_dirs or reload_includes or reload_excludes) and not self.should_reload:
281
+ logger.warning(
282
+ "Current configuration will not reload as not all conditions are met, " "please refer to documentation."
283
+ )
284
+
285
+ if self.should_reload:
286
+ reload_dirs = _normalize_dirs(reload_dirs)
287
+ reload_includes = _normalize_dirs(reload_includes)
288
+ reload_excludes = _normalize_dirs(reload_excludes)
289
+
290
+ self.reload_includes, self.reload_dirs = resolve_reload_patterns(reload_includes, reload_dirs)
291
+
292
+ self.reload_excludes, self.reload_dirs_excludes = resolve_reload_patterns(reload_excludes, [])
293
+
294
+ reload_dirs_tmp = self.reload_dirs.copy()
295
+
296
+ for directory in self.reload_dirs_excludes:
297
+ for reload_directory in reload_dirs_tmp:
298
+ if directory == reload_directory or directory in reload_directory.parents:
299
+ try:
300
+ self.reload_dirs.remove(reload_directory)
301
+ except ValueError: # pragma: full coverage
302
+ pass
303
+
304
+ for pattern in self.reload_excludes:
305
+ if pattern in self.reload_includes:
306
+ self.reload_includes.remove(pattern) # pragma: full coverage
307
+
308
+ if not self.reload_dirs:
309
+ if reload_dirs:
310
+ logger.warning(
311
+ "Provided reload directories %s did not contain valid "
312
+ + "directories, watching current working directory.",
313
+ reload_dirs,
314
+ )
315
+ self.reload_dirs = [Path(os.getcwd())]
316
+
317
+ logger.info(
318
+ "Will watch for changes in these directories: %s",
319
+ sorted(list(map(str, self.reload_dirs))),
320
+ )
321
+
322
+ if env_file is not None:
323
+ from dotenv import load_dotenv
324
+
325
+ logger.info("Loading environment from '%s'", env_file)
326
+ load_dotenv(dotenv_path=env_file)
327
+
328
+ if workers is None and "WEB_CONCURRENCY" in os.environ:
329
+ self.workers = int(os.environ["WEB_CONCURRENCY"])
330
+
331
+ self.forwarded_allow_ips: list[str] | str
332
+ if forwarded_allow_ips is None:
333
+ self.forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
334
+ else:
335
+ self.forwarded_allow_ips = forwarded_allow_ips # pragma: full coverage
336
+
337
+ if self.reload and self.workers > 1:
338
+ logger.warning('"workers" flag is ignored when reloading is enabled.')
339
+
340
+ @property
341
+ def asgi_version(self) -> Literal["2.0", "3.0"]:
342
+ mapping: dict[str, Literal["2.0", "3.0"]] = {
343
+ "asgi2": "2.0",
344
+ "asgi3": "3.0",
345
+ "wsgi": "3.0",
346
+ }
347
+ return mapping[self.interface]
348
+
349
+ @property
350
+ def is_ssl(self) -> bool:
351
+ return bool(self.ssl_keyfile or self.ssl_certfile)
352
+
353
+ @property
354
+ def use_subprocess(self) -> bool:
355
+ return bool(self.reload or self.workers > 1)
356
+
357
+ def configure_logging(self) -> None:
358
+ logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")
359
+
360
+ if self.log_config is not None:
361
+ if isinstance(self.log_config, dict):
362
+ if self.use_colors in (True, False):
363
+ self.log_config["formatters"]["default"]["use_colors"] = self.use_colors
364
+ self.log_config["formatters"]["access"]["use_colors"] = self.use_colors
365
+ logging.config.dictConfig(self.log_config)
366
+ elif isinstance(self.log_config, str) and self.log_config.endswith(".json"):
367
+ with open(self.log_config) as file:
368
+ loaded_config = json.load(file)
369
+ logging.config.dictConfig(loaded_config)
370
+ elif isinstance(self.log_config, str) and self.log_config.endswith((".yaml", ".yml")):
371
+ # Install the PyYAML package or the uvicorn[standard] optional
372
+ # dependencies to enable this functionality.
373
+ import yaml
374
+
375
+ with open(self.log_config) as file:
376
+ loaded_config = yaml.safe_load(file)
377
+ logging.config.dictConfig(loaded_config)
378
+ else:
379
+ # See the note about fileConfig() here:
380
+ # https://docs.python.org/3/library/logging.config.html#configuration-file-format
381
+ logging.config.fileConfig(self.log_config, disable_existing_loggers=False)
382
+
383
+ if self.log_level is not None:
384
+ if isinstance(self.log_level, str):
385
+ log_level = LOG_LEVELS[self.log_level]
386
+ else:
387
+ log_level = self.log_level
388
+ logging.getLogger("uvicorn.error").setLevel(log_level)
389
+ logging.getLogger("uvicorn.access").setLevel(log_level)
390
+ logging.getLogger("uvicorn.asgi").setLevel(log_level)
391
+ if self.access_log is False:
392
+ logging.getLogger("uvicorn.access").handlers = []
393
+ logging.getLogger("uvicorn.access").propagate = False
394
+
395
+ def load(self) -> None:
396
+ assert not self.loaded
397
+
398
+ if self.is_ssl:
399
+ assert self.ssl_certfile
400
+ self.ssl: ssl.SSLContext | None = create_ssl_context(
401
+ keyfile=self.ssl_keyfile,
402
+ certfile=self.ssl_certfile,
403
+ password=self.ssl_keyfile_password,
404
+ ssl_version=self.ssl_version,
405
+ cert_reqs=self.ssl_cert_reqs,
406
+ ca_certs=self.ssl_ca_certs,
407
+ ciphers=self.ssl_ciphers,
408
+ )
409
+ else:
410
+ self.ssl = None
411
+
412
+ encoded_headers = [(key.lower().encode("latin1"), value.encode("latin1")) for key, value in self.headers]
413
+ self.encoded_headers = (
414
+ [(b"server", b"uvicorn")] + encoded_headers
415
+ if b"server" not in dict(encoded_headers) and self.server_header
416
+ else encoded_headers
417
+ )
418
+
419
+ if isinstance(self.http, str):
420
+ http_protocol_class = import_from_string(HTTP_PROTOCOLS[self.http])
421
+ self.http_protocol_class: type[asyncio.Protocol] = http_protocol_class
422
+ else:
423
+ self.http_protocol_class = self.http
424
+
425
+ if isinstance(self.ws, str):
426
+ ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws])
427
+ self.ws_protocol_class: type[asyncio.Protocol] | None = ws_protocol_class
428
+ else:
429
+ self.ws_protocol_class = self.ws
430
+
431
+ self.lifespan_class = import_from_string(LIFESPAN[self.lifespan])
432
+
433
+ try:
434
+ self.loaded_app = import_from_string(self.app)
435
+ except ImportFromStringError as exc:
436
+ logger.error("Error loading ASGI app. %s" % exc)
437
+ sys.exit(1)
438
+
439
+ try:
440
+ self.loaded_app = self.loaded_app()
441
+ except TypeError as exc:
442
+ if self.factory:
443
+ logger.error("Error loading ASGI app factory: %s", exc)
444
+ sys.exit(1)
445
+ else:
446
+ if not self.factory:
447
+ logger.warning(
448
+ "ASGI app factory detected. Using it, " "but please consider setting the --factory flag explicitly."
449
+ )
450
+
451
+ if self.interface == "auto":
452
+ if inspect.isclass(self.loaded_app):
453
+ use_asgi_3 = hasattr(self.loaded_app, "__await__")
454
+ elif inspect.isfunction(self.loaded_app):
455
+ use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app)
456
+ else:
457
+ call = getattr(self.loaded_app, "__call__", None)
458
+ use_asgi_3 = asyncio.iscoroutinefunction(call)
459
+ self.interface = "asgi3" if use_asgi_3 else "asgi2"
460
+
461
+ if self.interface == "wsgi":
462
+ self.loaded_app = WSGIMiddleware(self.loaded_app)
463
+ self.ws_protocol_class = None
464
+ elif self.interface == "asgi2":
465
+ self.loaded_app = ASGI2Middleware(self.loaded_app)
466
+
467
+ if logger.getEffectiveLevel() <= TRACE_LOG_LEVEL:
468
+ self.loaded_app = MessageLoggerMiddleware(self.loaded_app)
469
+ if self.proxy_headers:
470
+ self.loaded_app = ProxyHeadersMiddleware(self.loaded_app, trusted_hosts=self.forwarded_allow_ips)
471
+
472
+ self.loaded = True
473
+
474
+ def setup_event_loop(self) -> None:
475
+ loop_setup: Callable | None = import_from_string(LOOP_SETUPS[self.loop])
476
+ if loop_setup is not None:
477
+ loop_setup(use_subprocess=self.use_subprocess)
478
+
479
+ def bind_socket(self) -> socket.socket:
480
+ logger_args: list[str | int]
481
+ if self.uds: # pragma: py-win32
482
+ path = self.uds
483
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
484
+ try:
485
+ sock.bind(path)
486
+ uds_perms = 0o666
487
+ os.chmod(self.uds, uds_perms)
488
+ except OSError as exc: # pragma: full coverage
489
+ logger.error(exc)
490
+ sys.exit(1)
491
+
492
+ message = "Uvicorn running on unix socket %s (Press CTRL+C to quit)"
493
+ sock_name_format = "%s"
494
+ color_message = "Uvicorn running on " + click.style(sock_name_format, bold=True) + " (Press CTRL+C to quit)"
495
+ logger_args = [self.uds]
496
+ elif self.fd: # pragma: py-win32
497
+ sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
498
+ message = "Uvicorn running on socket %s (Press CTRL+C to quit)"
499
+ fd_name_format = "%s"
500
+ color_message = "Uvicorn running on " + click.style(fd_name_format, bold=True) + " (Press CTRL+C to quit)"
501
+ logger_args = [sock.getsockname()]
502
+ else:
503
+ family = socket.AF_INET
504
+ addr_format = "%s://%s:%d"
505
+
506
+ if self.host and ":" in self.host: # pragma: full coverage
507
+ # It's an IPv6 address.
508
+ family = socket.AF_INET6
509
+ addr_format = "%s://[%s]:%d"
510
+
511
+ sock = socket.socket(family=family)
512
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
513
+ try:
514
+ sock.bind((self.host, self.port))
515
+ except OSError as exc: # pragma: full coverage
516
+ logger.error(exc)
517
+ sys.exit(1)
518
+
519
+ message = f"Uvicorn running on {addr_format} (Press CTRL+C to quit)"
520
+ color_message = "Uvicorn running on " + click.style(addr_format, bold=True) + " (Press CTRL+C to quit)"
521
+ protocol_name = "https" if self.is_ssl else "http"
522
+ logger_args = [protocol_name, self.host, sock.getsockname()[1]]
523
+ logger.info(message, *logger_args, extra={"color_message": color_message})
524
+ sock.set_inheritable(True)
525
+ return sock
526
+
527
+ @property
528
+ def should_reload(self) -> bool:
529
+ return isinstance(self.app, str) and self.reload
evalkit_tf446/lib/python3.10/site-packages/uvicorn/importer.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ from typing import Any
3
+
4
+
5
+ class ImportFromStringError(Exception):
6
+ pass
7
+
8
+
9
+ def import_from_string(import_str: Any) -> Any:
10
+ if not isinstance(import_str, str):
11
+ return import_str
12
+
13
+ module_str, _, attrs_str = import_str.partition(":")
14
+ if not module_str or not attrs_str:
15
+ message = 'Import string "{import_str}" must be in format "<module>:<attribute>".'
16
+ raise ImportFromStringError(message.format(import_str=import_str))
17
+
18
+ try:
19
+ module = importlib.import_module(module_str)
20
+ except ModuleNotFoundError as exc:
21
+ if exc.name != module_str:
22
+ raise exc from None
23
+ message = 'Could not import module "{module_str}".'
24
+ raise ImportFromStringError(message.format(module_str=module_str))
25
+
26
+ instance = module
27
+ try:
28
+ for attr_str in attrs_str.split("."):
29
+ instance = getattr(instance, attr_str)
30
+ except AttributeError:
31
+ message = 'Attribute "{attrs_str}" not found in module "{module_str}".'
32
+ raise ImportFromStringError(message.format(attrs_str=attrs_str, module_str=module_str))
33
+
34
+ return instance
evalkit_tf446/lib/python3.10/site-packages/uvicorn/logging.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import http
4
+ import logging
5
+ import sys
6
+ from copy import copy
7
+ from typing import Literal
8
+
9
+ import click
10
+
11
+ TRACE_LOG_LEVEL = 5
12
+
13
+
14
+ class ColourizedFormatter(logging.Formatter):
15
+ """
16
+ A custom log formatter class that:
17
+
18
+ * Outputs the LOG_LEVEL with an appropriate color.
19
+ * If a log call includes an `extras={"color_message": ...}` it will be used
20
+ for formatting the output, instead of the plain text message.
21
+ """
22
+
23
+ level_name_colors = {
24
+ TRACE_LOG_LEVEL: lambda level_name: click.style(str(level_name), fg="blue"),
25
+ logging.DEBUG: lambda level_name: click.style(str(level_name), fg="cyan"),
26
+ logging.INFO: lambda level_name: click.style(str(level_name), fg="green"),
27
+ logging.WARNING: lambda level_name: click.style(str(level_name), fg="yellow"),
28
+ logging.ERROR: lambda level_name: click.style(str(level_name), fg="red"),
29
+ logging.CRITICAL: lambda level_name: click.style(str(level_name), fg="bright_red"),
30
+ }
31
+
32
+ def __init__(
33
+ self,
34
+ fmt: str | None = None,
35
+ datefmt: str | None = None,
36
+ style: Literal["%", "{", "$"] = "%",
37
+ use_colors: bool | None = None,
38
+ ):
39
+ if use_colors in (True, False):
40
+ self.use_colors = use_colors
41
+ else:
42
+ self.use_colors = sys.stdout.isatty()
43
+ super().__init__(fmt=fmt, datefmt=datefmt, style=style)
44
+
45
+ def color_level_name(self, level_name: str, level_no: int) -> str:
46
+ def default(level_name: str) -> str:
47
+ return str(level_name) # pragma: no cover
48
+
49
+ func = self.level_name_colors.get(level_no, default)
50
+ return func(level_name)
51
+
52
+ def should_use_colors(self) -> bool:
53
+ return True # pragma: no cover
54
+
55
+ def formatMessage(self, record: logging.LogRecord) -> str:
56
+ recordcopy = copy(record)
57
+ levelname = recordcopy.levelname
58
+ seperator = " " * (8 - len(recordcopy.levelname))
59
+ if self.use_colors:
60
+ levelname = self.color_level_name(levelname, recordcopy.levelno)
61
+ if "color_message" in recordcopy.__dict__:
62
+ recordcopy.msg = recordcopy.__dict__["color_message"]
63
+ recordcopy.__dict__["message"] = recordcopy.getMessage()
64
+ recordcopy.__dict__["levelprefix"] = levelname + ":" + seperator
65
+ return super().formatMessage(recordcopy)
66
+
67
+
68
+ class DefaultFormatter(ColourizedFormatter):
69
+ def should_use_colors(self) -> bool:
70
+ return sys.stderr.isatty() # pragma: no cover
71
+
72
+
73
+ class AccessFormatter(ColourizedFormatter):
74
+ status_code_colours = {
75
+ 1: lambda code: click.style(str(code), fg="bright_white"),
76
+ 2: lambda code: click.style(str(code), fg="green"),
77
+ 3: lambda code: click.style(str(code), fg="yellow"),
78
+ 4: lambda code: click.style(str(code), fg="red"),
79
+ 5: lambda code: click.style(str(code), fg="bright_red"),
80
+ }
81
+
82
+ def get_status_code(self, status_code: int) -> str:
83
+ try:
84
+ status_phrase = http.HTTPStatus(status_code).phrase
85
+ except ValueError:
86
+ status_phrase = ""
87
+ status_and_phrase = f"{status_code} {status_phrase}"
88
+ if self.use_colors:
89
+
90
+ def default(code: int) -> str:
91
+ return status_and_phrase # pragma: no cover
92
+
93
+ func = self.status_code_colours.get(status_code // 100, default)
94
+ return func(status_and_phrase)
95
+ return status_and_phrase
96
+
97
+ def formatMessage(self, record: logging.LogRecord) -> str:
98
+ recordcopy = copy(record)
99
+ (
100
+ client_addr,
101
+ method,
102
+ full_path,
103
+ http_version,
104
+ status_code,
105
+ ) = recordcopy.args # type: ignore[misc]
106
+ status_code = self.get_status_code(int(status_code)) # type: ignore[arg-type]
107
+ request_line = f"{method} {full_path} HTTP/{http_version}"
108
+ if self.use_colors:
109
+ request_line = click.style(request_line, bold=True)
110
+ recordcopy.__dict__.update(
111
+ {
112
+ "client_addr": client_addr,
113
+ "request_line": request_line,
114
+ "status_code": status_code,
115
+ }
116
+ )
117
+ return super().formatMessage(recordcopy)
evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__init__.py ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (172 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-310.pyc ADDED
Binary file (545 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/auto.cpython-310.pyc ADDED
Binary file (553 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-310.pyc ADDED
Binary file (423 Bytes). View file