| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
import re |
| 29 |
import weakref |
| 30 |
import sys, zlib |
| 31 |
import os.path |
| 32 |
import warnings, traceback, linecache |
| 33 |
|
| 34 |
from .decorator import decorator |
| 35 |
|
| 36 |
from .. import param e |
| 37 |
from sympy import sympify |
| 38 |
|
| 39 |
|
| 40 |
def is_in(element, _list): |
| 41 |
"""Teste si l'élement est dans la liste, en effectuant un test d'identité (is) et non d'égalité (==).""" |
| 42 |
for elt in _list: |
| 43 |
if elt is element: |
| 44 |
return True |
| 45 |
return False |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
.""" |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
.""" |
| 55 |
|
| 56 |
|
| 57 |
def mreplace(main_string, list_of_strings, new_string = ""): |
| 58 |
"""Remplace, dans "main_string", toutes les sous-chaines de "list_of_strings", par la chaine "new_string".""" |
| 59 |
for old_string in list_of_strings: |
| 60 |
main_string = main_string.replace(old_string, new_string) |
| 61 |
return main_string |
| 62 |
|
| 63 |
def recursive_replace(main_string, old_string, new_string = "", max_loops = 10000, max_len = 1000000): |
| 64 |
"""Remplace, dans "main_string", la sous-chaîne "old_string" par "new_string", au besoin en plusieurs passes. |
| 65 |
|
| 66 |
En fin de processus, la sous-chaîne old_string ne subsiste plus dans la chaîne. |
| 67 |
Renvoie une erreur si le processus ne semble pas converger. |
| 68 |
(C'est en particulier le cas si old_string est strictement inclus dans new_string) |
| 69 |
|
| 70 |
La différence avec replace est claire sur cette exemple : |
| 71 |
>>> from wxgeometrie.pylib.fonctions import recursive_replace |
| 72 |
>>> "Hi HelloHello world world !".replace("Hello world", "") |
| 73 |
'Hi Hello world !' |
| 74 |
>>> recursive_replace("Hi HelloHello world world !", "Hello world", "") |
| 75 |
'Hi !' |
| 76 |
|
| 77 |
Il y a un cas particulier ou la sous-chaîne reste présente : |
| 78 |
>>> recursive_replace("Hi HelloHello world world !", "Hello world", "Hello world") |
| 79 |
'Hi HelloHello world world !' |
| 80 |
""" |
| 81 |
|
| 82 |
chaine = "" |
| 83 |
loops = 0 |
| 84 |
while chaine != main_string: |
| 85 |
loops += 1 |
| 86 |
chaine = main_string |
| 87 |
main_string = main_string.replace(old_string, new_string) |
| 88 |
if loops > max_loops: |
| 89 |
raise RuntimeError("Nombre de passes superieur au maximum autorise.") |
| 90 |
if len(main_string) > max_len: |
| 91 |
raise OverflowError("Taille de la chaine superieure au maximum autorise.") |
| 92 |
return main_string |
| 93 |
|
| 94 |
|
| 95 |
def recursive_mreplace(main_string, list_of_strings, new_string = "", max_loops = 10000, max_len = 1000000): |
| 96 |
"""Remplace, dans "main_string", toutes les sous-chaines de "list_of_strings" par "new_string", au besoin en plusieurs passes. |
| 97 |
|
| 98 |
En fin de processus, la sous-chaîne old_string ne subsiste plus dans la chaîne. |
| 99 |
Renvoie une erreur si le processus ne semble pas converger. |
| 100 |
|
| 101 |
Voir également recursive_replace() et mreplace(). |
| 102 |
|
| 103 |
Remarque: recursive_mreplace n'est pas équivalent des appels successifs de recursive_replace(). |
| 104 |
>>> from wxgeometrie.pylib.fonctions import recursive_replace, recursive_mreplace |
| 105 |
>>> s = "tbtbaoao" |
| 106 |
>>> s = recursive_mreplace(s, ("to", "ba")) |
| 107 |
>>> s |
| 108 |
'' |
| 109 |
>>> s="tbtbaoao" |
| 110 |
>>> for i in ("to", "ba"): |
| 111 |
... s = recursive_replace(s, i) |
| 112 |
>>> s |
| 113 |
'tbtoao' |
| 114 |
""" |
| 115 |
|
| 116 |
chaine = "" |
| 117 |
loops = 0 |
| 118 |
while chaine != main_string: |
| 119 |
loops += 1 |
| 120 |
chaine = main_string |
| 121 |
main_string = mreplace(main_string, list_of_strings, new_string) |
| 122 |
if loops > max_loops: |
| 123 |
raise RuntimeError("Nombre de passes superieur au maximum autorise.") |
| 124 |
if len(main_string) > max_len: |
| 125 |
raise OverflowError("Taille de la chaine superieure au maximum autorise.") |
| 126 |
return main_string |
| 127 |
|
| 128 |
|
| 129 |
def mfind(chaine, car): |
| 130 |
n = 0 |
| 131 |
l = [] |
| 132 |
while True: |
| 133 |
n = chaine.find(car, n) |
| 134 |
if n == -1: break |
| 135 |
l.append(n) |
| 136 |
n += 1 |
| 137 |
return l |
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
def msplit(main_string, list_of_separators): |
| 142 |
"""Découpe la chaine "main_string", selon les séparateurs définis dans "list_of_separators".""" |
| 143 |
return mreplace(main_string, list_of_separators[1:], list_of_separators[0]).split(list_of_separators[0]) |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
def removeend(main_string, *substrings): |
| 148 |
"Enlève les éventuelles occurences de substring en fin de chaine." |
| 149 |
if substrings and '' not in substrings: e. |
| 150 |
run = True |
| 151 |
while run: |
| 152 |
run = False |
| 153 |
for sub in substrings: |
| 154 |
if main_string.endswith(sub): |
| 155 |
main_string = main_string[:-len(sub)] |
| 156 |
run = True |
| 157 |
return main_string |
| 158 |
|
| 159 |
|
| 160 |
def removestart(main_string, *substrings): |
| 161 |
"Enlève les éventuelles occurences de substring en début de chaine." |
| 162 |
if substrings and '' not in substrings: e. |
| 163 |
run = True |
| 164 |
while run: |
| 165 |
run = False |
| 166 |
for sub in substrings: |
| 167 |
if main_string.startswith(sub): |
| 168 |
main_string = main_string[len(sub):] |
| 169 |
run = True |
| 170 |
return main_string |
| 171 |
|
| 172 |
|
| 173 |
def no_twin(liste): |
| 174 |
"""Elimine les doublons dans une liste. |
| 175 |
Si tous les élements de la liste sont 'hashables', mieux vaut utiliser la fonction set.""" |
| 176 |
dico = {} |
| 177 |
for elt in liste: |
| 178 |
dico[id(elt)] = elt |
| 179 |
return list(dico.values()) |
| 180 |
|
| 181 |
!? |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
def advanced_split(main_string, separator, keep_empty_str = False, symbols = "([{}])"): |
| 187 |
"""Découpe la chaine "main_string" de manière intelligente, |
| 188 |
en ignorant les séparateurs compris dans un groupe entre parenthèses, crochets, accolades, guillemets. |
| 189 |
Attention, separateur ne peut donc pas être une parenthèse, un crochet, une accolade ou un guillemet ! |
| 190 |
Par défaut, supprime également les chaines vides.""" |
| 191 |
in_string = False |
| 192 |
in_string_sep = "'" |
| 193 |
parentheses = 0 |
| 194 |
crochets = 0 |
| 195 |
accolades = 0 |
| 196 |
coupures = [-1] |
| 197 |
for i in range(len(main_string)): |
| 198 |
a = main_string[i] |
| 199 |
if a in ("'", '"'): |
| 200 |
if in_string: |
| 201 |
if in_string_sep == a: |
| 202 |
in_string = False |
| 203 |
else: |
| 204 |
in_string = True |
| 205 |
in_string_sep = a |
| 206 |
elif a in symbols: |
| 207 |
if a == "(" and not in_string: |
| 208 |
parentheses += 1 |
| 209 |
elif a == ")" and not in_string: |
| 210 |
parentheses -= 1 |
| 211 |
elif a == "[" and not in_string: |
| 212 |
crochets += 1 |
| 213 |
elif a == "]" and not in_string: |
| 214 |
crochets -= 1 |
| 215 |
elif a == "{" and not in_string: |
| 216 |
accolades += 1 |
| 217 |
elif a == "}" and not in_string: |
| 218 |
accolades -= 1 |
| 219 |
elif a == separator and not (in_string or parentheses or crochets or accolades) : |
| 220 |
coupures.append(i) |
| 221 |
coupures.append(None) |
| 222 |
|
| 223 |
|
| 224 |
return [main_string[i+1:j] for i, j in zip(coupures[:-1], coupures[1:]) if main_string[i+1:j] or keep_empty_str] |
| 225 |
|
| 226 |
|
| 227 |
def regsub(regular_exp, main_string, action = ""): |
| 228 |
"""Transforme la chaine "main_string" : |
| 229 |
Il applique aux parties vérifiant "regular_exp" le traitement "action". |
| 230 |
|
| 231 |
>>> from wxgeometrie.pylib.fonctions import regsub |
| 232 |
>>> regsub("[a-z]", "salut les amis !", "?") |
| 233 |
'????? ??? ???? !' |
| 234 |
>>> regsub("[a-z]+", "hello world !", lambda s: s[1:]) |
| 235 |
'ello orld !' |
| 236 |
""" |
| 237 |
if isinstance(action, str): |
| 238 |
return re.sub(regular_exp, action, main_string) |
| 239 |
else: |
| 240 |
return re.sub(regular_exp, lambda x: action(x.group(0)), main_string) |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
class WeakList(weakref.WeakValueDictionary): |
| 246 |
"""Une 'liste' de réferences faibles. |
| 247 |
|
| 248 |
Le terme 'liste' est trompeur, la syntaxe des listes de python n'est pas implémentée, |
| 249 |
exceptée les méthodes append(), et remove(), et la conversion en liste. |
| 250 |
|
| 251 |
En outre, le contenu s'obtient par la méthode values(). |
| 252 |
|
| 253 |
Note: |
| 254 |
L'implémentation de remove est un peu différente : |
| 255 |
'remove' utilise le comparateur 'is', et non "==", ce qui fait que remove([]) ne fera jamais rien, par exemple. |
| 256 |
(Il faut qu'il s'agisse du meme objet, et non d'un objet égal). |
| 257 |
Sinon, il faut utiliser compare_and_remove.""" |
| 258 |
|
| 259 |
def __init__(self): |
| 260 |
weakref.WeakValueDictionary.__init__(self) |
| 261 |
|
| 262 |
def append(self, valeur): |
| 263 |
u"Ajoute une valeur en fin de liste." |
| 264 |
self[max(self.keys(), default=0) + 1] = valeur |
| 265 |
|
| 266 |
def remove(self, valeur): |
| 267 |
"""Supprime la valeur de la liste. |
| 268 |
|
| 269 |
Un test d'identité (et non d'égalité) est effectué ('is' et non '=='). |
| 270 |
Si la valeur est présente plusieurs fois, elle n'est supprimée qu'une seule fois. |
| 271 |
Si la valeur n'est pas présente, une erreur de type ValueError est émise. |
| 272 |
""" |
| 273 |
for key, value in self.items(): |
| 274 |
if value is valeur: |
| 275 |
del self[key] t |
| 276 |
return |
| 277 |
raise ValueError(repr(valeur) + " is not in WeakList") |
| 278 |
|
| 279 |
def compare_and_remove(self, valeur): |
| 280 |
"""Supprime la valeur de la liste. |
| 281 |
|
| 282 |
Un test d'égalité est effectué ('==' et non 'is'). |
| 283 |
Si la valeur est présente plusieurs fois, elle n'est supprimée qu'une seule fois. |
| 284 |
Si la valeur n'est pas présente, une erreur de type ValueError est émise. |
| 285 |
""" |
| 286 |
for key, value in self.items(): |
| 287 |
if value == valeur: |
| 288 |
del self[key] t |
| 289 |
return |
| 290 |
raise ValueError(repr(valeur) + " not in WeakList") |
| 291 |
|
| 292 |
def remove_all(self, valeur): |
| 293 |
"""Supprime la valeur de la liste. |
| 294 |
|
| 295 |
Un test d'identité (et non d'égalité) est effectué ('is' et non '=='). |
| 296 |
Toutes les occurences de la valeur sont supprimées. |
| 297 |
Si la valeur n'est pas présente, aucune erreur n'est émise.""" |
| 298 |
for key, value in self.items(): |
| 299 |
if value is valeur: del self[key] t |
| 300 |
|
| 301 |
def compare_and_remove_all(self, valeur): |
| 302 |
"""Supprime la valeur de la liste. |
| 303 |
|
| 304 |
Un test d'égalité est effectué ('==' et non 'is'). |
| 305 |
Toutes les occurences de la valeur sont supprimées. |
| 306 |
Si la valeur n'est pas présente, aucune erreur n'est émise.""" |
| 307 |
for key, value in self.items(): |
| 308 |
if value == valeur: del self[key] t |
| 309 |
|
| 310 |
def __str__(self): |
| 311 |
return str(list(self.values())) + " (WeakList)" |
| 312 |
|
| 313 |
def __iter__(self): |
| 314 |
return iter(self.values()) |
| 315 |
|
| 316 |
def __getitem__(self, n): |
| 317 |
return list(self.values())[n] |
| 318 |
|
| 319 |
def __contains__(self, item): |
| 320 |
return item in self.values() |
| 321 |
|
| 322 |
|
| 323 |
class WeakMultiSet(weakref.WeakKeyDictionary): |
| 324 |
"""A WeakValueDictionary which keeps count of how many times an object was added. |
| 325 |
|
| 326 |
The interface implements only the methods remove() and add() |
| 327 |
to emulate a set. |
| 328 |
|
| 329 |
When an element is removed, the count is actually decrease. |
| 330 |
If count reaches 0, the element is discarded (key is removed). |
| 331 |
|
| 332 |
Additionnaly, method remove_completely() discard the element |
| 333 |
whatever the count. |
| 334 |
|
| 335 |
This is quite similar to collect.Counter, except that entries are deleted |
| 336 |
when count reaches 0, and weak refrences are used.""" |
| 337 |
def remove(self, elt): |
| 338 |
self[elt] -= 1 |
| 339 |
if self[elt] == 0: |
| 340 |
del self[elt] |
| 341 |
|
| 342 |
def add(self, elt): |
| 343 |
if elt in self: |
| 344 |
self[elt] += 1 |
| 345 |
else: |
| 346 |
self[elt] = 1 |
| 347 |
|
| 348 |
def remove_completely(self, elt): |
| 349 |
del self[elt] |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
def extract_error(chaine=''): |
| 354 |
lignes = [] |
| 355 |
if chaine: |
| 356 |
lignes.append(chaine) |
| 357 |
typ, val, tb = sys.exc_info() |
| 358 |
tb = traceback.extract_tb(tb) |
| 359 |
lignes.append('Traceback (most recent call last)') |
| 360 |
for fichier, ligne, fonction, code in tb: |
| 361 |
lignes.append(' File "%s", line %s, in %s' |
| 362 |
% (str(fichier), str(ligne), str(fonction))) |
| 363 |
if code is not None: |
| 364 |
lignes.append(' ' + str(code)) |
| 365 |
lignes.append(typ.__name__ + ": " + str(val)) |
| 366 |
lignes.append("Warning: this error was not raised.") |
| 367 |
return '\n'.join(lignes) |
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
def print_error(chaine=''): |
| 372 |
"""Affiche l'erreur sans interrompre le programme. |
| 373 |
C'est un alias de sys.excepthook, mais qui est plus souple avec les encodages. |
| 374 |
""" |
| 375 |
print(extract_error(chaine)) |
| 376 |
|
| 377 |
|
| 378 |
def rstrip_(s, end): |
| 379 |
"""Supprime récursivement 'end' de la fin de la chaîne 's'. |
| 380 |
|
| 381 |
>>> from wxgeometrie.pylib.fonctions import rstrip_ |
| 382 |
>>> rstrip_('blabla_suffixe_fixe_suffixe_suffixe', '_suffixe') |
| 383 |
'blabla_suffixe_fixe' |
| 384 |
|
| 385 |
Nota : |
| 386 |
* ne pas confondre avec str.rstrip() : |
| 387 |
>>> 'blabla_suffixe_fixe_suffixe_suffixe'.rstrip('_suffixe') |
| 388 |
'blabla' |
| 389 |
|
| 390 |
* si end == '', la chaîne de départ est retournée : |
| 391 |
>>> rstrip_('bonjour', '') |
| 392 |
'bonjour' |
| 393 |
""" |
| 394 |
if not end: |
| 395 |
return s |
| 396 |
i = -len(end) |
| 397 |
while s.endswith(end): |
| 398 |
s = s[:i] |
| 399 |
return s |
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
def rreplace(s, old, new, count): |
| 404 |
"""rreplace (s, old, new, count) -> string |
| 405 |
|
| 406 |
Return a copy of string S with the first count occurrences of substring |
| 407 |
old replaced by new, starting from right to left.""" |
| 408 |
return new.join(s.rsplit(old, count)) |
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
def split_geoname(name): |
| 413 |
"""Tente de décomposer un nom d'objet géométrique en plusieurs noms. |
| 414 |
|
| 415 |
Ex: |
| 416 |
1) "AB" -> ("A","B") |
| 417 |
2) "A12B" -> ("A12","B") |
| 418 |
3) "AB1" -> ("A","B1") |
| 419 |
4) "A'B\"" -> ("A'", "B\"") |
| 420 |
5) "ABC" -> ("A", "B", "C") |
| 421 |
""" |
| 422 |
|
| 423 |
return tuple(nom.strip() for nom in re.split("""([ ]*[A-Za-z][_]?[0-9"']*[ ]*)""", name) if nom) |
| 424 |
|
| 425 |
|
| 426 |
def convert_geoname(name, level = 0): |
| 427 |
"""Convertit le nom entré par l'utilisateur en un nom réellement interprétable. |
| 428 |
|
| 429 |
Une conversion de niveau 1 est appliquée dans les boîtes de dialogue. |
| 430 |
|
| 431 |
Une conversion de niveau 0 est appliquée dans la console.""" |
| 432 |
|
| 433 |
if level > 0: |
| 434 |
if level > 1: |
| 435 |
if " " not in name: |
| 436 |
name = " ".join(split_geoname) |
| 437 |
name = name.replace('"', "''") |
| 438 |
name = name.replace("'''", "_tierce") |
| 439 |
name = name.replace("''", "_seconde") |
| 440 |
name = name.replace("'", "_prime") |
| 441 |
name = name.replace("```", "_tierce") |
| 442 |
name = name.replace("``", "_seconde") |
| 443 |
name = name.replace("`", "_prime") |
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
def split_around_parenthesis(main_string, position = 0, leftbracket = "("): |
| 449 |
"""Coupe le premier groupe entre parentheses rencontré, en tenant compte des guillemets. |
| 450 |
|
| 451 |
'leftbracket' peut prendre les valeurs "(", "[" ou "{" |
| 452 |
La parenthese ouvrante du groupe sera la première trouvée à droite de 'position' |
| 453 |
Exemple: '1+4*(5+3*(2+7)+2-")")*7+(2-3)+4' -> ['1+4*', '(5+3*(2+7)+2-")")', '*7+(2-3)+4'] |
| 454 |
""" |
| 455 |
in_string = False |
| 456 |
in_string_sep = "'" |
| 457 |
position = main_string.find(leftbracket, position) |
| 458 |
if position == -1: |
| 459 |
return (main_string,) |
| 460 |
parentheses = 1 |
| 461 |
rightbracket = {"(": ")", "[": "]", "{": "}"}[leftbracket] |
| 462 |
prefixe = main_string[:position] |
| 463 |
chaine = main_string[position + 1:] |
| 464 |
for i in range(len(chaine)): |
| 465 |
a = chaine[i] |
| 466 |
if a in ("'", '"'): |
| 467 |
if in_string: |
| 468 |
if in_string_sep == a: |
| 469 |
in_string = False |
| 470 |
else: |
| 471 |
in_string = True |
| 472 |
in_string_sep = a |
| 473 |
elif a == leftbracket and not in_string: |
| 474 |
parentheses += 1 |
| 475 |
elif a == rightbracket and not in_string: |
| 476 |
parentheses -= 1 |
| 477 |
if parentheses == 0: |
| 478 |
chaine = chaine |
| 479 |
return (prefixe, leftbracket + chaine[:i + 1], chaine[i + 1:]) |
| 480 |
return (main_string,) pe. |
| 481 |
|
| 482 |
|
| 483 |
def find_closing_bracket(expr, start = 0, brackets = '{}'): |
| 484 |
expr_deb = expr[:min(len(expr), 30)] |
| 485 |
|
| 486 |
index = 0 |
| 487 |
balance = 1 |
| 488 |
|
| 489 |
|
| 490 |
string_type = None |
| 491 |
reg = re.compile('["' + brackets + "']") |
| 492 |
open_bracket = brackets[0] |
| 493 |
close_bracket = brackets[1] |
| 494 |
if start: |
| 495 |
expr = expr[start:] |
| 496 |
while balance: |
| 497 |
m = re.search(reg, expr) |
| 498 |
|
| 499 |
if m is None: |
| 500 |
break |
| 501 |
|
| 502 |
result = m.group() |
| 503 |
i = m.start() |
| 504 |
if result == open_bracket: |
| 505 |
if string_type is None: |
| 506 |
balance += 1 |
| 507 |
elif result == close_bracket: |
| 508 |
if string_type is None: |
| 509 |
balance -= 1 |
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
elif result in ("'", '"'): |
| 514 |
if string_type is None: |
| 515 |
if expr[i:].startswith(3*result): |
| 516 |
string_type = 3*result |
| 517 |
i += 2 |
| 518 |
else: |
| 519 |
string_type = result |
| 520 |
elif string_type == result: |
| 521 |
string_type = None |
| 522 |
elif string_type == 3*result: |
| 523 |
if expr[i:].startswith(3*result): |
| 524 |
string_type = None |
| 525 |
i += 2 |
| 526 |
|
| 527 |
i += 1 |
| 528 |
index += i |
| 529 |
expr = expr[i:] |
| 530 |
|
| 531 |
else: |
| 532 |
return start + index - 1 |
| 533 |
|
| 534 |
raise ValueError('unbalanced brackets (%s) while scanning %s...' %(balance, repr(expr_deb))) |
| 535 |
|
| 536 |
|
| 537 |
def warning(message, type_warning = Warning, level=0): |
| 538 |
if param.warning: |
| 539 |
warnings.warn(message, type_warning, stacklevel = (level + 3)) |
| 540 |
|
| 541 |
def deprecation(message, level=0): |
| 542 |
warnings.warn(message, DeprecationWarning, stacklevel = (level + 3)) |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
def path2(chemin): |
| 549 |
"""Transforme le chemin en remplaçant les / et \\ selon le séparateur utilisé par le système. |
| 550 |
|
| 551 |
% est remplacé par l'emplacement du programme (contenu dans param.EMPLACEMENT). |
| 552 |
Exemple : path2("%/wxgeometrie/images/archives/old.png"). |
| 553 |
~ fait référence au répertoire personnel de l'utilisateur (ex: /home/SteveB/ sous Linux. |
| 554 |
""" |
| 555 |
return os.path.normpath(os.path.expanduser(chemin.replace("%", param.EMPLACEMENT))) |
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
e, |
| 560 |
nt. |
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
. |
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
. |
| 585 |
|
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
. |
| 598 |
|
| 599 |
|
| 600 |
.""" |
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
|
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
|
| 648 |
|
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
def debug(*messages): |
| 675 |
"""Affiche un (ou plusieurs) message(s) si le déboguage est actif.""" |
| 676 |
if param.debug: |
| 677 |
for message in messages: |
| 678 |
print(message) |
| 679 |
|
| 680 |
@decorator |
| 681 |
def trace(f, *args, **kw): |
| 682 |
if param.debug: |
| 683 |
print("Calling %s with args %s, %s" % (f.__name__, args, kw)) |
| 684 |
return f(*args, **kw) |
| 685 |
|
| 686 |
@decorator |
| 687 |
def full_trace(f, *args, **kw): |
| 688 |
if param.debug: |
| 689 |
print('** Debugging info **') |
| 690 |
traceback.print_stack() |
| 691 |
print("Calling %s with args %s, %s" % (f.__name__, args, kw)) |
| 692 |
print('-------------------\n') |
| 693 |
return f(*args, **kw) |
| 694 |
|
| 695 |
|
| 696 |
def deprecated(message = ''): |
| 697 |
"A decorator for deprecated functions" |
| 698 |
@decorator |
| 699 |
def _deprecated(func, *args, **kw): |
| 700 |
"A decorator for deprecated functions" |
| 701 |
warnings.warn('\n'.join(('La fonction %r est desuette.' %func.__name__, message)), |
| 702 |
DeprecationWarning, stacklevel = 3) |
| 703 |
return func(*args, **kw) |
| 704 |
return _deprecated |
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
def traceit(frame, event, arg): |
| 719 |
"""'Trace' (suit) une fonction python. |
| 720 |
|
| 721 |
Usage: |
| 722 |
import sys |
| 723 |
sys.settrace(traceit)""" |
| 724 |
if event == "line": |
| 725 |
lineno = frame.f_lineno |
| 726 |
filename = frame.f_globals["__file__"] |
| 727 |
if (filename.endswith(".pyc") or |
| 728 |
filename.endswith(".pyo")): |
| 729 |
filename = filename[:-1] |
| 730 |
name = frame.f_globals["__name__"] |
| 731 |
line = linecache.getline(filename, lineno) |
| 732 |
print("%s:%s: %s" % (name, lineno, line.rstrip())) |
| 733 |
return traceit |
| 734 |
|
| 735 |
|
| 736 |
def tracer_(booleen = True): |
| 737 |
if booleen: |
| 738 |
sys.settrace(traceit) |
| 739 |
else: |
| 740 |
sys.settrace(None) |
| 741 |
|
| 742 |
|
| 743 |
def property2(fonction): |
| 744 |
return property(fonction, fonction) |
| 745 |
|
| 746 |
|
| 747 |
def _archive(string): |
| 748 |
return zlib.compress(string.encode('utf8')) |
| 749 |
|
| 750 |
def _extract(data): |
| 751 |
return zlib.decompress(data).decode('utf8') |
| 752 |
|
| 753 |
|
| 754 |
class CompressedList(list): |
| 755 |
def append(self, s): |
| 756 |
list.append(self, _archive(s)) |
| 757 |
|
| 758 |
def __getitem__(self, i): |
| 759 |
return _extract(list.__getitem__(self, i)) |
| 760 |
|
| 761 |
def __setitem__(self, i, s): |
| 762 |
list.__setitem__(self, i, _archive(s)) |
| 763 |
|
| 764 |
def remove(self, s): |
| 765 |
list.remove(self, _archive(s)) |
| 766 |
|
| 767 |
def count(self, s): |
| 768 |
return list.count(self, _archive(s)) |
| 769 |
|
| 770 |
def extend(self, iterable): |
| 771 |
list.extend(self, (_archive(s) for s in iterable)) |
| 772 |
|
| 773 |
def index(self, s): |
| 774 |
list.index(self, _archive(s)) |
| 775 |
|
| 776 |
def insert(self, i, s): |
| 777 |
list.insert(self, i, _archive(s)) |
| 778 |
|
| 779 |
def pop(self, i = -1): |
| 780 |
return _extract(list.pop(self, i)) |
| 781 |
|
| 782 |
|
| 783 |
def pstfunc(chaine): |
| 784 |
args = [] |
| 785 |
dict_op = {'mul':'*','add':'+','exp':'**','div':'/','sub':'-'} |
| 786 |
dict_fn = {'ln':'ln'} |
| 787 |
|
| 788 |
def code_arg(s): |
| 789 |
return '(' + str(sympify(s)) + ')' |
| 790 |
|
| 791 |
for s in chaine.split(' '): |
| 792 |
if s in dict_op: |
| 793 |
args = [code_arg(dict_op[s].join(args))] |
| 794 |
elif s in dict_fn: |
| 795 |
assert len(args) == 1 |
| 796 |
args = [code_arg(dict_fn + '(' + args[0] + ')')] |
| 797 |
elif s: |
| 798 |
args.append(code_arg(s)) |
| 799 |
assert len(args) == 1 |
| 800 |
return args[0] |
| 801 |
|
| 802 |
|
| 803 |
class NoArgument(object): |
| 804 |
'''Utilisé comme valeur par défaut, pour savoir si un argument optionnel |
| 805 |
a été passé. Une seule instance peut-être crée.''' |
| 806 |
__instance = None |
| 807 |
|
| 808 |
def __new__(cls): |
| 809 |
if cls.__instance is None: |
| 810 |
cls.__instance = object.__new__(cls) |
| 811 |
return cls.__instance |
| 812 |
|
| 813 |
no_argument = NoArgument() |
| 814 |
|
| 815 |
|
| 816 |
|
| 817 |
class OrderedDict(dict): |
| 818 |
def __init__(self, seq = ()): |
| 819 |
self.__keys = [] |
| 820 |
dict.__init__(self) |
| 821 |
for key, val in seq: |
| 822 |
self[key] = val |
| 823 |
|
| 824 |
def __setitem__(self, key, value): |
| 825 |
if key not in self: |
| 826 |
self.__keys.append(key) |
| 827 |
dict.__setitem__(self, key, value) |
| 828 |
|
| 829 |
def __delitem__(self, key): |
| 830 |
dict.__delitem__(self, key) |
| 831 |
self.__keys.remove(key) |
| 832 |
|
| 833 |
def __iter__(self): |
| 834 |
return iter(self.__keys) |
| 835 |
|
| 836 |
def __repr__(self): |
| 837 |
return "MyOrderedDict(%s)"%repr(list(self.items())) |
| 838 |
|
| 839 |
def keys(self): |
| 840 |
return self.__keys[:] |
| 841 |
|
| 842 |
def values(self): |
| 843 |
return [self[key] for key in self.__keys] |
| 844 |
|
| 845 |
def items(self): |
| 846 |
return [(key, self[key]) for key in self.__keys] |
| 847 |
|
| 848 |
def copy(self): |
| 849 |
return self.__class__(iter(self.items())) |
| 850 |
|
| 851 |
def iterkeys(self): |
| 852 |
return iter(self) |
| 853 |
|
| 854 |
def iteritems(self): |
| 855 |
return ((key, self[key]) for key in self.__keys) |
| 856 |
|
| 857 |
def itervalues(self): |
| 858 |
return (self[key] for key in self.__keys) |
| 859 |
|
| 860 |
def update(self, E, **F): |
| 861 |
if hasattr(E, 'keys'): |
| 862 |
for k in E: |
| 863 |
self[k] = E[k] |
| 864 |
else: |
| 865 |
for (k, v) in E: |
| 866 |
self[k] = v |
| 867 |
for k in F: |
| 868 |
self[k] = F[k] |
| 869 |
|
| 870 |
def setdefaut(self, k, d = None): |
| 871 |
if k not in self: |
| 872 |
self[k] = d |
| 873 |
return self[k] |
| 874 |
|
| 875 |
def clear(self): |
| 876 |
del self.__keys[:] |
| 877 |
dict.clear(self) |
| 878 |
|
| 879 |
def pop(self, k, d=no_argument): |
| 880 |
try: |
| 881 |
v = dict.pop(self, k) |
| 882 |
self.__keys.remove(k) |
| 883 |
return v |
| 884 |
except KeyError: |
| 885 |
if d is no_argument: |
| 886 |
raise |
| 887 |
return d |
| 888 |
|
| 889 |
def __reversed__(self): |
| 890 |
return reversed(self.__keys) |
| 891 |
|
| 892 |
def popitem(self): |
| 893 |
if not self: |
| 894 |
raise KeyError('dictionary is empty') |
| 895 |
key = self.__keys.pop() |
| 896 |
value = dict.pop(self, key) |
| 897 |
return key, value |