Attachment 'sstable-1.0.2.py'
Download 1
2 """
3 MoinMoin - sstable a Processor for spread sheet calculations using only Python.
4
5 @license: GNU GPL, see COPYING for details.
6
7 PURPOSE:
8 This processor is used to do some spread sheet calculation in a regular wiki
9 table using only Python. The first column/first line coordinate is A0.
10
11 This code is based on the spreadsheet code posted by Raymond Hettinger and
12 Richard Copeland at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355045
13 It is also based on the sctable parser by Reimar Bauer (R.Bauer AT fz-juelich.de).
14
15 CALLING SEQUENCE:
16 {{{
17 #!sstable [-column_header, -row_header, -show_formular, -format,
18 -input_separator, -output_separator ]
19 }}}
20
21 OPTIONAL INPUTS:
22 -column_header: additional in the result the column header is shown
23 -row_header: additional in the result the line number header is shown
24 -show_formular: if set the formular instead of the result is shown,
25 data is arranged in textmode. Blanks in formulars are removed
26 -format: is used to the set the number of digits for the column values
27 -input_separator: used to read tables delimitted by something other than the
28 default '||'
29 -output_separator: used to write tables delimitted by something other than the
30 default '||'
31
32
33 EXAMPLE:
34 {{{
35 SUM over columns}}}
36 {{{
37 #!sstable
38 ||1||2||=A0+B0||
39 ||10||20||=@sum(A1:B1)||
40 }}}
41
42 RESULT:
43 ||<)>1.00||<)>2.00||<)>3.00||
44 ||<)>10.00||<)>20.00||<)>30.00||
45 -----
46
47 {{{
48 cell B1 no data}}}
49
50 {{{
51 #!sstable
52 ||A||B||C||D||
53 ||1||||2||=A1+C1||
54 }}}
55
56 RESULT:
57 ||<(>A||<(>B||<(>C||<(>D||
58 ||<)>1.00||<)>||<)>2.00||<)>3.00||
59
60 -----
61 {{{
62 SUM over rows}}}
63 {{{
64 #!sstable
65 ||1||2||=A0+B0||
66 ||10||20||30||
67 ||=@sum(A0:A1)||=@sum(B0:B1)||=@sum(C0:C1)||
68 }}}
69
70 RESULT:
71 ||<)>1.00||<)>2.00||<)>3.00||
72 ||<)>10.00||<)>20.00||<)>30.00||
73 ||<)>11.00||<)>22.00||<)>33.00||
74
75 -----
76 {{{
77 SUM over rows and columns}}}
78 {{{
79 #!sstable
80 ||A||B||C||
81 ||1||2||=A1+B1||
82 ||10||20||=@sum(A2:B2)||
83 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
84 }}}
85
86 RESULT:
87 ||<(>A||<(>B||<(>C||
88 ||<)>1.00||<)>2.00||<)>3.00||
89 ||<)>10.00||<)>20.00||<)>30.00||
90 ||<)>11.00||<)>22.00||<)>33.00||
91
92 -----
93 {{{
94 -column_header}}}
95 {{{
96 #!sstable -column_header
97 ||1||2||
98 ||3||4||
99 ||5||6||
100 }}}
101
102 RESULT:
103 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
104 ||<)>1.00||<)>2.00||
105 ||<)>3.00||<)>4.00||
106 ||<)>5.00||<)>6.00||
107
108
109 -----
110 {{{
111 -row_header}}}
112 {{{
113 #!sstable -row_header
114 ||1||2||
115 ||3||4||
116 ||5||6||
117 }}}
118
119 RESULT:
120 ||<)5%#CCCCCC>'''0'''||<)>1.00||<)>2.00||
121 ||<)5%#CCCCCC>'''1'''||<)>3.00||<)>4.00||
122 ||<)5%#CCCCCC>'''2'''||<)>5.00||<)>6.00||
123
124 -----
125 {{{
126 -column_header -row_header}}}
127 {{{
128 #!sstable -column_header -row_header
129 ||1||2||
130 ||3||4||
131 ||5||6||
132 }}}
133
134 RESULT:
135 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
136 ||<)5%#CCCCCC>'''0'''||<)>1.00||<)>2.00||
137 ||<)5%#CCCCCC>'''1'''||<)>3.00||<)>4.00||
138 ||<)5%#CCCCCC>'''2'''||<)>5.00||<)>6.00||
139
140 -----
141 {{{
142 -show_formular -column_header -row_header}}}
143 {{{
144 #!sstable -show_formular -column_header -row_header
145 ||m||p||
146 ||1||=A1 * 5||
147 ||2||=A2-3||
148 ||3||4||
149 }}}
150
151 RESULT:
152 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
153 ||<)5%#CCCCCC>'''0'''||<(>m||<(>p||
154 ||<)5%#CCCCCC>'''1'''||<(>1||<(>=A1*5||
155 ||<)5%#CCCCCC>'''2'''||<(>2||<(>=A2-3||
156 ||<)5%#CCCCCC>'''3'''||<(>3||<(>4||
157
158 -----
159 {{{
160 -column_header and blanks in cells}}}
161 {{{
162 #!sstable -column_header
163 ||Name Vorname|| || || 3 || || 5||
164 ||Name Vorname|| 1 || 2 || || 4 || 5||
165 ||Name Vorname|| 1 || 2 || || || 5||
166 }}}
167
168 RESULT:
169 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||<:#CCCCCC>'''C'''||<:#CCCCCC>'''D'''||<:#CCCCCC>'''E'''||<:#CCCCCC>'''F'''||
170 ||<(>Name Vorname|| || ||<)>3.00|| ||<)>5.00||
171 ||<(>Name Vorname||<)>1.00||<)>2.00|| ||<)>4.00||<)>5.00||
172 ||<(>Name Vorname||<)>1.00||<)>2.00|| || ||<)>5.00||
173
174 -----
175 {{{
176 -format 1,1}}}
177 {{{
178 #!sstable -format 1,1
179 ||1||2||
180 ||3||4||
181 ||=@sum(a0:a1)||=a2*4||
182 }}}
183
184 RESULT:
185 ||<)>1.0||<)>2.0||
186 ||<)>3.0||<)>4.0||
187 ||<)>4.0||<)>16.0||
188
189 -----
190 {{{ useage of variable names -show_formular -column_header -row_header
191 }}}
192 {{{#!sstable -show_formular -column_header -row_header
193 ||A||B||C||
194 ||1||{two}2||=A1+two||
195 ||10||20||=@sum(A2:B2)||
196 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
197 }}}
198
199
200 RESULT:
201 ||<:5%#CCCCCC> ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||<:#CCCCCC>'''C'''||
202 ||<)5%#CCCCCC>'''0'''||<(>A||<(>B||<(>C||
203 ||<)5%#CCCCCC>'''1'''||<(>1||<(>{two}2||<(>=A1+two||
204 ||<)5%#CCCCCC>'''2'''||<(>10||<(>20||<(>=@sum(A2:B2)||
205 ||<)5%#CCCCCC>'''3'''||<(>=@sum(A1:A2)||<(>=@sum(B1:B2)||<(>=@sum(C1:C2)||
206
207 and if we calculate [[BR]]
208 RESULT:
209 {{{#!sstable -column_header -row_header
210 ||A||B||C||
211 ||1||{two}2||=A1+two||
212 ||10||20||=@sum(A2:B2)||
213 ||=@sum(A1:A2)||=@sum(B1:B2)||=@sum(C1:C2)||
214 }}}
215 -----
216 {{{color in cells
217 }}}
218 {{{#!sstable
219 ||<:rowbgcolor=lightcyan>'''A'''||<:>'''B'''||<:>'''C'''||
220 ||<)#dddddd>1||<)#dddddd>{two}2||<)#cccccc>=A1+two||
221 ||<(>10||<)>20||<:#dddddd>=@sum(A2:B2)||
222 ||<rowbgcolor="#cc99ff">=@sum(A1:A2)||=@sum(B1:B2)||<bgcolor=magenta>=@sum(C1:C2)||
223 }}}
224
225 RESULT:
226 ||<:rowbgcolor=lightcyan>'''A'''||<:>'''B'''||<:>'''C'''||
227 ||<)#dddddd>1.00||<)#dddddd>2.00||<)#cccccc>3.00||
228 ||<(>10.00||<)>20.00||<:#dddddd>30.00||
229 ||<rowbgcolor="#cc99ff">11.00||22.00||<bgcolor=magenta>33.00||
230 -----
231 {{{delimit input with ','
232 }}}
233 {{{
234 #!sstable -column_header -input_separator ,
235 ,1,2,
236 ,3,4,
237 ,5,6,
238 }}}
239
240 RESULT:
241 ||<:#CCCCCC>'''A'''||<:#CCCCCC>'''B'''||
242 ||<)>1.00||<)>2.00||
243 ||<)>3.00||<)>4.00||
244 ||<)>5.00||<)>6.00||
245 -----
246 {{{delimit input and output with ','
247 }}}
248 {{{
249 #!sstable -column_header -row_header -input_separator , -output_separator ,
250 1,2
251 3,4
252 5,6
253 }}}
254
255 RESULT:
256 {{{
257 ,''' ''','''A''','''B''',
258 ,'''0''', 1.00, 2.00,
259 ,'''1''', 3.00, 4.00,
260 ,'''2''', 5.00, 6.00,
261 }}}
262 -----
263
264
265
266 PROCEDURE:
267 All formulars have to start by a "=" sign.
268 All formulars do not need to start with a "@", but they can.
269
270 Please remove the version number from the routine name!
271
272
273 MODIFICATION:
274 @copyright: 2006-03-25 by Andrew Shewmaker (agshew AT gmail) sstable-1.0
275
276 1.0.2: improved cell range functions - Andrew Shewmaker
277 correct special character handling - Reimar Bauer
278 1.0.1: use unicode function - Andrew Shewmaker
279 1.0: based on sctable-1.5.2-5 by Reimar Bauer (R.Bauer AT fz-juelich.de)
280 """
281
282 Dependencies = []
283 import re
284 from math import *
285 from MoinMoin.parser import wiki
286 from MoinMoin.action import AttachFile
287 from MoinMoin.Page import Page
288 from MoinMoin import wikiutil
289
290 class SpreadSheet:
291 _cells = {}
292 tools = {}
293 _cache = None
294 def __init__(self):
295 self.tools.update({'__builtins__':None})
296 pmath = { 'ceil':ceil, 'floor':floor, \
297 'fabs':fabs, \
298 'fmod':fmod, 'modf':modf, \
299 'frexp':frexp, 'ldexp':ldexp, \
300 'exp':exp, \
301 'log':log, 'log10':log10, \
302 'pow':pow, \
303 'sqrt':sqrt, \
304 'acos':acos, 'asin':asin, 'atan':atan, 'atan2':atan2, \
305 'cos':cos, 'sin':sin, 'tan':tan, \
306 'cosh':cosh, 'sinh':sinh, 'tanh':tanh, \
307 'hypot':hypot, \
308 'degrees':degrees, 'radians':radians, \
309 'pi':pi, 'e':e, \
310 'cmp':cmp, \
311 'len':len, \
312 'round':round, \
313 'hex':hex, 'oct':oct, \
314 'max':self.max, 'min':self.min, \
315 'sum':self.sum, 'average':self.average, 'median':self.median, \
316 }
317 self.tools.update(pmath)
318
319 def getformula(self, key):
320 return self._cells[key]
321
322 def max(self, keys):
323 return max(map(self.__getitem__, self.cellrange(keys)))
324
325 def min(self, keys):
326 return min(map(self.__getitem__, self.cellrange(keys)))
327
328 def sum(self, keys):
329 return sum(map(self.__getitem__, self.cellrange(keys)))
330
331 def average(self, keys):
332 cells = map(self.__getitem__, self.cellrange(keys))
333 return sum(cells)/float(len(cells))
334
335 def median(self, keys):
336 cells = map(self.__getitem__, self.cellrange(keys))
337 n = len(cells)
338 midpt = n/2
339 if (n%2): # Number of elements in data set is odd.
340 return cells[midpt]
341 else: # Number of elements in data set is even.
342 return (cells[midpt-1] + cells[midpt])/2.0
343
344 def __setitem__(self, key, formula):
345 self._cells[key.lower()] = formula
346
347 def __getitem__(self, key):
348 bCache = self._cache is None
349 if bCache: self._cache = {}
350 while True:
351 try:
352 if ( self._cells[key] == None or self._cells[key] == ''):
353 rv = ''
354 else:
355 rv = eval(self._cells[key], self.tools, self._cache)
356 break
357 except NameError, ne:
358 name = ne.args[0][6:-16] # Extract name from NameError
359 if name in self._cells:
360 self._cache[name] = self[name]
361 else:
362 self._cache[key] = None
363 self._cells[key] = None
364 except SyntaxError, se:
365 rv = self._cells[key]
366 break
367 except TypeError, te:
368 rv = 'type error: ' + self._cells[key] + ', ' + str(te)
369 break
370
371 if bCache: self._cache = None
372 return rv
373
374 def cellrange(self, keys):
375 m = re.search('([a-z]+)(\d+):([a-z])+(\d+)?', keys)
376
377 result = []
378 if m == None:
379 result = re.split(',', keys)
380 return result
381
382 (c1, r1, c2, r2) = m.groups()
383
384 mincol = min(c1, c2)
385 maxcol = max(c1, c2)
386 minrow = min(int(r1), int(r2))
387 maxrow = max(int(r1), int(r2))
388
389 col_names = 'abcdefghijklmnopqrstuvwxyz'
390 for i in range(col_names.index(mincol), col_names.index(maxcol)+1):
391 for j in range(minrow, maxrow+1):
392 result.append(col_names[i] + str(j))
393
394 return result
395
396
397 class Parser:
398
399 def __init__(self, raw, request, **kw):
400 self.ss = SpreadSheet()
401 self.raw = raw
402 self.request = request
403 self.form = request.form
404 self._ = request.getText
405 self.kw = []
406 for arg in kw.get('format_args','').split():
407 self.kw.append(arg)
408
409
410 def format(self, formatter):
411 lines = self.raw.split('\n')
412
413 kw = self.kw
414 column_header = 0
415 row_header = 0
416 show_formular = 0
417 format = ''
418 insep = '||'
419 outsep = '||'
420 right_format = '<)>'
421 left_format = '<(>'
422 colheader_format = '<:#CCCCCC>'
423 rowheader_format = '<)5%#CCCCCC>'
424 zt = 0
425 for test in kw:
426 if test == '-column_header': column_header = 1
427 if test == '-row_header': row_header = 1
428 if test == '-show_formular': show_formular = 1
429 if test == '-format': format = re.split(',', kw[zt+1])
430 if test == '-input_separator': insep = kw[zt+1]
431 if test == '-output_separator':
432 outsep = kw[zt+1]
433 right_format = ''
434 left_format = ''
435 colheader_format = ''
436 rowheader_format = ''
437 zt += 1
438
439 formats = {} # { (row,col): '<wikiformat>', ... }
440 r = 0 # row counter
441 c = 0 # column counter
442 col_names = 'abcdefghijklmnopqrstuvwxyz'
443 maxcolumns = 0
444
445 for txt in lines:
446 txt = txt.lstrip()
447 if ( txt == '' ):
448 continue
449 columns = txt.split(insep)
450 if re.search('^' + insep, txt):
451 columns = columns[1:]
452 if re.search(insep + '$', txt):
453 columns = columns[:-1]
454
455 if ( len(columns) > maxcolumns):
456 maxcolumns = len(columns)
457
458 c = 0
459 for cell in columns:
460 cellname = col_names[c]+str(r)
461 cell = cell.strip()
462
463 # check for wiki formatting string at beginning of ss data: "<format>..."
464 if cell.startswith('<'):
465 p = cell.find('>') + 1
466 if p > 1:
467 formats[(r,c)] , cell = cell[:p] , cell[p:]
468 cell = cell.strip()
469 else:
470 formats[(r,c)] = ""
471
472 # compatibility with other spreadsheet syntax
473 # case insensitivity for everything after an '='
474 m = re.search('=@?(.+)', cell)
475 nonstr_match = re.match('^[\d+-\.\{]', cell)
476 if m == None and nonstr_match == None:
477 cell = '"' + cell + '"'
478 elif m != None:
479 cell = m.group(1).lower()
480
481 # cell ranges are parsed as strings
482 m = re.search('(\w+).(\w+:\w+).', cell)
483 if m != None:
484 cell = m.group(1) + "('" + m.group(2) + "')"
485
486 # lowercase variable names
487 m = re.search('\{(.+)\}(.+)', cell)
488 if m != None:
489 cell = m.group(2).lower()
490 self.ss[m.group(1)] = cellname
491
492 # '=' and '@' are unnecessary after the parsing above
493 cell = re.sub('=@?', '', cell)
494
495 self.ss[cellname] = cell
496
497 c += 1
498
499 r += 1
500
501 maxrows = r
502 result = ""
503
504 if outsep != '||':
505 self.request.write('<pre>')
506
507 if column_header == 1:
508 header_names = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
509 result += '\n' + outsep
510 if row_header == 1:
511 start = 0
512 else:
513 start = 1
514
515 for name in header_names[start:maxcolumns+1]:
516 result += colheader_format + "'''" + name + "'''" + outsep
517
518 for r in range(maxrows):
519 result += '\n' + outsep
520
521 if row_header == 1:
522 result += rowheader_format + "'''" + str(r) + "'''" + outsep
523
524 for c in range(maxcolumns):
525 cellname = col_names[c]+str(r)
526
527 if self.ss[cellname] == '':
528 cell = ' '
529 else:
530 cell = str(self.ss[cellname])
531
532 if show_formular == 0:
533 nonstr_match = re.match('^[\d+-\.\{]', cell)
534 if nonstr_match != None:
535 fmt = right_format
536 if formats[(r,c)] != '':
537 fmt = formats[(r,c)]
538
539 if format == '':
540 cell = '%s %.*f' % (fmt, 2, float(self.ss[cellname]))
541 else:
542 cell = '%s %.*f' % (fmt, int(format[c-1]), float(self.ss[cellname]))
543
544 elif show_formular == 1:
545 cell = self.ss.getformula(cellname)
546 else:
547 if formats[(r,c)] == '':
548 cell = left_format + cell
549 else:
550 cell = formats[(r,c)] + cell
551
552 result += cell + outsep
553
554 if outsep != '||':
555 self.request.write(result + '</pre>')
556 else:
557 result = result[1:]
558 result = wikiutil.unquoteWikiname(result)
559 wikiizer = wiki.Parser(result,self.request) # parser for wiki tabular
560 wikiizer.format(formatter)
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.