Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata_processing.py
More file actions
Latest commit
125 lines (102 loc) · 4.89 KB
/
Copy pathdata_processing.py
File metadata and controls
125 lines (102 loc) · 4.89 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
importcollections
importitertools
importmultiprocessing
importsubprocess
fromtimeimportsleep
fromtypingimportAny, Callable, Iterable, Set, Tuple, Union, List, Dict
take_first_n: Callable[[Iterable[Any], int], Any] =itertools.islice
defpipeline(functions: Iterable[Callable], initial_data: Any, parallel: bool=True) ->Any:
"""
Modeled after Node.js async.series().
Takes a series of transformations to map over your data.
Passes the result of mapping the first function into the second,
the result of which gets passed into the third, etc.
"""
data=initial_data
ifparallel:
withmultiprocessing.Pool(multiprocessing.cpu_count()) aspool:
forfinfunctions:
data=pool.map(f, data)
else:
forfinfunctions:
data=synchronous_map(f, data)
returndata
defparallel_map(function: Callable, data: Iterable[Any]) ->Iterable[Any]:
withmultiprocessing.Pool(multiprocessing.cpu_count()) aspool:
returnpool.map(function, data)
defsynchronous_map(fn: Callable, data: Iterable[Any]):
returnlist(map(fn, data))
defsynchronous_subprocess(*args: Any, **kwargs: Any) ->subprocess.CompletedProcess:
iflen(args) ==1:
ifisinstance(args[0], list):
args=args[0]
elifisinstance(args[0], str):
args=args[0].split(' ')
try:
out=subprocess.run([str(arg) forarginargs],
stdout=Noneif'capture_stdout'inkwargsandnotkwargs['capture_stdout'] elsesubprocess.PIPE,
stderr=Noneif'capture_stderr'inkwargsandnotkwargs['capture_stderr'] elsesubprocess.PIPE,
cwd=str(kwargs['cwd']) if'cwd'inkwargselseNone,
check=kwargs['check'] if'check'inkwargselseNone)
exceptsubprocess.CalledProcessErrorase:
e.stderr=e.stderr.decode(errors='replace') ife.stderrelse''
e.stdout=e.stdout.decode(errors='replace') ife.stdoutelse''
raisee
else: # Let's not make clients down the line deal with bytes objects
out.stderr=out.stderr.decode(errors='replace') ifout.stderrelse''
out.stdout=out.stdout.decode(errors='replace') ifout.stdoutelse''
returnout
defchecked_subprocess(*args: Any, **kwargs: Any) ->subprocess.CompletedProcess:
kwargs['check'] =True
returnsynchronous_subprocess(*args, **kwargs)
defremove_none(collection: Iterable[Any]) ->List[Any]:
return [itemforitemincollectionifitemisnotNone]
defflatten(list_of_list_of_lists: Union[List[Any], Tuple[Any], Set[Any]]) ->Iterable[Any]:
foriinlist_of_list_of_lists:
ifisinstance(i, (list, tuple, set)):
forjinflatten(i):
yieldj
else:
yieldi
defflatten_dict_items(d: Dict[Any, Any]) ->List[Any]:
"""
Recursively flattens a dict. Values in the dict must be either single values, lists of individual values,
or other dicts which themselves have the same constraints.
>>> flatten_dict_items(collections.OrderedDict(a=1, b=2, c=3))
[1, 2, 3]
>>> flatten_dict_items(collections.OrderedDict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> flatten_dict_items(collections.OrderedDict(a=1, b=[2, 2.25, 2.5, 2.75], c=3))
[1, 2, 2.25, 2.5, 2.75, 3]
>>> flatten_dict_items(collections.OrderedDict(a=1, b=collections.OrderedDict(d=2, e=[2.25, 2.5, 2.75], f=2.8), c=[3, 4, 5]))
[1, 2, 2.25, 2.5, 2.75, 2.8, 3, 4, 5]
"""
out= []
forkey, item_or_itemsind.items():
ifisinstance(item_or_items, collections.Mapping): # dict-like
out+=flatten_dict_items(item_or_items)
elifisinstance(item_or_items, collections.Iterable):
out+=list(item_or_items)
else: # must be an individual value
out.append(item_or_items)
returnout
defpartition(pred: Callable[[Any], bool], iterable: Iterable[Any]) ->Tuple[Iterable[Any], Iterable[Any]]:
"""Use a predicate to partition entries into false entries and true entries
E.g, partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9"""
t1, t2=itertools.tee(iterable)
returnitertools.filterfalse(pred, t1), filter(pred, t2)
defreified_partition(pred: Callable[[Any], bool], iterable: Iterable[Any]) ->Tuple[List[Any], List[Any]]:
"""partition() with its return value as a pair of lists, not generators"""
p1, p2=partition(pred, iterable)
returnlist(p1), list(p2)
defreified_filter(pred: Callable[[Any], bool], iterable: Iterable[Any]) ->List[Any]:
returnlist(filter(pred, iterable))
defreified_chain(*args):
returnlist(itertools.chain(*args))
defretry(action: Callable, max_tries=5):
forattemptedinrange(max_tries):
try:
returnaction()
except:
sleep(attempted+1)
returnaction()