Attachment 'sstable-1.0.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@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: based on sctable-1.5.2-5
 277 """
 278 
 279 Dependencies = []
 280 import re
 281 from math import *
 282 from MoinMoin.parser import wiki
 283 from MoinMoin.action import AttachFile
 284 from MoinMoin.Page import Page
 285 
 286 class SpreadSheet:
 287     _cells = {}
 288     tools = {}
 289     _cache = None
 290     def __init__(self):
 291       self.tools.update({'__builtins__':None})  
 292       pmath = { 'ceil':ceil, 'floor':floor, \
 293                 'fabs':fabs, \
 294                 'fmod':fmod, 'modf':modf, \
 295                 'frexp':frexp, 'ldexp':ldexp, \
 296                 'exp':exp, \
 297                 'log':log, 'log10':log10, \
 298                 'pow':pow, \
 299                 'sqrt':sqrt, \
 300                 'acos':acos, 'asin':asin, 'atan':atan, 'atan2':atan2, \
 301                 'cos':cos, 'sin':sin, 'tan':tan, \
 302                 'cosh':cosh, 'sinh':sinh, 'tanh':tanh, \
 303                 'hypot':hypot, \
 304                 'degrees':degrees, 'radians':radians, \
 305                 'pi':pi, \
 306                 'e':e, \
 307                 'max':self.max, 'min':self.min, \
 308                 'sum':self.sum, \
 309                }
 310       self.tools.update(pmath)
 311 
 312     def getformula(self, key):
 313         return self._cells[key]
 314 
 315     def max(self, key):
 316         result = 0
 317         for cellname in self.cellrange(key):
 318             result = max(self.__getitem__(cellname), result)
 319 
 320         return result
 321 
 322     def min(self, key):
 323         result = self.cellrange(key)
 324         for cellname in self.cellrange(key):
 325             result = min(self.__getitem__(cellname), result)
 326 
 327         return result
 328 
 329     def sum(self, key):
 330         result = 0
 331         for cellname in self.cellrange(key):
 332             result += self.__getitem__(cellname)
 333 
 334         return result
 335 
 336     def __setitem__(self, key, formula):
 337         self._cells[key.lower()] = formula
 338 
 339     def __getitem__(self, key):
 340         bCache = self._cache is None
 341         if bCache: self._cache = {}
 342         while True:
 343             try:
 344                 if ( self._cells[key] == None or self._cells[key] == ''):
 345                     rv = ''
 346                 else:
 347                     rv = eval(self._cells[key], self.tools, self._cache)
 348                 break
 349             except NameError, ne:
 350                 name = ne.args[0][6:-16] # Extract name from NameError
 351                 if name in self._cells:
 352                     self._cache[name] = self[name]
 353                 else:
 354                     self._cache[key] = None
 355                     self._cells[key] = None
 356             except SyntaxError, se:
 357                 rv = self._cells[key]
 358                 break
 359             except TypeError, te:
 360                 rv = 'type error: ' + self._cells[key] + ', ' + str(te)
 361                 break
 362                 
 363         if bCache: self._cache = None
 364         return rv
 365 
 366     def cellrange(self, keys):
 367         m = re.search('([a-z]+)(\d+):([a-z])+(\d+)?', keys)
 368         
 369         result = []
 370         if m == None:
 371             result = re.split(',', keys)
 372             return result
 373         
 374         (c1, r1, c2, r2) = m.groups()
 375         
 376         mincol = min(c1, c2)
 377         maxcol = max(c1, c2)
 378         minrow = min(int(r1), int(r2))
 379         maxrow = max(int(r1), int(r2))
 380         
 381         col_names = 'abcdefghijklmnopqrstuvwxyz'
 382         for i in range(col_names.index(mincol), col_names.index(maxcol)+1):
 383             for j in range(minrow, maxrow+1):
 384                 result.append(col_names[i] + str(j))
 385         
 386         return result
 387 
 388 
 389 class Parser:
 390 
 391     def __init__(self, raw, request, **kw):
 392         self.ss = SpreadSheet()
 393         self.raw = raw
 394         self.request = request
 395         self.form = request.form
 396         self._ = request.getText
 397         self.kw = []
 398         for arg in kw.get('format_args','').split():
 399             self.kw.append(arg)
 400 
 401             
 402     def format(self, formatter):
 403         lines = self.raw.split('\n')
 404         
 405         kw = self.kw
 406         column_header = 0
 407         row_header = 0
 408         show_formular = 0
 409         format = ''
 410         insep = '||'
 411         outsep = '||'
 412         right_format = '<)>'
 413         left_format = '<(>'
 414         colheader_format = '<:#CCCCCC>'
 415         rowheader_format = '<)5%#CCCCCC>'
 416         zt = 0
 417         for test in kw:
 418              if test == '-column_header': column_header = 1
 419              if test == '-row_header': row_header = 1
 420              if test == '-show_formular': show_formular = 1
 421              if test == '-format': format = re.split(',', kw[zt+1])
 422              if test == '-input_separator': insep = kw[zt+1]
 423              if test == '-output_separator':
 424                  outsep = kw[zt+1]
 425                  right_format = ''
 426                  left_format = ''
 427                  colheader_format = ''
 428                  rowheader_format = ''
 429              zt += 1
 430 
 431         formats = {} # { (row,col): '<wikiformat>', ... }
 432         r = 0 # row counter
 433         c = 0 # column counter
 434         col_names = 'abcdefghijklmnopqrstuvwxyz'
 435         maxcolumns = 0
 436     
 437         for txt in lines:
 438             txt = txt.lstrip()
 439             if ( txt == '' ):
 440                 continue
 441             columns = txt.split(insep)
 442             if re.search('^' + insep, txt):
 443                 columns = columns[1:]
 444             if re.search(insep + '$', txt):
 445                 columns = columns[:-1]
 446                     
 447             if ( len(columns) > maxcolumns):
 448                 maxcolumns = len(columns)
 449             
 450             c = 0
 451             for cell in columns:
 452                 cellname = col_names[c]+str(r)
 453                 cell = cell.strip()
 454                 
 455                 # check for wiki formatting string at beginning of ss data: "<format>..."
 456                 if cell.startswith('<'):
 457                     p = cell.find('>') + 1
 458                     if p > 1:
 459                         formats[(r,c)] , cell = cell[:p] , cell[p:]
 460                         cell = cell.strip()
 461                 else:
 462                     formats[(r,c)] = ""
 463     
 464                 # compatibility with other spreadsheet syntax
 465                 # case insensitivity for everything after an '='
 466                 m = re.search('=@?(.+)', cell)
 467                 nonstr_match = re.match('^[\d+-\.\{]', cell)
 468                 if m == None and nonstr_match == None:
 469                     cell = '"' + cell + '"'
 470                 elif m != None:
 471                     cell = m.group(1).lower()
 472 
 473                 # cell ranges are parsed as strings
 474                 m = re.search('(\w+).(\w+:\w+).', cell)
 475                 if m != None:
 476                     cell = m.group(1) + "('" + m.group(2) + "')"
 477 
 478                 # lowercase variable names
 479                 m = re.search('\{(.+)\}(.+)', cell)
 480                 if m != None:
 481                     cell = m.group(2).lower()
 482                     self.ss[m.group(1)] = cellname
 483 
 484                 # '=' and '@' are unnecessary after the parsing above
 485                 cell = re.sub('=@?', '', cell)
 486 
 487                 self.ss[cellname] = cell
 488 
 489                 c += 1
 490     
 491             r += 1
 492         
 493         maxrows = r
 494         result = ""
 495 
 496         if outsep != '||':
 497             self.request.write('<pre>')
 498 
 499         if column_header == 1:
 500             header_names = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 501             result += '\n' + outsep
 502             if row_header == 1:
 503                 start = 0
 504             else:
 505                 start = 1
 506         
 507             for name in header_names[start:maxcolumns+1]:
 508                 result += colheader_format + "'''" + name + "'''" + outsep
 509 
 510         for r in range(maxrows):
 511             result += '\n' + outsep
 512 
 513             if row_header == 1:
 514                 result += rowheader_format + "'''" + str(r) + "'''" + outsep
 515 
 516             for c in range(maxcolumns):
 517                 cellname = col_names[c]+str(r)
 518 
 519                 if self.ss[cellname] == '':
 520                     cell = ' '
 521                 else:
 522                     cell = str(self.ss[cellname])
 523 
 524                 if show_formular == 0:
 525                     nonstr_match = re.match('^[\d+-\.\{]', cell)
 526                     if nonstr_match != None:
 527                         fmt = right_format
 528                         if formats[(r,c)] != '':
 529                             fmt = formats[(r,c)]
 530 
 531                         if format == '':
 532                             cell = '%s %.*f' % (fmt, 2, float(self.ss[cellname]))
 533                         else:
 534                             cell = '%s %.*f' % (fmt, int(format[c-1]), float(self.ss[cellname]))
 535 
 536                 elif show_formular == 1:
 537                     cell = self.ss.getformula(cellname)
 538                 else:
 539                     if formats[(r,c)] == '':
 540                         cell = left_format + cell
 541                     else:
 542                         cell = formats[(r,c)] + cell
 543 
 544                 result += cell + outsep
 545 
 546         if outsep != '||':
 547             self.request.write(result + '</pre>')
 548         else:
 549             result = result[1:]
 550             wikiizer = wiki.Parser(result,self.request) # parser for wiki tabular
 551             #wikiizer = wiki.Parser(unicode(result,'latin-1'),self.request) # parser for wiki tabular
 552             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.
  • [get | view] (2006-04-01 17:45:06, 14.7 KB) [[attachment:sstable-1.0.1.py]]
  • [get | view] (2006-04-02 07:33:02, 15.3 KB) [[attachment:sstable-1.0.2.py]]
  • [get | view] (2006-04-25 05:57:23, 15.4 KB) [[attachment:sstable-1.0.3.py]]
  • [get | view] (2006-04-26 13:08:24, 15.5 KB) [[attachment:sstable-1.0.4.py]]
  • [get | view] (2006-04-01 07:10:19, 14.7 KB) [[attachment:sstable-1.0.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.