| 1 |
# Copyright (c) 2005 Gavin E. Crooks <[email protected]> |
| 2 |
# |
| 3 |
# This software is distributed under the MIT Open Source License. |
| 4 |
# <http://www.opensource.org/licenses/mit-license.html> |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a |
| 7 |
# copy of this software and associated documentation files (the "Software"), |
| 8 |
# to deal in the Software without restriction, including without limitation |
| 9 |
# the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 10 |
# and/or sell copies of the Software, and to permit persons to whom the |
| 11 |
# Software is furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included |
| 14 |
# in all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
|
| 26 |
"""Extra utilities and core classes not in standard python.""" |
| 27 |
|
| 28 |
from typing import Any, Iterable, List, Optional |
| 29 |
|
| 30 |
__all__ = ( |
| 31 |
"isblank", |
| 32 |
"isfloat", |
| 33 |
"isint", |
| 34 |
"ischar", |
| 35 |
"remove_whitespace", |
| 36 |
"invert_dict", |
| 37 |
"stdrepr", |
| 38 |
"Token", |
| 39 |
"deoptparse", |
| 40 |
"crc32", |
| 41 |
"crc64", |
| 42 |
"ArgumentError", |
| 43 |
"group_count", |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
def isblank(s: Any) -> bool: |
| 48 |
"""Is this whitespace or an empty string?""" |
| 49 |
if isinstance(s, str): |
| 50 |
if not s: |
| 51 |
return True |
| 52 |
else: |
| 53 |
return s.isspace() |
| 54 |
else: |
| 55 |
return False |
| 56 |
|
| 57 |
|
| 58 |
def isfloat(s: Any) -> bool: |
| 59 |
"""Does this object represent a floating point number?""" |
| 60 |
try: |
| 61 |
float(s) |
| 62 |
return True |
| 63 |
except (ValueError, TypeError): |
| 64 |
return False |
| 65 |
|
| 66 |
|
| 67 |
def isint(s: Any) -> bool: |
| 68 |
"""Does this object represent an integer?""" |
| 69 |
try: |
| 70 |
int(s) |
| 71 |
return True |
| 72 |
except (ValueError, TypeError): |
| 73 |
return False |
| 74 |
|
| 75 |
|
| 76 |
def ischar(s: Any) -> bool: |
| 77 |
"""Does this object represent a character?""" |
| 78 |
# Adapted from: https://stackoverflow.com/a/14321721 and |
| 79 |
# https://mail.python.org/pipermail/python-list/2007-March/425058.html |
| 80 |
return isinstance(s, str) and bool(s) and s == len(s) * s[0] |
| 81 |
|
| 82 |
|
| 83 |
def remove_whitespace(astring: str) -> str: |
| 84 |
"""Remove all whitespace from a string.""" |
| 85 |
# TODO: Is this horrible slow? |
| 86 |
return "".join(astring.split()) |
| 87 |
|
| 88 |
|
| 89 |
def invert_dict(dictionary: dict) -> dict: |
| 90 |
"""Constructs a new dictionary with inverted mappings so that keys |
| 91 |
become values and vice versa. If the values of the original dictionary |
| 92 |
are not unique then only one of the original keys will be included |
| 93 |
in the new dictionary. |
| 94 |
""" |
| 95 |
return dict((value, key) for key, value in dictionary.items()) |
| 96 |
|
| 97 |
|
| 98 |
def stdrepr( |
| 99 |
obj: Any, attributes: Optional[List[str]] = None, name: Optional[str] = None |
| 100 |
) -> str: |
| 101 |
"""Create a standard representation of an object.""" |
| 102 |
if name is None: |
| 103 |
name = obj.__class__.__name__ |
| 104 |
if attributes is None: |
| 105 |
attributes = obj.__class__.__slots__ |
| 106 |
args = [] |
| 107 |
for a in attributes: |
| 108 |
if a[0] == "_": |
| 109 |
continue # pragma: no cover |
| 110 |
args.append("%s=%s" % (a, repr(getattr(obj, a)))) |
| 111 |
arg_str = ",\n".join(args).replace("\n", "\n ") |
| 112 |
|
| 113 |
return "%s(\n %s\n)" % (name, arg_str) |
| 114 |
|
| 115 |
|
| 116 |
def group_count(i: Iterable) -> list: |
| 117 |
"""An iteration that returns tuples of items and the number of consecutive |
| 118 |
occurrences. Thus group_count('aabbbc') yields ('a',2), ('b',3), ('c',1) |
| 119 |
""" |
| 120 |
from itertools import groupby |
| 121 |
|
| 122 |
return [(item, sum(1 for n in group)) for item, group in groupby(i)] |
| 123 |
|
| 124 |
|
| 125 |
class Token: |
| 126 |
"""Represents the items returned by a file scanner, normally processed |
| 127 |
by a parser. |
| 128 |
|
| 129 |
Attributes : |
| 130 |
o typeof -- a string describing the kind of token |
| 131 |
o data -- the value of the token |
| 132 |
o lineno -- the line of the file on which the data was found (if known) |
| 133 |
o offset -- the offset of the data within the line (if known) |
| 134 |
""" |
| 135 |
|
| 136 |
__slots__ = ["typeof", "data", "lineno", "offset"] |
| 137 |
|
| 138 |
def __init__( |
| 139 |
self, |
| 140 |
typeof: str, |
| 141 |
data: Optional[str] = None, |
| 142 |
lineno: int = -1, |
| 143 |
offset: int = -1, |
| 144 |
) -> None: |
| 145 |
self.typeof = typeof |
| 146 |
self.data = data |
| 147 |
self.lineno = lineno |
| 148 |
self.offset = offset |
| 149 |
|
| 150 |
def __repr__(self) -> str: |
| 151 |
return stdrepr(self) |
| 152 |
|
| 153 |
def __str__(self) -> str: |
| 154 |
coord = str(self.lineno) |
| 155 |
if self.offset != -1: |
| 156 |
coord += ":" + str(self.offset) |
| 157 |
coord = coord.ljust(7) |
| 158 |
return (coord + " " + self.typeof + " : ").ljust(32) + str(self.data or "") |
| 159 |
|
| 160 |
|
| 161 |
def crc32(string: str) -> str: |
| 162 |
"""Return the standard CRC32 checksum as a hexidecimal string.""" |
| 163 |
import binascii |
| 164 |
|
| 165 |
return "%08X" % binascii.crc32(string.encode()) |
| 166 |
|
| 167 |
|
| 168 |
_crc64_table = None |
| 169 |
|
| 170 |
|
| 171 |
def crc64(string: str) -> str: |
| 172 |
"""Calculate ISO 3309 standard cyclic redundancy checksum. |
| 173 |
Used, for example, by SWISS-PROT. |
| 174 |
|
| 175 |
Returns : The CRC as a hexadecimal string. |
| 176 |
|
| 177 |
Reference: |
| 178 |
o W. H. Press, S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery, |
| 179 |
"Numerical recipes in C", 2nd ed., Cambridge University Press. |
| 180 |
Pages 896ff. |
| 181 |
""" |
| 182 |
# Adapted from biopython, which was adapted from bioperl |
| 183 |
global _crc64_table |
| 184 |
if _crc64_table is None: |
| 185 |
# Initialisation of CRC64 table |
| 186 |
table = [] |
| 187 |
for i in range(256): |
| 188 |
k = i |
| 189 |
part_h = 0 |
| 190 |
for j in range(8): |
| 191 |
rflag = k & 1 |
| 192 |
k >>= 1 |
| 193 |
if part_h & 1: |
| 194 |
k |= 1 << 31 # pragma: no cover |
| 195 |
part_h >>= 1 |
| 196 |
if rflag: |
| 197 |
part_h ^= 0xD8000000 |
| 198 |
table.append(part_h) |
| 199 |
_crc64_table = tuple(table) |
| 200 |
|
| 201 |
crcl = 0 |
| 202 |
crch = 0 |
| 203 |
for c in string: |
| 204 |
shr = (crch & 0xFF) << 24 |
| 205 |
temp1h = crch >> 8 |
| 206 |
temp1l = (crcl >> 8) | shr |
| 207 |
idx = (crcl ^ ord(c)) & 0xFF |
| 208 |
crch = temp1h ^ _crc64_table[idx] |
| 209 |
crcl = temp1l |
| 210 |
|
| 211 |
return "%08X%08X" % (crch, crcl) |
| 212 |
|
| 213 |
|
| 214 |
# End crc64 |
| 215 |
|
| 216 |
|
| 217 |
class ArgumentError(ValueError): |
| 218 |
"""A subclass of ValueError raised when a function receives an argument |
| 219 |
that has the right type but an inappropriate value, and the situation is |
| 220 |
not described by a more precise exception such as IndexError. The name of |
| 221 |
the argument or component at fault and (optionally) the value |
| 222 |
are also stored. |
| 223 |
""" |
| 224 |
|
| 225 |
def __init__(self, message: str, key: str, value: Optional[Any] = None) -> None: |
| 226 |
"""Args: |
| 227 |
- msg -- An error message. |
| 228 |
- key -- The name of the argument or component at fault. |
| 229 |
- value -- Optional value of the argument. |
| 230 |
""" |
| 231 |
ValueError.__init__(self, key, message) |
| 232 |
# Changed .message to .msg because of deprecation warning in python 2.6 |
| 233 |
self.msg = message |
| 234 |
self.key = key |
| 235 |
self.value = value |
| 236 |
|
| 237 |
|
| 238 |
# end class ArgumentError |