This file is indexed.

/usr/share/pyshared/schooltool/calendar/utils.py is in python-schooltool 1:2.1.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2005 Shuttleworth Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
"""
Utility functions for SchoolTool calendaring.

These include various date manipulation routines.
"""

import re
import calendar
from datetime import date, datetime, timedelta, time

from pytz import timezone, utc
from zope.testing.cleanup import addCleanUp


def prev_month(date):
    """Calculate the first day of the previous month for a given date.

        >>> prev_month(date(2004, 8, 1))
        datetime.date(2004, 7, 1)
        >>> prev_month(date(2004, 8, 31))
        datetime.date(2004, 7, 1)
        >>> prev_month(date(2004, 12, 15))
        datetime.date(2004, 11, 1)
        >>> prev_month(date(2005, 1, 28))
        datetime.date(2004, 12, 1)

    """
    return (date.replace(day=1) - timedelta(1)).replace(day=1)


def next_month(date):
    """Calculate the first day of the next month for a given date.

        >>> next_month(date(2004, 8, 1))
        datetime.date(2004, 9, 1)
        >>> next_month(date(2004, 8, 31))
        datetime.date(2004, 9, 1)
        >>> next_month(date(2004, 12, 15))
        datetime.date(2005, 1, 1)
        >>> next_month(date(2004, 2, 28))
        datetime.date(2004, 3, 1)
        >>> next_month(date(2004, 2, 29))
        datetime.date(2004, 3, 1)
        >>> next_month(date(2005, 2, 28))
        datetime.date(2005, 3, 1)

    """
    return (date.replace(day=28) + timedelta(7)).replace(day=1)


def week_start(date, first_day_of_week=0):
    """Calculate the first day of the week for a given date.

    Assuming that week starts on Mondays:

        >>> week_start(date(2004, 8, 19))
        datetime.date(2004, 8, 16)
        >>> week_start(date(2004, 8, 15))
        datetime.date(2004, 8, 9)
        >>> week_start(date(2004, 8, 14))
        datetime.date(2004, 8, 9)
        >>> week_start(date(2004, 8, 21))
        datetime.date(2004, 8, 16)
        >>> week_start(date(2004, 8, 22))
        datetime.date(2004, 8, 16)
        >>> week_start(date(2004, 8, 23))
        datetime.date(2004, 8, 23)

    Assuming that week starts on Sundays:

        >>> import calendar
        >>> week_start(date(2004, 8, 19), calendar.SUNDAY)
        datetime.date(2004, 8, 15)
        >>> week_start(date(2004, 8, 15), calendar.SUNDAY)
        datetime.date(2004, 8, 15)
        >>> week_start(date(2004, 8, 14), calendar.SUNDAY)
        datetime.date(2004, 8, 8)
        >>> week_start(date(2004, 8, 21), calendar.SUNDAY)
        datetime.date(2004, 8, 15)
        >>> week_start(date(2004, 8, 22), calendar.SUNDAY)
        datetime.date(2004, 8, 22)
        >>> week_start(date(2004, 8, 23), calendar.SUNDAY)
        datetime.date(2004, 8, 22)

    """
    assert 0 <= first_day_of_week < 7
    delta = date.weekday() - first_day_of_week
    if delta < 0:
        delta += 7
    return date - timedelta(delta)


def weeknum_bounds(year, weeknum):
    """Calculate the inclusive date bounds for a (year, weeknum) tuple.

    Week numbers are as defined in ISO 8601 and returned by
    datetime.date.isocalendar().

        >>> weeknum_bounds(2003, 52)
        (datetime.date(2003, 12, 22), datetime.date(2003, 12, 28))
        >>> weeknum_bounds(2004, 1)
        (datetime.date(2003, 12, 29), datetime.date(2004, 1, 4))
        >>> weeknum_bounds(2004, 2)
        (datetime.date(2004, 1, 5), datetime.date(2004, 1, 11))

    """
    # The first week of a year is at least 4 days long, so January 4th
    # is in the first week.
    firstweek = week_start(date(year, 1, 4), calendar.MONDAY)
    # move forward to the right week number
    weekstart = firstweek + timedelta(weeks=weeknum-1)
    weekend = weekstart + timedelta(days=6)
    return (weekstart, weekend)


def check_weeknum(year, weeknum):
    """Check to see whether a (year, weeknum) tuple refers to a real
    ISO week number.

        >>> check_weeknum(2004, 1)
        True
        >>> check_weeknum(2004, 53)
        True
        >>> check_weeknum(2004, 0)
        False
        >>> check_weeknum(2004, 54)
        False
        >>> check_weeknum(2003, 52)
        True
        >>> check_weeknum(2003, 53)
        False

    """
    weekstart, weekend = weeknum_bounds(year, weeknum)
    isoyear, isoweek, isoday = weekstart.isocalendar()
    return (year, weeknum) == (isoyear, isoweek)


def parse_date(value):
    """Parse a ISO-8601 YYYY-MM-DD date value.

    Examples:

        >>> parse_date('2003-09-01')
        datetime.date(2003, 9, 1)
        >>> parse_date('20030901')
        Traceback (most recent call last):
          ...
        ValueError: Invalid date: '20030901'
        >>> parse_date('2003-IX-01')
        Traceback (most recent call last):
          ...
        ValueError: Invalid date: '2003-IX-01'
        >>> parse_date('2003-09-31')
        Traceback (most recent call last):
          ...
        ValueError: Invalid date: '2003-09-31'
        >>> parse_date('2003-09-30-15-42')
        Traceback (most recent call last):
          ...
        ValueError: Invalid date: '2003-09-30-15-42'

    """
    try:
        y, m, d = map(int, value.split('-'))
        return date(y, m, d)
    except ValueError:
        raise ValueError("Invalid date: %r" % value)


def parse_datetime(s):
    """Parse a ISO 8601 date/time value.

    Only a small subset of ISO 8601 is accepted:

      YYYY-MM-DD HH:MM:SS
      YYYY-MM-DD HH:MM:SS.ssssss
      YYYY-MM-DDTHH:MM:SS
      YYYY-MM-DDTHH:MM:SS.ssssss

    Returns a datetime.datetime object without a time zone.

    Examples:

        >>> parse_datetime('2003-04-05 11:22:33.456789')
        datetime.datetime(2003, 4, 5, 11, 22, 33, 456789)

        >>> parse_datetime('2003-04-05 11:22:33.456')
        datetime.datetime(2003, 4, 5, 11, 22, 33, 456000)

        >>> parse_datetime('2003-04-05 11:22:33.45678999')
        datetime.datetime(2003, 4, 5, 11, 22, 33, 456789)

        >>> parse_datetime('01/02/03')
        Traceback (most recent call last):
          ...
        ValueError: Bad datetime: 01/02/03

    """
    m = re.match(r"(\d+)-(\d+)-(\d+)[ T](\d+):(\d+):(\d+)([.](\d+))?$", s)
    if not m:
        raise ValueError("Bad datetime: %s" % s)
    ssssss = m.groups()[7]
    if ssssss:
        ssssss = int((ssssss + "00000")[:6])
    else:
        ssssss = 0
    y, m, d, hh, mm, ss = map(int, m.groups()[:6])
    return datetime(y, m, d, hh, mm, ss, ssssss)


def parse_datetimetz(s):
    """Parse a ISO 8601 date/time value in UTC.

    Only a small subset of ISO 8601 is accepted:

      YYYY-MM-DD HH:MM:SS
      YYYY-MM-DD HH:MM:SS.ssssss
      YYYY-MM-DDTHH:MM:SS
      YYYY-MM-DDTHH:MM:SS.ssssss

    optionally followed by the letter Z to indicate UTC time.

    Returns a datetime.datetime object with tzinfo=UTC.

    Examples:

        >>> dt1 = parse_datetimetz('2003-04-05 11:22:33.456789Z')
        >>> dt1.date()
        datetime.date(2003, 4, 5)
        >>> dt1.time()
        datetime.time(11, 22, 33, 456789)
        >>> dt1.tzname()
        'UTC'

        >>> dt2 = parse_datetimetz('2003-04-05 11:22:33.456')
        >>> dt2.date()
        datetime.date(2003, 4, 5)
        >>> dt2.time()
        datetime.time(11, 22, 33, 456000)

        >>> dt3 = parse_datetimetz('2003-04-05 11:22:33.45678999')
        >>> dt3.date()
        datetime.date(2003, 4, 5)
        >>> dt3.time()
        datetime.time(11, 22, 33, 456789)
        >>> dt3.tzname()
        'UTC'

        >>> dt4 = parse_datetimetz('2003-04-05 11:22:33+00:00')
        >>> dt4.date()
        datetime.date(2003, 4, 5)

        >>> dt5 = parse_datetimetz('2003-04-05 11:22:33.45678999-09:00')
        >>> dt5.time()
        datetime.time(11, 22, 33, 456789)

        >>> dt6 = parse_datetimetz('01/02/03')
        Traceback (most recent call last):
          ...
        ValueError: Bad datetime: 01/02/03

    """
    m = re.match(r"(\d+)-(\d+)-(\d+)[ T]"
                 r"(\d+):(\d+):(\d+)([.](\d+))?([-+](\d+):(\d+))?Z?$", s)
    if not m:
        raise ValueError("Bad datetime: %s" % s)
    ssssss = m.groups()[7]
    if ssssss:
        ssssss = int((ssssss + "00000")[:6])
    else:
        ssssss = 0
    y, m, d, hh, mm, ss = map(int, m.groups()[:6])
    return datetime(y, m, d, hh, mm, ss, ssssss, tzinfo=utc)


def parse_time(s):
    """Parse a ISO 8601 time value.

    Only a small subset of ISO 8601 is accepted:

      HH:MM
      HH:MM:SS

    Returns a datetime.time object without a time zone.

    Examples:

        >>> parse_time('11:22:33')
        datetime.time(11, 22, 33)

        >>> parse_time('11:22')
        datetime.time(11, 22)

        >>> parse_time('11:66')
        Traceback (most recent call last):
          ...
        ValueError: minute must be in 0..59

    """
    parts = s.split(":")
    hh, mm = map(int, parts[:2])
    ss = 0
    if len(parts) > 2:
        ss = int(parts[2])
    return time(hh, mm, ss)


def parse_timetz(s, tz=utc):
    """Timezone aware time parser.

    If no timezone preference is given, default to UTC.

        >>> t1 = parse_timetz('11:22:33')
        >>> t1.hour
        11
        >>> t1.minute
        22
        >>> t1.second
        33
        >>> t1.tzname()
        'UTC'

        >>> t2 = parse_timetz('11:22')
        >>> t2.hour
        11
        >>> t2.minute
        22
        >>> t2.second
        0
        >>> t2.tzname()
        'UTC'

        >>> eastern = timezone('US/Eastern')
        >>> teastern = parse_timetz('11:22', tz=eastern)
        >>> teastern.tzname()
        'US/Eastern'

        >>> parse_timetz('11:66')
        Traceback (most recent call last):
          ...
        ValueError: minute must be in 0..59


    """
    parts = s.split(":")
    hh, mm = map(int, parts[:2])
    ss = 0
    if len(parts) > 2:
        ss = int(parts[2])
    return time(hh, mm, ss, tzinfo=tz)


# A hook for unit tests and functional tests:  overrides the "now"
# utcnow() will return its return value if it is not None
_utcnow_hook = None


def utcnow():
    """Return the datetime of now with a UTC timezone.

        >>> tick = utc.localize(datetime.utcnow())
        >>> tack = utcnow()
        >>> tock = utc.localize(datetime.utcnow())
        >>> tick <= tack <= tock
        True

        >>> tack.tzinfo
        <UTC>

    Is hookable for tests by setting the utcnow_hook module global:

        >>> from schooltool.calendar import utils
        >>> utils._utcnow_hook = lambda: datetime(1970, 1, 1, 1, 1, tzinfo=utc)
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 1, 1, tzinfo=<UTC>)

    Clean up:

        >>> utils._utcnow_hook = None
    """
    global _utcnow_hook
    if _utcnow_hook is not None:
        return _utcnow_hook()
    else:
        return utc.localize(datetime.utcnow())


def stub_utcnow(value):
    """Provide a fake value that utcnow will return.

    The fake value can be a datetime:

        >>> stub_utcnow(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)

    Alternatively, it can be a callable:

        >>> def faketime():
        ...    yield datetime(1970, 1, 1, 0, 0, tzinfo=utc)
        ...    yield datetime(1970, 1, 1, 0, 1, tzinfo=utc)
        ...    yield datetime(1970, 1, 1, 0, 2, tzinfo=utc)

        >>> stub_utcnow(faketime().next)
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 0, 1, tzinfo=<UTC>)
        >>> utcnow()
        datetime.datetime(1970, 1, 1, 0, 2, tzinfo=<UTC>)

    When we set the stubbed value to None, utcnow starts returning real time:

        >>> stub_utcnow(None)

        >>> tick = utc.localize(datetime.utcnow())
        >>> tack = utcnow()
        >>> tock = utc.localize(datetime.utcnow())
        >>> tick <= tack <= tock
        True

    """
    global _utcnow_hook
    if value is None:
        _utcnow_hook = None
    elif callable(value):
        _utcnow_hook = value
    else:
        _utcnow_hook = lambda: value


addCleanUp(stub_utcnow, (None, ))