Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
136 lines (108 loc) · 3.36 KB
/
Copy path__init__.py
File metadata and controls
136 lines (108 loc) · 3.36 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
import collections
from datetime import datetime
from stream_framework.exceptions import DuplicateActivityException
import functools
import itertools
import logging
import time
logger = logging.getLogger(__name__)
def chunks(iterable, n=10000):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
def datetime_to_epoch(dt):
return time.mktime(dt.timetuple())
def epoch_to_datetime(time_):
return datetime.fromtimestamp(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(str(e), exc_info=sys.exc_info(), extra={
'data': {
'body': str(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 = {}
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 args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[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))