PK]5J+Waapytils/__init__.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Simple processing for russian strings """ __id__ = __revision__ = "$Id: __init__.py 35 2006-10-28 17:30:17Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/__init__.py $" __all__ = ["numeral", "dt", "translit", "test", "utils"] # версия PyTils VERSION_MAJOR = 0 #: Major version of PyTils (i.e. branch) VERSION_MINOR = 2 #: Minor version of PyTils (i.e. release) VERSION_TINY = 0 #: Tiny version of PyTils (i.e. subrelease) VERSION = "%d.%d.%d" % (VERSION_MAJOR, VERSION_MINOR, VERSION_TINY) #: Version's string REL_DATE = '20061029' #: Release date def _get_svn_date_from_id(id_string): """Returns date of last update (extract from __id__)""" if id_string.replace('$', '') == "Id": return REL_DATE else: return id_string.split()[3].replace('-', '') _module_dates = [_get_svn_date_from_id(__id__), ] #: Last changes in submodules # импорт модулей for _module_name in __all__: _imported_module = __import__("pytils."+_module_name, globals(), locals(), ["pytils"]) _module_dates.append(_get_svn_date_from_id(_imported_module.__id__)) SVN_DATE = max(_module_dates) #: Last change in submodules # если взяли с svn, то версия будет # X.Y.Z-svnYYYYMMDD, где X.Y.Z - номер оригинальной версии, # а YYYYMMDD - дата последнего изменения в модулях # единственная сложность остается, если взяли не через svn, # а через webdav, в этом случае Id не проставляется и версия # будет оригинальной. Это можно обойти, скажем, учитывая дату # изменения файлов, но я пока не вижу в этом смысла. if SVN_DATE > REL_DATE: VERSION = "%s-svn%s" % (VERSION, SVN_DATE) #: Version's string (with appended svndate) PK]5wd8U~~ pytils/dt.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_dt -*- # License: GNU GPL2 # Author: Pythy """ Russian dates without locales """ __id__ = __revision__ = "$Id: dt.py 29 2006-10-21 08:28:27Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/dt.py $" import datetime from pytils import numeral, utils DAY_ALTERNATIVES = { 1: (u"вчера", u"завтра"), 2: (u"позавчера", u"послезавтра") } #: Day alternatives (i.e. one day ago -> yesterday) DAY_VARIANTS = ( u"день", u"дня", u"дней", ) #: Forms (1, 2, 5) for noun 'day' HOUR_VARIANTS = ( u"час", u"часа", u"часов", ) #: Forms (1, 2, 5) for noun 'hour' MINUTE_VARIANTS = ( u"минуту", u"минуты", u"минут", ) #: Forms (1, 2, 5) for noun 'minute' PREFIX_IN = u"через" #: Prefix 'in' (i.e. B{in} three hours) SUFFIX_AGO = u"назад" #: Prefix 'ago' (i.e. three hours B{ago}) MONTH_NAMES = ( (u"янв", u"январь", u"января"), (u"фев", u"февраль", u"февраля"), (u"мар", u"март", u"марта"), (u"апр", u"апрель", u"апреля"), (u"май", u"май", u"мая"), (u"июн", u"июнь", u"июня"), (u"июл", u"июль", u"июля"), (u"авг", u"август", u"августа"), (u"сен", u"сентябрь", u"сентября"), (u"окт", u"октябрь", u"октября"), (u"ноя", u"ноябрь", u"ноября"), (u"дек", u"декабрь", u"декабря"), ) #: Month names (abbreviated, full, inflected) DAY_NAMES = ( (u"пн", u"понедельник", u"понедельник"), (u"вт", u"вторник", u"вторник"), (u"ср", u"среда", u"среду"), (u"чт", u"четверг", u"четверг"), (u"пт", u"пятница", u"пятницу"), (u"сб", u"суббота", u"субботу"), (u"вск", u"воскресенье", u"субботу"), ) #: Day names (abbreviated, full, inflected) def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise TypeError: input parameters' check failed @raise ValueError: accuracy is lesser or equal zero """ current = False if to_time is None: current = True to_time = datetime.datetime.now() utils.check_type('from_time', (int, float, datetime.datetime)) utils.check_type('to_time', (int, float, datetime.datetime)) utils.check_type('accuracy', int) utils.check_positive('accuracy', strict=True) if not isinstance(from_time, datetime.datetime): from_time = datetime.datetime.fromtimestamp(from_time) if not isinstance(to_time, datetime.datetime): to_time = datetime.datetime.fromtimestamp(to_time) dt_delta = to_time - from_time difference = dt_delta.days*86400 + dt_delta.seconds seconds_orig = int(abs(difference)) minutes_orig = int(abs(difference)/60.0) hours_orig = int(abs(difference)/3600.0) days_orig = int(abs(difference)/86400.0) in_future = from_time > to_time words = [] values = [] alternatives = [] days = days_orig hours = hours_orig - days_orig*24 words.append(u"%d %s" % (days, numeral.choose_plural(days, DAY_VARIANTS))) values.append(days) words.append(u"%d %s" % \ (hours, numeral.choose_plural(hours, HOUR_VARIANTS))) values.append(hours) hours == 1 and current and alternatives.append(u"час") minutes = minutes_orig - hours_orig*60 words.append(u"%d %s" % (minutes, numeral.choose_plural(minutes, MINUTE_VARIANTS))) values.append(minutes) minutes == 1 and current and alternatives.append(u"минуту") real_words = words # убираем из values и words конечные нули while values and not values[-1]: values.pop() words.pop() # убираем из values и words начальные нули while values and not values[0]: values.pop(0) words.pop(0) limit = min(accuracy, len(words)) real_words = words[:limit] real_values = values[:limit] # снова убираем конечные нули while real_values and not real_values[-1]: real_values.pop() real_words.pop() limit -= 1 real_str = u" ".join(real_words) # альтернативные варианты нужны только если в real_words одно значение # и, вдобавок, если используется текущее время alter_str = limit == 1 and current and \ alternatives and alternatives[0] _result_str = alter_str or real_str result_str = in_future and u"%s %s" % (PREFIX_IN, _result_str) \ or u"%s %s" % (_result_str, SUFFIX_AGO) # если же прошло менее минуты, то real_words -- пустой, и поэтому # нужно брать alternatives[0], а не result_str zero_str = minutes == 0 and not real_words and \ (in_future and u"менее чем через минуту" \ or u"менее минуты назад") # нужно использовать вчера/позавчера/завтра/послезавтра # если days 1..2 и в real_words одно значение day_alternatives = DAY_ALTERNATIVES.get(days, False) alternate_day = day_alternatives and current and limit == 1 and \ ((in_future and day_alternatives[1]) \ or day_alternatives[0]) final_str = not real_words and zero_str or alternate_day or result_str return final_str def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False, inflected_day=False): """ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @type date: C{datetime.date} or C{datetime.datetime} @return: strftime string @rtype: unicode @raise TypeError: input parameters' check failed """ if date is None: date = datetime.datetime.today() utils.check_type('date', (datetime.date, datetime.datetime)) utils.check_type('format', unicode) midx = inflected and 2 or 1 didx = inflected_day and 2 or 1 format = format.replace(u'%a', DAY_NAMES[date.weekday()][0]) format = format.replace(u'%A', DAY_NAMES[date.weekday()][didx]) format = format.replace(u'%b', MONTH_NAMES[date.month-1][0]) format = format.replace(u'%B', MONTH_NAMES[date.month-1][midx]) # strftime must be str, so encode it to utf8: s_format = format.encode("utf-8") s_res = date.strftime(s_format) # and back to unicode u_res = s_res.decode("utf-8") return u_res PK{U5!z3z3pytils/numeral.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_numeral -*- # License: GNU GPL2 # Author: Pythy """ Plural forms and in-word representation for numerals. """ __id__ = __revision__ = "$Id: numeral.py 29 2006-10-21 08:28:27Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/numeral.py $" from pytils import utils FRACTIONS = ( (u"десятая", u"десятых", u"десятых"), (u"сотая", u"сотых", u"сотых"), (u"тысячная", u"тысячных", u"тысячных"), (u"десятитысячная", u"десятитысячных", u"десятитысячных"), (u"стотысячная", u"стотысячных", u"стотысячных"), (u"миллионная", u"милллионных", u"милллионных"), (u"десятимиллионная", u"десятимилллионных", u"десятимиллионных"), (u"стомиллионная", u"стомилллионных", u"стомиллионных"), (u"миллиардная", u"миллиардных", u"миллиардных"), ) #: Forms (1, 2, 5) for fractions ONES = { 0: (u"", u"", u""), 1: (u"один", u"одна", u"одно"), 2: (u"два", u"две", u"два"), 3: (u"три", u"три", u"три"), 4: (u"четыре", u"четыре", u"четыре"), 5: (u"пять", u"пять", u"пять"), 6: (u"шесть", u"шесть", u"шесть"), 7: (u"семь", u"семь", u"семь"), 8: (u"восемь", u"восемь", u"восемь"), 9: (u"девять", u"девять", u"девять"), } #: Forms (1, 2, 5) for ones TENS = { 0: u"", # 1 - особый случай 10: u"десять", 11: u"одиннадцать", 12: u"двенадцать", 13: u"тринадцать", 14: u"четырнадцать", 15: u"пятнадцать", 16: u"шестнадцать", 17: u"семнадцать", 18: u"восемнадцать", 19: u"девятнадцать", 2: u"двадцать", 3: u"тридцать", 4: u"сорок", 5: u"пятьдесят", 6: u"шестьдесят", 7: u"семьдесят", 8: u"восемьдесят", 9: u"девяносто", } #: Tens HUNDREDS = { 0: u"", 1: u"сто", 2: u"двести", 3: u"триста", 4: u"четыреста", 5: u"пятьсот", 6: u"шестьсот", 7: u"семьсот", 8: u"восемьсот", 9: u"девятьсот", } #: Hundreds def _get_float_remainder(fvalue, signs=9): """ Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{int} or C{float} @param signs: maximum number of signs @type signs: C{int} @return: remainder @rtype: C{str} @raise TypeError: fvalue neither C{int}, no C{float} @raise ValueError: fvalue is negative @raise ValueError: signs overflow """ utils.check_type('fvalue', (int, float)) utils.check_positive('fvalue') if isinstance(fvalue, int): return "0" signs = min(signs, len(FRACTIONS)) # нужно remainder в строке, потому что дробные X.0Y # будут "ломаться" до X.Y remainder = str(fvalue).split('.')[1] iremainder = int(remainder) orig_remainder = remainder factor = len(str(remainder)) - signs if factor > 0: # после запятой цифр больше чем signs, округляем iremainder = int(round(iremainder / (10.0**factor))) format = "%%0%dd" % min(len(remainder), signs) remainder = format % iremainder if len(remainder) > signs: # при округлении цифр вида 0.998 ругаться raise ValueError("Signs overflow: I can't round only fractional part \ of %s to fit %s in %d signs" % \ (str(fvalue), orig_remainder, signs)) return remainder def choose_plural(amount, variants): """ Choose proper case depending on amount @param amount: amount of objects @type amount: C{int} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with delimeter ',') @return: proper variant @rtype: C{unicode} @raise TypeError: amount isn't C{int}, variants isn't C{sequence} @raise ValueError: amount is negative @raise ValueError: variants' length lesser than 3 """ utils.check_type('amount', int) utils.check_positive('amount') utils.check_type('variants', (list, tuple, unicode)) if isinstance(variants, unicode): variants = [v.strip() for v in variants.split(',')] if amount % 10 == 1 and amount % 100 != 11: variant = 0 elif amount % 10 >= 2 and amount % 10 <= 4 and \ (amount % 100 < 10 or amount % 100 >= 20): variant = 1 else: variant = 2 utils.check_length('variants', 3) return variants[variant] def rubles(amount, zero_for_kopeck=False): """ Get string for money @param amount: amount of money @type amount: C{int} or C{float} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's amount @rtype: C{unicode} @raise TypeError: amount neither C{int}, no C{float} @raise ValueError: amount is negative """ utils.check_type('amount', (int, float)) utils.check_positive('amount') pts = [] amount = round(amount, 2) pts.append(sum_string(int(amount), 1, (u"рубль", u"рубля", u"рублей"))) remainder = _get_float_remainder(amount, 2) iremainder = int(remainder) if iremainder != 0 or zero_for_kopeck: # если 3.1, то это 10 копеек, а не одна if iremainder < 10 and len(remainder) == 1: iremainder *= 10 pts.append(sum_string(iremainder, 2, (u"копейка", u"копейки", u"копеек"))) return u" ".join(pts) def in_words_int(amount, gender=1): """ Integer in words @param amount: numeral @type amount: C{int} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} @raise TypeError: when amount is not C{int} @raise ValueError: amount is negative """ utils.check_type('amount', int) utils.check_positive('amount') return sum_string(amount, gender) def in_words_float(amount, _gender=2): """ Float in words @param amount: float numeral @type amount: C{float} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise TypeError: when amount is not C{float} @raise ValueError: when ammount is negative """ utils.check_type('amount', float) utils.check_positive('amount') pts = [] # преобразуем целую часть pts.append(sum_string(int(amount), 2, (u"целая", u"целых", u"целых"))) # теперь то, что после запятой remainder = _get_float_remainder(amount) signs = len(str(remainder)) - 1 pts.append(sum_string(int(remainder), 2, FRACTIONS[signs])) return u" ".join(pts) def in_words(amount, gender=None): """ Numeral in words @param amount: numeral @type amount: C{int} or C{float} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise TypeError: when amount not C{int} or C{float} raise ValueError: when amount is negative raise TypeError: when gender is not C{int} (and not None) raise ValueError: if gender isn't in (1,2,3) """ utils.check_positive('amount') gender is not None and utils.check_type('gender', int) if not (gender is None or 1 <= gender <= 3): raise ValueError("Gender must be male (1), female (2), " + \ "neuter (3), not %d" % gender) if gender is None: args = (amount,) else: args = (amount, gender) # если целое if isinstance(amount, int): return in_words_int(*args) # если дробное elif isinstance(amount, float): return in_words_float(*args) # ни float, ни int else: raise TypeError("Amount must be float or int, not %s" % \ type(amount)) def sum_string(amount, gender, items=None): """ Get sum in words @param amount: amount of objects @type amount: C{int} @param gender: gender of object (male=1, female=2, neuter=3) @type gender: C{int} @param items: variants of object in three forms: for one object, for two objects and for five objects @type items: 3-element C{sequence} of C{unicode} or just C{unicode} (three variants with delimeter ',') @return: in-words representation objects' amount @rtype: C{unicode} @raise TypeError: input parameters' check failed @raise ValueError: items isn't 3-element C{sequence} @raise ValueError: amount bigger than 10**11 @raise ValueError: amount is negative """ if isinstance(items, unicode): items = [i.strip() for i in items.split(',')] if items is None: items = (u"", u"", u"") utils.check_type('items', (list, tuple)) try: one_item, two_items, five_items = items except ValueError: raise ValueError("Items must be 3-element sequence") utils.check_type('amount', int) utils.check_type('gender', int) utils.check_type('one_item', unicode) utils.check_type('two_items', unicode) utils.check_type('five_items', unicode) utils.check_positive('amount') if amount == 0: return u"ноль %s" % five_items into = u'' tmp_val = amount # единицы into, tmp_val = _sum_string_fn(into, tmp_val, gender, items) # тысячи into, tmp_val = _sum_string_fn(into, tmp_val, 2, (u"тысяча", u"тысячи", u"тысяч")) # миллионы into, tmp_val = _sum_string_fn(into, tmp_val, 1, (u"миллион", u"миллиона", u"миллионов")) # миллиарды into, tmp_val = _sum_string_fn(into, tmp_val, 1, (u"миллиард", u"миллиарда", u"миллиардов")) if tmp_val == 0: return into else: raise ValueError("Cannot operand with numbers bigger than 10**11") def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{int} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise TypeError: input parameters' check failed @raise ValueError: tmp_val is negative """ if items is None: items = (u"", u"", u"") one_item, two_items, five_items = items utils.check_type('into', unicode) utils.check_type('tmp_val', int) utils.check_type('gender', int) utils.check_type('one_item', unicode) utils.check_type('two_items', unicode) utils.check_type('five_items', unicode) utils.check_positive('tmp_val') if tmp_val == 0: return into, tmp_val rest = rest1 = end_word = None words = [] rest = tmp_val % 1000 tmp_val = tmp_val / 1000 if rest == 0: # последние три знака нулевые if into == u"": into = u"%s " % five_items return into, tmp_val # начинаем подсчет с rest end_word = five_items # сотни words.append(HUNDREDS[rest / 100]) # десятки rest = rest % 100 rest1 = rest / 10 # особый случай -- tens=1 tens = rest1 == 1 and TENS[rest] or TENS[rest1] words.append(tens) # единицы if rest1 < 1 or rest1 > 1: amount = rest % 10 end_word = choose_plural(amount, items) words.append(ONES[amount][gender-1]) words.append(end_word) # добавляем то, что уже было words.append(into) # убираем пустые подстроки words = filter(lambda x: len(x) > 0, words) # склеиваем и отдаем return u" ".join(words).strip(), tmp_val PKu\5ٶpytils/translit.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_translit -*- # License: GNU GPL2 # Author: Pythy """ Simple transliteration """ __id__ = __revision__ = "$Id: translit.py 32 2006-10-28 07:10:43Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/translit.py $" import re from pytils import utils TRANSTABLE = ( (u"‘", u"'"), (u"’", u"'"), (u"«", u'"'), (u"»", u'"'), (u"–", u"-"), (u"…", u"..."), (u"№", u"#"), ## верхний регистр # трехбуквенные замены (u"Щ", u"Sch"), # при замене русский->английский будет первая замена, # т.е. Sch # а вот если английский->русский, то вариант SCH и Sch -- # оба пройдут (u"Щ", u"SCH"), # двухбуквенные замены (u"Ё", u"Yo"), (u"Ё", u"YO"), (u"Ж", u"Zh"), (u"Ж", u"ZH"), (u"Ц", u"Ts"), (u"Ц", u"TS"), (u"Ч", u"Ch"), (u"Ч", u"CH"), (u"Ш", u"Sh"), (u"Ш", u"SH"), (u"Ы", u"Yi"), (u"Ы", u"YI"), (u"Ю", u"Yu"), (u"Ю", u"YU"), (u"Я", u"Ya"), (u"Я", u"YA"), # однобуквенные замены (u"А", u"A"), (u"Б", u"B"), (u"В", u"V"), (u"Г", u"G"), (u"Д", u"D"), (u"Е", u"E"), (u"З", u"Z"), (u"И", u"I"), (u"Й", u"J"), (u"К", u"K"), (u"Л", u"L"), (u"М", u"M"), (u"Н", u"N"), (u"О", u"O"), (u"П", u"P"), (u"Р", u"R"), (u"С", u"S"), (u"Т", u"T"), (u"У", u"U"), (u"Ф", u"F"), (u"Х", u"H"), (u"Э", u"E"), (u"Ъ", u"`"), (u"Ь", u"'"), ## нижний регистр # трехбуквенные замены (u"щ", u"sch"), # двухбуквенные замены (u"ё", u"yo"), (u"ж", u"zh"), (u"ц", u"ts"), (u"ч", u"ch"), (u"ш", u"sh"), (u"ы", u"yi"), (u"ю", u"yu"), (u"я", u"ya"), # однобуквенные замены (u"а", u"a"), (u"б", u"b"), (u"в", u"v"), (u"г", u"g"), (u"д", u"d"), (u"е", u"e"), (u"з", u"z"), (u"и", u"i"), (u"й", u"j"), (u"к", u"k"), (u"л", u"l"), (u"м", u"m"), (u"н", u"n"), (u"о", u"o"), (u"п", u"p"), (u"р", u"r"), (u"с", u"s"), (u"т", u"t"), (u"у", u"u"), (u"ф", u"f"), (u"х", u"h"), (u"э", u"e"), (u"ъ", u"`"), (u"ь", u"'"), # для полноты английского алфавит (в slugify) # дополняем английскими буквами, которых # не в парах (u"c", u"c"), (u"q", u"q"), (u"y", u"y"), (u"x", u"x"), (u"C", u"C"), (u"Q", u"Q"), (u"Y", u"Y"), (u"X", u"X"), (u"1", u"1"), (u"2", u"2"), (u"3", u"3"), (u"4", u"4"), (u"5", u"5"), (u"6", u"6"), (u"7", u"7"), (u"8", u"8"), (u"9", u"9"), (u"0", u"0"), ) #: Translation table RU_ALPHABET = [x[0] for x in TRANSTABLE] #: Russian alphabet that we can translate EN_ALPHABET = [x[1] for x in TRANSTABLE] #: English alphabet that we can detransliterate ALPHABET = RU_ALPHABET + EN_ALPHABET #: Alphabet that we can (de)transliterate def translify(in_string): """ Translify russian text @param in_string: input string @type in_string: C{unicode} @return: transliterated string @rtype: C{str} @raise TypeError: when in_string is not C{unicode} @raise ValueError: when string doesn't transliterate completely """ utils.check_type('in_string', unicode) translit = in_string for symb_in, symb_out in TRANSTABLE: translit = translit.replace(symb_in, symb_out) try: translit = str(translit) except UnicodeEncodeError: raise ValueError("Unicode string doesn't transliterate completely, " + \ "is it russian?") return translit def detranslify(in_string): """ Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{str} @raise TypeError: when in_string neither C{str}, no C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii """ utils.check_type('in_string', basestring) # в unicode try: russian = unicode(in_string) except UnicodeDecodeError: raise ValueError("We expects when in_string is str type," + \ "it is an ascii, but now it isn't. Use unicode " + \ "in this case.") for symb_out, symb_in in TRANSTABLE: russian = russian.replace(symb_in, symb_out) return russian def slugify(in_string): """ Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise TypeError: when in_string isn't C{unicode} or C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii """ utils.check_type('in_string', basestring) try: u_in_string = unicode(in_string) except UnicodeDecodeError: raise ValueError("We expects when in_string is str type," + \ "it is an ascii, but now it isn't. Use unicode " + \ "in this case.") # convert & to "and" u_in_string = re.sub('\&\;|\&', ' and ', u_in_string) # replace spaces by hyphen u_in_string = re.sub('[-\s]+', '-', u_in_string) # remove symbols that not in alphabet u_in_string = u''.join([symb for symb in u_in_string if symb in ALPHABET]) # translify it out_string = translify(u_in_string) # remove non-alpha return re.sub('[^\w\s-]', '', out_string).strip().lower() def dirify(in_string): """ Alias for L{slugify} """ slugify(in_string) PKdxU5ػ, pytils/utils.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_utils -*- # License: GNU GPL2 # Author: Pythy """ Misc utils for internal use """ __id__ = __revision__ = "$Id: utils.py 28 2006-10-21 08:03:02Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/utils.py $" import sys def provide_unicode(stext, encoding, default=u"неизвестно"): """ Provide Unicode from text @param stext: text @type stext: C{str} @param encoding: encoding if input text @type encoding: C{str} @return: C{unicode} """ try: utext = str(stext).decode(encoding) except UnicodeDecodeError, err: utext = default % {'error': err, 'value': u""} return utext def provide_str(utext, encoding, default="unknown"): """ Provide text from Unicode @param utext: unicode text @type utext: C{unicode} @param encoding: encoding of output text @type encoding: C{str} @return: C{str} """ try: stext = unicode(utext).encode(encoding) except UnicodeEncodeError, err: stext = default % {'error': err, 'value': ""} return stext def get_value_by_name(variable_name, depth=1): """ Return value of variable by it's name @param variable_name: name of variable @type variable_name: C{str} @param depth: stack depth @type depth: C{int} @raise RuntimeError: when unable to fetch variable """ try: variable_value = sys._getframe(depth).f_locals[variable_name] except KeyError: raise RuntimeError("Unable to fetch variable %s (depth %d)" % \ (variable_name, depth)) return variable_value def check_type(variable_name, typ): """ Checks type of variable @param variable_name: name of variable @type variable_name: C{str} @param typ: type checking for @type typ: C{type} or C{tuple} of types @return: None when check successful @raise TypeError: check failed """ variable_value = get_value_by_name(variable_name, 2) if not isinstance(variable_value, typ): raise TypeError("%s must be %s, not %s" % \ (variable_name, str(typ), type(variable_value))) def check_length(variable_name, length): """ Checks length of variable's value @param variable_name: name of variable @type variable_name: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ variable_value = get_value_by_name(variable_name, 2) _length = len(variable_value) if _length != length: raise ValueError("%s's length must be %d, but it %d" % \ (variable_name, length, _length)) def check_positive(variable_name, strict=False): """ Checks if variable is positive @param variable_name: name of variable @type variable_name: C{str} @return: None when check successful @raise ValueError: check failed """ variable_value = get_value_by_name(variable_name, 2) if not strict and variable_value < 0: raise ValueError("%s must be positive or zero, not %s" % \ (variable_name, str(variable_value))) if strict and variable_value <= 0: raise ValueError("%s must be positive, not %s" % \ (variable_name, str(variable_value))) PK]5@jpytils/__init__.pyc; CEc@sdZdZZdZdddddgZdZd ZdZd eeefZd Z d Z e egZ xFeD]>Z e d e eedgZe ie eiquWee Zee jodeefZndS(s' Simple processing for russian strings s4$Id: __init__.py 35 2006-10-28 17:30:17Z the.pythy $sH$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/__init__.py $snumeralsdtstranslitstestsutilsiis%d.%d.%ds20061029cCs?|idddjotSn|ididdSdS(s1Returns date of last update (extract from __id__)s$ssIdis-N(s id_stringsreplacesREL_DATEssplit(s id_string((s-build/bdist.linux-i686/egg/pytils/__init__.pys_get_svn_date_from_idsspytils.spytilss%s-svn%sN(s__doc__s__id__s __revision__s__url__s__all__s VERSION_MAJORs VERSION_MINORs VERSION_TINYsVERSIONsREL_DATEs_get_svn_date_from_ids _module_datess _module_names __import__sglobalsslocalss_imported_modulesappendsmaxsSVN_DATE(s_get_svn_date_from_ids __revision__s__all__s VERSION_MAJORs VERSION_TINYsSVN_DATEs__url__sVERSIONsREL_DATEs__id__s_imported_modules _module_names _module_datess VERSION_MINOR((s-build/bdist.linux-i686/egg/pytils/__init__.pys?s(     PK]591 pytils/dt.pyc; CEc@sdZdZZdZdkZdklZlZhdddf<dd d fd?fd@dAdAfdBdCdDfdEdFdGfdHdIdGffZdedJZdKeeedLZdS(Ms Russian dates without locales s.$Id: dt.py 29 2006-10-21 08:28:27Z the.pythy $sB$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/dt.py $N(snumeralsutilsiu вчераu завтраiuпозавчераuпослезавтраuденьuдняuднейuчасuчасаu часовu минутуu минутыu минутu черезu назадuянвu январьu январяuфевuфевральuфевраляuмарuмартu мартаuапрu апрельu апреляuмайuмаяuиюнuиюньuиюняuиюлuиюльuиюляuавгu августuавгустаuсенuсентябрьuсентябряuоктuоктябрьuоктябряuнояu ноябрьu ноябряuдекuдекабрьuдекабряuпнuпонедельникuвтuвторникuсрu средаu средуuчтuчетвергuптuпятницаuпятницуuсбuсубботаuсубботуuвскuвоскресеньеcCs*t}|tjot}tii}ntidt t tiftidt t tiftidt ti ddtt |ti otii|}nt |ti otii|}n||}|id|i}t t|}t t|d}t t|d}t t|d} ||j}g}g}g}| }|| d }|id |ti|t f|i||id |ti|t!f|i||d jo|o |id ||d }|id |ti|t#f|i||d jo|o |id|}x,|o |d o|i%|i%qhWx2|o |d o|i%d|i%dqWt&|t(|}|| }|| } x6| o | d o"| i%|i%|d 8}qWdi+|}|d jo|o|o|d}|p|}|odt/|fpd|t0f} |djo| o|odpd} t3i4|t} | o.|o'|d jo|o| d p| d}| o| p |p| }|SdS(sL Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise TypeError: input parameters' check failed @raise ValueError: accuracy is lesser or equal zero s from_timesto_timesaccuracysstrictiQf60.0f3600.0f86400.0iu%d %siuчасi<u минутуiiu u%s %su)менее чем через минутуu"менее минуты назадN(8sFalsescurrentsto_timesNonesTruesdatetimesnowsutilss check_typesintsfloatscheck_positives isinstances from_times fromtimestampsdt_deltasdaysssecondss differencesabss seconds_origs minutes_origs hours_origs days_origs in_futureswordssvaluess alternativesshourssappendsnumerals choose_plurals DAY_VARIANTSs HOUR_VARIANTSsminutessMINUTE_VARIANTSs real_wordsspopsminsaccuracyslenslimits real_valuessjoinsreal_strs alter_strs _result_strs PREFIX_INs SUFFIX_AGOs result_strszero_strsDAY_ALTERNATIVESsgetsday_alternativess alternate_days final_str(s from_timesaccuracysto_timesdt_deltas _result_strs alternativess alter_strslimits in_futures result_strs real_valuessday_alternativess days_origszero_strscurrents real_wordss final_strsreal_strs seconds_origshourss minutes_origswordss differences alternate_daysdayss hours_origsvaluessminutes((s'build/bdist.linux-i686/egg/pytils/dt.pysdistance_of_time_in_wordsDsx   # # !# !      % ()7u%d.%m.%Yc Cs+|tjotii}ntidtitiftidt|odpd}|odpd}|i dt |id}|i dt |i|}|i dt|idd}|i d t|id|}|id }|i|}|id }|Sd S( s_ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @type date: C{datetime.date} or C{datetime.datetime} @return: strftime string @rtype: unicode @raise TypeError: input parameters' check failed sdatesformatiiu%aiu%Au%bu%Bsutf-8N(sdatesNonesdatetimestodaysutilss check_typesunicodes inflectedsmidxs inflected_daysdidxsformatsreplaces DAY_NAMESsweekdays MONTH_NAMESsmonthsencodess_formatsstrftimess_ressdecodesu_res( sformatsdates inflecteds inflected_daysmidxss_formatss_ressu_ressdidx((s'build/bdist.linux-i686/egg/pytils/dt.pys ru_strftimes   !!(s__doc__s__id__s __revision__s__url__sdatetimespytilssnumeralsutilssDAY_ALTERNATIVESs DAY_VARIANTSs HOUR_VARIANTSsMINUTE_VARIANTSs PREFIX_INs SUFFIX_AGOs MONTH_NAMESs DAY_NAMESsNonesdistance_of_time_in_wordssFalses ru_strftime(s MONTH_NAMESs __revision__s ru_strftimes PREFIX_INsutilssdatetimes__url__s HOUR_VARIANTSs__id__s DAY_NAMESsDAY_ALTERNATIVESsnumeralsMINUTE_VARIANTSs SUFFIX_AGOsdistance_of_time_in_wordss DAY_VARIANTS((s'build/bdist.linux-i686/egg/pytils/dt.pys?s  $Z uPK]5j255pytils/numeral.pyc; 29Ec @sdZdZZdZdklZdddfdddfdd d fd d d fd d d fdddfdddfdddfdddff Zhddddf<ddddf<ddd df<d!d"d"d"f<d#d$d$d$f<d%d&d&d&f<d'd(d(d(f<d)d*d*d*f<d+d,d,d,f<d-d.d.d.f<d?d@<dAdB<ddC<d!dD<d#dE<d%dF<d'dG<d)dH<d+dI<d-dJ '05' @param fvalue: input value @type fvalue: C{int} or C{float} @param signs: maximum number of signs @type signs: C{int} @return: remainder @rtype: C{str} @raise TypeError: fvalue neither C{int}, no C{float} @raise ValueError: fvalue is negative @raise ValueError: signs overflow sfvalues0s.iif10.0s%%0%ddshSigns overflow: I can't round only fractional part of %s to fit %s in %d signsN(sutilss check_typesintsfloatscheck_positives isinstancesfvaluesminssignsslens FRACTIONSsstrssplits remainders iremaindersorig_remaindersfactorsroundsformats ValueError(sfvaluessignssorig_remainders iremaindersformatsfactors remainder((s,build/bdist.linux-i686/egg/pytils/numeral.pys_get_float_remainderKs"    #cCstidttidtidtttft|to:gi }|i dD]}||i q]~}n|ddjo|ddjo d}nU|dd jo0|dd jo|ddjp|dd jo d}nd }tidd ||Sd S(s. Choose proper case depending on amount @param amount: amount of objects @type amount: C{int} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with delimeter ',') @return: proper variant @rtype: C{unicode} @raise TypeError: amount isn't C{int}, variants isn't C{sequence} @raise ValueError: amount is negative @raise ValueError: variants' length lesser than 3 samountsvariantss,i iidi iiiiiN(sutilss check_typesintscheck_positivesliststuplesunicodes isinstancesvariantssappends_[1]ssplitsvsstripsamountsvariants check_length(samountsvariantssvariants_[1]sv((s,build/bdist.linux-i686/egg/pytils/numeral.pys choose_pluralzs :" D cCstidttftidg}t|d}|it t|ddddft |d}t|}|djp|oT|djot|djo|d9}n|it |dd d d fnd i|Sd S(s Get string for money @param amount: amount of money @type amount: C{int} or C{float} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's amount @rtype: C{unicode} @raise TypeError: amount neither C{int}, no C{float} @raise ValueError: amount is negative samountiiu рубльu рубляu рублейii uкопейкаuкопейкиu копеекu N(sutilss check_typesintsfloatscheck_positivesptssroundsamountsappends sum_strings_get_float_remainders remainders iremainderszero_for_kopeckslensjoin(samountszero_for_kopecks remainders iremainderspts((s,build/bdist.linux-i686/egg/pytils/numeral.pysrubless (  cCs.tidttidt||SdS(sF Integer in words @param amount: numeral @type amount: C{int} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} @raise TypeError: when amount is not C{int} @raise ValueError: amount is negative samountN(sutilss check_typesintscheck_positives sum_stringsamountsgender(samountsgender((s,build/bdist.linux-i686/egg/pytils/numeral.pys in_words_ints cCstidttidg}|itt|ddddft |}t t |d}|itt|dt|di|SdS(s Float in words @param amount: float numeral @type amount: C{float} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise TypeError: when amount is not C{float} @raise ValueError: when ammount is negative samountiu целаяu целыхiu N(sutilss check_typesfloatscheck_positivesptssappends sum_stringsintsamounts_get_float_remainders remainderslensstrssignss FRACTIONSsjoin(samounts_genders remainderssignsspts((s,build/bdist.linux-i686/egg/pytils/numeral.pysin_words_floats   #cCstid|tj otidt|tjpd|jo djn otdd|n|tjo |f}n ||f}t |tot |Sn5t |t ot |Snt dt|dS( s Numeral in words @param amount: numeral @type amount: C{int} or C{float} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise TypeError: when amount not C{int} or C{float} raise ValueError: when amount is negative raise TypeError: when gender is not C{int} (and not None) raise ValueError: if gender isn't in (1,2,3) samountsgenderiis%Gender must be male (1), female (2), sneuter (3), not %ds#Amount must be float or int, not %sN(sutilsscheck_positivesgendersNones check_typesints ValueErrorsamountsargss isinstances in_words_intsfloatsin_words_floats TypeErrorstype(samountsgendersargs((s,build/bdist.linux-i686/egg/pytils/numeral.pysin_wordss ,   c Cst|to:gi}|idD]}||iq'~}n|tjodddf}nt i dt t fy|\}}}Wntj otdnXt i dtt i dtt i dtt i dtt i d tt id|d jo d |Snd}|} t|| ||\}} t|| d d ddf\}} t|| ddddf\}} t|| ddddf\}} | d jo|Sn tddS(s Get sum in words @param amount: amount of objects @type amount: C{int} @param gender: gender of object (male=1, female=2, neuter=3) @type gender: C{int} @param items: variants of object in three forms: for one object, for two objects and for five objects @type items: 3-element C{sequence} of C{unicode} or just C{unicode} (three variants with delimeter ',') @return: in-words representation objects' amount @rtype: C{unicode} @raise TypeError: input parameters' check failed @raise ValueError: items isn't 3-element C{sequence} @raise ValueError: amount bigger than 10**11 @raise ValueError: amount is negative s,usitemss Items must be 3-element sequencesamountsgendersone_items two_itemss five_itemsiu ноль %siu тысячаu тысячиu тысячiuмиллионuмиллионаuмиллионовuмиллиардuмиллиардаuмиллиардовs.Cannot operand with numbers bigger than 10**11N(s isinstancesitemssunicodesappends_[1]ssplitsisstripsNonesutilss check_typesliststuplesone_items two_itemss five_itemss ValueErrorsintscheck_positivesamountsintostmp_vals_sum_string_fnsgender( samountsgendersitemssone_itemsis five_itemss two_itemss_[1]sintostmp_val((s,build/bdist.linux-i686/egg/pytils/numeral.pys sum_strings<:        c Cs |tjodddf}n|\}} }tidttidttidttidttidttidtti d|djo||fSnt}}} g} |d }|d }|djo)|djod |}n||fSn|} | it|d |d }|d }|d jot|pt|}| i||d jp |d jo6|d } t| |} | it| |d n| i| | i|td| } di| i|fSdS(s2 Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{int} @param gender: gender (male=1, female=2, neuter=3) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise TypeError: input parameters' check failed @raise ValueError: tmp_val is negative usintostmp_valsgendersone_items two_itemss five_itemsiiu%s idi icCst|djS(Ni(slensx(sx((s,build/bdist.linux-i686/egg/pytils/numeral.pyssu N(sitemssNonesone_items two_itemss five_itemssutilss check_typesunicodesintscheck_positivestmp_valsintosrestsrest1send_wordswordssappendsHUNDREDSsTENSstenssamounts choose_pluralsONESsgendersfiltersjoinsstrip( sintostmp_valsgendersitemssone_items five_itemssrestsrest1stenss two_itemsswordssend_wordsamount((s,build/bdist.linux-i686/egg/pytils/numeral.pys_sum_string_fnVsF         "    N(s__doc__s__id__s __revision__s__url__spytilssutilss FRACTIONSsONESsTENSsHUNDREDSs_get_float_remainders choose_pluralsFalsesrubless in_words_intsin_words_floatsNonesin_wordss sum_strings_sum_string_fn(s FRACTIONSsrubless __revision__s in_words_ints choose_pluralsutilssin_words_floatsHUNDREDSs__url__s_sum_string_fnsONESs__id__sTENSs_get_float_remaindersin_wordss sum_string((s,build/bdist.linux-i686/egg/pytils/numeral.pys?s  r ` / $ "   & @PK]5j8`pytils/translit.pyc;  CEce@s>dZdZZdZdkZdklZddfddfdd fd d fd d fd dfddfddfddfddfddfddfddfddfddfddfddfd d!fd d"fd#d$fd#d%fd&d'fd&d(fd)d*fd)d+fd,d-fd.d/fd0d1fd2d3fd4d5fd6d7fd8d9fd:d;fd<d=fd>d?fd@dAfdBdCfdDdEfdFdGfdHdIfdJdKfdLdMfdNdOfdPdQfdRdSfdTdUfdVd7fdWdXfdYdfdZd[fd\d]fd^d_fd`dafdbdcfdddefdfdgfdhdifdjdkfdldmfdndofdpdqfdrdsfdtdufdvdwfdxdyfdzd{fd|d}fd~dfddfddfddfddfddfddfddfddfddfddfddfddwfddXfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddffdZgiZ eD]Z e e dq[ Z giZ eD]Z e e dq[ Z e e Z dZdZdZdZdS(s Simple transliteration s4$Id: translit.py 32 2006-10-28 07:10:43Z the.pythy $sH$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/translit.py $N(sutilsu‘u'u’u«u"u»u–u-u…u...u№u#uЩuSchuSCHuЁuYouYOuЖuZhuZHuЦuTsuTSuЧuChuCHuШuShuSHuЫuYiuYIuЮuYuuYUuЯuYauYAuАuAuБuBuВuVuГuGuДuDuЕuEuЗuZuИuIuЙuJuКuKuЛuLuМuMuНuNuОuOuПuPuРuRuСuSuТuTuУuUuФuFuХuHuЭuЪu`uЬuщuschuёuyouжuzhuцutsuчuchuшushuыuyiuюuyuuяuyauаuauбubuвuvuгuguдuduеueuзuzuиuiuйujuкukuлuluмumuнunuоuouпupuрuruсusuтutuуuuuфufuхuhuэuъuьucuquyuxuCuQuYuXu1u2u3u4u5u6u7u8u9u0iicCs}tidt|}x&tD]\}}|i||}qWyt |}Wn#t j ot ddnX|SdS(s Translify russian text @param in_string: input string @type in_string: C{unicode} @return: transliterated string @rtype: C{str} @raise TypeError: when in_string is not C{unicode} @raise ValueError: when string doesn't transliterate completely s in_strings1Unicode string doesn't transliterate completely, sis it russian?N( sutilss check_typesunicodes in_stringstranslits TRANSTABLEssymb_inssymb_outsreplacesstrsUnicodeEncodeErrors ValueError(s in_stringssymb_inssymb_outstranslit((s-build/bdist.linux-i686/egg/pytils/translit.pys translifys  cCs{tidtyt|}Wn'tj otdddnXx&tD]\}}|i ||}qQW|SdS(s Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{str} @raise TypeError: when in_string neither C{str}, no C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii s in_strings&We expects when in_string is str type,s.it is an ascii, but now it isn't. Use unicode s in this case.N( sutilss check_types basestringsunicodes in_stringsrussiansUnicodeDecodeErrors ValueErrors TRANSTABLEssymb_outssymb_insreplace(s in_stringssymb_outssymb_insrussian((s-build/bdist.linux-i686/egg/pytils/translit.pys detranslifys  cCstidtyt|}Wn'tj otdddnXti dd|}ti dd|}d i gi }|D]!}|tjo||qq~}t|}ti d d |iiSd S( s4 Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise TypeError: when in_string isn't C{unicode} or C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii s in_strings&We expects when in_string is str type,s.it is an ascii, but now it isn't. Use unicode s in this case.s \&\;|\&s and s[-\s]+s-us[^\w\s-]sN(sutilss check_types basestringsunicodes in_strings u_in_stringsUnicodeDecodeErrors ValueErrorsressubsjoinsappends_[1]ssymbsALPHABETs translifys out_stringsstripslower(s in_stringssymbs u_in_strings_[1]s out_string((s-build/bdist.linux-i686/egg/pytils/translit.pysslugifys A cCst|dS(s Alias for L{slugify} N(sslugifys in_string(s in_string((s-build/bdist.linux-i686/egg/pytils/translit.pysdirifys(s__doc__s__id__s __revision__s__url__srespytilssutilss TRANSTABLEsappends_[1]sxs RU_ALPHABETs EN_ALPHABETsALPHABETs translifys detranslifysslugifysdirify(s TRANSTABLEs_[1]s __revision__s translifysALPHABETsutilssdirifys EN_ALPHABETs__url__sres__id__s RU_ALPHABETsxs detranslifysslugify((s-build/bdist.linux-i686/egg/pytils/translit.pys?s   v++    "PK]55_g((pytils/utils.pyc; <9Ec@sedZdZZdZdkZddZddZdd Zd Zd Z e d Z dS( s Misc utils for internal use s1$Id: utils.py 28 2006-10-21 08:03:02Z the.pythy $sE$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/utils.py $NuнеизвестноcCsUyt|i|}Wn1tj o%}|hd|<dd<}nX|SdS(s Provide Unicode from text @param stext: text @type stext: C{str} @param encoding: encoding if input text @type encoding: C{str} @return: C{unicode} serrorsvalueuN(sstrsstextsdecodesencodingsutextsUnicodeDecodeErrorserrsdefault(sstextsencodingsdefaultserrsutext((s*build/bdist.linux-i686/egg/pytils/utils.pysprovide_unicodes !sunknowncCsUyt|i|}Wn1tj o%}|hd|<dd<}nX|SdS(s Provide text from Unicode @param utext: unicode text @type utext: C{unicode} @param encoding: encoding of output text @type encoding: C{str} @return: C{str} serrorsvaluesN(sunicodesutextsencodesencodingsstextsUnicodeEncodeErrorserrsdefault(sutextsencodingsdefaultserrsstext((s*build/bdist.linux-i686/egg/pytils/utils.pys provide_str s !icCsNyti|i|}Wn)tj otd||fnX|SdS(s Return value of variable by it's name @param variable_name: name of variable @type variable_name: C{str} @param depth: stack depth @type depth: C{int} @raise RuntimeError: when unable to fetch variable s&Unable to fetch variable %s (depth %d)N(ssyss _getframesdepthsf_localss variable_namesvariable_valuesKeyErrors RuntimeError(s variable_namesdepthsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pysget_value_by_name2s cCsMt|d}t|| o)td|t|t|fndS(s  Checks type of variable @param variable_name: name of variable @type variable_name: C{str} @param typ: type checking for @type typ: C{type} or C{tuple} of types @return: None when check successful @raise TypeError: check failed is%s must be %s, not %sN(sget_value_by_names variable_namesvariable_values isinstancestyps TypeErrorsstrstype(s variable_namestypsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pys check_typeFs cCsIt|d}t|}||jotd|||fndS(s Checks length of variable's value @param variable_name: name of variable @type variable_name: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed is!%s's length must be %d, but it %dN(sget_value_by_names variable_namesvariable_valueslens_lengthslengths ValueError(s variable_nameslengthsvariable_values_length((s*build/bdist.linux-i686/egg/pytils/utils.pys check_lengthYs   cCs|t|d}| o |djo td|t|fn|o |djo td|t|fndS(s Checks if variable is positive @param variable_name: name of variable @type variable_name: C{str} @return: None when check successful @raise ValueError: check failed iis#%s must be positive or zero, not %ss%s must be positive, not %sN(sget_value_by_names variable_namesvariable_valuesstricts ValueErrorsstr(s variable_namesstrictsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pyscheck_positivems  ( s__doc__s__id__s __revision__s__url__ssyssprovide_unicodes provide_strsget_value_by_names check_types check_lengthsFalsescheck_positive( ssyss __revision__sprovide_unicodes check_typesget_value_by_names provide_strscheck_positives check_lengths__url__s__id__((s*build/bdist.linux-i686/egg/pytils/utils.pys?s       PKuU5ȶpytils/test/__init__.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Unit tests for pytils """ __id__ = __revision__ = "$Id: __init__.py 11 2006-09-28 17:45:00Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/__init__.py $" __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils"] import unittest def get_suite(): """Return TestSuite for all unit-test of PyTils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) return suite def run(verbosity=1): """Run all unit-test of PyTils""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2) PK:]5j**pytils/test/test_dt.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Unit-tests for pytils.dt """ __id__ = __revision__ = "$Id: test_dt.py 18 2006-10-17 15:58:01Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_dt.py $" import datetime import time import unittest import pytils class DistanceOfTimeInWordsTestCase(unittest.TestCase): """ Test case for pytils.dt.distance_of_time_in_words """ def setUp(self): """ Setting up environment for tests """ self.time = 1156862275.7711999 self.dtime = {} self.updateTime(self.time) def updateTime(self, _time): """Update all time-related values for current time """ self.dtime['10sec_ago'] = _time - 10 self.dtime['1min_ago'] = _time - 60 self.dtime['10min_ago'] = _time - 600 self.dtime['1hr_ago'] = _time - 3720 self.dtime['10hr_ago'] = _time - 36600 self.dtime['1day_ago'] = _time - 87600 self.dtime['1day1hr_ago'] = _time - 90600 self.dtime['2day_ago'] = _time - 87600*2 self.dtime['in_10sec'] = _time + 10 self.dtime['in_1min'] = _time + 61 self.dtime['in_10min'] = _time + 601 self.dtime['in_1hr'] = _time + 3721 self.dtime['in_10hr'] = _time + 36601 self.dtime['in_1day'] = _time + 87601 self.dtime['in_1day1hr'] = _time + 90601 self.dtime['in_2day'] = _time + 87600*2 + 1 def ckDefaultAccuracy(self, typ, estimated): """ Checks with default value for accuracy """ t0 = time.time() # --- change state !!! attention self.updateTime(t0) # --- t1 = self.dtime[typ] res = pytils.dt.distance_of_time_in_words(from_time=t1, to_time=t0) # --- revert state to original value self.updateTime(self.time) # --- self.assertEquals(res, estimated) def ckDefaultToTime(self, typ, accuracy, estimated): """ Checks with default value of time """ t0 = time.time() # --- change state !!! attention self.updateTime(t0) # --- t1 = self.dtime[typ] res = pytils.dt.distance_of_time_in_words(t1, accuracy) # --- revert state to original value self.updateTime(self.time) # --- self.assertEquals(res, estimated) def testDOTIWDefaultAccuracy(self): """ Unit-test for distance_of_time_in_words with default accuracy """ self.ckDefaultAccuracy("10sec_ago", u"менее минуты назад") self.ckDefaultAccuracy("1min_ago", u"1 минуту назад") self.ckDefaultAccuracy("10min_ago", u"10 минут назад") self.ckDefaultAccuracy("1hr_ago", u"1 час назад") self.ckDefaultAccuracy("10hr_ago", u"10 часов назад") self.ckDefaultAccuracy("1day_ago", u"1 день назад") self.ckDefaultAccuracy("1day1hr_ago", u"1 день назад") self.ckDefaultAccuracy("2day_ago", u"2 дня назад") self.ckDefaultAccuracy("in_10sec", u"менее чем через минуту") self.ckDefaultAccuracy("in_1min", u"через 1 минуту") self.ckDefaultAccuracy("in_10min", u"через 10 минут") self.ckDefaultAccuracy("in_1hr", u"через 1 час") self.ckDefaultAccuracy("in_10hr", u"через 10 часов") self.ckDefaultAccuracy("in_1day", u"через 1 день") self.ckDefaultAccuracy("in_1day1hr", u"через 1 день") self.ckDefaultAccuracy("in_2day", u"через 2 дня") def testDOTIWDefaultToTimeAcc1(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=1 """ # accuracy = 1 self.ckDefaultToTime("10sec_ago", 1, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 1, u"минуту назад") self.ckDefaultToTime("10min_ago", 1, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 1, u"час назад") self.ckDefaultToTime("10hr_ago", 1, u"10 часов назад") self.ckDefaultToTime("1day_ago", 1, u"вчера") self.ckDefaultToTime("1day1hr_ago", 1, u"вчера") self.ckDefaultToTime("2day_ago", 1, u"позавчера") self.ckDefaultToTime("in_10sec", 1, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 1, u"через минуту") self.ckDefaultToTime("in_10min", 1, u"через 10 минут") self.ckDefaultToTime("in_1hr", 1, u"через час") self.ckDefaultToTime("in_10hr", 1, u"через 10 часов") self.ckDefaultToTime("in_1day", 1, u"завтра") self.ckDefaultToTime("in_1day1hr", 1, u"завтра") self.ckDefaultToTime("in_2day", 1, u"послезавтра") def testDOTIWDefaultToTimeAcc2(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=2 """ # accuracy = 2 self.ckDefaultToTime("10sec_ago", 2, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 2, u"минуту назад") self.ckDefaultToTime("10min_ago", 2, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 2, u"1 час 2 минуты назад") self.ckDefaultToTime("10hr_ago", 2, u"10 часов 10 минут назад") self.ckDefaultToTime("1day_ago", 2, u"вчера") self.ckDefaultToTime("1day1hr_ago", 2, u"1 день 1 час назад") self.ckDefaultToTime("2day_ago", 2, u"позавчера") self.ckDefaultToTime("in_10sec", 2, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 2, u"через минуту") self.ckDefaultToTime("in_10min", 2, u"через 10 минут") self.ckDefaultToTime("in_1hr", 2, u"через 1 час 2 минуты") self.ckDefaultToTime("in_10hr", 2, u"через 10 часов 10 минут") self.ckDefaultToTime("in_1day", 2, u"завтра") self.ckDefaultToTime("in_1day1hr", 2, u"через 1 день 1 час") self.ckDefaultToTime("in_2day", 2, u"послезавтра") def testDOTIWDefaultToTimeAcc3(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=3 """ # accuracy = 3 self.ckDefaultToTime("10sec_ago", 3, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 3, u"минуту назад") self.ckDefaultToTime("10min_ago", 3, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 3, u"1 час 2 минуты назад") self.ckDefaultToTime("10hr_ago", 3, u"10 часов 10 минут назад") self.ckDefaultToTime("1day_ago", 3, u"1 день 0 часов 20 минут назад") self.ckDefaultToTime("1day1hr_ago", 3, u"1 день 1 час 10 минут назад") self.ckDefaultToTime("2day_ago", 3, u"2 дня 0 часов 40 минут назад") self.ckDefaultToTime("in_10sec", 3, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 3, u"через минуту") self.ckDefaultToTime("in_10min", 3, u"через 10 минут") self.ckDefaultToTime("in_1hr", 3, u"через 1 час 2 минуты") self.ckDefaultToTime("in_10hr", 3, u"через 10 часов 10 минут") self.ckDefaultToTime("in_1day", 3, u"через 1 день 0 часов 20 минут") self.ckDefaultToTime("in_1day1hr", 3, u"через 1 день 1 час 10 минут") self.ckDefaultToTime("in_2day", 3, u"через 2 дня 0 часов 40 минут") def testDOTWDatetimeType(self): """ Unit-tests for testing datetime.datetime as input values """ first_time = datetime.datetime.now() second_time = first_time + datetime.timedelta(0, 1000) self.assertEquals(pytils.dt.distance_of_time_in_words( from_time=first_time, accuracy=1, to_time=second_time), u"16 минут назад") def testDOTIWExceptions(self): """ Unit-tests for testings distance_of_time_in_words' exceptions """ self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, "test") self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, time.time(), "test") self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, time.time(), 2, "test") self.assertRaises(ValueError, pytils.dt.distance_of_time_in_words, time.time(), 0) class RuStrftimeTestCase(unittest.TestCase): """ Test case for pytils.dt.ru_strftime """ def setUp(self): """ Setting up environment for tests """ self.date = datetime.date(2006, 8, 25) def ck(self, format, estimates): """ Checks w/o inflected """ res = pytils.dt.ru_strftime(format, self.date) self.assertEquals(res, estimates) def ckInflected(self, format, estimates): """ Checks with inflected """ res = pytils.dt.ru_strftime(format, self.date, True) self.assertEquals(res, estimates) def ckInflectedDay(self, format, estimates): """ Checks with inflected day """ res = pytils.dt.ru_strftime(format, self.date, inflected_day=True) self.assertEquals(res, estimates) def testRuStrftime(self): """ Unit-tests for pytils.dt.ru_strftime """ self.ck(u"тест %a", u"тест пт") self.ck(u"тест %A", u"тест пятница") self.ck(u"тест %b", u"тест авг") self.ck(u"тест %B", u"тест август") self.ckInflected(u"тест %B", u"тест августа") self.ckInflected(u"тест выполнен %d %B %Y года", u"тест выполнен 25 августа 2006 года") self.ckInflectedDay(u"тест выполнен в %A", u"тест выполнен в пятницу") def testRuStrftimeExceptions(self): """ Unit-tests for testing pytils.dt.ru_strftime's exceptions """ self.assertRaises(TypeError, pytils.dt.ru_strftime, time.time()) self.assertRaises(TypeError, pytils.dt.ru_strftime, u"%Y.%m.%d%", time.time()) if __name__ == '__main__': unittest.main() PKuU5B>ƫ..pytils/test/test_numeral.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Unit-tests for pytils.numeral """ __id__ = __revision__ = "$Id: test_numeral.py 15 2006-10-02 11:56:20Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_numeral.py $" import unittest import pytils class ChoosePluralTestCase(unittest.TestCase): """ Test case for pytils.numeral.choose_plural """ def setUp(self): """ Setting up environment for tests """ self.variants = (u"гвоздь", u"гвоздя", u"гвоздей") def checkChoosePlural(self, amount, estimated): """ Checks choose_plural """ self.assertEquals(pytils.numeral.choose_plural(amount, self.variants), estimated) def testChoosePlural(self): """ Unit-test for choose_plural """ self.checkChoosePlural(1, u"гвоздь") self.checkChoosePlural(2, u"гвоздя") self.checkChoosePlural(3, u"гвоздя") self.checkChoosePlural(5, u"гвоздей") self.checkChoosePlural(11, u"гвоздей") self.checkChoosePlural(109, u"гвоздей") def testChoosePluralExceptions(self): """ Unit-test for testing choos_plural's exceptions """ self.assertRaises(TypeError, pytils.numeral.choose_plural, "25", u"any,bene,raba") self.assertRaises(TypeError, pytils.numeral.choose_plural, 25, 30) self.assertRaises(ValueError, pytils.numeral.choose_plural, 25, u"any,bene") self.assertRaises(ValueError, pytils.numeral.choose_plural, -25, u"any,bene,raba") def testChoosePluralVariantsInStr(self): self.assertEquals( pytils.numeral.choose_plural(1,u"гвоздь,гвоздя, гвоздей"), u"гвоздь") class GetFloatRemainderTestCase(unittest.TestCase): """ Test case for pytils.numeral._get_float_remainder """ def testFloatRemainder(self): """ Unit-test for _get_float_remainder """ self.assertEquals(pytils.numeral._get_float_remainder(1.3), '3') self.assertEquals(pytils.numeral._get_float_remainder(2.35, 1), '4') self.assertEquals(pytils.numeral._get_float_remainder(123.1234567891), '123456789') self.assertEquals(pytils.numeral._get_float_remainder(2.353, 2), '35') self.assertEquals(pytils.numeral._get_float_remainder(0.01), '01') self.assertEquals(pytils.numeral._get_float_remainder(5), '0') def testFloatRemainderExceptions(self): """ Unit-test for testing _get_float_remainder's exceptions """ self.assertRaises(ValueError, pytils.numeral._get_float_remainder, 2.998, 2) self.assertRaises(TypeError, pytils.numeral._get_float_remainder, "1.23") self.assertRaises(ValueError, pytils.numeral._get_float_remainder, -1.23) class RublesTestCase(unittest.TestCase): """ Test case for pytils.numeral.rubles """ def testRubles(self): """ Unit-test for rubles """ self.assertEquals(pytils.numeral.rubles(10.01), u"десять рублей одна копейка") self.assertEquals(pytils.numeral.rubles(10.10), u"десять рублей десять копеек") self.assertEquals(pytils.numeral.rubles(2.353), u"два рубля тридцать пять копеек") self.assertEquals(pytils.numeral.rubles(2.998), u"три рубля") self.assertEquals(pytils.numeral.rubles(3), u"три рубля") self.assertEquals(pytils.numeral.rubles(3, True), u"три рубля ноль копеек") def testRublesExceptions(self): """ Unit-test for testing rubles' exceptions """ self.assertRaises(TypeError, pytils.numeral.rubles, "3") self.assertRaises(ValueError, pytils.numeral.rubles, -15) class InWordsTestCase(unittest.TestCase): """ Test case for pytils.numeral.in_words """ def testInt(self): """ Unit-test for in_words_int """ self.assertEquals(pytils.numeral.in_words_int(10), u"десять") self.assertEquals(pytils.numeral.in_words_int(5), u"пять") self.assertEquals(pytils.numeral.in_words_int(102), u"сто два") self.assertEquals(pytils.numeral.in_words_int(3521), u"три тысячи пятьсот двадцать один") self.assertEquals(pytils.numeral.in_words_int(3500), u"три тысячи пятьсот") self.assertEquals(pytils.numeral.in_words_int(5231000), u"пять миллионов двести тридцать одна тысяча") def testIntExceptions(self): """ Unit-test for testing in_words_int's exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words_int, 2.5) self.assertRaises(ValueError, pytils.numeral.in_words_int, -3) def testFloat(self): """ Unit-test for in_words_float """ self.assertEquals(pytils.numeral.in_words_float(10.0), u"десять целых ноль десятых") self.assertEquals(pytils.numeral.in_words_float(2.25), u"две целых двадцать пять сотых") self.assertEquals(pytils.numeral.in_words_float(0.01), u"ноль целых одна сотая") self.assertEquals(pytils.numeral.in_words_float(0.10), u"ноль целых одна десятая") def testFloatExceptions(self): """ Unit-test for testing in_words_float's exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words_float, '2') self.assertRaises(TypeError, pytils.numeral.in_words_float, 2) self.assertRaises(ValueError, pytils.numeral.in_words_float, -2.3) def testWithGender(self): """ Unit-test for in_words_float with gender """ self.assertEquals(pytils.numeral.in_words(21, 1), u"двадцать один") self.assertEquals(pytils.numeral.in_words(21, 2), u"двадцать одна") self.assertEquals(pytils.numeral.in_words(21, 3), u"двадцать одно") # на дробные пол не должен влиять - всегда в женском роде self.assertEquals(pytils.numeral.in_words(21.0, 1), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, 2), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, 3), u"двадцать одна целая ноль десятых") def testCommon(self): """ Unit-test for general in_words """ self.assertEquals(pytils.numeral.in_words(10), u"десять") self.assertEquals(pytils.numeral.in_words(5), u"пять") self.assertEquals(pytils.numeral.in_words(102), u"сто два") self.assertEquals(pytils.numeral.in_words(3521), u"три тысячи пятьсот двадцать один") self.assertEquals(pytils.numeral.in_words(3500), u"три тысячи пятьсот") self.assertEquals(pytils.numeral.in_words(5231000), u"пять миллионов двести тридцать одна тысяча") self.assertEquals(pytils.numeral.in_words(10.0), u"десять целых ноль десятых") self.assertEquals(pytils.numeral.in_words(2.25), u"две целых двадцать пять сотых") self.assertEquals(pytils.numeral.in_words(0.01), u"ноль целых одна сотая") self.assertEquals(pytils.numeral.in_words(0.10), u"ноль целых одна десятая") def testCommonExceptions(self): """ Unit-test for testing in_words' exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words, "0.2") self.assertRaises(TypeError, pytils.numeral.in_words, 0.2, "1") self.assertRaises(ValueError, pytils.numeral.in_words, 0.2, 5) self.assertRaises(ValueError, pytils.numeral.in_words, -2) class SumStringTestCase(unittest.TestCase): """ Test case for pytils.numeral.sum_string """ def setUp(self): """ Setting up environment for tests """ self.variants_male = (u"гвоздь", u"гвоздя", u"гвоздей") self.variants_female = (u"шляпка", u"шляпки", u"шляпок") def ckMale(self, amount, estimated): """ Checks sum_string with male gender """ self.assertEquals(pytils.numeral.sum_string(amount, 1, self.variants_male), estimated) def ckFemale(self, amount, estimated): """ Checks sum_string with female gender """ self.assertEquals(pytils.numeral.sum_string(amount, 2, self.variants_female), estimated) def testSumString(self): """ Unit-test for sum_string """ self.ckMale(10, u"десять гвоздей") self.ckMale(2, u"два гвоздя") self.ckMale(31, u"тридцать один гвоздь") self.ckFemale(10, u"десять шляпок") self.ckFemale(2, u"две шляпки") self.ckFemale(31, u"тридцать одна шляпка") self.assertEquals(u"одиннадцать негритят", pytils.numeral.sum_string( 11, 1, u"негритенок,негритенка,негритят" )) def testSumStringExceptions(self): """ Unit-test for testing sum_string's exceptions """ self.assertRaises(TypeError, pytils.numeral.sum_string, "1", 1) self.assertRaises(TypeError, pytils.numeral.sum_string, 1, "1") self.assertRaises(TypeError, pytils.numeral.sum_string, 1, "1", 23) self.assertRaises(TypeError, pytils.numeral.sum_string, 1, 1, (23,24,25)) self.assertRaises(ValueError, pytils.numeral.sum_string, 1, 1, (23,)) self.assertRaises(ValueError, pytils.numeral.sum_string, -1, 1, u"any,bene,raba") if __name__ == '__main__': unittest.main() PKu\5so! ! pytils/test/test_translit.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Unit-tests for pytils.translit """ __id__ = __revision__ = "$Id: test_translit.py 33 2006-10-28 07:14:40Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_translit.py $" import unittest import pytils class TranslitTestCase(unittest.TestCase): """ Test case for pytils.translit """ def ckTransl(self, in_, out_): """ Checks translify """ self.assertEquals(pytils.translit.translify(in_), out_) def ckDetransl(self, in_, out_): """ Checks detranslify """ self.assertEquals(pytils.translit.detranslify(in_), out_) def ckSlug(self, in_, out_): """ Checks slugify """ self.assertEquals(pytils.translit.slugify(in_), out_) def testTransliteration(self): """ Unit-test for transliterations """ self.ckTransl(u"тест", 'test') self.ckTransl(u"проверка", 'proverka') self.ckTransl(u"транслит", 'translit') self.ckTransl(u"правда ли это", 'pravda li eto') self.ckTransl(u"Щука", 'Schuka') def testTransliterationExceptions(self): """ Unit-test for testing translify's exceptions """ self.assertRaises(TypeError, pytils.translit.translify, 25) self.assertRaises(ValueError, pytils.translit.translify, u'\u00bfHabla espa\u00f1ol?') def testDetransliteration(self): """ Unit-test for detransliterations """ self.ckDetransl('test', u"тест") self.ckDetransl('proverka', u"проверка") self.ckDetransl('translit', u"транслит") self.ckDetransl('SCHuka', u"Щука") self.ckDetransl('Schuka', u"Щука") def testDetransliterationExceptions(self): """ Unit-test for testing detranslify's exceptions """ self.assertRaises(TypeError, pytils.translit.detranslify, 25) self.assertRaises(ValueError, pytils.translit.detranslify, "тест") def testSlug(self): """ Unit-test for slugs """ self.ckSlug(u"ТеСт", 'test') self.ckSlug(u"Проверка связи", 'proverka-svyazi') self.ckSlug(u"me&you", 'me-and-you') self.ckSlug(u"и еще один тест", 'i-esche-odin-test') def testSlugExceptions(self): """ Unit-test for testing slugify's exceptions """ self.assertRaises(TypeError, pytils.translit.slugify, 25) self.assertRaises(ValueError, pytils.translit.slugify, "тест") def testTranslifyAdditionalUnicodeSymbols(self): """ Unit-test for testing additional unicode symbols """ self.ckTransl(u"«Вот так вот»", '"Vot tak vot"') self.ckTransl(u"‘Или вот так’", "'Ili vot tak'") self.ckTransl(u"– Да…", "- Da...") def testSlugifyIssue10(self): """ Unit-test for testing that bug#10 fixed """ self.ckSlug(u"Проверка связи…", 'proverka-svyazi') self.ckSlug(u"Проверка\x0aсвязи 2", 'proverka-svyazi-2') self.ckSlug(u"Проверка\201связи 3", 'proverkasvyazi-3') if __name__ == '__main__': unittest.main() PKuU5X}  pytils/test/test_utils.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Unit-tests for pytils.utils """ __id__ = __revision__ = "$Id: test_utils.py 18 2006-10-17 15:58:01Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_utils.py $" import unittest import pytils class UnicodeTestCase(unittest.TestCase): """ Test case for unicode-utils """ def ckProvideUnicode(self, stext, encoding, utext): """ Check pytils.provide_unicode """ self.assertEquals( pytils.utils.provide_unicode(stext, encoding), utext ) def ckProvideStr(self, utext, encoding, stext): """ Check pytils.provide_str """ self.assertEquals( pytils.utils.provide_str(utext, encoding), stext ) def testProvideUnicode(self): """ Unit-tests for pytils.utils.provide_unicode """ self.ckProvideUnicode("тест №1", "utf-8", u"тест №1") def testProvideStr(self): """ Unit-tests for pytils.utils.provide_str """ self.ckProvideStr(u"тест №1", "utf-8", "тест №1") self.ckProvideStr(u"тест №1", "koi8-r", "unknown") def testProvideStrNonDefault(self): """ Unit-tests for pytils.utils.provide_str with 'default' parameter """ self.assertEquals( pytils.utils.provide_str(u"тест №1", "koi8-r", default="hz"), "hz" ) class ChecksTestCase(unittest.TestCase): """ Test case for check_* utils """ def testGetValueByName(self): """ Unit-test for pytils.utils.get_value_by_name """ var1 = '25' var2 = 25 self.assertEquals('25', pytils.utils.get_value_by_name('var1', depth=1)) self.assertEquals(25, pytils.utils.get_value_by_name('var2', depth=1)) self.assertRaises(RuntimeError, pytils.utils.get_value_by_name, 'var3') def testCheckType(self): """ Unit-test for pytils.utils.check_type """ var = '25' # нельзя assertRaises, потому что глубина стека вызовов тогда не 2, # а гораздо больше try: pytils.utils.check_type('var', int) except TypeError, err: self.assertEquals("var must be , not ", str(err)) try: pytils.utils.check_type('var', (int, float)) except TypeError, err: self.assertEquals("var must be (, ), " + \ "not ", str(err)) self.assertEquals(None, pytils.utils.check_type('var', str)) self.assertEquals(None, pytils.utils.check_type('var', (str, basestring))) def testCheckLength(self): """ Unit-test for pytils.utils.check_length """ var = 'test' self.assertEquals(None, pytils.utils.check_length('var', 4)) try: pytils.utils.check_length('var', 5) except ValueError, err: self.assertEquals("var's length must be 5, but it 4", str(err)) def testCheckPositive(self): """ Unit-test for pytils.utils.check_positive """ var1 = 1 var2 = 1.25 var3 = -2 var4 = -2.12 self.assertEquals(None, pytils.utils.check_positive('var1')) self.assertEquals(None, pytils.utils.check_positive('var2')) try: pytils.utils.check_positive('var3') except ValueError, err: self.assertEquals("var3 must be positive or zero, not -2", str(err)) try: pytils.utils.check_positive('var4') except ValueError, err: self.assertEquals("var4 must be positive or zero, not -2.12", str(err)) def testCheckPositiveStrict(self): """ Unit-test for pytils.utils.check_positive """ var1 = 1 var2 = 0 var3 = -2 self.assertEquals(None, pytils.utils.check_positive('var1', strict=True)) try: pytils.utils.check_positive('var2', strict=True) except ValueError, err: self.assertEquals("var2 must be positive, not 0", str(err)) try: pytils.utils.check_positive('var3') except ValueError, err: self.assertEquals("var3 must be positive or zero, not -2", str(err)) if __name__ == '__main__': unittest.main() PK]5ç]33pytils/test/__init__.pyc; @9Ec@sedZdZZdZddddgZdkZdZd d Zed joed ndS( s Unit tests for pytils s4$Id: __init__.py 11 2006-09-28 17:45:00Z the.pythy $sM$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/__init__.py $s test_numeralstest_dts test_translits test_utilsNcCsfti}xOtD]G}td|ttdg}ti }|i |i |qW|SdS(s,Return TestSuite for all unit-test of PyTilss pytils.test.s pytils.testN( sunittests TestSuitessuites__all__s module_names __import__sglobalsslocalssimported_modulesdefaultTestLoadersloadersaddTestsloadTestsFromModule(sloaders module_namessuitesimported_module((s2build/bdist.linux-i686/egg/pytils/test/__init__.pys get_suites    icCs&t}tid|i|dS(sRun all unit-test of PyTilss verbosityN(s get_suitessuitesunittestsTextTestRunners verbositysrun(s verbosityssuite((s2build/bdist.linux-i686/egg/pytils/test/__init__.pysruns s__main__i( s__doc__s__id__s __revision__s__url__s__all__sunittests get_suitesruns__name__(s __revision__sruns__all__s get_suitesunittests__url__s__id__((s2build/bdist.linux-i686/egg/pytils/test/__init__.pys?s    PK]5-22pytils/test/test_dt.pyc; CEc@sdZdZZdZdkZdkZdkZdkZdeifdYZ deifdYZ e djoei ndS( s Unit-tests for pytils.dt s3$Id: test_dt.py 18 2006-10-17 15:58:01Z the.pythy $sL$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_dt.py $NsDistanceOfTimeInWordsTestCasecBshtZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( s; Test case for pytils.dt.distance_of_time_in_words cCs&d|_h|_|i|idS(s2 Setting up environment for tests f1156862275.7711999N(sselfstimesdtimes updateTime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pyssetUps  cCs |d|id<|d|id<|d|id<|d|id<|d |id <|d |id <|d |id<|d d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d dd|id Unit-test for testing translify's exceptions iu¿Habla español?N(sselfs assertRaisess TypeErrorspytilsstranslits translifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestTransliterationExceptions1scCsT|idd|idd|idd|idd|id dd S( s2 Unit-test for detransliterations stestuтестsproverkauпроверкаstranslituтранслитsSCHukauЩукаsSchukaN(sselfs ckDetransl(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestDetransliteration8s cCs6|ittiid|ittiiddS(s@ Unit-test for testing detranslify's exceptions isтестN(sselfs assertRaisess TypeErrorspytilsstranslits detranslifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestDetransliterationExceptionsBscCsD|idd|idd|idd|iddd S( s% Unit-test for slugs uТеСтstestuПроверка связиsproverka-svyaziume&yous me-and-youuи еще один тестsi-esche-odin-testN(sselfsckSlug(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugIs cCs6|ittiid|ittiiddS(s< Unit-test for testing slugify's exceptions isтестN(sselfs assertRaisess TypeErrorspytilsstranslitsslugifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugExceptionsRscCs4|idd|idd|idddS(s4 Unit-test for testing additional unicode symbols u«Вот так вот»s "Vot tak vot"u‘Или вот так’s 'Ili vot tak'u – Да…s- Da...N(sselfsckTransl(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pys%testTranslifyAdditionalUnicodeSymbolsYscCs4|idd|idd|idddS(s+ Unit-test for testing that bug#10 fixed uПроверка связи…sproverka-svyaziuПроверка связи 2sproverka-svyazi-2uПроверкасвязи 3sproverkasvyazi-3N(sselfsckSlug(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugifyIssue10bs(s__name__s __module__s__doc__sckTransls ckDetranslsckSlugstestTransliterationstestTransliterationExceptionsstestDetransliterationstestDetransliterationExceptionsstestSlugstestSlugExceptionss%testTranslifyAdditionalUnicodeSymbolsstestSlugifyIssue10(((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pysTranslitTestCases        s__main__( s__doc__s__id__s __revision__s__url__sunittestspytilssTestCasesTranslitTestCases__name__smain(s __revision__sunittestsTranslitTestCases__url__s__id__spytils((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pys?s   Z PK]5ϗpytils/test/test_utils.pyc; @9Ec@sydZdZZdZdkZdkZdeifdYZdeifdYZe djoei ndS( s Unit-tests for pytils.utils s6$Id: test_utils.py 18 2006-10-17 15:58:01Z the.pythy $sO$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_utils.py $NsUnicodeTestCasecBs;tZdZdZdZdZdZdZRS(s& Test case for unicode-utils cCs#|itii|||dS(s. Check pytils.provide_unicode N(sselfs assertEqualsspytilssutilssprovide_unicodesstextsencodingsutext(sselfsstextsencodingsutext((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysckProvideUnicodescCs#|itii|||dS(s* Check pytils.provide_str N(sselfs assertEqualsspytilssutilss provide_strsutextsencodingsstext(sselfsutextsencodingsstext((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys ckProvideStrscCs|iddddS(s= Unit-tests for pytils.utils.provide_unicode s тест №1sutf-8u тест №1N(sselfsckProvideUnicode(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideUnicode%scCs*|iddd|iddddS(s9 Unit-tests for pytils.utils.provide_str u тест №1sutf-8s тест №1skoi8-rsunknownN(sselfs ckProvideStr(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideStr+scCs)|itiiddddddS(sR Unit-tests for pytils.utils.provide_str with 'default' parameter u тест №1skoi8-rsdefaultshzN(sselfs assertEqualsspytilssutilss provide_str(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideStrNonDefault2s(s__name__s __module__s__doc__sckProvideUnicodes ckProvideStrstestProvideUnicodestestProvideStrstestProvideStrNonDefault(((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysUnicodeTestCases   sChecksTestCasecBs;tZdZdZdZdZdZdZRS(s% Test case for check_* utils cCsmd}d}|idtiiddd|idtiiddd|ittiiddS( s> Unit-test for pytils.utils.get_value_by_name s25isvar1sdepthisvar2svar3N( svar1svar2sselfs assertEqualsspytilssutilssget_value_by_names assertRaisess RuntimeError(sselfsvar1svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestGetValueByName@s ""cCsd}ytiidtWn+tj o}|idt |nXytiidtt fWn/tj o#}|iddt |nX|it tiidt |it tiidt t fdS(s7 Unit-test for pytils.utils.check_type s25svars*var must be , not s,var must be (, ), snot N( svarspytilssutilss check_typesints TypeErrorserrsselfs assertEqualssstrsfloatsNones basestring(sselfserrsvar((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys testCheckTypeKs  cCsnd}|ittiiddytiiddWn+tj o}|idt |nXdS(s9 Unit-test for pytils.utils.check_length stestsvariis var's length must be 5, but it 4N( svarsselfs assertEqualssNonespytilssutilss check_lengths ValueErrorserrsstr(sselfserrsvar((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckLengthas cCsd}d}d}d}|ittii d|ittii dytii dWn+t j o}|idt |nXytii d Wn+t j o}|id t |nXd S( s; Unit-test for pytils.utils.check_positive if1.25if-2.1200000000000001svar1svar2svar3s%var3 must be positive or zero, not -2svar4s(var4 must be positive or zero, not -2.12N( svar1svar2svar3svar4sselfs assertEqualssNonespytilssutilsscheck_positives ValueErrorserrsstr(sselfsvar4svar1serrsvar3svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckPositivems"  cCsd}d}d}|ittiiddt ytiiddt Wn+t j o}|idt |nXytiidWn+t j o}|id t |nXd S( s; Unit-test for pytils.utils.check_positive iiisvar1sstrictsvar2svar2 must be positive, not 0svar3s%var3 must be positive or zero, not -2N( svar1svar2svar3sselfs assertEqualssNonespytilssutilsscheck_positivesTrues ValueErrorserrsstr(sselfsvar1serrsvar3svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckPositiveStricts"  (s__name__s __module__s__doc__stestGetValueByNames testCheckTypestestCheckLengthstestCheckPositivestestCheckPositiveStrict(((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysChecksTestCase;s   s__main__( s__doc__s__id__s __revision__s__url__sunittestspytilssTestCasesUnicodeTestCasesChecksTestCases__name__smain(s __revision__sUnicodeTestCasesunittests__url__sChecksTestCases__id__spytils((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys?s   -_ PKuU5 99pytils/templatetags/__init__.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ Pytils templatetags for Django web-framework """ __id__ = __revision__ = "$Id: __init__.py 11 2006-09-28 17:45:00Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/__init__.py $" PK{U5A6 pytils/templatetags/pytils_dt.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ pytils.dt templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_dt.py 29 2006-10-21 08:28:27Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_dt.py $" import time from django import template, conf from pytils import dt, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters -- def distance_of_time(from_time, accuracy=1): """ Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_of_time }} {{ some_dtime|distance_of_time:2 }} """ try: res = utils.provide_str( dt.distance_of_time_in_words(from_time, accuracy), encoding, default=default_value) except Exception, err: # because filter must die silently try: default_distance = "%s seconds" % str(int(time.time() - from_time)) except Exception: default_distance = "" res = default_value % {'error': err, 'value': default_distance} return res def ru_strftime(date, format="%d.%m.%Y", inflected_day=False): """ Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strftime: http://docs.python.org/lib/module-time.html Examples:: {{ some_date|ru_strftime:"%d %B %Y, %A" }} """ try: uformat = utils.provide_unicode(format, encoding, default=u"%d.%m.%Y") ures = dt.ru_strftime(uformat, date, inflected=True, inflected_day=inflected_day) res = utils.provide_str(ures, encoding) except Exception, err: # because filter must die silently try: default_date = date.strftime(format) except Exception: default_date = "" res = default_value % {'error': err, 'value': default_date} return res def ru_strftime_inflected(date, format="%d.%m.%Y", inflected_day=True): """ Russian strftime with inflected day, formats date with given format (similar to ru_strftime), also inflects day in proper form. Examples:: {{ some_date|ru_strftime_inflected:"in %A (%d %B %Y)" """ return ru_strftime(date, format, inflected_day) # -- register filters register.filter('distance_of_time', distance_of_time) register.filter('ru_strftime', ru_strftime) register.filter('ru_strftime_inflected', ru_strftime_inflected) PK{U5I%pytils/templatetags/pytils_numeral.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ pytils.numeral templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_numeral.py 29 2006-10-21 08:28:27Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_numeral.py $" from django import template, conf from pytils import numeral, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} """ try: if isinstance(variants, str): uvariants = utils.provide_unicode(variants, encoding, default_value) else: uvariants = [utils.provide_unicode(v, encoding, default_uvalue) for v in variants] res = utils.provide_str( numeral.choose_plural(amount, uvariants), encoding, default=default_value ) except Exception, err: # because filter must die silently try: default_variant = variants[0] except Exception: default_variant = "" res = default_value % {'error': err, 'value': default_variant} return res def rubles(amount, zero_for_kopeck=False): """Converts float value to in-words representation (for money)""" try: res = utils.provide_str( numeral.rubles(amount, zero_for_kopeck), encoding, default=default_value ) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return res def in_words(amount, gender=None): """ In-words representation of amount. Parameter is a gender: 1=male, 2=female, 3=neuter Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:2 }} """ try: res = utils.provide_str( numeral.in_words(amount, gender), encoding, default=default_value ) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return res # -- register filters register.filter('choose_plural', choose_plural) register.filter('rubles', rubles) register.filter('in_words', in_words) # -- tags def sum_string(amount, gender, items): """ in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (1=male, 2=female, 3=neuter). Third is a variants of forms for object name. Examples:: {% sum_string some_int 1 "пример,примера,примеров" %} {% sum_string some_other_int 2 "задача,задачи,задач" %} """ try: uitems = [utils.provide_unicode(i, encoding, default_uvalue) for i in items] res = utils.provide_str( numeral.sum_string(amount, gender, uitems), encoding, default=default_value ) except Exception, err: # because tag's renderer must die silently res = default_value % {'error': err, 'value': str(amount)} return res # -- register tags register.simple_tag(sum_string) PK{U5t b b &pytils/templatetags/pytils_translit.py# -*- coding: utf-8 -*- # License: GNU GPL2 # Author: Pythy """ pytils.translit templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_translit.py 29 2006-10-21 08:28:27Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_translit.py $" from django import template, conf from pytils import translit, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters -- def translify(stext): """Translify russian text""" try: res = translit.translify( utils.provide_unicode( stext, encoding, default=default_value )) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res def detranslify(stext): """Detranslify russian text""" try: res = utils.provide_str( translit.detranslify(stext), encoding, default=default_uvalue) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res def slugify(stext): """Make slug from (russian) text""" try: res = translit.slugify( utils.provide_unicode( stext, encoding, default=default_value )) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res # -- register filters register.filter('translify', translify) register.filter('detranslify', detranslify) register.filter('slugify', slugify) PK]5%l pytils/templatetags/__init__.pyc; A9Ec@sdZdZZdZdS(s. Pytils templatetags for Django web-framework s4$Id: __init__.py 11 2006-09-28 17:45:00Z the.pythy $sU$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/__init__.py $N(s__doc__s__id__s __revision__s__url__(s__url__s __revision__s__id__((s:build/bdist.linux-i686/egg/pytils/templatetags/__init__.pys?s PK]5i!pytils/templatetags/pytils_dt.pyc; 29Ec@sdZdZZdZdkZdklZlZdkl Z l Z ei Z ei iZei iZeei deZeodZdZn$eod Zd Zn d Zd Zd dZdedZdedZe idee idee idedS(s1 pytils.dt templatetags for Django web-framework s5$Id: pytils_dt.py 29 2006-10-21 08:28:27Z the.pythy $sV$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_dt.py $N(stemplatesconf(sdtsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssuicCsy(titi||tdt}Wnqt j oe}y$dt t t i |}Wnt j o d}nXthd|<d|<}nX|SdS(sF Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_of_time }} {{ some_dtime|distance_of_time:2 }} sdefaults %s secondssserrorsvalueN(sutilss provide_strsdtsdistance_of_time_in_wordss from_timesaccuracysencodings default_valuesress Exceptionserrsstrsintstimesdefault_distance(s from_timesaccuracyserrsressdefault_distance((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pysdistance_of_time%s $ !s%d.%m.%YcCsyLti|tdd}ti||dtd|}ti |t}Wn`t j oT}y|i|}Wnt j o d}nXthd|<d|<}nX|SdS( sb Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strftime: http://docs.python.org/lib/module-time.html Examples:: {{ some_date|ru_strftime:"%d %B %Y, %A" }} sdefaultu%d.%m.%Ys inflecteds inflected_daysserrorsvalueN(sutilssprovide_unicodesformatsencodingsuformatsdts ru_strftimesdatesTrues inflected_daysuress provide_strsress Exceptionserrsstrftimes default_dates default_value(sdatesformats inflected_dayserrsressuress default_datesuformat((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pys ru_strftime@s    !cCst|||SdS(s Russian strftime with inflected day, formats date with given format (similar to ru_strftime), also inflects day in proper form. Examples:: {{ some_date|ru_strftime_inflected:"in %A (%d %B %Y)" N(s ru_strftimesdatesformats inflected_day(sdatesformats inflected_day((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pysru_strftime_inflected\ssdistance_of_times ru_strftimesru_strftime_inflected(s__doc__s__id__s __revision__s__url__stimesdjangostemplatesconfspytilssdtsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvaluesdistance_of_times ru_strftimesTruesru_strftime_inflectedsfilter(s default_values __revision__stemplatesencodingsutilssregisters__url__s show_values__id__sconfstimesdebugsdts ru_strftimesdefault_uvaluesru_strftime_inflectedsdistance_of_time((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pys?s.         PK]5nyy&pytils/templatetags/pytils_numeral.pyc; 29Ec@sdZdZZdZdklZlZdklZl Z ei Z ei i Zei iZeei deZeodZdZn$eodZd Zn d Zd Zd Zed ZedZe idee idee idedZe iedS(s6 pytils.numeral templatetags for Django web-framework s:$Id: pytils_numeral.py 29 2006-10-21 08:28:27Z the.pythy $s[$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_numeral.py $(stemplatesconf(snumeralsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssucCsyt|toti|tt}n7gi}|D]}|ti|tt q:~}ti t i||tdt}Wn[tj oO}y|d}Wntj o d}nXthd|<d|<}nX|SdS(sI Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} sdefaultisserrorsvalueN(s isinstancesvariantssstrsutilssprovide_unicodesencodings default_values uvariantssappends_[1]svsdefault_uvalues provide_strsnumerals choose_pluralsamountsress Exceptionserrsdefault_variant(samountsvariantsserrsress uvariantssdefault_variants_[1]sv((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys choose_plural$s 6 !cCsjy(titi||tdt}Wn7t j o+}thd|<dt |<}nX|SdS(s;Converts float value to in-words representation (for money)sdefaultserrorsvalueN( sutilss provide_strsnumeralsrublessamountszero_for_kopecksencodings default_valuesress Exceptionserrsstr(samountszero_for_kopeckserrsres((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pysrublesCs'cCsjy(titi||tdt}Wn7t j o+}thd|<dt |<}nX|SdS(s In-words representation of amount. Parameter is a gender: 1=male, 2=female, 3=neuter Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:2 }} sdefaultserrorsvalueN( sutilss provide_strsnumeralsin_wordssamountsgendersencodings default_valuesress Exceptionserrsstr(samountsgenderserrsres((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pysin_wordsPs 's choose_pluralsrublessin_wordscCsyagi}|D]}|ti|ttq~}ti t i |||tdt}Wn7tj o+}thd|<dt|<}nX|SdS(s in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (1=male, 2=female, 3=neuter). Third is a variants of forms for object name. Examples:: {% sum_string some_int 1 "пример,примера,примеров" %} {% sum_string some_other_int 2 "задача,задачи,задач" %} sdefaultserrorsvalueN(sappends_[1]sitemssisutilssprovide_unicodesencodingsdefault_uvaluesuitemss provide_strsnumerals sum_stringsamountsgenders default_valuesress Exceptionserrsstr(samountsgendersitemssresserrsis_[1]suitems((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys sum_stringms 6'N(s__doc__s__id__s __revision__s__url__sdjangostemplatesconfspytilssnumeralsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvalues choose_pluralsrublessNonesin_wordssfilters sum_strings simple_tag(s default_valuesrubless __revision__stemplatesencodings choose_pluralsutilssregisters__url__s show_values__id__sconfsdebugsnumeralsin_wordssdefault_uvalues sum_string((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys?s0         PK]5j" " 'pytils/templatetags/pytils_translit.pyc; 29Ec@sdZdZZdZdklZlZdklZl Z ei Z ei i Zei iZeei deZeodZdZn$eodZd Zn d Zd Zd Zd ZdZe idee idee idedS(s7 pytils.translit templatetags for Django web-framework s;$Id: pytils_translit.py 29 2006-10-21 08:28:27Z the.pythy $s\$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_translit.py $(stemplatesconf(stranslitsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssucCsay%titi|tdt}Wn1tj o%}thd|<d|<}nX|SdS(sTranslify russian textsdefaultserrorsvalueN( stranslits translifysutilssprovide_unicodesstextsencodings default_valuesress Exceptionserr(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys translify%s!cCsay%titi|tdt}Wn1tj o%}t hd|<d|<}nX|SdS(sDetranslify russian textsdefaultserrorsvalueN( sutilss provide_strstranslits detranslifysstextsencodingsdefault_uvaluesress Exceptionserrs default_value(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys detranslify3s!cCsay%titi|tdt}Wn1tj o%}thd|<d|<}nX|SdS(sMake slug from (russian) textsdefaultserrorsvalueN( stranslitsslugifysutilssprovide_unicodesstextsencodings default_valuesress Exceptionserr(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pysslugify?s!s translifys detranslifysslugifyN(s__doc__s__id__s __revision__s__url__sdjangostemplatesconfspytilsstranslitsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvalues translifys detranslifysslugifysfilter(s default_values __revision__stemplatesencodingsutilssregisters__url__s detranslifys show_values__id__sconfsdebugsdefault_uvaluestranslitsslugifys translify((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys?s,        PK]5ȍEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: pytils Version: 0.2.0 Summary: Utils for easy processing string in russian. Home-page: http://gorod-omsk.ru/blog/pythy/projects/pytils/ Author: Pythy Author-email: the.pythy@gmail.com License: GPL Download-URL: http://cheeseshop.python.org/pypi/pytils/ Description: Simple tools for processing string in russian (choose proper form for plurals, in-words representation of numerals, dates in russian without locales, transliteration, etc) Platform: All Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Linguistic Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Natural Language :: Russian Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers PK]5|KKEGG-INFO/SOURCES.txtAUTHORS LICENSE MANIFEST.in README TODO setup.cfg setup.py doc/INSTALL doc/INSTALL.rus.txt doc/README.rus.txt doc/WEBFRAMEWORKS.rus.txt doc/api/class-tree.html doc/api/crarr.png doc/api/epydoc.css doc/api/epydoc.js doc/api/exceptions.AssertionError-class.html doc/api/frames.html doc/api/help.html doc/api/identifier-index.html doc/api/index.html doc/api/module-tree.html doc/api/pytils-module.html doc/api/pytils-pysrc.html doc/api/pytils.dt-module.html doc/api/pytils.dt-pysrc.html doc/api/pytils.numeral-module.html doc/api/pytils.numeral-pysrc.html doc/api/pytils.templatetags-module.html doc/api/pytils.templatetags-pysrc.html doc/api/pytils.templatetags.pytils_dt-module.html doc/api/pytils.templatetags.pytils_dt-pysrc.html doc/api/pytils.templatetags.pytils_numeral-module.html doc/api/pytils.templatetags.pytils_numeral-pysrc.html doc/api/pytils.templatetags.pytils_translit-module.html doc/api/pytils.templatetags.pytils_translit-pysrc.html doc/api/pytils.test-module.html doc/api/pytils.test-pysrc.html doc/api/pytils.test.test_dt-module.html doc/api/pytils.test.test_dt-pysrc.html doc/api/pytils.test.test_dt.DistanceOfTimeInWordsTestCase-class.html doc/api/pytils.test.test_dt.RuStrftimeTestCase-class.html doc/api/pytils.test.test_numeral-module.html doc/api/pytils.test.test_numeral-pysrc.html doc/api/pytils.test.test_numeral.ChoosePluralTestCase-class.html doc/api/pytils.test.test_numeral.GetFloatRemainderTestCase-class.html doc/api/pytils.test.test_numeral.InWordsTestCase-class.html doc/api/pytils.test.test_numeral.RublesTestCase-class.html doc/api/pytils.test.test_numeral.SumStringTestCase-class.html doc/api/pytils.test.test_translit-module.html doc/api/pytils.test.test_translit-pysrc.html doc/api/pytils.test.test_translit.TranslitTestCase-class.html doc/api/pytils.test.test_utils-module.html doc/api/pytils.test.test_utils-pysrc.html doc/api/pytils.test.test_utils.ChecksTestCase-class.html doc/api/pytils.test.test_utils.UnicodeTestCase-class.html doc/api/pytils.translit-module.html doc/api/pytils.translit-pysrc.html doc/api/pytils.utils-module.html doc/api/pytils.utils-pysrc.html doc/api/toc-everything.html doc/api/toc-pytils-module.html doc/api/toc-pytils.dt-module.html doc/api/toc-pytils.numeral-module.html doc/api/toc-pytils.templatetags-module.html doc/api/toc-pytils.templatetags.pytils_dt-module.html doc/api/toc-pytils.templatetags.pytils_numeral-module.html doc/api/toc-pytils.templatetags.pytils_translit-module.html doc/api/toc-pytils.test-module.html doc/api/toc-pytils.test.test_dt-module.html doc/api/toc-pytils.test.test_numeral-module.html doc/api/toc-pytils.test.test_translit-module.html doc/api/toc-pytils.test.test_utils-module.html doc/api/toc-pytils.translit-module.html doc/api/toc-pytils.utils-module.html doc/api/toc.html doc/examples/dt.distance_of_time_in_words.py doc/examples/dt.ru_strftime.py doc/examples/numeral.choose_plural.py doc/examples/numeral.in_words.py doc/examples/numeral.rubles.py doc/examples/numeral.sum_string.py doc/examples/translit.py doc/examples-django/README doc/examples-django/pytilsex/__init__.py doc/examples-django/pytilsex/manage.py doc/examples-django/pytilsex/settings.py doc/examples-django/pytilsex/urls.py doc/examples-django/pytilsex/static/css/style.css doc/examples-django/pytilsex/static/images/header_inner.png doc/examples-django/pytilsex/templates/base.html doc/examples-django/pytilsex/templates/dt.html doc/examples-django/pytilsex/templates/numeral.html doc/examples-django/pytilsex/templates/translit.html doc/examples-turbogears/README doc/examples-turbogears/dev.cfg doc/examples-turbogears/setup.py doc/examples-turbogears/start-pytilsex.py doc/examples-turbogears/pytilsex/__init__.py doc/examples-turbogears/pytilsex/controllers.py doc/examples-turbogears/pytilsex/model.py doc/examples-turbogears/pytilsex/config/__init__.py doc/examples-turbogears/pytilsex/config/app.cfg doc/examples-turbogears/pytilsex/config/log.cfg doc/examples-turbogears/pytilsex/static/css/style.css doc/examples-turbogears/pytilsex/static/images/favicon.ico doc/examples-turbogears/pytilsex/static/images/header_inner.png doc/examples-turbogears/pytilsex/templates/__init__.py doc/examples-turbogears/pytilsex/templates/dt.kid doc/examples-turbogears/pytilsex/templates/master.kid doc/examples-turbogears/pytilsex/templates/numeral.kid doc/examples-turbogears/pytilsex/templates/root.kid doc/examples-turbogears/pytilsex/templates/translit.kid pytils/__init__.py pytils/dt.py pytils/numeral.py pytils/translit.py pytils/utils.py pytils.egg-info/PKG-INFO pytils.egg-info/SOURCES.txt pytils.egg-info/dependency_links.txt pytils.egg-info/top_level.txt pytils.egg-info/zip-safe pytils/templatetags/__init__.py pytils/templatetags/pytils_dt.py pytils/templatetags/pytils_numeral.py pytils/templatetags/pytils_translit.py pytils/test/__init__.py pytils/test/test_dt.py pytils/test/test_numeral.py pytils/test/test_translit.py pytils/test/test_utils.py PK]52EGG-INFO/dependency_links.txt PK]5\_EGG-INFO/top_level.txtpytils PK]52EGG-INFO/zip-safe PK]5J+Waapytils/__init__.pyPK]5wd8U~~ pytils/dt.pyPK{U5!z3z39&pytils/numeral.pyPKu\5ٶYpytils/translit.pyPKdxU5ػ, rpytils/utils.pyPK]5@jpytils/__init__.pycPK]591 pytils/dt.pycPK]5j255pytils/numeral.pycPK]5j8`pytils/translit.pycPK]55_g((pytils/utils.pycPKuU5ȶpytils/test/__init__.pyPK:]5j**=pytils/test/test_dt.pyPKuU5B>ƫ..R1pytils/test/test_numeral.pyPKu\5so! ! 6`pytils/test/test_translit.pyPKuU5X}  mpytils/test/test_utils.pyPK]5ç]33Ԁpytils/test/__init__.pycPK]5-22=pytils/test/test_dt.pycPK]5B66pytils/test/test_numeral.pycPK]5$$pytils/test/test_translit.pycPK]5ϗJpytils/test/test_utils.pycPKuU5 99!pytils/templatetags/__init__.pyPK{U5A6 #pytils/templatetags/pytils_dt.pyPK{U5I%2pytils/templatetags/pytils_numeral.pyPK{U5t b b &Dpytils/templatetags/pytils_translit.pyPK]5%l Npytils/templatetags/__init__.pycPK]5i!Ppytils/templatetags/pytils_dt.pycPK]5nyy&apytils/templatetags/pytils_numeral.pycPK]5j" " 'tpytils/templatetags/pytils_translit.pycPK]5ȍ%EGG-INFO/PKG-INFOPK]5|KKEGG-INFO/SOURCES.txtPK]52^EGG-INFO/dependency_links.txtPK]5\_EGG-INFO/top_level.txtPK]52՗EGG-INFO/zip-safePK!!