util.py
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# -*- coding: utf-8 -*-
from django.utils.encoding import force_unicode
import json
import sys
from django.conf import urls
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
def uniopen(filename):
return (line.decode().rstrip('\n') for line in open(filename))
def uniprint(text, file=sys.stdout):
print >>file, text.encode('utf-8')
def debug(entry, text):
print>> sys.stderr, (u'%s: %s' % (entry, text)).encode()
def error_redirect(request, error, redirect_url='/'):
request.session['error'] = error
return HttpResponseRedirect(redirect_url)
def message_redirect(request, message, redirect_url='/'):
request.session['message'] = message
return HttpResponseRedirect(redirect_url)
def make_form(request, form_class, **kwargs):
if request.POST.get('det', '') == form_class.base_fields['det'].initial:
return form_class(data=request.POST, files=request.FILES, **kwargs)
else:
return form_class(**kwargs)
def invert(l):
return dict((e, nr) for (nr, e) in enumerate(l))
def generator_slice(generator, count):
res = []
try:
for i in range(count):
res.append(generator.next())
except StopIteration:
pass
return res
def url(regex, view, **kwargs):
if 'name' not in kwargs:
kwargs['name'] = view.rsplit('.', 1)[-1]
return urls.url(regex, view, **kwargs)
def stringify_keys(dictionary):
return dict((keyword.encode('ascii'), value)
for keyword, value in dictionary.iteritems())
# copypasta ze standardowego modułu bisect
def bisect_left(a, x, lo=0, hi=None, cmp=None):
if cmp is None:
cmp = __builtins__.cmp
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if cmp(a[mid], x) < 0:
lo = mid + 1
else:
hi = mid
return lo
def no_history():
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT set_config('var.user_id', '0', false)")
def reverse(seq):
return seq[::-1]
def flatten(seq):
return [item for subseq in seq for item in subseq]
def suffix(string, length):
return string[-length:] if length > 0 else ''
def suffixes(s):
return [s[i:] for i in range(len(s) + 1)]
def cut_end(s, end):
assert s.endswith(end)
n = len(end)
if n == 0:
return s
else:
return s[:-n]
def error_messages(form):
return '\n'.join(
'%s: %s' % (
force_unicode(form.fields[k].label),
' '.join(v))
if k != '__all__'
else ' '.join(v) for k, v in form.errors.iteritems())
class GroupDict(dict):
def add(self, key, value):
if key not in self:
self[key] = []
self[key].append(value)
def json_encode(obj, sort_keys=True, ensure_ascii=False):
return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
def json_decode(obj):
return json.loads(obj)
class FakeQueryset(list):
def all(self):
return self
def iterator(self):
return iter(self)
_prefetch_related_lookups = False
def format_date(date):
return date.strftime(force_unicode(_('%Y/%m/%d %I:%M %p')))
def format_date_exact(date):
return date.strftime(force_unicode(_('%Y/%m/%d %I:%M:%S.%f %p')))