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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import sys
  5. import datetime
  6. import locale as _locale
  7. __all__ = [
  8.     'IllegalMonthError',
  9.     'IllegalWeekdayError',
  10.     'setfirstweekday',
  11.     'firstweekday',
  12.     'isleap',
  13.     'leapdays',
  14.     'weekday',
  15.     'monthrange',
  16.     'monthcalendar',
  17.     'prmonth',
  18.     'month',
  19.     'prcal',
  20.     'calendar',
  21.     'timegm',
  22.     'month_name',
  23.     'month_abbr',
  24.     'day_name',
  25.     'day_abbr']
  26. error = ValueError
  27.  
  28. class IllegalMonthError(ValueError):
  29.     
  30.     def __init__(self, month):
  31.         self.month = month
  32.  
  33.     
  34.     def __str__(self):
  35.         return 'bad month number %r; must be 1-12' % self.month
  36.  
  37.  
  38.  
  39. class IllegalWeekdayError(ValueError):
  40.     
  41.     def __init__(self, weekday):
  42.         self.weekday = weekday
  43.  
  44.     
  45.     def __str__(self):
  46.         return 'bad weekday number %r; must be 0 (Monday) to 6 (Sunday)' % self.weekday
  47.  
  48.  
  49. January = 1
  50. February = 2
  51. mdays = [
  52.     0,
  53.     31,
  54.     28,
  55.     31,
  56.     30,
  57.     31,
  58.     30,
  59.     31,
  60.     31,
  61.     30,
  62.     31,
  63.     30,
  64.     31]
  65.  
  66. class _localized_month:
  67.     _months = [ datetime.date(2001, i + 1, 1).strftime for i in range(12) ]
  68.     _months.insert(0, (lambda x: ''))
  69.     
  70.     def __init__(self, format):
  71.         self.format = format
  72.  
  73.     
  74.     def __getitem__(self, i):
  75.         funcs = self._months[i]
  76.         if isinstance(i, slice):
  77.             return [ f(self.format) for f in funcs ]
  78.         return funcs(self.format)
  79.  
  80.     
  81.     def __len__(self):
  82.         return 13
  83.  
  84.  
  85.  
  86. class _localized_day:
  87.     _days = [ datetime.date(2001, 1, i + 1).strftime for i in range(7) ]
  88.     
  89.     def __init__(self, format):
  90.         self.format = format
  91.  
  92.     
  93.     def __getitem__(self, i):
  94.         funcs = self._days[i]
  95.         if isinstance(i, slice):
  96.             return [ f(self.format) for f in funcs ]
  97.         return funcs(self.format)
  98.  
  99.     
  100.     def __len__(self):
  101.         return 7
  102.  
  103.  
  104. day_name = _localized_day('%A')
  105. day_abbr = _localized_day('%a')
  106. month_name = _localized_month('%B')
  107. month_abbr = _localized_month('%b')
  108. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  109.  
  110. def isleap(year):
  111.     if not year % 4 == 0 and year % 100 != 0:
  112.         pass
  113.     return year % 400 == 0
  114.  
  115.  
  116. def leapdays(y1, y2):
  117.     y1 -= 1
  118.     y2 -= 1
  119.     return (y2 // 4 - y1 // 4 - y2 // 100 - y1 // 100) + (y2 // 400 - y1 // 400)
  120.  
  121.  
  122. def weekday(year, month, day):
  123.     return datetime.date(year, month, day).weekday()
  124.  
  125.  
  126. def monthrange(year, month):
  127.     if month <= month:
  128.         pass
  129.     elif not month <= 12:
  130.         raise IllegalMonthError(month)
  131.     
  132.     day1 = weekday(year, month, 1)
  133.     if month == February:
  134.         pass
  135.     ndays = mdays[month] + isleap(year)
  136.     return (day1, ndays)
  137.  
  138.  
  139. class Calendar(object):
  140.     
  141.     def __init__(self, firstweekday = 0):
  142.         self.firstweekday = firstweekday
  143.  
  144.     
  145.     def getfirstweekday(self):
  146.         return self._firstweekday % 7
  147.  
  148.     
  149.     def setfirstweekday(self, firstweekday):
  150.         self._firstweekday = firstweekday
  151.  
  152.     firstweekday = property(getfirstweekday, setfirstweekday)
  153.     
  154.     def iterweekdays(self):
  155.         for i in range(self.firstweekday, self.firstweekday + 7):
  156.             yield i % 7
  157.         
  158.  
  159.     
  160.     def itermonthdates(self, year, month):
  161.         date = datetime.date(year, month, 1)
  162.         days = (date.weekday() - self.firstweekday) % 7
  163.         date -= datetime.timedelta(days = days)
  164.         oneday = datetime.timedelta(days = 1)
  165.         while True:
  166.             yield date
  167.             date += oneday
  168.             if date.month != month and date.weekday() == self.firstweekday:
  169.                 break
  170.                 continue
  171.  
  172.     
  173.     def itermonthdays2(self, year, month):
  174.         for date in self.itermonthdates(year, month):
  175.             if date.month != month:
  176.                 yield (0, date.weekday())
  177.                 continue
  178.             yield (date.day, date.weekday())
  179.         
  180.  
  181.     
  182.     def itermonthdays(self, year, month):
  183.         for date in self.itermonthdates(year, month):
  184.             if date.month != month:
  185.                 yield 0
  186.                 continue
  187.             yield date.day
  188.         
  189.  
  190.     
  191.     def monthdatescalendar(self, year, month):
  192.         dates = list(self.itermonthdates(year, month))
  193.         return [ dates[i:i + 7] for i in range(0, len(dates), 7) ]
  194.  
  195.     
  196.     def monthdays2calendar(self, year, month):
  197.         days = list(self.itermonthdays2(year, month))
  198.         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
  199.  
  200.     
  201.     def monthdayscalendar(self, year, month):
  202.         days = list(self.itermonthdays(year, month))
  203.         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
  204.  
  205.     
  206.     def yeardatescalendar(self, year, width = 3):
  207.         months = [ self.monthdatescalendar(year, i) for i in range(January, January + 12) ]
  208.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  209.  
  210.     
  211.     def yeardays2calendar(self, year, width = 3):
  212.         months = [ self.monthdays2calendar(year, i) for i in range(January, January + 12) ]
  213.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  214.  
  215.     
  216.     def yeardayscalendar(self, year, width = 3):
  217.         months = [ self.monthdayscalendar(year, i) for i in range(January, January + 12) ]
  218.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  219.  
  220.  
  221.  
  222. class TextCalendar(Calendar):
  223.     
  224.     def prweek(self, theweek, width):
  225.         print self.formatweek(theweek, width),
  226.  
  227.     
  228.     def formatday(self, day, weekday, width):
  229.         if day == 0:
  230.             s = ''
  231.         else:
  232.             s = '%2i' % day
  233.         return s.center(width)
  234.  
  235.     
  236.     def formatweek(self, theweek, width):
  237.         return (None, ' '.join)((lambda .0: for d, wd in .0:
  238. self.formatday(d, wd, width))(theweek))
  239.  
  240.     
  241.     def formatweekday(self, day, width):
  242.         if width >= 9:
  243.             names = day_name
  244.         else:
  245.             names = day_abbr
  246.         return names[day][:width].center(width)
  247.  
  248.     
  249.     def formatweekheader(self, width):
  250.         return (None, ' '.join)((lambda .0: for i in .0:
  251. self.formatweekday(i, width))(self.iterweekdays()))
  252.  
  253.     
  254.     def formatmonthname(self, theyear, themonth, width, withyear = True):
  255.         s = month_name[themonth]
  256.         if withyear:
  257.             s = '%s %r' % (s, theyear)
  258.         
  259.         return s.center(width)
  260.  
  261.     
  262.     def prmonth(self, theyear, themonth, w = 0, l = 0):
  263.         print self.formatmonth(theyear, themonth, w, l),
  264.  
  265.     
  266.     def formatmonth(self, theyear, themonth, w = 0, l = 0):
  267.         w = max(2, w)
  268.         l = max(1, l)
  269.         s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
  270.         s = s.rstrip()
  271.         s += '\n' * l
  272.         s += self.formatweekheader(w).rstrip()
  273.         s += '\n' * l
  274.         for week in self.monthdays2calendar(theyear, themonth):
  275.             s += self.formatweek(week, w).rstrip()
  276.             s += '\n' * l
  277.         
  278.         return s
  279.  
  280.     
  281.     def formatyear(self, theyear, w = 2, l = 1, c = 6, m = 3):
  282.         w = max(2, w)
  283.         l = max(1, l)
  284.         c = max(2, c)
  285.         colwidth = (w + 1) * 7 - 1
  286.         v = []
  287.         a = v.append
  288.         a(repr(theyear).center(colwidth * m + c * (m - 1)).rstrip())
  289.         a('\n' * l)
  290.         header = self.formatweekheader(w)
  291.         for i, row in enumerate(self.yeardays2calendar(theyear, m)):
  292.             months = range(m * i + 1, min(m * (i + 1) + 1, 13))
  293.             a('\n' * l)
  294.             names = (lambda .0: for k in .0:
  295. self.formatmonthname(theyear, k, colwidth, False))(months)
  296.             a(formatstring(names, colwidth, c).rstrip())
  297.             a('\n' * l)
  298.             headers = (lambda .0: for k in .0:
  299. header)(months)
  300.             a(formatstring(headers, colwidth, c).rstrip())
  301.             a('\n' * l)
  302.             height = max((lambda .0: for cal in .0:
  303. len(cal))(row))
  304.             for j in range(height):
  305.                 weeks = []
  306.                 for cal in row:
  307.                     if j >= len(cal):
  308.                         weeks.append('')
  309.                         continue
  310.                     ((None, None, None),)
  311.                     weeks.append(self.formatweek(cal[j], w))
  312.                 
  313.                 a(formatstring(weeks, colwidth, c).rstrip())
  314.                 a('\n' * l)
  315.             
  316.         
  317.         return ''.join(v)
  318.  
  319.     
  320.     def pryear(self, theyear, w = 0, l = 0, c = 6, m = 3):
  321.         print self.formatyear(theyear, w, l, c, m)
  322.  
  323.  
  324.  
  325. class HTMLCalendar(Calendar):
  326.     cssclasses = [
  327.         'mon',
  328.         'tue',
  329.         'wed',
  330.         'thu',
  331.         'fri',
  332.         'sat',
  333.         'sun']
  334.     
  335.     def formatday(self, day, weekday):
  336.         if day == 0:
  337.             return '<td class="noday"> </td>'
  338.         return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
  339.  
  340.     
  341.     def formatweek(self, theweek):
  342.         s = (''.join,)((lambda .0: for d, wd in .0:
  343. self.formatday(d, wd))(theweek))
  344.         return '<tr>%s</tr>' % s
  345.  
  346.     
  347.     def formatweekday(self, day):
  348.         return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])
  349.  
  350.     
  351.     def formatweekheader(self):
  352.         s = (''.join,)((lambda .0: for i in .0:
  353. self.formatweekday(i))(self.iterweekdays()))
  354.         return '<tr>%s</tr>' % s
  355.  
  356.     
  357.     def formatmonthname(self, theyear, themonth, withyear = True):
  358.         if withyear:
  359.             s = '%s %s' % (month_name[themonth], theyear)
  360.         else:
  361.             s = '%s' % month_name[themonth]
  362.         return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  363.  
  364.     
  365.     def formatmonth(self, theyear, themonth, withyear = True):
  366.         v = []
  367.         a = v.append
  368.         a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
  369.         a('\n')
  370.         a(self.formatmonthname(theyear, themonth, withyear = withyear))
  371.         a('\n')
  372.         a(self.formatweekheader())
  373.         a('\n')
  374.         for week in self.monthdays2calendar(theyear, themonth):
  375.             a(self.formatweek(week))
  376.             a('\n')
  377.         
  378.         a('</table>')
  379.         a('\n')
  380.         return ''.join(v)
  381.  
  382.     
  383.     def formatyear(self, theyear, width = 3):
  384.         v = []
  385.         a = v.append
  386.         width = max(width, 1)
  387.         a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
  388.         a('\n')
  389.         a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
  390.         for i in range(January, January + 12, width):
  391.             months = range(i, min(i + width, 13))
  392.             a('<tr>')
  393.             for m in months:
  394.                 a('<td>')
  395.                 a(self.formatmonth(theyear, m, withyear = False))
  396.                 a('</td>')
  397.             
  398.             a('</tr>')
  399.         
  400.         a('</table>')
  401.         return ''.join(v)
  402.  
  403.     
  404.     def formatyearpage(self, theyear, width = 3, css = 'calendar.css', encoding = None):
  405.         if encoding is None:
  406.             encoding = sys.getdefaultencoding()
  407.         
  408.         v = []
  409.         a = v.append
  410.         a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
  411.         a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
  412.         a('<html>\n')
  413.         a('<head>\n')
  414.         a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
  415.         if css is not None:
  416.             a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
  417.         
  418.         a('<title>Calendar for %d</title>\n' % theyear)
  419.         a('</head>\n')
  420.         a('<body>\n')
  421.         a(self.formatyear(theyear, width))
  422.         a('</body>\n')
  423.         a('</html>\n')
  424.         return ''.join(v).encode(encoding, 'xmlcharrefreplace')
  425.  
  426.  
  427.  
  428. class TimeEncoding:
  429.     
  430.     def __init__(self, locale):
  431.         self.locale = locale
  432.  
  433.     
  434.     def __enter__(self):
  435.         self.oldlocale = _locale.setlocale(_locale.LC_TIME, self.locale)
  436.         return _locale.getlocale(_locale.LC_TIME)[1]
  437.  
  438.     
  439.     def __exit__(self, *args):
  440.         _locale.setlocale(_locale.LC_TIME, self.oldlocale)
  441.  
  442.  
  443.  
  444. class LocaleTextCalendar(TextCalendar):
  445.     
  446.     def __init__(self, firstweekday = 0, locale = None):
  447.         TextCalendar.__init__(self, firstweekday)
  448.         if locale is None:
  449.             locale = _locale.getdefaultlocale()
  450.         
  451.         self.locale = locale
  452.  
  453.     
  454.     def formatweekday(self, day, width):
  455.         
  456.         try:
  457.             encoding = _[1]
  458.             name = names[day]
  459.             if encoding is not None:
  460.                 name = name.decode(encoding)
  461.             
  462.             return name[:width].center(width)
  463.         finally:
  464.             pass
  465.  
  466.  
  467.     
  468.     def formatmonthname(self, theyear, themonth, width, withyear = True):
  469.         
  470.         try:
  471.             encoding = _[1]
  472.             s = month_name[themonth]
  473.             if withyear:
  474.                 s = '%s %r' % (s, theyear)
  475.             
  476.             return s.center(width)
  477.         finally:
  478.             pass
  479.  
  480.  
  481.  
  482.  
  483. class LocaleHTMLCalendar(HTMLCalendar):
  484.     
  485.     def __init__(self, firstweekday = 0, locale = None):
  486.         HTMLCalendar.__init__(self, firstweekday)
  487.         if locale is None:
  488.             locale = _locale.getdefaultlocale()
  489.         
  490.         self.locale = locale
  491.  
  492.     
  493.     def formatweekday(self, day):
  494.         
  495.         try:
  496.             encoding = _[1]
  497.             s = day_abbr[day]
  498.             return '<th class="%s">%s</th>' % (self.cssclasses[day], s)
  499.         finally:
  500.             pass
  501.  
  502.  
  503.     
  504.     def formatmonthname(self, theyear, themonth, withyear = True):
  505.         
  506.         try:
  507.             encoding = _[1]
  508.             s = month_name[themonth]
  509.             if withyear:
  510.                 s = '%s %s' % (s, theyear)
  511.             
  512.             return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  513.         finally:
  514.             pass
  515.  
  516.  
  517.  
  518. c = TextCalendar()
  519. firstweekday = c.getfirstweekday
  520.  
  521. def setfirstweekday(firstweekday):
  522.     if firstweekday <= firstweekday:
  523.         pass
  524.     elif not firstweekday <= SUNDAY:
  525.         raise IllegalWeekdayError(firstweekday)
  526.     
  527.     c.firstweekday = firstweekday
  528.  
  529. monthcalendar = c.monthdayscalendar
  530. prweek = c.prweek
  531. week = c.formatweek
  532. weekheader = c.formatweekheader
  533. prmonth = c.prmonth
  534. month = c.formatmonth
  535. calendar = c.formatyear
  536. prcal = c.pryear
  537. _colwidth = 20
  538. _spacing = 6
  539.  
  540. def format(cols, colwidth = _colwidth, spacing = _spacing):
  541.     print formatstring(cols, colwidth, spacing)
  542.  
  543.  
  544. def formatstring(cols, colwidth = _colwidth, spacing = _spacing):
  545.     spacing *= ' '
  546.     return (spacing.join,)((lambda .0: for c in .0:
  547. c.center(colwidth))(cols))
  548.  
  549. EPOCH = 1970
  550. _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
  551.  
  552. def timegm(tuple):
  553.     (year, month, day, hour, minute, second) = tuple[:6]
  554.     days = (datetime.date(year, month, 1).toordinal() - _EPOCH_ORD) + day - 1
  555.     hours = days * 24 + hour
  556.     minutes = hours * 60 + minute
  557.     seconds = minutes * 60 + second
  558.     return seconds
  559.  
  560.  
  561. def main(args):
  562.     import optparse
  563.     parser = optparse.OptionParser(usage = 'usage: %prog [options] [year [month]]')
  564.     parser.add_option('-w', '--width', dest = 'width', type = 'int', default = 2, help = 'width of date column (default 2, text only)')
  565.     parser.add_option('-l', '--lines', dest = 'lines', type = 'int', default = 1, help = 'number of lines for each week (default 1, text only)')
  566.     parser.add_option('-s', '--spacing', dest = 'spacing', type = 'int', default = 6, help = 'spacing between months (default 6, text only)')
  567.     parser.add_option('-m', '--months', dest = 'months', type = 'int', default = 3, help = 'months per row (default 3, text only)')
  568.     parser.add_option('-c', '--css', dest = 'css', default = 'calendar.css', help = 'CSS to use for page (html only)')
  569.     parser.add_option('-L', '--locale', dest = 'locale', default = None, help = 'locale to be used from month and weekday names')
  570.     parser.add_option('-e', '--encoding', dest = 'encoding', default = None, help = 'Encoding to use for output')
  571.     parser.add_option('-t', '--type', dest = 'type', default = 'text', choices = ('text', 'html'), help = 'output type (text or html)')
  572.     (options, args) = parser.parse_args(args)
  573.     if options.locale and not (options.encoding):
  574.         parser.error('if --locale is specified --encoding is required')
  575.         sys.exit(1)
  576.     
  577.     locale = (options.locale, options.encoding)
  578.     if options.type == 'html':
  579.         if options.locale:
  580.             cal = LocaleHTMLCalendar(locale = locale)
  581.         else:
  582.             cal = HTMLCalendar()
  583.         encoding = options.encoding
  584.         if encoding is None:
  585.             encoding = sys.getdefaultencoding()
  586.         
  587.         optdict = dict(encoding = encoding, css = options.css)
  588.         if len(args) == 1:
  589.             print cal.formatyearpage(datetime.date.today().year, **optdict)
  590.         elif len(args) == 2:
  591.             print cal.formatyearpage(int(args[1]), **optdict)
  592.         else:
  593.             parser.error('incorrect number of arguments')
  594.             sys.exit(1)
  595.     elif options.locale:
  596.         cal = LocaleTextCalendar(locale = locale)
  597.     else:
  598.         cal = TextCalendar()
  599.     optdict = dict(w = options.width, l = options.lines)
  600.     if len(args) != 3:
  601.         optdict['c'] = options.spacing
  602.         optdict['m'] = options.months
  603.     
  604.     if len(args) == 1:
  605.         result = cal.formatyear(datetime.date.today().year, **optdict)
  606.     elif len(args) == 2:
  607.         result = cal.formatyear(int(args[1]), **optdict)
  608.     elif len(args) == 3:
  609.         result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
  610.     else:
  611.         parser.error('incorrect number of arguments')
  612.         sys.exit(1)
  613.     if options.encoding:
  614.         result = result.encode(options.encoding)
  615.     
  616.     print result
  617.  
  618. if __name__ == '__main__':
  619.     main(sys.argv)
  620.  
  621.