home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2886 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  11.0 KB  |  373 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import time
  5. import locale
  6. import calendar
  7. from re import compile as re_compile
  8. from re import IGNORECASE
  9. from re import escape as re_escape
  10. from datetime import date as datetime_date
  11.  
  12. try:
  13.     from thread import allocate_lock as _thread_allocate_lock
  14. except:
  15.     from dummy_thread import allocate_lock as _thread_allocate_lock
  16.  
  17. __all__ = []
  18.  
  19. def _getlang():
  20.     return locale.getlocale(locale.LC_TIME)
  21.  
  22.  
  23. class LocaleTime(object):
  24.     
  25.     def __init__(self):
  26.         self.lang = _getlang()
  27.         self._LocaleTime__calc_weekday()
  28.         self._LocaleTime__calc_month()
  29.         self._LocaleTime__calc_am_pm()
  30.         self._LocaleTime__calc_timezone()
  31.         self._LocaleTime__calc_date_time()
  32.         if _getlang() != self.lang:
  33.             raise ValueError('locale changed during initialization')
  34.         _getlang() != self.lang
  35.  
  36.     
  37.     def __pad(self, seq, front):
  38.         seq = list(seq)
  39.         if front:
  40.             seq.insert(0, '')
  41.         else:
  42.             seq.append('')
  43.         return seq
  44.  
  45.     
  46.     def __calc_weekday(self):
  47.         a_weekday = [ calendar.day_abbr[i].lower() for i in range(7) ]
  48.         f_weekday = [ calendar.day_name[i].lower() for i in range(7) ]
  49.         self.a_weekday = a_weekday
  50.         self.f_weekday = f_weekday
  51.  
  52.     
  53.     def __calc_month(self):
  54.         a_month = [ calendar.month_abbr[i].lower() for i in range(13) ]
  55.         f_month = [ calendar.month_name[i].lower() for i in range(13) ]
  56.         self.a_month = a_month
  57.         self.f_month = f_month
  58.  
  59.     
  60.     def __calc_am_pm(self):
  61.         am_pm = []
  62.         for hour in (1, 22):
  63.             time_tuple = time.struct_time((1999, 3, 17, hour, 44, 55, 2, 76, 0))
  64.             am_pm.append(time.strftime('%p', time_tuple).lower())
  65.         
  66.         self.am_pm = am_pm
  67.  
  68.     
  69.     def __calc_date_time(self):
  70.         time_tuple = time.struct_time((1999, 3, 17, 22, 44, 55, 2, 76, 0))
  71.         date_time = [
  72.             None,
  73.             None,
  74.             None]
  75.         date_time[0] = time.strftime('%c', time_tuple).lower()
  76.         date_time[1] = time.strftime('%x', time_tuple).lower()
  77.         date_time[2] = time.strftime('%X', time_tuple).lower()
  78.         replacement_pairs = [
  79.             ('%', '%%'),
  80.             (self.f_weekday[2], '%A'),
  81.             (self.f_month[3], '%B'),
  82.             (self.a_weekday[2], '%a'),
  83.             (self.a_month[3], '%b'),
  84.             (self.am_pm[1], '%p'),
  85.             ('1999', '%Y'),
  86.             ('99', '%y'),
  87.             ('22', '%H'),
  88.             ('44', '%M'),
  89.             ('55', '%S'),
  90.             ('76', '%j'),
  91.             ('17', '%d'),
  92.             ('03', '%m'),
  93.             ('3', '%m'),
  94.             ('2', '%w'),
  95.             ('10', '%I')]
  96.         []([ (tz, '%Z') for tz_values in self.timezone for tz in tz_values ])
  97.         for offset, directive in ((0, '%c'), (1, '%x'), (2, '%X')):
  98.             current_format = date_time[offset]
  99.             for old, new in replacement_pairs:
  100.                 if old:
  101.                     current_format = current_format.replace(old, new)
  102.                     continue
  103.                 []
  104.             
  105.             time_tuple = time.struct_time((1999, 1, 3, 1, 1, 1, 6, 3, 0))
  106.             if '00' in time.strftime(directive, time_tuple):
  107.                 U_W = '%W'
  108.             else:
  109.                 U_W = '%U'
  110.             date_time[offset] = current_format.replace('11', U_W)
  111.         
  112.         self.LC_date_time = date_time[0]
  113.         self.LC_date = date_time[1]
  114.         self.LC_time = date_time[2]
  115.  
  116.     
  117.     def __calc_timezone(self):
  118.         
  119.         try:
  120.             time.tzset()
  121.         except AttributeError:
  122.             pass
  123.  
  124.         no_saving = frozenset([
  125.             'utc',
  126.             'gmt',
  127.             time.tzname[0].lower()])
  128.         if time.daylight:
  129.             has_saving = frozenset([
  130.                 time.tzname[1].lower()])
  131.         else:
  132.             has_saving = frozenset()
  133.         self.timezone = (no_saving, has_saving)
  134.  
  135.  
  136.  
  137. class TimeRE(dict):
  138.     
  139.     def __init__(self, locale_time = None):
  140.         if locale_time:
  141.             self.locale_time = locale_time
  142.         else:
  143.             self.locale_time = LocaleTime()
  144.         base = super(TimeRE, self)
  145.         base.__init__({
  146.             'd': '(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])',
  147.             'f': '(?P<f>[0-9]{1,6})',
  148.             'H': '(?P<H>2[0-3]|[0-1]\\d|\\d)',
  149.             'I': '(?P<I>1[0-2]|0[1-9]|[1-9])',
  150.             'j': '(?P<j>36[0-6]|3[0-5]\\d|[1-2]\\d\\d|0[1-9]\\d|00[1-9]|[1-9]\\d|0[1-9]|[1-9])',
  151.             'm': '(?P<m>1[0-2]|0[1-9]|[1-9])',
  152.             'M': '(?P<M>[0-5]\\d|\\d)',
  153.             'S': '(?P<S>6[0-1]|[0-5]\\d|\\d)',
  154.             'U': '(?P<U>5[0-3]|[0-4]\\d|\\d)',
  155.             'w': '(?P<w>[0-6])',
  156.             'y': '(?P<y>\\d\\d)',
  157.             'Y': '(?P<Y>\\d\\d\\d\\d)',
  158.             'A': self._TimeRE__seqToRE(self.locale_time.f_weekday, 'A'),
  159.             'a': self._TimeRE__seqToRE(self.locale_time.a_weekday, 'a'),
  160.             'B': self._TimeRE__seqToRE(self.locale_time.f_month[1:], 'B'),
  161.             'b': self._TimeRE__seqToRE(self.locale_time.a_month[1:], 'b'),
  162.             'p': self._TimeRE__seqToRE(self.locale_time.am_pm, 'p'),
  163.             'Z': self._TimeRE__seqToRE((lambda .0: for tz_names in .0:
  164. for tz in tz_names:
  165. tz)(self.locale_time.timezone), 'Z'),
  166.             '%': '%' })
  167.         base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
  168.         base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
  169.         base.__setitem__('x', self.pattern(self.locale_time.LC_date))
  170.         base.__setitem__('X', self.pattern(self.locale_time.LC_time))
  171.  
  172.     
  173.     def __seqToRE(self, to_convert, directive):
  174.         to_convert = sorted(to_convert, key = len, reverse = True)
  175.         for value in to_convert:
  176.             if value != '':
  177.                 break
  178.                 continue
  179.         else:
  180.             return ''
  181.         regex = None.join((lambda .0: for stuff in .0:
  182. re_escape(stuff))(to_convert))
  183.         regex = '(?P<%s>%s' % (directive, regex)
  184.         return '%s)' % regex
  185.  
  186.     
  187.     def pattern(self, format):
  188.         processed_format = ''
  189.         regex_chars = re_compile('([\\\\.^$*+?\\(\\){}\\[\\]|])')
  190.         format = regex_chars.sub('\\\\\\1', format)
  191.         whitespace_replacement = re_compile('\\s+')
  192.         format = whitespace_replacement.sub('\\s+', format)
  193.         while '%' in format:
  194.             directive_index = format.index('%') + 1
  195.             processed_format = '%s%s%s' % (processed_format, format[:directive_index - 1], self[format[directive_index]])
  196.             format = format[directive_index + 1:]
  197.         return '%s%s' % (processed_format, format)
  198.  
  199.     
  200.     def compile(self, format):
  201.         return re_compile(self.pattern(format), IGNORECASE)
  202.  
  203.  
  204. _cache_lock = _thread_allocate_lock()
  205. _TimeRE_cache = TimeRE()
  206. _CACHE_MAX_SIZE = 5
  207. _regex_cache = { }
  208.  
  209. def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
  210.     first_weekday = datetime_date(year, 1, 1).weekday()
  211.     if not week_starts_Mon:
  212.         first_weekday = (first_weekday + 1) % 7
  213.         day_of_week = (day_of_week + 1) % 7
  214.     
  215.     week_0_length = (7 - first_weekday) % 7
  216.     if week_of_year == 0:
  217.         return 1 + day_of_week - first_weekday
  218.     days_to_week = week_0_length + 7 * (week_of_year - 1)
  219.     return 1 + days_to_week + day_of_week
  220.  
  221.  
  222. def _strptime(data_string, format = '%a %b %d %H:%M:%S %Y'):
  223.     global _TimeRE_cache
  224.     _cache_lock.__enter__()
  225.     
  226.     try:
  227.         if len(_regex_cache) > _CACHE_MAX_SIZE:
  228.             _regex_cache.clear()
  229.         
  230.         locale_time = _TimeRE_cache.locale_time
  231.         format_regex = _regex_cache.get(format)
  232.         if not format_regex:
  233.             
  234.             try:
  235.                 format_regex = _TimeRE_cache.compile(format)
  236.             except KeyError:
  237.                 err = None
  238.                 bad_directive = err.args[0]
  239.                 if bad_directive == '\\':
  240.                     bad_directive = '%'
  241.                 
  242.                 del err
  243.                 raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format))
  244.             except IndexError:
  245.                 raise ValueError("stray %% in format '%s'" % format)
  246.  
  247.             _regex_cache[format] = format_regex
  248.     finally:
  249.         pass
  250.  
  251.     found = format_regex.match(data_string)
  252.     if not found:
  253.         raise ValueError('time data %r does not match format %r' % (data_string, format))
  254.     found
  255.     if len(data_string) != found.end():
  256.         raise ValueError('unconverted data remains: %s' % data_string[found.end():])
  257.     len(data_string) != found.end()
  258.     year = 1900
  259.     tz = -1
  260.     week_of_year = -1
  261.     week_of_year_start = -1
  262.     found_dict = found.groupdict()
  263.     for group_key in found_dict.iterkeys():
  264.         if group_key == 'y':
  265.             year = int(found_dict['y'])
  266.             if year <= 68:
  267.                 year += 2000
  268.             else:
  269.                 year += 1900
  270.         year <= 68
  271.         if group_key == 'Y':
  272.             year = int(found_dict['Y'])
  273.             continue
  274.         weekday = julian = -1
  275.         if group_key == 'm':
  276.             month = int(found_dict['m'])
  277.             continue
  278.         hour = minute = second = fraction = 0
  279.         if group_key == 'B':
  280.             month = locale_time.f_month.index(found_dict['B'].lower())
  281.             continue
  282.         month = day = 1
  283.         if group_key == 'b':
  284.             month = locale_time.a_month.index(found_dict['b'].lower())
  285.             continue
  286.         _cache_lock.__exit__
  287.         if group_key == 'd':
  288.             day = int(found_dict['d'])
  289.             continue
  290.         _cache_lock
  291.         if group_key == 'H':
  292.             hour = int(found_dict['H'])
  293.             continue
  294.         if group_key == 'I':
  295.             hour = int(found_dict['I'])
  296.             ampm = found_dict.get('p', '').lower()
  297.             if ampm in ('', locale_time.am_pm[0]):
  298.                 if hour == 12:
  299.                     hour = 0
  300.                 
  301.             elif ampm == locale_time.am_pm[1]:
  302.                 if hour != 12:
  303.                     hour += 12
  304.                 
  305.             
  306.         ampm in ('', locale_time.am_pm[0])
  307.         if group_key == 'M':
  308.             minute = int(found_dict['M'])
  309.             continue
  310.         if group_key == 'S':
  311.             second = int(found_dict['S'])
  312.             continue
  313.         if group_key == 'f':
  314.             s = found_dict['f']
  315.             s += '0' * (6 - len(s))
  316.             fraction = int(s)
  317.             continue
  318.         if group_key == 'A':
  319.             weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  320.             continue
  321.         if group_key == 'a':
  322.             weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  323.             continue
  324.         if group_key == 'w':
  325.             weekday = int(found_dict['w'])
  326.             if weekday == 0:
  327.                 weekday = 6
  328.             else:
  329.                 weekday -= 1
  330.         weekday == 0
  331.         if group_key == 'j':
  332.             julian = int(found_dict['j'])
  333.             continue
  334.         if group_key in ('U', 'W'):
  335.             week_of_year = int(found_dict[group_key])
  336.             if group_key == 'U':
  337.                 week_of_year_start = 6
  338.             else:
  339.                 week_of_year_start = 0
  340.         group_key == 'U'
  341.         if group_key == 'Z':
  342.             found_zone = found_dict['Z'].lower()
  343.             for value, tz_values in enumerate(locale_time.timezone):
  344.                 if found_zone in tz_values:
  345.                     if time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ('utc', 'gmt'):
  346.                         break
  347.                     else:
  348.                         tz = value
  349.                         break
  350.                 found_zone not in ('utc', 'gmt')
  351.             
  352.     
  353.     if julian == -1 and week_of_year != -1 and weekday != -1:
  354.         week_starts_Mon = None if week_of_year_start == 0 else False
  355.         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon)
  356.     
  357.     if julian == -1:
  358.         julian = (datetime_date(year, month, day).toordinal() - datetime_date(year, 1, 1).toordinal()) + 1
  359.     else:
  360.         datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
  361.         year = datetime_result.year
  362.         month = datetime_result.month
  363.         day = datetime_result.day
  364.     if weekday == -1:
  365.         weekday = datetime_date(year, month, day).weekday()
  366.     
  367.     return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
  368.  
  369.  
  370. def _strptime_time(data_string, format = '%a %b %d %H:%M:%S %Y'):
  371.     return _strptime(data_string, format)[0]
  372.  
  373.