util.py 1.4 KB
# -*- coding: utf-8 -*-

from django.conf.urls import defaults
from django.http import HttpResponseRedirect


def error_redirect(request, error, url='/'):
  request.session['error'] = error
  return HttpResponseRedirect(url)

def message_redirect(request, message, url='/'):
  request.session['message'] = message
  return HttpResponseRedirect(url)

def make_form(request, form_class, *args, **kwargs):
  if request.POST.get('det', '') == form_class.base_fields['det'].initial:
    return form_class(*args, data=request.POST, files=request.FILES, **kwargs)
  else:
    return form_class(*args, **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
  return defaults.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