Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
170 lines (133 loc) · 4.14 KB
/
Copy path__init__.py
File metadata and controls
170 lines (133 loc) · 4.14 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
from stream_framework.exceptions import DuplicateActivityException
import collections
from datetime import datetime, timedelta
import functools
import itertools
import logging
import six
logger = logging.getLogger(__name__)
MISSING = object()
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = collections.OrderedDict()
def get(self, key):
try:
value = self.cache.pop(key)
self.cache[key] = value
return value
except KeyError:
return MISSING
def set(self, key, value):
try:
self.cache.pop(key)
except KeyError:
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
def chunks(iterable, n=10000):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
epoch = datetime(1970, 1, 1)
def datetime_to_epoch(dt):
'''
Convert datetime object to epoch with millisecond accuracy
'''
delta = dt - epoch
since_epoch = delta.total_seconds()
return since_epoch
def epoch_to_datetime(time_):
return epoch + timedelta(seconds=time_)
def make_list_unique(sequence, marker_function=None):
'''
Makes items in a list unique
Performance based on this blog post:
http://www.peterbe.com/plog/uniqifiers-benchmark
'''
seen = {}
result = []
for item in sequence:
# gets the marker
marker = item
if marker_function is not None:
marker = marker_function(item)
# if no longer unique make unique
if marker in seen:
continue
seen[marker] = True
result.append(item)
return result
def warn_on_error(f, exceptions):
import sys
assert exceptions
assert isinstance(exceptions, tuple)
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except exceptions as e:
logger.warn(six.text_type(e), exc_info=sys.exc_info(), extra={
'data': {
'body': six.text_type(e),
}
})
return wrapper
def warn_on_duplicate(f):
exceptions = (DuplicateActivityException,)
return warn_on_error(f, exceptions)
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = LRUCache(10000)
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if self.cache.get(args) is not MISSING:
return self.cache.get(args)
else:
value = self.func(*args)
self.cache.set(args, value)
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
def get_metrics_instance():
"""
Returns an instance of the metric class as defined
in stream_framework settings.
"""
from stream_framework import settings
metric_cls = get_class_from_string(settings.STREAM_METRIC_CLASS)
return metric_cls(**settings.STREAM_METRICS_OPTIONS)
def get_class_from_string(path, default=None):
"""
Return the class specified by the string.
"""
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
i = path.rfind('.')
module, attr = path[:i], path[i + 1:]
mod = import_module(module)
try:
return getattr(mod, attr)
except AttributeError:
if default:
return default
else:
raise ImportError(
'Cannot import name {} (from {})'.format(attr, mod))