/usr/lib/python2.7/dist-packages/pycalendar/utils.py is in python-pycalendar 2.1~svn15020-1.
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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | ##
# Copyright (c) 2007-2013 Cyrus Daboo. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from pycalendar.parser import ParserContext
import cStringIO as StringIO
def readFoldedLine(ins, lines):
# If line2 already has data, transfer that into line1
if lines[1] is not None:
lines[0] = lines[1]
else:
# Fill first line
try:
myline = ins.readline()
if len(myline) == 0:
raise ValueError
if myline[-1] == "\n":
if myline[-2] == "\r":
lines[0] = myline[:-2]
else:
lines[0] = myline[:-1]
elif myline[-1] == "\r":
lines[0] = myline[:-1]
else:
lines[0] = myline
except IndexError:
lines[0] = ""
except:
lines[0] = None
return False
# Now loop looking ahead at the next line to see if it is folded
while True:
# Get next line
try:
myline = ins.readline()
if len(myline) == 0:
raise ValueError
if myline[-1] == "\n":
if myline[-2] == "\r":
lines[1] = myline[:-2]
else:
lines[1] = myline[:-1]
elif myline[-1] == "\r":
lines[1] = myline[:-1]
else:
lines[1] = myline
except IndexError:
lines[1] = ""
except:
lines[1] = None
return True
if not lines[1]:
return True
# Does it start with a space => folded
if lines[1][0].isspace():
# Copy folded line (without space) to current line and cycle
# for more
lines[0] = lines[0] + lines[1][1:]
else:
# Not folded - just exit loop
break
return True
def find_first_of(text, tokens, offset):
for ctr, c in enumerate(text[offset:]):
if c in tokens:
return offset + ctr
return -1
def escapeTextValue(value):
os = StringIO.StringIO()
writeTextValue(os, value)
return os.getvalue()
def writeTextValue(os, value):
try:
start_pos = 0
end_pos = find_first_of(value, "\r\n;\\,", start_pos)
if end_pos != -1:
while True:
# Write current segment
os.write(value[start_pos:end_pos])
# Write escape
os.write("\\")
c = value[end_pos]
if c == '\r':
os.write("r")
elif c == '\n':
os.write("n")
elif c == ';':
os.write(";")
elif c == '\\':
os.write("\\")
elif c == ',':
os.write(",")
# Bump past escapee and look for next segment
start_pos = end_pos + 1
end_pos = find_first_of(value, "\r\n;\\,", start_pos)
if end_pos == -1:
os.write(value[start_pos:])
break
else:
os.write(value)
except:
pass
def decodeTextValue(value):
os = StringIO.StringIO()
start_pos = 0
end_pos = find_first_of(value, "\\", start_pos)
size_pos = len(value)
if end_pos != -1:
while True:
# Write current segment upto but not including the escape char
os.write(value[start_pos:end_pos])
# Bump to escapee char but not past the end
end_pos += 1
if end_pos >= size_pos:
break
# Unescape
c = value[end_pos]
if c == 'r':
os.write('\r')
elif c == 'n':
os.write('\n')
elif c == 'N':
os.write('\n')
elif c == '':
os.write('')
elif c == '\\':
os.write('\\')
elif c == ',':
os.write(',')
elif c == ';':
os.write(';')
elif c == ':':
# ":" escape normally invalid
if ParserContext.INVALID_COLON_ESCAPE_SEQUENCE == ParserContext.PARSER_RAISE:
raise ValueError
elif ParserContext.INVALID_COLON_ESCAPE_SEQUENCE == ParserContext.PARSER_FIX:
os.write(':')
# Other escaped chars normally not allowed
elif ParserContext.INVALID_ESCAPE_SEQUENCES == ParserContext.PARSER_RAISE:
raise ValueError
elif ParserContext.INVALID_ESCAPE_SEQUENCES == ParserContext.PARSER_FIX:
os.write(c)
# Bump past escapee and look for next segment (not past the end)
start_pos = end_pos + 1
if start_pos >= size_pos:
break
end_pos = find_first_of(value, "\\", start_pos)
if end_pos == -1:
os.write(value[start_pos:])
break
else:
os.write(value)
return os.getvalue()
def encodeParameterValue(value):
"""
RFC6868 parameter encoding.
"""
# Test for encoded characters first as encoding is expensive and it is better to
# avoid doing it if it is not required (which is the common case)
encode = False
for c in "\r\n\"^":
if c in value:
encode = True
if encode:
encoded = []
last = ''
for c in value:
if c in "\r\n\"^":
if c == '\r':
encoded.append("^n")
elif c == '\n':
if last != '\r':
encoded.append("^n")
elif c == '"':
encoded.append("^'")
elif c == '^':
encoded.append("^^")
else:
encoded.append(c)
last = c
return "".join(encoded)
else:
return value
def decodeParameterValue(value):
"""
RFC6868 parameter decoding.
"""
# Test for encoded characters first as decoding is expensive and it is better to
# avoid doing it if it is not required (which is the common case)
if value is not None and "^" in value:
decoded = []
last = ''
for c in value:
if last == '^':
if c == 'n':
decoded.append('\n')
elif c == '\'':
decoded.append('"')
elif c == '^':
decoded.append('^')
c = ''
else:
decoded.append('^')
decoded.append(c)
elif c != '^':
decoded.append(c)
last = c
if last == '^':
decoded.append('^')
return "".join(decoded)
else:
return value
# vCard text list parsing/generation
def parseTextList(data, sep=';', always_list=False):
"""
Each element of the list has to be separately un-escaped
"""
results = []
item = []
pre_s = ''
for s in data:
if s == sep and pre_s != '\\':
results.append(decodeTextValue("".join(item)))
item = []
else:
item.append(s)
pre_s = s
results.append(decodeTextValue("".join(item)))
return tuple(results) if len(results) > 1 or always_list else (results[0] if len(results) else "")
def generateTextList(os, data, sep=';'):
"""
Each element of the list must be separately escaped
"""
try:
if isinstance(data, basestring):
data = (data,)
results = [escapeTextValue(value) for value in data]
os.write(sep.join(results))
except:
pass
# vCard double-nested list parsing/generation
def parseDoubleNestedList(data, maxsize):
results = []
items = [""]
pre_s = ''
for s in data:
if s == ';' and pre_s != '\\':
if len(items) > 1:
results.append(tuple([decodeTextValue(item) for item in items]))
elif len(items) == 1:
results.append(decodeTextValue(items[0]))
else:
results.append("")
items = [""]
elif s == ',' and pre_s != '\\':
items.append("")
else:
items[-1] += s
pre_s = s
if len(items) > 1:
results.append(tuple([decodeTextValue(item) for item in items]))
elif len(items) == 1:
results.append(decodeTextValue(items[0]))
else:
results.append("")
for _ignore in range(maxsize - len(results)):
results.append("")
if len(results) > maxsize:
if ParserContext.INVALID_ADR_N_VALUES == ParserContext.PARSER_FIX:
results = results[:maxsize]
elif ParserContext.INVALID_ADR_N_VALUES == ParserContext.PARSER_RAISE:
raise ValueError
return tuple(results)
def generateDoubleNestedList(os, data):
try:
def _writeElement(item):
if isinstance(item, basestring):
writeTextValue(os, item)
else:
if item:
writeTextValue(os, item[0])
for bit in item[1:]:
os.write(",")
writeTextValue(os, bit)
for item in data[:-1]:
_writeElement(item)
os.write(";")
_writeElement(data[-1])
except:
pass
# Date/time calcs
days_in_month = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days_in_month_leap = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
def daysInMonth(month, year):
# NB month is 1..12 so use dummy value at start of array to avoid index
# adjustment
if isLeapYear(year):
return days_in_month_leap[month]
else:
return days_in_month[month]
days_upto_month = (0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
days_upto_month_leap = (0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
def daysUptoMonth(month, year):
# NB month is 1..12 so use dummy value at start of array to avoid index
# adjustment
if isLeapYear(year):
return days_upto_month_leap[month]
else:
return days_upto_month[month]
cachedLeapYears = {}
def isLeapYear(year):
try:
return cachedLeapYears[year]
except KeyError:
if year <= 1752:
result = (year % 4 == 0)
else:
result = ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)
cachedLeapYears[year] = result
return result
cachedLeapDaysSince1970 = {}
def leapDaysSince1970(year_offset):
try:
return cachedLeapDaysSince1970[year_offset]
except KeyError:
if year_offset > 2:
result = (year_offset + 1) / 4
elif year_offset < -1:
# Python will round down negative numbers (i.e. -5/4 = -2, but we want -1), so
# what is (year_offset - 2) in C code is actually (year_offset - 2 + 3) in Python.
result = (year_offset + 1) / 4
else:
result = 0
cachedLeapDaysSince1970[year_offset] = result
return result
# Packed date
def packDate(year, month, day):
return (year << 16) | (month << 8) | (day + 128)
def unpackDate(data, unpacked):
unpacked[0] = (data & 0xFFFF0000) >> 16
unpacked[1] = (data & 0x0000FF00) >> 8
unpacked[2] = (data & 0xFF) - 128
def unpackDateYear(data):
return (data & 0xFFFF0000) >> 16
def unpackDateMonth(data):
return (data & 0x0000FF00) >> 8
def unpackDateDay(data):
return (data & 0xFF) - 128
# Display elements
def getMonthTable(month, year, weekstart, table, today_index):
from pycalendar.datetime import DateTime
# Get today
today = DateTime.getToday(None)
today_index = [-1, -1]
# Start with empty table
table = []
# Determine first weekday in month
temp = DateTime(year, month, 1, 0)
row = -1
initial_col = temp.getDayOfWeek() - weekstart
if initial_col < 0:
initial_col += 7
col = initial_col
# Counters
max_day = daysInMonth(month, year)
# Fill up each row
for day in range(1, max_day + 1):
# Insert new row if we are at the start of a row
if (col == 0) or (day == 1):
table.extend([0] * 7)
row += 1
# Set the table item to the current day
table[row][col] = packDate(temp.getYear(), temp.getMonth(), day)
# Check on today
if (temp.getYear() == today.getYear()) and (temp.getMonth() == today.getMonth()) and (day == today.getDay()):
today_index = [row, col]
# Bump column (modulo 7)
col += 1
if (col > 6):
col = 0
# Add next month to remainder
temp.offsetMonth(1)
if col != 0:
day = 1
while col < 7:
table[row][col] = packDate(temp.getYear(), temp.getMonth(), -day)
# Check on today
if (temp.getYear() == today.getYear()) and (temp.getMonth() == today.getMonth()) and (day == today.getDay()):
today_index = [row, col]
day += 1
col += 1
# Add previous month to start
temp.offsetMonth(-2)
if (initial_col != 0):
day = daysInMonth(temp.getMonth(), temp.getYear())
back_col = initial_col - 1
while(back_col >= 0):
table[row][back_col] = packDate(temp.getYear(), temp.getMonth(), -day)
# Check on today
if (temp.getYear() == today.getYear()) and (temp.getMonth() == today.getMonth()) and (day == today.getDay()):
today_index = [0, back_col]
back_col -= 1
day -= 1
return table, today_index
def set_difference(v1, v2):
if len(v1) == 0 or len(v2) == 0:
return v1
s1 = set(v1)
s2 = set(v2)
s3 = s1.difference(s2)
return list(s3)
|