-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathutils.py
More file actions
1569 lines (1290 loc) · 49.7 KB
/
utils.py
File metadata and controls
1569 lines (1290 loc) · 49.7 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utility functions useful in the implementation and testing of the Synapse client.
"""
import base64
import collections.abc
import datetime
import errno
import gc
import hashlib
import importlib
import inspect
import logging
import numbers
import os
import platform
import random
import re
import sys
import tempfile
import threading
import typing
import urllib.parse as urllib_parse
import uuid
import warnings
import zipfile
from dataclasses import asdict, fields, is_dataclass
from email.message import Message
from typing import TYPE_CHECKING, List, Optional, TypeVar
import requests
from deprecated import deprecated
from opentelemetry import trace
from tqdm import tqdm
from synapseclient.core.logging_setup import DEFAULT_LOGGER_NAME
if TYPE_CHECKING:
from synapseclient.models import Column, Evaluation, File, Folder, Project, Table
from synapseclient.models.dataset import EntityRef
R = TypeVar("R")
UNIX_EPOCH = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
ISO_FORMAT = "%Y-%m-%dT%H:%M:%S.000Z"
ISO_FORMAT_MICROS = "%Y-%m-%dT%H:%M:%S.%fZ"
GB = 2**30
MB = 2**20
KB = 2**10
BUFFER_SIZE = 8 * KB
tracer = trace.get_tracer("synapseclient")
SLASH_PREFIX_REGEX = re.compile(r"\/[A-Za-z]:")
# Set up logging
LOGGER_NAME = DEFAULT_LOGGER_NAME
LOGGER = logging.getLogger(LOGGER_NAME)
@tracer.start_as_current_span("synapse.util.md5")
def md5_for_file(
filename: str,
block_size: int = 2 * MB,
callback: typing.Callable = None,
progress_bar: Optional[tqdm] = None,
file_name: Optional[str] = None,
):
"""
Calculates the MD5 of the given file.
See source <http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python>.
Arguments:
filename: The file to read in
block_size: How much of the file to read in at once (bytes).
Defaults to 2 MB
callback: The callback function that help us show loading spinner on terminal.
Defaults to None
progress_bar: An optional TQDM progress bar to update
file_name: An optional name for the file, used in tracing attributes
Returns:
The MD5 Checksum
"""
loop_iteration = 0
data_read = 0
md5 = hashlib.new("md5", usedforsecurity=False) # nosec
with open(filename, "rb") as f:
while True:
loop_iteration += 1
if callback:
callback()
data = f.read(block_size)
if not data:
if progress_bar:
progress_bar.update(progress_bar.total - progress_bar.n)
progress_bar.refresh()
progress_bar.close()
break
md5.update(data)
data_length = len(data)
data_read += data_length
if progress_bar:
progress_bar.update(data_length)
del data
# Garbage collect every 100 iterations
if loop_iteration % 100 == 0:
gc.collect()
trace.get_current_span().set_attribute("synapse.md5.size", data_read)
trace.get_current_span().set_attribute(
"synapse.file.name", file_name or os.path.basename(filename) or "unknown_file"
)
return md5
def md5_for_file_hex(
filename: str, block_size: int = 2 * MB, callback: typing.Callable = None
) -> str:
"""
Calculates the MD5 of the given file.
See source <http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python>.
Arguments:
filename: The file to read in
block_size: How much of the file to read in at once (bytes).
Defaults to 2 MB
callback: The callback function that help us show loading spinner on terminal.
Defaults to None
Returns:
The MD5 Checksum
"""
return md5_for_file(filename, block_size, callback).hexdigest()
@tracer.start_as_current_span("synapse.util.md5")
def md5_fn(part, _) -> str:
"""Calculate the MD5 of a file-like object.
Arguments:
part: A file-like object to read from.
Returns:
The MD5 Checksum
"""
md5 = hashlib.new("md5", usedforsecurity=False) # nosec
md5.update(part)
trace.get_current_span().set_attribute("synapse.md5.size", len(part))
trace.get_current_span().set_attribute("synapse.file.name", "partial_file_md5")
return md5.hexdigest()
def download_file(url: str, localFilepath: str = None) -> str:
"""
Downloads a remote file.
Arguments:
localFilePath: May be None, in which case a temporary file is created
Returns:
localFilePath: The path to the downloaded file
"""
f = None
try:
if localFilepath:
dir = os.path.dirname(localFilepath)
if not os.path.exists(dir):
os.makedirs(dir)
f = open(localFilepath, "wb")
else:
f = tempfile.NamedTemporaryFile(delete=False)
localFilepath = f.name
r = requests.get(url, stream=True)
toBeTransferred = float(r.headers["content-length"])
for nChunks, chunk in enumerate(r.iter_content(chunk_size=1024 * 10)):
if chunk:
f.write(chunk)
printTransferProgress(nChunks * 1024 * 10, toBeTransferred)
finally:
if f:
f.close()
printTransferProgress(toBeTransferred, toBeTransferred)
return localFilepath
def extract_filename(content_disposition_header, default_filename=None):
"""
Extract a filename from an HTTP content-disposition header field.
See [this memo](http://tools.ietf.org/html/rfc6266) and
[this package](http://pypi.python.org/pypi/rfc6266)
for cryptic details.
"""
if not content_disposition_header:
return default_filename
message = Message()
message.add_header("content-disposition", content_disposition_header)
return message.get_filename(failobj=default_filename)
def extract_user_name(profile):
"""
Extract a displayable user name from a user's profile
"""
if "userName" in profile and profile["userName"]:
return profile["userName"]
elif "displayName" in profile and profile["displayName"]:
return profile["displayName"]
else:
if (
"firstName" in profile
and profile["firstName"]
and "lastName" in profile
and profile["lastName"]
):
return profile["firstName"] + " " + profile["lastName"]
elif "lastName" in profile and profile["lastName"]:
return profile["lastName"]
elif "firstName" in profile and profile["firstName"]:
return profile["firstName"]
else:
return str(profile.get("id", "Unknown-user"))
def _get_from_members_items_or_properties(obj, key):
if hasattr(obj, key):
return getattr(obj, key)
try:
if hasattr(obj, "properties") and key in obj.properties:
return obj.properties[key]
if key in obj:
return obj[key]
else:
return obj["properties"][key]
except (KeyError, TypeError):
# We cannot get the key from this obj. So this case will be treated as key not found.
pass
return None
# TODO: what does this do on an unsaved Synapse Entity object?
def id_of(obj: typing.Union[str, collections.abc.Mapping, numbers.Number]) -> str:
"""
Try to figure out the Synapse ID of the given object.
Arguments:
obj: May be a string, Entity object, or dictionary
Returns:
The ID
Raises:
ValueError: if the object doesn't have an ID
"""
if isinstance(obj, str):
return str(obj)
if isinstance(obj, numbers.Number):
return str(obj)
id_attr_names = [
"id",
"ownerId",
"tableId",
] # possible attribute names for a synapse Id
for attribute_name in id_attr_names:
syn_id = _get_from_members_items_or_properties(obj, attribute_name)
if syn_id is not None:
return str(syn_id)
raise ValueError("Invalid parameters: couldn't find id of " + str(obj))
def validate_submission_id(
submission_id: typing.Union[str, int, collections.abc.Mapping],
) -> str:
"""
Ensures that a given submission ID is either an integer or a string that
can be converted to an integer. Version notation is not supported for submission
IDs, therefore decimals are not allowed.
Arguments:
submission_id: The submission ID to validate
Returns:
The submission ID as a string
"""
if isinstance(submission_id, int):
return str(submission_id)
elif isinstance(submission_id, str) and submission_id.isdigit():
return submission_id
elif isinstance(submission_id, collections.abc.Mapping):
syn_id = _get_from_members_items_or_properties(submission_id, "id")
if syn_id is not None:
return validate_submission_id(syn_id)
else:
try:
int_submission_id = int(float(submission_id))
except ValueError:
raise ValueError(
f"Submission ID '{submission_id}' is not a valid submission ID. Please use digits only."
)
LOGGER.warning(
f"Submission ID '{submission_id}' contains decimals which are not supported. "
f"Submission ID will be converted to '{int_submission_id}'."
)
return str(int_submission_id)
def concrete_type_of(obj: collections.abc.Mapping):
"""
Return the concrete type of an object representing a Synapse entity.
This is meant to operate either against an actual Entity object, or the lighter
weight dictionary returned by Synapse#getChildren, both of which are Mappings.
"""
concrete_type = None
if isinstance(obj, collections.abc.Mapping):
for key in ("concreteType", "type"):
concrete_type = obj.get(key)
if concrete_type:
break
if not isinstance(concrete_type, str) or not concrete_type.startswith(
"org.sagebionetworks.repo.model"
):
raise ValueError("Unable to determine concreteType")
return concrete_type
def is_in_path(id: str, path: collections.abc.Mapping) -> bool:
"""Determines whether id is in the path as returned from /entity/{id}/path
Arguments:
id: synapse id string
path: object as returned from '/entity/{id}/path'
Returns:
True or False
"""
return id in [item["id"] for item in path["path"]]
def get_properties(entity):
"""Returns the dictionary of properties of the given Entity."""
return entity.properties if hasattr(entity, "properties") else entity
def is_url(s):
"""Return True if the string appears to be a valid URL."""
if isinstance(s, str):
try:
url_parts = urllib_parse.urlsplit(s)
# looks like a Windows drive letter?
if len(url_parts.scheme) == 1 and url_parts.scheme.isalpha():
return False
if url_parts.scheme == "file" and bool(url_parts.path):
return True
return bool(url_parts.scheme) and bool(url_parts.netloc)
except Exception:
return False
return False
def as_url(s):
"""Tries to convert the input into a proper URL."""
url_parts = urllib_parse.urlsplit(s)
# Windows drive letter?
if len(url_parts.scheme) == 1 and url_parts.scheme.isalpha():
return "file:///%s" % str(s).replace("\\", "/")
if url_parts.scheme:
return url_parts.geturl()
else:
return "file://%s" % str(s)
def guess_file_name(string):
"""Tries to derive a filename from an arbitrary string."""
path = normalize_path(urllib_parse.urlparse(string).path)
tokens = [x for x in path.split("/") if x != ""]
if len(tokens) > 0:
return tokens[-1]
# Try scrubbing the path of illegal characters
if len(path) > 0:
path = re.sub(r"[^a-zA-Z0-9_.+() -]", "", path)
if len(path) > 0:
return path
raise ValueError("Could not derive a name from %s" % string)
def normalize_path(path):
"""Transforms a path into an absolute path with forward slashes only."""
if path is None:
return None
return re.sub(r"\\", "/", os.path.normcase(os.path.abspath(path)))
def equal_paths(path1, path2):
"""
Compare file paths in a platform neutral way
"""
return normalize_path(path1) == normalize_path(path2)
def file_url_to_path(url: str, verify_exists: bool = False) -> typing.Union[str, None]:
"""
Convert a file URL to a path, handling some odd cases around Windows paths.
Arguments:
url: a file URL
verify_exists: If true, return an populated dict only if the resulting file
path exists on the local file system.
Returns:
a path or None if the URL is not a file URL.
"""
parts = urllib_parse.urlsplit(url)
if parts.scheme == "file" or parts.scheme == "":
path = parts.path
# A windows file URL, for example file:///c:/WINDOWS/asdf.txt
# will get back a path of: /c:/WINDOWS/asdf.txt, which we need to fix by
# lopping off the leading slash character. Apparently, the Python developers
# think this is not a bug: http://bugs.python.org/issue7965
if SLASH_PREFIX_REGEX.match(path):
path = path[1:]
if os.path.exists(path) or not verify_exists:
return path
return None
def is_same_base_url(url1: str, url2: str) -> bool:
"""Compares two urls to see if they are the same excluding up to the base path
Arguments:
url1: a URL
url2: a second URL
Returns:
A Boolean
"""
url1 = urllib_parse.urlsplit(url1)
url2 = urllib_parse.urlsplit(url2)
return url1.scheme == url2.scheme and url1.hostname == url2.hostname
def is_synapse_id_str(obj: str) -> typing.Union[str, None]:
"""If the input is a Synapse ID return it, otherwise return None"""
if isinstance(obj, str):
m = re.match(r"(syn\d+(\.\d+)?$)", obj)
if m:
return m.group(1)
return None
def get_synid_and_version(
obj: typing.Union[str, collections.abc.Mapping],
) -> typing.Tuple[str, typing.Union[int, None]]:
"""Extract the Synapse ID and version number from input entity
Arguments:
obj: May be a string, Entity object, or dictionary.
Returns:
A tuple containing the synapse ID and version number,
where the version number may be an integer or None if
the input object does not contain a versonNumber or
.version notation (if string).
Example: Get synID and version from string object
Extract the synID and version number of the entity string ID
from synapseclient.core import utils
utils.get_synid_and_version("syn123.4")
The call above will return the following tuple:
('syn123', 4)
"""
if isinstance(obj, str):
synapse_id_and_version = is_synapse_id_str(obj)
if not synapse_id_and_version:
raise ValueError("The input string was not determined to be a syn ID.")
m = re.match(r"(syn\d+)(?:\.(\d+))?", synapse_id_and_version)
id = m.group(1)
version = int(m.group(2)) if m.group(2) is not None else m.group(2)
return id, version
id = id_of(obj)
version = None
if "versionNumber" in obj:
version = obj["versionNumber"]
return id, version
def bool_or_none(input_value: str) -> typing.Union[bool, None]:
"""
Attempts to convert a string to a bool. Returns None if it fails.
Arguments:
input_value: The string to convert to a bool
Returns:
The bool or None if the conversion fails
"""
if input_value is None or input_value == "":
return None
return_value = None
if input_value.lower() == "true":
return_value = True
elif input_value.lower() == "false":
return_value = False
return return_value
def datetime_or_none(datetime_str: str) -> typing.Union[datetime.datetime, None]:
"""Attempts to convert a string to a datetime object. Returns None if it fails.
Some of the expected formats of datetime_str are:
- 2023-12-04T07:00:00Z
- 2001-01-01 15:00:00+07:00
- 2001-01-01 15:00:00-07:00
- 2023-12-04 07:00:00+00:00
- 2019-01-01
Arguments:
datetime_str: The string to convert to a datetime object
Returns:
The datetime object or None if the conversion fails
"""
try:
return datetime.datetime.fromisoformat(datetime_str.replace("Z", "+00:00"))
except Exception:
return None
def is_date(dt):
"""Objects of class datetime.date and datetime.datetime will be recognized as dates"""
return isinstance(dt, datetime.date) or isinstance(dt, datetime.datetime)
def to_list(value):
"""Convert the value (an iterable or a scalar value) to a list."""
if isinstance(value, collections.abc.Iterable) and not isinstance(value, str):
values = []
for val in value:
possible_datetime = None
if isinstance(val, str):
possible_datetime = datetime_or_none(value)
values.append(val if possible_datetime is None else possible_datetime)
return values
else:
possible_datetime = None
if isinstance(value, str):
possible_datetime = datetime_or_none(value)
return [value if possible_datetime is None else possible_datetime]
def _to_iterable(value):
"""Convert the value (an iterable or a scalar value) to an iterable."""
if isinstance(value, collections.abc.Iterable):
return value
return (value,)
def make_bogus_uuid_file() -> str:
"""
Makes a bogus test file with a uuid4 string for testing. It is the caller's
responsibility to clean up the file when finished.
Returns:
The name of the file
"""
data = uuid.uuid4()
f = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)
try:
f.write(str(data))
f.write("\n")
finally:
f.close()
return normalize_path(f.name)
def make_bogus_data_file(n: int = 100, seed: int = None) -> str:
"""
Makes a bogus data file for testing. It is the caller's responsibility
to clean up the file when finished.
Arguments:
n: How many random floating point numbers to be written into the file,
separated by commas
seed: Random seed for the random numbers
Returns:
The name of the file
"""
if seed is not None:
random.seed(seed)
data = [random.gauss(mu=0.0, sigma=1.0) for i in range(n)]
f = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)
try:
f.write(", ".join(str(n) for n in data))
f.write("\n")
finally:
f.close()
return normalize_path(f.name)
def make_bogus_binary_file(
n: int = 1 * KB, filepath: str = None, printprogress: bool = False
) -> str:
"""
Makes a bogus binary data file for testing. It is the caller's responsibility
to clean up the file when finished.
Arguments:
n: How many bytes to write
filepath: Where to write the data
printprogress: Toggle printing of progress
Returns:
The name of the file
"""
progress_bar = (
tqdm(
desc=f"Generating {filepath}",
unit_scale=True,
total=n,
smoothing=0,
unit="B",
leave=None,
)
if printprogress
else None
)
with (
open(filepath, "wb")
if filepath
else tempfile.NamedTemporaryFile(mode="wb", suffix=".dat", delete=False)
) as f:
if not filepath:
filepath = f.name
remaining = n
while remaining > 0:
buff_size = int(min(remaining, 1 * KB))
f.write(os.urandom(buff_size))
if progress_bar:
progress_bar.update(buff_size)
remaining -= buff_size
if progress_bar:
progress_bar.update(progress_bar.total - progress_bar.n)
progress_bar.refresh()
progress_bar.close()
return normalize_path(filepath)
def to_unix_epoch_time(dt: typing.Union[datetime.date, datetime.datetime, str]) -> int:
"""
Convert either [datetime.date or datetime.datetime objects](http://docs.python.org/2/library/datetime.html) to UNIX time.
"""
if type(dt) == str:
dt = datetime.datetime.fromisoformat(dt.replace("Z", "+00:00"))
if type(dt) == datetime.date:
current_timezone = datetime.datetime.now().astimezone().tzinfo
datetime_utc = datetime.datetime.combine(dt, datetime.time(0, 0, 0, 0)).replace(
tzinfo=current_timezone
)
else:
# If the datetime is not timezone aware, assume it is in the local timezone.
# This is required in order for windows to work with the `astimezone` method.
if dt.tzinfo is None:
current_timezone = datetime.datetime.now().astimezone().tzinfo
dt = dt.replace(tzinfo=current_timezone)
datetime_utc = dt.astimezone(datetime.timezone.utc)
return int((datetime_utc - UNIX_EPOCH).total_seconds() * 1000)
def to_unix_epoch_time_secs(
dt: typing.Union[datetime.date, datetime.datetime],
) -> float:
"""
Convert either [datetime.date or datetime.datetime objects](http://docs.python.org/2/library/datetime.html) to UNIX time.
"""
if type(dt) == datetime.date:
current_timezone = datetime.datetime.now().astimezone().tzinfo
datetime_utc = datetime.datetime.combine(dt, datetime.time(0, 0, 0, 0)).replace(
tzinfo=current_timezone
)
else:
# If the datetime is not timezone aware, assume it is in the local timezone.
# This is required in order for windows to work with the `astimezone` method.
if dt.tzinfo is None:
current_timezone = datetime.datetime.now().astimezone().tzinfo
dt = dt.replace(tzinfo=current_timezone)
datetime_utc = dt.astimezone(datetime.timezone.utc)
return (datetime_utc - UNIX_EPOCH).total_seconds()
def from_unix_epoch_time_secs(secs):
"""Returns a Datetime object given milliseconds since midnight Jan 1, 1970."""
if isinstance(secs, str):
secs = float(secs)
# utcfromtimestamp() fails for negative values (dates before 1970-1-1) on Windows
# so, here's a hack that enables ancient events, such as Chris's birthday to be
# converted from milliseconds since the UNIX epoch to higher level Datetime objects. Ha!
if platform.system() == "Windows" and secs < 0:
mirror_date = datetime.datetime.utcfromtimestamp(abs(secs)).replace(
tzinfo=datetime.timezone.utc
)
result = (UNIX_EPOCH - (mirror_date - UNIX_EPOCH)).replace(
tzinfo=datetime.timezone.utc
)
return result
datetime_instance = datetime.datetime.utcfromtimestamp(secs).replace(
tzinfo=datetime.timezone.utc
)
return datetime_instance
def from_unix_epoch_time(ms) -> datetime.datetime:
"""Returns a Datetime object given milliseconds since midnight Jan 1, 1970."""
if isinstance(ms, str):
ms = float(ms)
return from_unix_epoch_time_secs(ms / 1000.0)
def datetime_to_iso(
dt: datetime.datetime, sep: str = "T", include_milliseconds_if_zero: bool = True
) -> str:
"""
Round microseconds to milliseconds (as expected by older clients) and add back
the "Z" at the end.
See: http://stackoverflow.com/questions/30266188/how-to-convert-date-string-to-iso8601-standard
Arguments:
dt: The datetime to convert
sep: Seperator character to use.
include_milliseconds_if_zero: Whether or not to include millseconds in this result
if the number of millseconds is 0.
Returns:
The formatted string.
"""
fmt = (
"{time.year:04}-{time.month:02}-{time.day:02}"
"{sep}{time.hour:02}:{time.minute:02}:{time.second:02}.{millisecond:03}{tz}"
)
fmt_no_mills = (
"{time.year:04}-{time.month:02}-{time.day:02}"
"{sep}{time.hour:02}:{time.minute:02}:{time.second:02}{tz}"
)
if dt.microsecond >= 999500:
dt -= datetime.timedelta(microseconds=dt.microsecond)
dt += datetime.timedelta(seconds=1)
rounded_microseconds = int(round(dt.microsecond / 1000.0))
if include_milliseconds_if_zero or rounded_microseconds:
return fmt.format(time=dt, millisecond=rounded_microseconds, tz="Z", sep=sep)
else:
return fmt_no_mills.format(
time=dt, millisecond=rounded_microseconds, tz="Z", sep=sep
)
def iso_to_datetime(iso_time):
return datetime.datetime.strptime(iso_time, ISO_FORMAT_MICROS)
def format_time_interval(seconds):
"""
Format a time interval given in seconds to a readable value,
e.g. \"5 minutes, 37 seconds\".
"""
periods = (
("year", 60 * 60 * 24 * 365),
("month", 60 * 60 * 24 * 30),
("day", 60 * 60 * 24),
("hour", 60 * 60),
("minute", 60),
("second", 1),
)
result = []
for period_name, period_seconds in periods:
if seconds > period_seconds or period_name == "second":
period_value, seconds = divmod(seconds, period_seconds)
if period_value > 0 or period_name == "second":
if period_value == 1:
result.append("%d %s" % (period_value, period_name))
else:
result.append("%d %ss" % (period_value, period_name))
return ", ".join(result)
def _find_used(activity, predicate):
"""Finds a particular used resource in an activity that matches a predicate."""
for resource in activity["used"]:
if predicate(resource):
return resource
return None
def itersubclasses(cls, _seen=None):
"""
<http://code.activestate.com/recipes/576949/> (r3)
itersubclasses(cls)
Generator over all subclasses of a given class, in depth first order.
>>> list(itersubclasses(int)) == [bool]
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in itersubclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS
['type', ...'tuple', ...]
"""
if not isinstance(cls, type):
raise TypeError(
"itersubclasses must be called with " "new-style classes, not %.100r" % cls
)
if _seen is None:
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError: # fails only when cls is type
subs = cls.__subclasses__(cls)
for sub in subs:
if sub not in _seen:
_seen.add(sub)
yield sub
for inner_sub in itersubclasses(sub, _seen):
yield inner_sub
def normalize_whitespace(s):
"""
Strips the string and replace all whitespace sequences and other
non-printable characters with a single space.
"""
assert isinstance(s, str)
return re.sub(r"[\x00-\x20\s]+", " ", s.strip())
def normalize_lines(s):
assert isinstance(s, str)
s2 = re.sub(r"[\t ]*\n[\t ]*", "\n", s.strip())
return re.sub(r"[\t ]+", " ", s2)
def _synapse_error_msg(ex):
"""
Format a human readable error message
"""
if isinstance(ex, str):
return ex
# one line for the root exception and then an additional line per chained cause
error_str = ""
depth = 0
while ex:
error_str += (
"\n"
+ (" " * depth)
+ ("caused by " if depth > 0 else "")
+ ex.__class__.__name__
+ ": "
+ str(ex)
)
ex = ex.__cause__
if ex:
depth += 1
else:
break
return error_str + "\n\n"
def _limit_and_offset(uri, limit=None, offset=None):
"""
Set limit and/or offset query parameters of the given URI.
"""
parts = urllib_parse.urlparse(uri)
query = urllib_parse.parse_qs(parts.query)
if limit is None:
query.pop("limit", None)
else:
query["limit"] = limit
if offset is None:
query.pop("offset", None)
else:
query["offset"] = offset
new_query_string = urllib_parse.urlencode(query, doseq=True)
return urllib_parse.urlunparse(
urllib_parse.ParseResult(
scheme=parts.scheme,
netloc=parts.netloc,
path=parts.path,
params=parts.params,
query=new_query_string,
fragment=parts.fragment,
)
)
def query_limit_and_offset(
query: str, hard_limit: int = 1000
) -> typing.Tuple[str, int, int]:
"""
Extract limit and offset from the end of a query string.
Returns:
A tuple containing the query with limit and offset removed,
the limit at most equal to the hard_limit,
and the offset which defaults to 1
"""
# Regex a lower-case string to simplify matching
tempQueryStr = query.lower()
regex = r"\A(.*\s)(offset|limit)\s*(\d*\s*)\Z"
# Continue to strip off and save the last limit/offset
match = re.search(regex, tempQueryStr)
options = {}
while match is not None:
options[match.group(2)] = int(match.group(3))
tempQueryStr = match.group(1)
match = re.search(regex, tempQueryStr)
# Get a truncated version of the original query string (not in lower-case)
query = query[: len(tempQueryStr)].strip()
# Continue querying until the entire query has been fetched (or crash out)
limit = min(options.get("limit", hard_limit), hard_limit)
offset = options.get("offset", 1)
return query, limit, offset
def extract_synapse_id_from_query(query):
"""
An unfortunate hack to pull the synapse ID out of a table query of the form
"select column1, column2 from syn12345 where...."
needed to build URLs for table services.
"""
m = re.search(r"from\s+(syn\d+)", query, re.IGNORECASE)
if m:
return m.group(1)
else:
raise ValueError('Couldn\'t extract synapse ID from query: "%s"' % query)
def printTransferProgress(
transferred: int,
toBeTransferred: int,
prefix: str = "",
postfix: str = "",
isBytes: bool = True,
dt: float = None,