~openerp-community/openobject-server/training

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
# macros.py

# Subversion Details
# $LastChangedDate: 2005-05-28 12:14:08 +0100 (Sat, 28 May 2005) $
# $LastChangedBy: fuzzyman $
# $HeadURL: https://svn.rest2web.python-hosting.com/trunk/rest2web.py $
# $LastChangedRevision: 28 $

# macros for rest2web
# http://www.voidspace.org.uk/python/rest2web

# Adapted from macros.py for Firedrop2 by Hans Nowak
# http://zephyrfalcon.org

# Copyright Michael Foord, 2004 & 2005.
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml

# For information about bugfixes, updates, and support,
# please join the Pythonutils mailing list.
# http://groups.google.com/group/pythonutils/
# Comments, suggestions, and bug reports, welcome.
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# E-mail fuzzyman@voidspace.org.uk

# FIXME: Sort smiley stuff....
# XXXX
smiley_path, smiley_url = 'smilies', '/smilies/'


adblock = '    <!--#include virtual="/includes/adblock.shtml" -->'
hiddennetwork = '    <!--#include virtual="/includes/_hiddennetwork.shtml" -->'

import cStringIO
import os
import sys
import traceback

uservalues = {}
namespace = {}

def _set_uservalues(n, u):
    """Set the namespace and uservalues for the page."""
    global namespace
    global uservalues
    uservalues = u
    namespace = n

##sys.__stdout__.write(os.getcwd())

# curlyl and curlyr is a way of including literal
# curly brackets in pages
curlyl = '{'
curlyr = '}'

cl = curlyl
cr = curlyr

# {emoticon;name}  e.g. {emoticon;smile}
def emoticon(name):
    """
    Return a link to a named gif file
    in the emoticons/ folder.
    """
    name = name.strip()
    if q in ('movpy', 'firedrop2'):
        return '<img src="emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
    else:
        return '<img src="/emoticons/%s.gif" alt="emoticon:%s" />' % (name, name)
emo = emoticon

def acronym(acronym, meaning=None):
    """
    Return the HTML for an acronym.
    """
    if meaning is None:
        # will raise a KeyError if the acronym isn't found
        meaning = acronyms[acronym.lower()]
    return '<acronym title="%s">%s</acronym>' % (meaning, acronym)
acro = acronym

# a dictionary of standard acronyms
# keys should be lowercase
acronyms = {
    'wysiwyg': 'What You See Is What You Get',
    'html': 'HyperText Markup Language',
    'xml': 'eXtensible Markup Language',
    'xhtml': 'eXtensible HyperText Markup Language',
    'rest': 'ReStructuredText',
    'css': 'Cascading Style Sheets',
    'ie': 'Internet Exploder',
    'ide': 'Integrated Development Environment',
    'afaik': 'As Far as I Know',
    'ianal': 'I am not a Lawyer',
    'ssi': 'Server Side Includes',
    'cgi': 'Common Gateway Interface',
    'lol': 'Laughing Out Loud',
    'rotfl': 'Roll On the Floor Laughing',
    'http': 'HyperText Transfer Protocol',
    'ascii': 'American Standard Code for Information Interchange',
    'gui': 'Graphical User Interface',
    'cli': 'Command Line Interface',
    'pda': 'Personal Digital Assistant',
    'rtfm': 'Read the Manual',
    'ftp': 'File Transfer Protocol',
    'nntp': 'Network News Transfer Protocol',
    'uk': 'United Kingdom',
    'pc': 'Personal Computer',
    'url': 'Uniform Resource Locator',
    'uri': 'Uniform Resource Identifier',
    'tcp/ip': 'Transport Control Protocol/Internet Protocol',
    'udp': 'User Data Paragram',
    'yagni': 'You Aint Gonna Need It',
    }

def include(filename, escape='False'):
    """
    Include a file in the page.
    HTML only of course.
    """
    data = open(filename, 'r').read()
    if escape.lower() not in ['false', 'off', '0', 'no']:
        # FIXME: Should we check for invalid options and raise an error ?
        data = data.replace('\r\n', '\n')
        data = data.replace('\r', '\n')
        data = data.replace('\n', '<br />\n').replace('  ', '&nbsp;&nbsp;')
    return data
inc = include

try:
    import smiley as smiley_module
except ImportError:
    def smiley(text):
        """
        Attempting to use this without having the smiley module available
        will raise an ImportError.
        """
        raise ImportError, "Importing smiley.py failed."
#
else:
    smile = None
    def smiley(text):
        """
        Create a smiley.
        The smiley lib is only created on the first run through.
        """
        global smile
        if smile is None:
             smile = smiley_module.lib(smiley_path, smiley_url)
        s = smile.makehappy(' %s ' % text)
        s = s.replace('\n', '')
        return s.replace(' />', ' height="15" width="15" />')    # add the height
sm = smiley


# syntax coloring with Pygments
try:
    from pygments import highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import HtmlFormatter
except ImportError:
    def colorize(filename):
        raise ImportError, 'Importing pygments failed.'
    class coloring:
        def open(self, data):
            raise ImportError, 'Importing pygments failed.'
        def close(self, *args):
            pass
else:
    class coloring:

        lexer_options = dict(
                stripall=True
        )
        formatter_options = dict(
            linenos=True,
            cssclass="highlight"
        )

        def __init__(self, lexer_options=None, formatter_options=None):
            self.lexer_options = self.lexer_options.copy()
            if lexer_options:
                self.lexer_options.update(lexer_otions)
            self.formatter_options = self.formatter_options.copy()
            if formatter_options:
                self.formatter_options.update(formatter_otions)

        def open(self, data):
            lexer = get_lexer_by_name("python", **self.lexer_options)
            formatter = HtmlFormatter(**self.formatter_options)
            return highlight(data, lexer, formatter)

        def close(self, *args):
            pass

    def colorize(filename):
        """Format Python script as syntax coloured HTML.

        Using the appropriate css it will be nicely colored.

        Needs the Pygments package.

        """
        fullname = os.path.join(filename)
        f = open(fullname, 'r')
        data = f.read()
        f.close()
        #
        colorizer = coloring()
        return colorizer.open(data)

col = colorize


def name(n):
    return '<a name="%s" id="%s"></a>' % (n, n)

def title(text, size=3):
    """For titles of a named size"""
    return '<h%s>%s</h%s>' % (size, text, size)

def small(text):
    return '<small>%s</small>' % text

#############################################################
#
# Anything below this line is specific to Voidspace
# and probably not useful (except maybe as examples....)

def target_title(target, title, cls='', ):
    """Return a title as a target."""
    t = '<a href="#%s" %s><h2>%s</h2></a>'
    if cls:
        cls = 'class="%s"' % cls
    return t % (target, cls, title)

def index_title(Title, subtitle=''):
    """target_title for voidspace"""
    a = target_title('index', Title, 'titlelink')
    if subtitle:
        a += title(subtitle)
    return a

class IndexTable:
    """
    For generating Index Tables

    The first line is the number of columns and the width in pixels.
    The next line is the summary.
    The next line is the title.
    Following lines are either target and title, or just a single value
    if they are the same.
    """
    def open(self, data):
        data = [line.strip() for line in data.split('\n') if line.strip()]
        cols, width = data.pop(0).split(' ')
        cols = int(cols)
        start = ('<div class="index-table"><table class="index-table"'
            'border="1" width="%s" summary="%s">')
        start = start % (width, data.pop(0))
        #
        out = [start, '<colgroup>']
        width = 100 / cols
        for i in range(cols):
            out.append('<col width="%s" />' % width)
        out.append('</colgroup>')
        #
        title = data.pop(0)
        out.append('<thead valign="bottom"><tr><th class="head" '
                   'colspan="%s">%s</th></tr></thead>' % (cols, title))
        out.append('<tbody valign="top">')
        #
        out.append('<tr>')
        i = -1
        while i < len(data) -1:
            i += 1
            val = data[i].split(' ', 1)
            if len(val) == 2:
                target, name = val
            else:
                target = name = val[0]
            if i and not i % cols:
                out.append('</tr><tr>')
            line = '<td><a href="#%s">%s</a></td>'
            out.append(line %(target, name))
        for i in range((i+1) % cols):
            out.append('<td>&nbsp;</td>')
        out.append('</tr><tr>')
        for i in range(cols):
            out.append('<td>&nbsp;</td>')
        out.append('</tr></tbody></table></div>')
        return '\n'.join(out)

    def close(self, *args):
        pass


_link = "/cgi-bin/voidspace/downman.py?file=%s"
def dl(file, text=''):
    """Create a download link for downman."""
    if not text:
        text = file
    link = _link % file
    return '<a href="%s">%s</a>' % (link, text)


# a dictionary allowing you to dynamically
# assign your smiley URL depending on where you're running this
# from.
_smiley_loc = { 'makedoc': ('smilies', 'smilies/'),
                'Webstuff Python': ('../makedoc/smilies', '/smilies/'),
                'General Blog': ('../../makedoc/smilies', '/smilies/'),
                'building blog': ('../../makedoc/smilies', '/smilies/'),
                'Techie Blog': ('../../makedoc/smilies', '/smilies/'),
                'movpy': ('docs_html/images/smilies', 'images/smilies/'),
                'firedrop2': ('../smilies', 'smilies/'),
                'branches': ('firedrop2-dist/firedrop2/docs_html/smilies', 'smilies/'),
                }

p = os.getcwd().replace('/', '\\')
q = True
while p and q:
    p, q = os.path.split(p)
    if q in _smiley_loc and 'Python Projects' in p:
        smiley_path, smiley_url = _smiley_loc[q]
        smiley_path = os.path.abspath(smiley_path)
        break

##print os.path.abspath(smiley_path)

##_links = {
##    'python': 'http://www.python.org',
##    'firedrop2': 'http://zephyrfalcon.org/labs',
##    'Pythonutils Mailing List': 'http://groups.google.com/group/pythonutils/',
##    'Jesus Fellowship Church': 'http://www.jesus.org.uk',
##    'Hans Nowak': 'http://zephyrfalcon.org/weblog2',
##    'rest': 'http://docutils.sourceforge.net',
##    'The Techie Blog': '/python/weblog/',
##    'The Voidspace Blogspot': '/voidspace/index.shtml',
##    '': '',
##    '': '',
##}
##
##def standardlinks():
##    out = ['']
##    for entry in _links:
##        if entry:
##            out.append(('.. _%s: ' % entry) + _links[entry])
##    return '\n'.join(out) + '\n'

"""
TODO

Add a globaldict with some values for the current page - e.g. the encoding being used and the current page location.

CHANGELOG
2005/06/16
Added a set of standard acronyms.

2005/06/03
Added the coloring advanced macro.

2005/05/31
curlyl and curlyr added.
Some docstrings added.
Removed __all__ as it's not actually used.
Changed the smiley macro so that it doesn't create a new smiley object each run through.
colorize raises an import error if you attempt to use it and colorize.py isn't available.
Added escape option to the include macro.
In the event of error - colorize raises the error rather than trapping it.
Added the col=colorize alias.
Added the inc=include alias.

2005/05/28
Integrated with rest2web, via the config file.

"""