Commit f90d18e7 authored by Martijn Pieters's avatar Martijn Pieters

Clean up indentation and trailing whitespace.

parent 023c1df8
......@@ -31,7 +31,7 @@ class UnitTestSecurityPolicy:
, *args
, **kw):
return 1
def checkPermission( self, permission, object, context) :
return 1
......@@ -41,7 +41,7 @@ class UnitTestUser( Acquisition.Implicit ):
"""
def getId( self ):
return 'unit_tester'
getUserName = getId
def allowed( self, object, object_roles=None ):
......@@ -55,7 +55,7 @@ def makeConnection():
return ZODB.DB( s ).open()
class TestCopySupport( unittest.TestCase ):
def setUp( self ):
self.connection = makeConnection()
......@@ -230,4 +230,3 @@ def main():
if __name__ == '__main__':
main()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import os, sys, unittest
......@@ -36,7 +36,7 @@ def createBigFile():
size = (1<<16) * 5
file = cStringIO.StringIO()
def addLetter(x, add=file.write, l=string.letters,
def addLetter(x, add=file.write, l=string.letters,
c=random.choice):
add(c(l))
filter(addLetter, range(size))
......@@ -106,7 +106,7 @@ class TestRequestRange(unittest.TestCase):
def createLastModifiedDate(self, offset=0):
return rfc1123_date(self.file._p_mtime + offset)
def expectUnsatisfiable(self, range):
req = self.app.REQUEST
rsp = req.RESPONSE
......@@ -115,7 +115,7 @@ class TestRequestRange(unittest.TestCase):
req.environ['HTTP_RANGE'] = 'bytes=%s' % range
body = self.doGET(req, rsp)
self.failUnless(rsp.getStatus() == 416,
'Expected a 416 status, got %s' % rsp.getStatus())
......@@ -138,7 +138,7 @@ class TestRequestRange(unittest.TestCase):
req.environ['HTTP_IF_RANGE'] = if_range
body = self.doGET(req, rsp)
self.failUnless(rsp.getStatus() == 200,
'Expected a 200 status, got %s' % rsp.getStatus())
......@@ -152,7 +152,7 @@ class TestRequestRange(unittest.TestCase):
req.environ['HTTP_IF_RANGE'] = if_range
body = self.doGET(req, rsp)
self.failUnless(rsp.getStatus() == 206,
'Expected a 206 status, got %s' % rsp.getStatus())
......@@ -167,7 +167,7 @@ class TestRequestRange(unittest.TestCase):
'Incorrect Content-Length is set! Expected %d, got %d.' % (
rsp.getHeader('content-length'), len(body)))
self.failUnless(body == self.data[start:end],
self.failUnless(body == self.data[start:end],
'Incorrect range returned, expected %s, got %s' % (
`self.data[start:end]`, `body`))
......@@ -183,10 +183,10 @@ class TestRequestRange(unittest.TestCase):
req.environ['HTTP_REQUEST_RANGE'] = 'bytes=%s' % range
body = self.doGET(req, rsp)
self.failUnless(rsp.getStatus() == 206,
'Expected a 206 status, got %s' % rsp.getStatus())
self.failIf(rsp.getHeader('content-range'),
self.failIf(rsp.getHeader('content-range'),
'The Content-Range header should not be set!')
ct = string.split(rsp.getHeader('content-type'), ';')[0]
......@@ -231,7 +231,7 @@ class TestRequestRange(unittest.TestCase):
# in Python 2.2.
if body[-2:] == '\r\n':
body = body[:-2]
self.failIf(len(body) != end - start,
'Part (%d, %d) is of wrong length, expected %d, got %d.' % (
start, end, end - start, len(body)))
......@@ -313,14 +313,14 @@ class TestRequestRange(unittest.TestCase):
def testMultipleRangesBigFile(self):
self.uploadBigFile()
self.expectMultipleRanges('3-700,10-15,-10000',
self.expectMultipleRanges('3-700,10-15,-10000',
[(3, 701), (len(self.data) - 10000, len(self.data))])
def testMultipleRangesBigFileEndOverflow(self):
self.uploadBigFile()
l = len(self.data)
start, end = l - 100, l + 100
self.expectMultipleRanges('3-700,%s-%s' % (start, end),
self.expectMultipleRanges('3-700,%s-%s' % (start, end),
[(3, 701), (len(self.data) - 100, len(self.data))])
# If-Range headers
......
......@@ -30,7 +30,7 @@ class UnitTestSecurityPolicy:
, *args
, **kw):
return 1
def checkPermission( self, permission, object, context) :
return 1
......@@ -40,7 +40,7 @@ class UnitTestUser( Acquisition.Implicit ):
"""
def getId( self ):
return 'unit_tester'
getUserName = getId
def allowed( self, object, object_roles=None ):
......@@ -54,7 +54,7 @@ def makeConnection():
return ZODB.DB( s ).open()
class TestTraverse( unittest.TestCase ):
def setUp( self ):
self.connection = makeConnection()
......@@ -137,4 +137,3 @@ def main():
if __name__ == '__main__':
main()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Restricted Python Expressions
"""
__rcs_id__='$Id: Eval.py,v 1.4 2001/11/28 15:51:11 matt Exp $'
__version__='$Revision: 1.4 $'[11:-2]
__rcs_id__='$Id: Eval.py,v 1.5 2002/08/14 21:44:31 mj Exp $'
__version__='$Revision: 1.5 $'[11:-2]
from string import translate, strip
import string
......@@ -84,8 +84,8 @@ class RestrictionCapableEval:
i=0
code=co.co_code
l=len(code)
LOAD_NAME=101
HAVE_ARGUMENT=90
LOAD_NAME=101
HAVE_ARGUMENT=90
while(i < l):
c=ord(code[i])
if c==LOAD_NAME:
......@@ -119,4 +119,3 @@ class RestrictionCapableEval:
def __call__(self, **kw):
return self.eval(kw)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
from __future__ import nested_scopes
__version__='$Revision: 1.7 $'[11:-2]
__version__='$Revision: 1.8 $'[11:-2]
import new
......@@ -58,7 +58,7 @@ def _full_read_guard(g_attr, g_item):
def __setattr__(self, attr, val):
setattr(write(ob), attr, val)
return Wrapper()
return guard
return guard
def _write_wrapper():
......@@ -100,7 +100,7 @@ def _full_write_guard():
return ob
# Hand the object to the Wrapper instance, then return the instance.
return Wrapper(ob)
return guard
return guard
full_write_guard = _full_write_guard()
def guarded_setattr(object, name, value):
......@@ -110,7 +110,3 @@ safe_builtins['setattr'] = guarded_setattr
def guarded_delattr(object, name):
delattr(full_write_guard(object), name)
safe_builtins['delattr'] = guarded_delattr
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.3 $'[11:-2]
__version__='$Revision: 1.4 $'[11:-2]
limited_builtins = {}
......@@ -44,4 +44,3 @@ def limited_tuple(seq):
raise TypeError, 'cannot convert string to tuple'
return tuple(seq)
limited_builtins['tuple'] = limited_tuple
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.5 $'[11:-2]
__version__='$Revision: 1.6 $'[11:-2]
from SelectCompiler import ast
......@@ -72,4 +72,3 @@ class MutatingWalker:
def walk(tree, visitor):
return MutatingWalker(visitor).dispatchNode(tree)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.3 $'[11:-2]
__version__='$Revision: 1.4 $'[11:-2]
class PrintCollector:
'''Collect written text, and return it when called.'''
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Compiles restricted code using the compiler module from the
Python standard library.
"""
__version__='$Revision: 1.2 $'[11:-2]
__version__='$Revision: 1.3 $'[11:-2]
from compiler import ast, parse, misc, syntax
......@@ -146,4 +146,3 @@ def compile_restricted(source, filename, mode):
"'eval' or 'single'")
gen.compile()
return gen.getCode()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.2 $'[11:-2]
__version__='$Revision: 1.3 $'[11:-2]
import sys
from traceback import format_exception_only
......@@ -56,7 +56,7 @@ def compile_restricted_function(p, body, name, filename):
if err:
if len(err) > 1:
# Drop the first line of the error and adjust the next two.
err[1].pop(0)
err[1].pop(0)
err[1][0] = 'parameters: %s\n' % err[1][0][10:-8]
err[1][1] = ' ' + err[1][1]
return err
......@@ -94,38 +94,38 @@ def compile_restricted_exec(s, filename='<string>', nested_scopes=1):
return gen.getCode(), (), rm.warnings, rm.used_names
if 1:
def compile_restricted_eval(s, filename='<string>', nested_scopes=1):
'''Compile a restricted expression.'''
r = compile_restricted_exec('def f(): return \\\n' + s, filename,
nested_scopes)
err = r[1]
if err:
if len(err) > 1:
err.pop(0) # Discard first line of error
else:
# Extract the code object representing the function body
r = (r[0].co_consts[1],) + r[1:]
return r
def compile_restricted_eval(s, filename='<string>', nested_scopes=1):
'''Compile a restricted expression.'''
r = compile_restricted_exec('def f(): return \\\n' + s, filename,
nested_scopes)
err = r[1]
if err:
if len(err) > 1:
err.pop(0) # Discard first line of error
else:
# Extract the code object representing the function body
r = (r[0].co_consts[1],) + r[1:]
return r
else:
def compile_restricted_eval(s, filename='<string>'):
'''Compile a restricted expression.'''
rm = RestrictionMutator()
tree, err = tryParsing(s, 'eval')
if err:
err[1].pop(0) # Discard first line of error
return err
MutatingWalker.walk(tree, rm)
if rm.errors:
return None, rm.errors, rm.warnings, rm.used_names
# XXX No "EvalCodeGenerator" exists
# so here's a hack that gets around it.
gen = pycodegen.ModuleCodeGenerator(filename)
gen.emit('SET_LINENO', 0)
visitor.walk(tree, gen)
gen.emit('RETURN_VALUE')
return gen.getCode(), (), rm.warnings, rm.used_names
def compile_restricted_eval(s, filename='<string>'):
'''Compile a restricted expression.'''
rm = RestrictionMutator()
tree, err = tryParsing(s, 'eval')
if err:
err[1].pop(0) # Discard first line of error
return err
MutatingWalker.walk(tree, rm)
if rm.errors:
return None, rm.errors, rm.warnings, rm.used_names
# XXX No "EvalCodeGenerator" exists
# so here's a hack that gets around it.
gen = pycodegen.ModuleCodeGenerator(filename)
gen.emit('SET_LINENO', 0)
visitor.walk(tree, gen)
gen.emit('RETURN_VALUE')
return gen.getCode(), (), rm.warnings, rm.used_names
DEBUG = 0
def compile_restricted(source, filename, mode):
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''
RestrictionMutator modifies a tree produced by
compiler.transformer.Transformer, restricting and enhancing the
code in various ways before sending it to pycodegen.
'''
__version__='$Revision: 1.9 $'[11:-2]
__version__='$Revision: 1.10 $'[11:-2]
from SelectCompiler import ast, parse, OP_ASSIGN, OP_DELETE, OP_APPLY
......@@ -271,4 +271,3 @@ class RestrictionMutator:
def visitAugAssign(self, node, walker):
node.node.in_aug_assign = 1
return walker.defaultVisitNode(node)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Read-only Mapping class based on MultiMapping
$Id: SafeMapping.py,v 1.2 2001/11/28 15:51:11 matt Exp $'''
__version__='$Revision: 1.2 $'[11:-2]
$Id: SafeMapping.py,v 1.3 2002/08/14 21:44:31 mj Exp $'''
__version__='$Revision: 1.3 $'[11:-2]
from MultiMapping import MultiMapping
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''
Compiler selector.
$Id: SelectCompiler.py,v 1.3 2001/12/22 16:39:05 Brian Exp $
$Id: SelectCompiler.py,v 1.4 2002/08/14 21:44:31 mj Exp $
'''
import sys
......@@ -40,5 +40,3 @@ else:
compile_restricted_function, \
compile_restricted_exec, \
compile_restricted_eval
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
import string, math, random, whrandom
import DocumentTemplate.sequence
......@@ -65,7 +65,7 @@ def reorder(s, with=None, without=()):
if type(i) is tt and len(i)==2: k, v = i
else: k= v = i
if h(k): del d[k]
for i in with:
if type(i) is tt and len(i)==2: k, v = i
else: k= v = i
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''
RestrictedPython package.
$Id: __init__.py,v 1.4 2001/12/21 19:34:47 shane Exp $
$Id: __init__.py,v 1.5 2002/08/14 21:44:31 mj Exp $
'''
from SelectCompiler import *
from PrintCollector import PrintCollector
......@@ -21,4 +21,3 @@ compile(filename)
from transformer import parse, parseFile
from visitor import walk
from pycodegen import compile
......@@ -496,7 +496,7 @@ class Function(Node):
self.varargs = 1
if flags & CO_VARKEYWORDS:
self.kwargs = 1
def _getChildren(self):
return self.name, self.argnames, self.defaults, self.flags, self.doc, self.code
......
......@@ -17,7 +17,7 @@ def is_future(stmt):
class FutureParser:
features = ("nested_scopes",)
def __init__(self):
self.found = {} # set
......@@ -76,4 +76,3 @@ if __name__ == "__main__":
walk(tree, v)
print v.found
print
......@@ -64,4 +64,3 @@ def mangle(name, klass):
klass = klass[:MANGLE_LEN-tlen]
return "_%s%s" % (klass, name)
......@@ -657,7 +657,7 @@ def twobyte(val):
class LineAddrTable:
"""lnotab
This class builds the lnotab, which is documented in compile.c.
Here's a brief recap:
......
......@@ -143,7 +143,7 @@ class CodeGenerator:
NameFinder, FunctionGen, and ClassGen. These attributes can be
defined in the initClass() method, which is a hook for
initializing these methods after all the classes have been
defined.
defined.
"""
optimized = 0 # is namespace access optimized?
......@@ -245,7 +245,7 @@ class CodeGenerator:
self.emit(prefix + '_NAME', name)
def set_lineno(self, node, force=0):
"""Emit SET_LINENO if node has lineno attribute and it is
"""Emit SET_LINENO if node has lineno attribute and it is
different than the last lineno emitted.
Returns true if SET_LINENO was emitted.
......@@ -475,7 +475,7 @@ class CodeGenerator:
# list comprehensions
__list_count = 0
def visitListComp(self, node):
self.set_lineno(node)
# setup list
......@@ -485,7 +485,7 @@ class CodeGenerator:
self.emit('DUP_TOP')
self.emit('LOAD_ATTR', 'append')
self._implicitNameOp('STORE', append)
stack = []
for i, for_ in zip(range(len(node.quals)), node.quals):
start, anchor = self.visit(for_)
......@@ -500,7 +500,7 @@ class CodeGenerator:
self.visit(node.expr)
self.emit('CALL_FUNCTION', 1)
self.emit('POP_TOP')
for start, cont, anchor in stack:
if cont:
skip_one = self.newBlock()
......@@ -511,7 +511,7 @@ class CodeGenerator:
self.emit('JUMP_ABSOLUTE', start)
self.startBlock(anchor)
self._implicitNameOp('DELETE', append)
self.__list_count = self.__list_count - 1
def visitListCompFor(self, node):
......@@ -592,7 +592,7 @@ class CodeGenerator:
self.setups.pop()
self.emit('JUMP_FORWARD', lElse)
self.startBlock(handlers)
last = len(node.handlers) - 1
for i in range(len(node.handlers)):
expr, target, body = node.handlers[i]
......@@ -623,7 +623,7 @@ class CodeGenerator:
self.nextBlock(lElse)
self.visit(node.else_)
self.nextBlock(end)
def visitTryFinally(self, node):
body = self.newBlock()
final = self.newBlock()
......@@ -662,7 +662,7 @@ class CodeGenerator:
def visitName(self, node):
self.set_lineno(node)
self.loadName(node.name)
def visitPass(self, node):
self.set_lineno(node)
......@@ -1104,7 +1104,7 @@ class NestedScopeCodeGenerator(CodeGenerator):
self.emit('CALL_FUNCTION', 0)
self.emit('BUILD_CLASS')
self.storeName(node.name)
class LGBScopeMixin:
"""Defines initClass() for Python 2.1-compatible scoping"""
......@@ -1124,7 +1124,7 @@ class ModuleCodeGenerator(LGBScopeMixin, CodeGenerator):
__super_init = CodeGenerator.__init__
scopes = None
def __init__(self, filename):
self.graph = pyassem.PyFlowGraph("<module>", filename)
self.__super_init(filename)
......@@ -1132,7 +1132,7 @@ class ModuleCodeGenerator(LGBScopeMixin, CodeGenerator):
class NestedScopeModuleCodeGenerator(NestedScopeMixin,
NestedScopeCodeGenerator):
__super_init = CodeGenerator.__init__
def __init__(self, filename):
self.graph = pyassem.PyFlowGraph("<module>", filename)
self.__super_init(filename)
......@@ -1153,8 +1153,8 @@ class AbstractFunctionCode:
else:
name = func.name
args, hasTupleArg = generateArgList(func.argnames)
self.graph = pyassem.PyFlowGraph(name, filename, args,
optimized=1)
self.graph = pyassem.PyFlowGraph(name, filename, args,
optimized=1)
self.isLambda = isLambda
self.super_init(filename)
......@@ -1183,7 +1183,7 @@ class AbstractFunctionCode:
if type(arg) == types.TupleType:
self.emit('LOAD_FAST', '.%d' % (i * 2))
self.unpackSequence(arg)
def unpackSequence(self, tup):
if VERSION > 1:
self.emit('UNPACK_SEQUENCE', len(tup))
......@@ -1198,7 +1198,7 @@ class AbstractFunctionCode:
unpackTuple = unpackSequence
class FunctionCodeGenerator(LGBScopeMixin, AbstractFunctionCode,
CodeGenerator):
CodeGenerator):
super_init = CodeGenerator.__init__ # call be other init
scopes = None
......
......@@ -130,7 +130,7 @@ class Scope:
rather than free.
Be careful to stop if a child does not think the name is
free.
free.
"""
self.globals[name] = 1
if self.frees.has_key(name):
......@@ -171,7 +171,7 @@ class Scope:
class ModuleScope(Scope):
__super_init = Scope.__init__
def __init__(self):
self.__super_init("global", self)
......@@ -182,7 +182,7 @@ class LambdaScope(FunctionScope):
__super_init = Scope.__init__
__counter = 1
def __init__(self, module, klass=None):
i = self.__counter
self.__counter += 1
......@@ -198,7 +198,7 @@ class SymbolVisitor:
def __init__(self):
self.scopes = {}
self.klass = None
# node that define new scopes
def visitModule(self, node):
......@@ -217,7 +217,7 @@ class SymbolVisitor:
self.visit(node.code, scope)
self.handle_free_vars(scope, parent)
scope.DEBUG()
def visitLambda(self, node, parent):
for n in node.defaults:
self.visit(n, parent)
......@@ -368,8 +368,8 @@ if __name__ == "__main__":
def get_names(syms):
return [s for s in [s.get_name() for s in syms.get_symbols()]
if not (s.startswith('_[') or s.startswith('.'))]
if not (s.startswith('_[') or s.startswith('.'))]
for file in sys.argv[1:]:
print file
f = open(file)
......
......@@ -659,14 +659,14 @@ class Transformer:
n = Backquote(self.com_node(nodelist[1]))
n.lineno = nodelist[0][2]
return n
def atom_number(self, nodelist):
### need to verify this matches compile.c
k = eval(nodelist[0][1])
n = Const(k)
n.lineno = nodelist[0][2]
return n
def atom_string(self, nodelist):
### need to verify this matches compile.c
k = ''
......@@ -699,7 +699,7 @@ class Transformer:
# here, Render it harmless. (genc discards ('discard',
# ('const', xxxx)) Nodes)
return Discard(Const(None))
def com_arglist(self, nodelist):
# varargslist:
# (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
......@@ -758,7 +758,7 @@ class Transformer:
return node[1][1]
def com_fplist(self, node):
# fplist: fpdef (',' fpdef)* [',']
# fplist: fpdef (',' fpdef)* [',']
if len(node) == 2:
return self.com_fpdef(node[1])
list = []
......@@ -807,7 +807,7 @@ class Transformer:
def com_try_finally(self, nodelist):
# try_fin_stmt: "try" ":" suite "finally" ":" suite
n = TryFinally(self.com_node(nodelist[2]),
self.com_node(nodelist[5]))
self.com_node(nodelist[5]))
n.lineno = nodelist[0][2]
return n
......@@ -875,7 +875,7 @@ class Transformer:
raise SyntaxError, "can't assign to operator"
primary = self.com_apply_trailer(primary, ch)
return self.com_assign_trailer(primary, node[-1],
assigning)
assigning)
node = node[1]
elif t == symbol.atom:
t = node[1][0]
......@@ -970,7 +970,7 @@ class Transformer:
# list_if: 'if' test [list_iter]
# XXX should raise SyntaxError for assignment
lineno = node[1][2]
fors = []
while node:
......@@ -1047,7 +1047,7 @@ class Transformer:
for i in range(1, len_nodelist, 2):
node = nodelist[i]
if node[0] == token.STAR or node[0] == token.DOUBLESTAR:
break
break
kw, result = self.com_argument(node, kw)
args.append(result)
else:
......@@ -1092,7 +1092,7 @@ class Transformer:
def com_subscriptlist(self, primary, nodelist, assigning):
# slicing: simple_slicing | extended_slicing
# simple_slicing: primary "[" short_slice "]"
# extended_slicing: primary "[" slice_list "]"
# extended_slicing: primary "[" slice_list "]"
# slice_list: slice_item ("," slice_item)* [","]
# backwards compat slice for '[i:j]'
......
......@@ -79,7 +79,7 @@ class ExampleASTVisitor(ASTVisitor):
you still have to do.
"""
examples = {}
def dispatch(self, node, *args):
self.node = node
meth = self._cache.get(node.__class__, None)
......
......@@ -58,7 +58,7 @@ def allowed_simple():
s = s[:100] + 'b'
s += 'c'
_ = q
return q['x'] + q['y'] + q['z'] + r[0] + r[1] + r[2] + s
def allowed_write(ob):
......@@ -97,7 +97,7 @@ def denied_getitem(ob):
def denied_getitem2(ob):
#ob[1] += 1
ob[1]
def denied_setitem(ob):
ob['x'] = 2
......@@ -154,4 +154,3 @@ def nested_scopes_1():
def f2():
return a
return f1() + f2()
# These are all supposed to raise a SyntaxError when using
# compile_restricted() but not when using compile().
# Each function in this module is compiled using compile_restricted().
......
from string import rfind
import sys, os
......@@ -283,7 +282,7 @@ def main():
runner.run(alltests)
def debug():
test_suite().debug()
test_suite().debug()
def pdebug():
import pdb
......
##############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -8,7 +8,7 @@
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
#############################################################################
from Lexicon import Lexicon
......@@ -82,7 +82,7 @@ class GlobbingLexicon(Lexicon):
return digrams
def getWordId(self, word):
"""Provided 'word', return the matching integer word id."""
......@@ -110,7 +110,7 @@ class GlobbingLexicon(Lexicon):
try: insert=inverse.insert
except AttributeError:
# we have an "old" BTree object
if inverse:
if inverse:
wid=inverse.keys()[-1]+1
else:
self._inverseLex=IOBTree()
......@@ -133,7 +133,7 @@ class GlobbingLexicon(Lexicon):
return wid
def get(self, pattern):
""" Query the lexicon for words matching a pattern."""
wc_set = [self.multi_wc, self.single_wc]
......@@ -161,7 +161,7 @@ class GlobbingLexicon(Lexicon):
if result is None:
return ()
return (result, )
## now get all of the intsets that contain the result digrams
result = None
for digram in digrams:
......@@ -185,7 +185,7 @@ class GlobbingLexicon(Lexicon):
hits.insert(x)
return hits
def __getitem__(self, word):
""" """
return self.get(word)
......@@ -235,12 +235,11 @@ class GlobbingLexicon(Lexicon):
transTable = string.maketrans("", "")
result = string.translate(pat, transTable,
r'()&|!@#$%^{}\<>.')
# First, deal with multi-character globbing
result = string.replace(result, '*', '.*')
# Next, we need to deal with single-character globbing
result = string.replace(result, '?', '.')
return "%s$" % result
return "%s$" % result
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Simple column indices"""
__version__='$Revision: 1.29 $'[11:-2]
__version__='$Revision: 1.30 $'[11:-2]
from Persistence import Persistent
from BTrees.OOBTree import OOBTree
......@@ -54,8 +54,8 @@ class Index(Persistent):
either an attribute name or a record key.
"""
######################################################################
# For b/w compatability, have to allow __init__ calls with zero args
######################################################################
# For b/w compatability, have to allow __init__ calls with zero args
if not data==schema==id==ignore_ex==call_methods==None:
self._data = data
......@@ -64,7 +64,7 @@ class Index(Persistent):
self.ignore_ex=ignore_ex
self.call_methods=call_methods
self._index = OOBTree()
self._reindex()
else:
pass
......@@ -95,7 +95,7 @@ class Index(Persistent):
if not withLengths: return tuple(
filter(nonEmpty,self._index.keys())
)
else:
else:
rl=[]
for i in self._index.keys():
if not nonEmpty(i): continue
......@@ -112,7 +112,7 @@ class Index(Persistent):
index=self._index
get=index.get
if not start: index.clear()
id = self.id
......@@ -180,7 +180,7 @@ class Index(Persistent):
if set is not None: set.remove(i)
def _apply_index(self, request, cid=''):
def _apply_index(self, request, cid=''):
"""Apply the index to query parameters given in the argument,
request
......@@ -244,20 +244,3 @@ class Index(Persistent):
else: return None
return r, (id,)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__=""" Module breaks out Zope specific methods and behavior. In
......@@ -50,7 +50,7 @@ class Lexicon(Persistent, Implicit):
def clear(self):
self._lexicon = OIBTree()
self._inverseLex = IOBTree()
def _convertBTrees(self, threshold=200):
if (type(self._lexicon) is OIBTree and
type(getattr(self, '_inverseLex', None)) is IOBTree):
......@@ -73,7 +73,7 @@ class Lexicon(Persistent, Implicit):
self._inverseLex._p_jar=self._p_jar
convert(inverseLex, self._inverseLex, threshold)
def set_stop_syn(self, stop_syn):
""" pass in a mapping of stopwords and synonyms. Format is:
......@@ -84,22 +84,22 @@ class Lexicon(Persistent, Implicit):
"""
self.stop_syn = stop_syn
def getWordId(self, word):
""" return the word id of 'word' """
wid=self._lexicon.get(word, None)
if wid is None:
if wid is None:
wid=self.assignWordId(word)
return wid
set = getWordId
def getWord(self, wid):
""" post-2.3.1b2 method, will not work with unconverted lexicons """
return self._inverseLex.get(wid, None)
def assignWordId(self, word):
"""Assigns a new word id to the provided word and returns it."""
# First make sure it's not already in there
......@@ -148,7 +148,7 @@ class Lexicon(Persistent, Implicit):
def query_hook(self, q):
""" we don't want to modify the query cuz we're dumb """
return q
......@@ -200,7 +200,3 @@ stop_words=(
)
stop_word_dict={}
for word in stop_words: stop_word_dict[word]=None
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Pluggable Index Base Class """
__version__='$Revision: 1.3 $'[11:-2]
__version__='$Revision: 1.4 $'[11:-2]
import Interface
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
from BTrees.IIBTree import IIBucket
......@@ -16,13 +16,13 @@ from BTrees.IIBTree import weightedIntersection, weightedUnion, difference
from BTrees.OOBTree import OOSet, union
class ResultList:
def __init__(self, d, words, index, TupleType=type(())):
self._index = index
if type(words) is not OOSet: words=OOSet(words)
self._words = words
if (type(d) is TupleType):
d = IIBucket((d,))
elif type(d) is not IIBucket:
......@@ -43,7 +43,7 @@ class ResultList:
def has_key(self, key): return self._dict.has_key(key)
def items(self): return self._dict.items()
def items(self): return self._dict.items()
def __and__(self, x):
return self.__class__(
......@@ -58,7 +58,7 @@ class ResultList:
self._words,
self._index,
)
def __or__(self, x):
return self.__class__(
weightedUnion(self._dict, x._dict)[1],
......@@ -89,7 +89,6 @@ class ResultList:
if d==lp: score = min(score,xdict[id]) # synonyms
else: score = (score+xdict[id])/d
result[id] = score
return self.__class__(
result, union(self._words, x._words), self._index)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Text Index
......@@ -71,7 +71,7 @@ Notes on a new text index design
tree introduces overhead.
Trie structure currently introduces an excessive number of nodes.
Typically, a node per two or three words. Trie has potential to
Typically, a node per two or three words. Trie has potential to
reduce storage because key storage is shared between words.
Maybe an alternative to a Trie is some sort of nested BTree. Or
......@@ -86,9 +86,9 @@ Notes on a new text index design
Then:
- After some point, tree objects no longer change
If this is case, then it doesn\'t make sense to optimize tree for
change.
change.
Additional notes
......@@ -112,7 +112,7 @@ Notes on a new text index design
textSearchResult -- id -> (score, positions)
id -- integer, say 4-byte.
positions -- sequence of integers.
score -- numeric measure of relevence, f(numberOfWords, positions)
......@@ -130,7 +130,7 @@ Notes on a new text index design
space.
"""
__version__='$Revision: 1.30 $'[11:-2]
__version__='$Revision: 1.31 $'[11:-2]
#XXX I strongly suspect that this is broken, but I'm not going to fix it. :(
......@@ -242,7 +242,7 @@ class TextIndex(Persistent):
pass
def unindex_item(self, i, obj=None):
def unindex_item(self, i, obj=None):
return self.index_item(i, obj, 1)
......@@ -255,12 +255,12 @@ class TextIndex(Persistent):
tupleType=type(()),
dictType=type({}),
):
src = Splitter(document_text, self._syn)
src = Splitter(document_text, self._syn)
d = {}
old = d.has_key
last = None
for s in src:
if s[0] == '\"': last=self.subindex(s[1:-1], d, old, last)
else:
......@@ -305,7 +305,7 @@ class TextIndex(Persistent):
def _subindex(self, isrc, d, old, last):
src = Splitter(isrc, self._syn)
src = Splitter(isrc, self._syn)
for s in src:
if s[0] == '\"': last=self.subindex(s[1:-1],d,old,last)
......@@ -328,7 +328,7 @@ class TextIndex(Persistent):
r = self._index.get(word,None)
if r is None: r = {}
return ResultList(r, (word,), self)
r = None
for word in src:
rr = self[word]
......@@ -338,7 +338,7 @@ class TextIndex(Persistent):
return r
def _apply_index(self, request, cid='', ListType=[]):
def _apply_index(self, request, cid='', ListType=[]):
""" Apply the index to query parameters given in the argument,
request
......@@ -350,7 +350,7 @@ class TextIndex(Persistent):
Otherwise two objects are returned. The first object is a
ResultSet containing the record numbers of the matching
records. The second object is a tuple containing the names of
all data fields used.
all data fields used.
"""
id = self.id
......@@ -376,7 +376,7 @@ class TextIndex(Persistent):
if r is None: r = rr
else:
# Note that we *and*/*narrow* multiple search terms.
r = r.intersection(rr)
r = r.intersection(rr)
if r is not None: return r, (id,)
return IISet(), (id,)
......@@ -433,7 +433,7 @@ def parse2(q, default_operator,
if ((i % 2) != 0):
# This word should be an operator; if it is not, splice in
# the default operator.
if type(q[i]) is not ListType and isop(q[i]):
q[i] = operator_dict[q[i]]
else: q[i : i] = [ default_operator ]
......@@ -450,7 +450,7 @@ def parens(s, parens_re = re.compile(r'(\|)').search):
while 1:
index = parens_re(s, index)
if index is None : break
if s[index] == '(':
paren_count = paren_count + 1
if open_index == 0 : open_index = index + 1
......@@ -465,36 +465,36 @@ def parens(s, parens_re = re.compile(r'(\|)').search):
if paren_count == 0: # No parentheses Found
return None
else:
raise QueryError, "Mismatched parentheses"
raise QueryError, "Mismatched parentheses"
def quotes(s, ws = (string.whitespace,)):
# split up quoted regions
splitted = re.split( '[%s]*\"[%s]*' % (ws * 2),s)
split=string.split
# split up quoted regions
splitted = re.split( '[%s]*\"[%s]*' % (ws * 2),s)
split=string.split
if (len(splitted) > 1):
if ((len(splitted) % 2) == 0): raise QueryError, "Mismatched quotes"
for i in range(1,len(splitted),2):
# split the quoted region into words
splitted[i] = filter(None, split(splitted[i]))
if (len(splitted) > 1):
if ((len(splitted) % 2) == 0): raise QueryError, "Mismatched quotes"
# put the Proxmity operator in between quoted words
for j in range(1, len(splitted[i])):
splitted[i][j : j] = [ Near ]
for i in range(1,len(splitted),2):
# split the quoted region into words
splitted[i] = filter(None, split(splitted[i]))
for i in range(len(splitted)-1,-1,-2):
# split the non-quoted region into words
splitted[i:i+1] = filter(None, split(splitted[i]))
# put the Proxmity operator in between quoted words
for j in range(1, len(splitted[i])):
splitted[i][j : j] = [ Near ]
splitted = filter(None, splitted)
else:
# No quotes, so just split the string into words
splitted = filter(None, split(s))
for i in range(len(splitted)-1,-1,-2):
# split the non-quoted region into words
splitted[i:i+1] = filter(None, split(splitted[i]))
return splitted
splitted = filter(None, splitted)
else:
# No quotes, so just split the string into words
splitted = filter(None, split(s))
return splitted
def get_operands(q, i, index, ListType=type([]), StringType=type('')):
'''Evaluate and return the left and right operands for an operator'''
......@@ -523,7 +523,7 @@ def evaluate(q, index, ListType=type([])):
return evaluate(q[0], index)
return index[q[0]]
i = 0
while (i < len(q)):
if q[i] is AndNot:
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Simple column indices"""
__version__='$Revision: 1.30 $'[11:-2]
__version__='$Revision: 1.31 $'[11:-2]
from Globals import Persistent
from Acquisition import Implicit
......@@ -42,7 +42,7 @@ class UnIndex(Persistent, Implicit):
UnIndexes are indexes that contain two index components, the
forward index (like plain index objects) and an inverted
index. The inverted index is so that objects can be unindexed
index. The inverted index is so that objects can be unindexed
even when the old value of the object is not known.
e.g.
......@@ -63,7 +63,7 @@ class UnIndex(Persistent, Implicit):
to ignore exceptions raised while indexing instead of
propagating them.
'call_methods' -- should be set to true if you want the index
'call_methods' -- should be set to true if you want the index
to call the attribute 'id' (note: 'id' should be callable!)
You will also need to pass in an object in the index and
uninded methods for this to work.
......@@ -90,7 +90,7 @@ class UnIndex(Persistent, Implicit):
_index=self._index
self._index=OOBTree()
def convertSet(s,
IITreeSet=IITreeSet, IntType=type(0),
type=type, len=len,
......@@ -103,7 +103,7 @@ class UnIndex(Persistent, Implicit):
except: pass # This is just an optimization.
return IITreeSet(s)
convert(_index, self._index, threshold, convertSet)
_unindex=self._unindex
......@@ -152,8 +152,8 @@ class UnIndex(Persistent, Implicit):
return self._unindex.get(documentId)
else:
return self._unindex.get(documentId, default)
def removeForwardIndexEntry(self, entry, documentId):
"""Take the entry provided and remove any reference to documentId
in its entry in the index."""
......@@ -170,7 +170,7 @@ class UnIndex(Persistent, Implicit):
# index row is an int
del self._index[entry]
try: self.__len__.change(-1)
except AttributeError: pass # pre-BTrees-module instance
except AttributeError: pass # pre-BTrees-module instance
except:
LOG(self.__class__.__name__, ERROR,
('unindex_object could not remove '
......@@ -184,7 +184,7 @@ class UnIndex(Persistent, Implicit):
'from index %s but couldn\'t. This '
'should not happen.' % (repr(entry), str(self.id))))
def insertForwardIndexEntry(self, entry, documentId):
"""Take the entry provided and put it in the correct place
in the forward index.
......@@ -192,7 +192,7 @@ class UnIndex(Persistent, Implicit):
This will also deal with creating the entire row if necessary."""
global _marker
indexRow = self._index.get(entry, _marker)
# Make sure there's actually a row there already. If not, create
# an IntSet and stuff it in first.
if indexRow is _marker:
......@@ -221,7 +221,7 @@ class UnIndex(Persistent, Implicit):
datum = datum()
except AttributeError:
datum = _marker
# We don't want to do anything that we don't have to here, so we'll
# check to see if the new and existing information is the same.
oldDatum = self._unindex.get(documentId, _marker)
......@@ -247,14 +247,14 @@ class UnIndex(Persistent, Implicit):
return None
self.removeForwardIndexEntry(unindexRecord, documentId)
try:
del self._unindex[documentId]
except:
LOG('UnIndex', ERROR, 'Attempt to unindex nonexistent document'
' with id %s' % documentId)
def _apply_index(self, request, cid='', type=type, None=None):
def _apply_index(self, request, cid='', type=type, None=None):
"""Apply the index to query parameters given in the request arg.
The request argument should be a mapping object.
......@@ -366,7 +366,7 @@ class UnIndex(Persistent, Implicit):
if not withLengths:
return tuple(self._index.keys())
else:
else:
rl=[]
for i in self._index.keys():
set = self._index[i]
......@@ -387,4 +387,3 @@ class UnIndex(Persistent, Implicit):
v = IISet((v,))
items.append((k, v))
return items
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
from UnIndex import UnIndex
......@@ -19,9 +19,9 @@ from BTrees.OOBTree import OOSet, difference
class UnKeywordIndex(UnIndex):
meta_type = 'Keyword Index'
"""Like an UnIndex only it indexes sequences of items
Searches match any keyword.
This should have an _apply_index that returns a relevance score
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Text Index
......@@ -19,7 +19,7 @@ undo information so that objects can be unindexed when the old value
is no longer known.
"""
__version__ = '$Revision: 1.52 $'[11:-2]
__version__ = '$Revision: 1.53 $'[11:-2]
import string, re
......@@ -84,13 +84,13 @@ class UnTextIndex(Persistent, Implicit):
'lexicon' is the lexicon object to specify, if None, the
index will use a private lexicon."""
self.id = id
self.ignore_ex = ignore_ex
self.call_methods = call_methods
self.clear()
if lexicon is None:
## if no lexicon is provided, create a default one
self._lexicon = Lexicon()
......@@ -102,7 +102,7 @@ class UnTextIndex(Persistent, Implicit):
def getLexicon(self, vocab_id):
"""Return the Lexicon in use.
Bit of a hack, indexes have been made acquirers so that they
can acquire a vocabulary object from the object system in
Zope. I don't think indexes were ever intended to participate
......@@ -117,7 +117,7 @@ class UnTextIndex(Persistent, Implicit):
def __nonzero__(self):
return not not self._unindex
# Too expensive
#def __len__(self):
# """Return the number of objects indexed."""
......@@ -132,7 +132,7 @@ class UnTextIndex(Persistent, Implicit):
def _convertBTrees(self, threshold=200):
if type(self._lexicon) is type(''):
# Turn the name reference into a hard reference.
# Turn the name reference into a hard reference.
self._lexicon=self.getLexicon(self._lexicon)
if type(self._index) is IOBTree: return
......@@ -148,7 +148,7 @@ class UnTextIndex(Persistent, Implicit):
if type(scores) is not TupleType and type(scores) is not IIBTree():
scores=IIBTree(scores)
return scores
convert(_index, self._index, threshold, convertScores)
......@@ -182,8 +182,8 @@ class UnTextIndex(Persistent, Implicit):
else:
return tuple(map(self.getLexicon(self._lexicon).getWord,
results))
def insertForwardIndexEntry(self, entry, documentId, score=1):
"""Uses the information provided to update the indexes.
......@@ -219,12 +219,12 @@ class UnTextIndex(Persistent, Implicit):
else:
if indexRow.get(documentId, -1) != score:
# score changed (or new entry)
if type(indexRow) is DictType:
indexRow[documentId] = score
if len(indexRow) > 3:
# Big enough to give it's own database record
indexRow=IIBTree(indexRow)
indexRow=IIBTree(indexRow)
index[entry] = indexRow
else:
indexRow[documentId] = score
......@@ -236,7 +236,7 @@ class UnTextIndex(Persistent, Implicit):
def index_object(self, documentId, obj, threshold=None):
""" Index an object:
'documentId' is the integer id of the document
'obj' is the objects to be indexed
'threshold' is the number of words to process between
......@@ -253,13 +253,13 @@ class UnTextIndex(Persistent, Implicit):
source = str(source)
except (AttributeError, TypeError):
return 0
lexicon = self.getLexicon(self._lexicon)
splitter=lexicon.Splitter
wordScores = OIBTree()
last = None
# Run through the words and score them
for word in splitter(source):
if word[0] == '\"':
......@@ -281,7 +281,7 @@ class UnTextIndex(Persistent, Implicit):
# Get rid of document words that are no longer indexed
self.unindex_objectWids(documentId, difference(currentWids, widScores))
# Now index the words. Note that the new xIBTrees are clever
# enough to do nothing when there isn't a change. Woo hoo.
insert=self.insertForwardIndexEntry
......@@ -307,10 +307,10 @@ class UnTextIndex(Persistent, Implicit):
return last
def unindex_object(self, i):
def unindex_object(self, i):
""" carefully unindex document with integer id 'i' from the text
index and do not fail if it does not exist """
index = self._index
unindex = self._unindex
wids = unindex.get(i, None)
......@@ -318,7 +318,7 @@ class UnTextIndex(Persistent, Implicit):
self.unindex_objectWids(i, wids)
del unindex[i]
def unindex_objectWids(self, i, wids):
def unindex_objectWids(self, i, wids):
""" carefully unindex document with integer id 'i' from the text
index and do not fail if it does not exist """
......@@ -355,7 +355,7 @@ class UnTextIndex(Persistent, Implicit):
Note that this differentiates between being passed an Integer
and a String. Strings are looked up in the lexicon, whereas
Integers are assumed to be resolved word ids. """
if isinstance(word, IntType):
# We have a word ID
result = self._index.get(word, {})
......@@ -365,7 +365,7 @@ class UnTextIndex(Persistent, Implicit):
if not splitSource:
return ResultList({}, (word,), self)
if len(splitSource) == 1:
splitSource = splitSource[0]
if splitSource[:1] == splitSource[-1:] == '"':
......@@ -392,7 +392,7 @@ class UnTextIndex(Persistent, Implicit):
return r
def _apply_index(self, request, cid=''):
def _apply_index(self, request, cid=''):
""" Apply the index to query parameters given in the argument,
request
......@@ -400,11 +400,11 @@ class UnTextIndex(Persistent, Implicit):
If the request does not contain the needed parameters, then
None is returned.
Otherwise two objects are returned. The first object is a
ResultSet containing the record numbers of the matching
records. The second object is a tuple containing the names of
all data fields used.
all data fields used.
"""
if request.has_key(self.id):
keys = request[self.id]
......@@ -430,9 +430,9 @@ class UnTextIndex(Persistent, Implicit):
if not keys or not string.strip(keys):
return None
keys = [keys]
r = None
for key in keys:
key = string.strip(key)
if not key:
......@@ -443,7 +443,7 @@ class UnTextIndex(Persistent, Implicit):
if r is not None:
return r, (self.id,)
return (IIBucket(), (self.id,))
......@@ -481,7 +481,7 @@ class UnTextIndex(Persistent, Implicit):
def query(self, s, default_operator=Or):
""" Evaluate a query string.
Convert the query string into a data structure of nested lists
and strings, based on the grouping of whitespace-separated
strings by parentheses and quotes. The 'Near' operator is
......@@ -525,7 +525,7 @@ class UnTextIndex(Persistent, Implicit):
if operandType is IntType:
left = self[left]
elif operandType is StringType:
left = self[left]
left = self[left]
elif operandType is ListType:
left = self.evaluate(left)
......@@ -533,7 +533,7 @@ class UnTextIndex(Persistent, Implicit):
if operandType is IntType:
right = self[right]
elif operandType is StringType:
right = self[right]
right = self[right]
elif operandType is ListType:
right = self.evaluate(right)
......@@ -638,12 +638,12 @@ def parens(s, parens_re=re.compile('[()]').search):
mo = parens_re(s)
if mo is None:
return
open_index = mo.start(0) + 1
paren_count = 0
while mo is not None:
index = mo.start(0)
if s[index] == '(':
paren_count = paren_count + 1
else:
......@@ -655,23 +655,23 @@ def parens(s, parens_re=re.compile('[()]').search):
break
mo = parens_re(s, index + 1)
raise QueryError, "Mismatched parentheses"
raise QueryError, "Mismatched parentheses"
def quotes(s):
split=string.split
if '"' not in s:
return split(s)
# split up quoted regions
splitted = re.split('\s*\"\s*', s)
if (len(splitted) % 2) == 0: raise QueryError, "Mismatched quotes"
for i in range(1,len(splitted),2):
# split the quoted region into words
words = splitted[i] = split(splitted[i])
# put the Proxmity operator in between quoted words
j = len(words) - 1
while j > 0:
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Collected utilities to support database indexing.
$Id: __init__.py,v 1.9 2001/11/28 15:51:11 matt Exp $'''
__version__='$Revision: 1.9 $'[11:-2]
$Id: __init__.py,v 1.10 2002/08/14 21:46:24 mj Exp $'''
__version__='$Revision: 1.10 $'[11:-2]
import warnings
warnings.warn("The usage of the SearchIndex package is deprecated since \
Zope 2.4.\n\
......@@ -23,4 +23,3 @@ and will go away in a future release.\n\
\n\
Please use instead the re-factored modules in Products/PluginIndexes.\n\
",DeprecationWarning)
##############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -8,7 +8,7 @@
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
#############################################################################
import whrandom
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import unittest
from SearchIndex.Splitter import Splitter
class Tests(unittest.TestCase):
def testSplitNormalText(self):
text = 'this is a long string of words'
a = Splitter(text)
r = map(None, a)
assert r == ['this', 'is', 'long', 'string', 'of', 'words']
def testSplitNormalText(self):
text = 'this is a long string of words'
a = Splitter(text)
r = map(None, a)
assert r == ['this', 'is', 'long', 'string', 'of', 'words']
def testDropNumeric(self):
text = '123 456 789 foobar without you nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['foobar', 'without', 'you', 'nothing'], r
def testDropSingleLetterWords(self):
text = 'without you I nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
def testSplitOnNonAlpha(self):
text = 'without you I\'m nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
def testDropNumeric(self):
text = '123 456 789 foobar without you nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['foobar', 'without', 'you', 'nothing'], r
def testDropSingleLetterWords(self):
text = 'without you I nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
def testSplitOnNonAlpha(self):
text = 'without you I\'m nothing'
a = Splitter(text)
r = map(None, a)
assert r == ['without', 'you', 'nothing'], r
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Tests),
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import unittest
......@@ -22,10 +22,10 @@ class Dummy:
def foo( self ):
return self._foo
def __str__( self ):
return '<Dummy: %s>' % self._foo
__repr__ = __str__
class Tests( unittest.TestCase ):
......@@ -45,7 +45,7 @@ class Tests( unittest.TestCase ):
, ( 4, Dummy( ['a', 'b', 'c', 'd'] ) )
, ( 5, Dummy( ['a', 'b', 'c', 'e'] ) )
, ( 6, Dummy( ['a', 'b', 'c', 'e', 'f'] ))
, ( 7, Dummy( [0] ) )
, ( 7, Dummy( [0] ) )
]
self._noop_req = { 'bar': 123 }
self._all_req = { 'foo': ['a'] }
......@@ -90,7 +90,7 @@ class Tests( unittest.TestCase ):
self._index.index_object(999, None)
finally:
zLOG.log_write=old_log_write
def testEmpty( self ):
assert len( self._index ) == 0
assert len( self._index.referencedObjects() ) == 0
......@@ -109,7 +109,7 @@ class Tests( unittest.TestCase ):
self._checkApply( self._some_req, [] )
self._checkApply( self._overlap_req, [] )
self._checkApply( self._string_req, [] )
def testPopulated( self ):
self._populateIndex()
values = self._values
......@@ -154,7 +154,7 @@ class Tests( unittest.TestCase ):
)
result = result.keys()
assert 6 not in result
def testReindexNoChange(self):
self._populateIndex()
expected = Dummy(['foo', 'bar'])
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import unittest
......@@ -23,10 +23,10 @@ class Dummy:
def foo( self ):
return self._foo
def __str__( self ):
return '<Dummy: %s>' % self._foo
__repr__ = __str__
class Tests( unittest.TestCase ):
......@@ -54,7 +54,7 @@ class Tests( unittest.TestCase ):
self._backward[k] = v
keys = self._forward.get( v, [] )
self._forward[v] = keys
self._noop_req = { 'bar': 123 }
self._request = { 'foo': 'abce' }
self._min_req = { 'foo': 'abc'
......@@ -77,7 +77,7 @@ class Tests( unittest.TestCase ):
def _populateIndex( self ):
for k, v in self._values:
self._index.index_object( k, v )
def _checkApply( self, req, expectedValues ):
result, used = self._index._apply_index( req )
if hasattr(result, 'keys'):
......@@ -87,7 +87,7 @@ class Tests( unittest.TestCase ):
'%s | %s' % ( map( None, result ), expectedValues )
for k, v in expectedValues:
assert k in result
def testEmpty( self ):
"Test an empty FieldIndex."
......@@ -108,7 +108,7 @@ class Tests( unittest.TestCase ):
self._checkApply( self._min_req, [] )
self._checkApply( self._max_req, [] )
self._checkApply( self._range_req, [] )
def testPopulated( self ):
""" Test a populated FieldIndex """
self._populateIndex()
......@@ -166,10 +166,10 @@ class Tests( unittest.TestCase ):
40, 41, 42, 43, 50, 51, 52, 53, 60, 61, 62, 63, 70, 71, 72, 73,
80, 81, 82, 83, 90, 91, 92, 93
]
assert r==expect, r
assert r==expect, r
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Tests),
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision$'[11:-2]
......@@ -142,7 +142,7 @@ class NameAssignments:
class Bindings:
__ac_permissions__ = (
('View management screens', ('getBindingAssignments',)),
('Change bindings', ('ZBindings_edit', 'ZBindings_setClient')),
......@@ -188,7 +188,7 @@ class Bindings:
def _createBindCode(self, names):
return names._createCodeBlockForMapping()
def _prepareBindCode(self):
# Creates:
# - a code block that quickly generates "bound_data" and
......@@ -210,7 +210,7 @@ class Bindings:
if bindcount is _marker:
self._prepareBindCode()
bindcount = self._v_bindcount
return bindcount
return bindcount
def _getContext(self):
# Utility for bindcode.
......@@ -281,6 +281,3 @@ class Bindings:
exec bindcode
bound_data = bound_data[0]
return self._exec(bound_data, args, kw)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision$'[11:-2]
......@@ -17,7 +17,7 @@ import Globals
from Bindings import Bindings
class BindingsUI(Bindings):
manage_options = (
{'label':'Bindings',
'action':'ZBindingsHTML_editForm',
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Script module
......@@ -54,4 +54,3 @@ class Script(SimpleItem, BindingsUI):
raise "Redirect", "%s?%s" % (REQUEST['URL1'], join(vv, '&'))
from Signature import _setFuncSignature
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Signature module
......@@ -16,7 +16,7 @@
This provides support for simulating function signatures
"""
__version__='$Revision: 1.5 $'[11:-2]
__version__='$Revision: 1.6 $'[11:-2]
class FuncCode:
......@@ -42,4 +42,3 @@ def _setFuncSignature(self, defaults=None, varnames=(), argcount=-1):
code = FuncCode(varnames, argcount)
if self.func_code != code:
self.func_code = code
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision$'[11:-2]
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Shared classes and functions
$Id: Aqueduct.py,v 1.55 2002/02/15 16:30:29 evan Exp $'''
__version__='$Revision: 1.55 $'[11:-2]
$Id: Aqueduct.py,v 1.56 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.56 $'[11:-2]
import Globals, os
from Globals import Persistent
......@@ -73,12 +73,12 @@ class BaseQuery(Persistent, SimpleItem.Item,
try:
if not arg['optional']: missing.append(name)
except: missing.append(name)
# Note: the code above tries to check if an argument of the
# ZSQL method above has the "optional" flag set (in case the
# argument is omitted from the ZSQL function call). But there
# is neither corresponding code inside the parse() function to
# check for the "optional" parameter nor any documentation.
# is neither corresponding code inside the parse() function to
# check for the "optional" parameter nor any documentation.
# So we omit the check for the optional parameter. There will
# be probably no code break but there will be hopefully more code
# to work as supposed to work.
......@@ -114,7 +114,7 @@ class Searchable(BaseQuery):
def manage_test(self, REQUEST):
'Perform an actual query'
result=self(REQUEST)
report=HTML(custom_default_report(self.id, result))
return apply(report,(self,REQUEST),{self.id:result})
......@@ -123,7 +123,7 @@ class Searchable(BaseQuery):
" "
raise 'Redirect', ("%s/manage_testForm" % URL1)
class Composite:
class Composite:
def _getquery(self,id):
......@@ -141,7 +141,7 @@ class Composite:
if i > 100: raise AttributeError, id
i=i+1
o=o.aq_parent
def myQueryIds(self):
return map(
lambda k, queries=self.queries:
......@@ -291,10 +291,10 @@ def decode(input,output):
output.write(s)
def decodestring(s):
f = StringIO(s)
g = StringIO()
decode(f, g)
return g.getvalue()
f = StringIO(s)
g = StringIO()
decode(f, g)
return g.getvalue()
class Args:
def __init__(self, data, keys):
......@@ -400,7 +400,7 @@ def decapitate(html, RESPONSE=None,
):
mo = header_re.match(html)
mo = header_re.match(html)
if mo is None: return html
headers, html = mo.group(1,3)
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Generic Database Connection Support
$Id: Connection.py,v 1.34 2001/11/28 15:51:13 matt Exp $'''
__version__='$Revision: 1.34 $'[11:-2]
$Id: Connection.py,v 1.35 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.35 $'[11:-2]
import Globals, OFS.SimpleItem, AccessControl.Role, Acquisition, sys
from DateTime import DateTime
......@@ -30,7 +30,7 @@ class Connection(
AccessControl.Role.RoleManager,
OFS.SimpleItem.Item,
Acquisition.Implicit,
):
):
# Specify definitions for tabs:
manage_options=(
......@@ -42,7 +42,7 @@ class Connection(
+AccessControl.Role.RoleManager.manage_options
+OFS.SimpleItem.Item.manage_options
)
# Specify how individual operations add up to "permissions":
__ac_permissions__=(
('View management screens', ('manage_main',)),
......@@ -69,7 +69,7 @@ class Connection(
s=Connection.inheritedAttribute('title_and_id')(self)
if hasattr(self, '_v_connected') and self._v_connected:
s="%s, which is connected" % s
else:
else:
s="%s, which is <font color=red> not connected</font>" % s
return s
......@@ -77,7 +77,7 @@ class Connection(
s=Connection.inheritedAttribute('title_or_id')(self)
if hasattr(self, '_v_connected') and self._v_connected:
s="%s (connected)" % s
else:
else:
s="%s (<font color=red> not connected</font>)" % s
return s
......@@ -87,7 +87,7 @@ class Connection(
self.title=title
self.connection_string=connection_string
if check: self.connect(connection_string)
manage_properties=DTMLFile('dtml/connectionEdit', globals())
def manage_edit(self, title, connection_string, check=None, REQUEST=None):
"""Change connection
......@@ -116,7 +116,7 @@ class Connection(
if REQUEST is None:
return result #return unadulterated result objects
if result._searchable_result_columns():
r=custom_default_report(self.id, result)
else:
......@@ -132,7 +132,7 @@ class Connection(
report=apply(report,(self,REQUEST),{self.id:result})
return report
manage_main=DTMLFile('dtml/connectionStatus', globals())
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Generic Database adapter'''
__version__='$Revision: 1.104 $'[11:-2]
__version__='$Revision: 1.105 $'[11:-2]
import OFS.SimpleItem, Aqueduct, RDB, re
import DocumentTemplate, marshal, md5, base64, Acquisition, os
......@@ -74,7 +74,7 @@ class DA(
_zclass=None
allow_simple_one_argument_traversal=None
template_class=SQL
manage_options=(
(
{'label':'Edit', 'action':'manage_main',
......@@ -87,7 +87,7 @@ class DA(
+AccessControl.Role.RoleManager.manage_options
+OFS.SimpleItem.Item.manage_options
)
# Specify how individual operations add up to "permissions":
__ac_permissions__=(
('View management screens',
......@@ -100,12 +100,12 @@ class DA(
'manage_product_zclass_info', 'PUT')),
('Use Database Methods', ('__call__',''), ('Anonymous','Manager')),
)
def __init__(self, id, title, connection_id, arguments, template):
self.id=str(id)
self.manage_edit(title, connection_id, arguments, template)
manage_advancedForm=DTMLFile('dtml/advanced', globals())
test_url___roles__=None
......@@ -125,7 +125,7 @@ class DA(
def _er(self,title,connection_id,arguments,template,
SUBMIT,sql_pref__cols,sql_pref__rows,REQUEST):
dr,dc = self._size_changes[SUBMIT]
rows=max(1,atoi(sql_pref__rows)+dr)
cols=max(40,atoi(sql_pref__cols)+dc)
e=(DateTime('GMT') + 365).rfc822()
......@@ -162,7 +162,7 @@ class DA(
if self.wl_isLocked():
raise ResourceLockedError, 'SQL Method is locked via WebDAV'
self.title=str(title)
self.connection_id=str(connection_id)
arguments=str(arguments)
......@@ -211,7 +211,7 @@ class DA(
'lib/python/Products/ACMEWidgets/Extensions/foo.py'. If this
failes, then the file 'Extensions/ACMEWidgets.foo.py' will be
used.
"""
# paranoid type checking
if type(max_rows) is not type(1):
......@@ -219,10 +219,10 @@ class DA(
if type(max_cache) is not type(1):
max_cache=atoi(max_cache)
if type(cache_time) is not type(1):
cache_time=atoi(cache_time)
cache_time=atoi(cache_time)
class_name=str(class_name)
class_file=str(class_file)
self.max_rows_ = max_rows
self.max_cache_, self.cache_time_ = max_cache, cache_time
self._v_cache={}, Bucket()
......@@ -236,7 +236,7 @@ class DA(
self._zclass=d['meta_class']
break
if REQUEST is not None:
m="ZSQL Method advanced settings have been set"
return self.manage_advancedForm(self,REQUEST,manage_tabs_message=m)
......@@ -329,7 +329,7 @@ class DA(
None, REQUEST, t, v, tb, None, report)
return report
finally: tb=None
def index_html(self, REQUEST):
......@@ -359,7 +359,7 @@ class DA(
if int(cache[q][0]) == key:
del cache[q]
del keys[-1]
if cache.has_key(query):
k, r = cache[query]
if k > t: return r
......@@ -398,7 +398,7 @@ class DA(
try: DB__=dbc()
except: raise 'Database Error', (
'%s is not connected to a database' % self.id)
if hasattr(self, 'aq_parent'):
p=self.aq_parent
if self._isBeingAccessedAsZClassDefinedInstanceMethod():
......@@ -455,7 +455,7 @@ class DA(
r=results[0]
# if hasattr(self, 'aq_parent'): r=r.__of__(self.aq_parent)
return r
self._arg[key] # raise KeyError if not an arg
return Traverse(self,{},key)
......@@ -481,8 +481,8 @@ class DA(
x['selected'] = (z is Z) and 'selected' or ''
del x['meta_class']
r.append(x)
return r
return r
......@@ -515,7 +515,7 @@ class Traverse(ExtensionClass.Base):
args[name]=key
if len(args) < len(da._arg):
if len(args) < len(da._arg):
return self.__class__(da, args)
key=self # "consume" key
......@@ -547,4 +547,3 @@ class Traverse(ExtensionClass.Base):
r=self.__dict__['_r']
if hasattr(r, name): return getattr(r,name)
return getattr(self.__dict__['_da'], name)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Class for reading RDB files
$Id: RDB.py,v 1.32 2001/11/28 15:51:13 matt Exp $'''
__version__='$Revision: 1.32 $'[11:-2]
$Id: RDB.py,v 1.33 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.33 $'[11:-2]
from string import split, strip, lower, upper, atof, atoi, atol, find, join,find
import DateTime,re
......@@ -43,7 +43,7 @@ Parsers={'n': atof,
class SQLAlias(ExtensionClass.Base):
def __init__(self, name): self._n=name
def __of__(self, parent): return getattr(parent, self._n)
class NoBrains: pass
class DatabaseResults:
......@@ -63,7 +63,7 @@ class DatabaseResults:
self._parent=parent
if zbrains is None: zbrains=NoBrains
while line and line.find('#') != -1 : line=readline()
line=line[:-1]
......@@ -91,14 +91,14 @@ class DatabaseResults:
line=readline()
line=line[:-1]
if line[-1:] in '\r\n': line=line[:-1]
self._defs=defs=split(line,'\t')
if not defs: raise ValueError, 'No column definitions'
if len(defs) != nv:
raise ValueError, (
"""The number of column names and the number of column
definitions are different.""")
i=0
self._parsers=parsers=[]
defre=re.compile(r'([0-9]*)([a-zA-Z])?')
......@@ -126,7 +126,7 @@ class DatabaseResults:
d={'name': name, 'type': type, 'width': width, 'parser': parser}
items.append(d)
dd[name]=d
parsers.append((i,parser))
i=i+1
......@@ -134,7 +134,7 @@ class DatabaseResults:
names=tuple(names)
class r(Record, Implicit, brains, zbrains):
'Result record class'
'Result record class'
r.__record_schema__=schema
for k in filter(lambda k: k[:2]=='__', Record.__dict__.keys()):
......@@ -153,7 +153,7 @@ class DatabaseResults:
binit(self.__of__(parent))
r.__dict__['__init__']=__init__
self._class=r
......@@ -191,7 +191,7 @@ class DatabaseResults:
raise ValueError, (
"""The number of items in record %s is invalid
<pre>%s\n%s\n%s\n%s</pre>
"""
"""
% (index, ('='*40), line, ('='*40), fields))
for i, parser in self._parsers:
try: v=parser(fields[i])
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import ExtensionClass
import string
......@@ -19,7 +19,7 @@ from Record import Record
class SQLAlias(ExtensionClass.Base):
def __init__(self, name): self._n=name
def __of__(self, parent): return getattr(parent, self._n)
class NoBrains: pass
class Results:
......@@ -60,12 +60,12 @@ class Results:
i=i+1
self._nv=nv=len(names)
# Create a record class to hold the records.
names=tuple(names)
class r(Record, Implicit, brains, zbrains):
'Result record class'
'Result record class'
r.__record_schema__=schema
for k in Record.__dict__.keys():
......@@ -86,7 +86,7 @@ class Results:
binit(self)
r.__dict__['__init__']=__init__
self._class=r
# OK, we've read meta data, now get line indexes
......@@ -137,7 +137,7 @@ class Results:
else: nstrings.append(i)
if item.has_key('width'): append('%s%s' % (item['width'], t))
else: r.append(t)
r=[join(self._names, '\t'), join(r,'\t')]
append=r.append
......@@ -157,5 +157,5 @@ class Results:
row[i]=tostr(d[i])
append(join(row,'\t'))
append('')
return join(r,'\n')
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''Search Interface Wizard
$Id: Search.py,v 1.19 2002/07/19 18:24:23 efge Exp $'''
__version__='$Revision: 1.19 $'[11:-2]
$Id: Search.py,v 1.20 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.20 $'[11:-2]
from Globals import DTMLFile
from Aqueduct import custom_default_report, custom_default_zpt_report, nicify, Args
......@@ -39,14 +39,14 @@ def manage_addZSearch(self, report_id, report_title, report_style,
arguments={}
keys=[]
checkPermission=getSecurityManager().checkPermission
checkPermission=getSecurityManager().checkPermission
for q in qs:
url=q.absolute_url()
if input_id:
for name, arg in q._searchable_arguments().items():
if len(qs) > 1: key="%s/%s" % (id,name)
else: key=name
else: key=name
arguments[key]=arg
keys.append(key)
if q._searchable_result_columns() is None:
......@@ -75,7 +75,7 @@ def manage_addZSearch(self, report_id, report_title, report_style,
self.manage_addDocument(
report_id,report_title,
('<dtml-var standard_html_header>\n%s\n'
'<dtml-var standard_html_footer>' %
'<dtml-var standard_html_footer>' %
join(map(lambda q, report_style=report_style:
custom_default_report(q.id, q, no_table=report_style), qs),
'\n<hr>\n')))
......@@ -99,13 +99,13 @@ def manage_addZSearch(self, report_id, report_title, report_style,
self.manage_addProduct['PageTemplates'].manage_addPageTemplate(
report_id,report_title,
('<html><body>\n%s\n'
'</body></html>' %
'</body></html>' %
join(map(lambda q, report_style=report_style:
custom_default_zpt_report(q.id, q, no_table=report_style), qs),
'\n<hr>\n')))
if REQUEST: return self.manage_main(self,REQUEST)
def ZQueryIds(self):
# Note that report server configurations will expend on this
......@@ -133,26 +133,26 @@ def ZQueryIds(self):
# Now extend search to parent
try: o=o.aq_parent
except: return t
if n > 100: return t # Seat belt
n=n+1
def _getquery(self,id):
o=self
i=0
while 1:
__traceback_info__=o
q=getattr(o,id)
try:
if hasattr(q,'_searchable_arguments'):
try: q=q.__of__(self.aq_parent)
except: pass
return q
except: pass
if i > 100: raise AttributeError, id
i=i+1
o=o.aq_parent
o=self
i=0
while 1:
__traceback_info__=o
q=getattr(o,id)
try:
if hasattr(q,'_searchable_arguments'):
try: q=q.__of__(self.aq_parent)
except: pass
return q
except: pass
if i > 100: raise AttributeError, id
i=i+1
o=o.aq_parent
def default_input_form(arguments,action='query',
......@@ -252,14 +252,3 @@ def default_input_zpt_form(arguments,action='query',
'</body></html>\n'
% (tabs, action)
)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
import TM, ThreadLock
......@@ -18,7 +18,7 @@ thunk_lock=ThreadLock.allocate_lock()
class THUNKED_TM(TM.TM):
"""A big heavy hammer for handling non-thread safe DAs
"""
def _register(self):
if not self._registered:
thunk_lock.acquire()
......@@ -30,7 +30,7 @@ class THUNKED_TM(TM.TM):
raise
else:
self._registered=1
def tpc_finish(self, *ignored):
if self._registered:
try: self._finish()
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Provide support for linking an external transaction manager with Zope's
"""
......@@ -26,7 +26,7 @@ class TM:
"""
_registered=None
def _begin(self): pass
def _register(self):
......@@ -52,7 +52,7 @@ class TM:
def tpc_finish(self, *ignored):
if self._finalize:
if self._finalize:
try: self._finish()
finally: self._registered=0
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''short description
$Id: dbi_db.py,v 1.9 2001/11/28 15:51:13 matt Exp $'''
# Copyright
$Id: dbi_db.py,v 1.10 2002/08/14 21:50:59 mj Exp $'''
# Copyright
#
# Copyright 1997 Digital Creations, Inc, 910 Princess Anne
# Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
# rights reserved.
#
__version__='$Revision: 1.9 $'[11:-2]
# rights reserved.
#
__version__='$Revision: 1.10 $'[11:-2]
import string, sys
from string import strip, split, find, join
......@@ -51,7 +51,7 @@ class DB:
self.connection=connection
db=self.db=self.Database_Connection(connection)
self.cursor=db.cursor()
def str(self,v, StringType=type('')):
if v is None: return ''
r=str(v)
......@@ -70,7 +70,7 @@ class DB:
if self._registered: return
get_transaction().register(self)
self._registered=1
def query(self,query_string, max_rows=9999999):
global failures, calls
......@@ -126,7 +126,7 @@ class DB:
desc=c.description
else:
raise sys.exc_info()
if result:
result=join(
map(
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''Inserting optional tests with 'sqlgroup'
It is sometimes useful to make inputs to an SQL statement
optinal. Doing so can be difficult, because not only must the
test be inserted conditionally, but SQL boolean operators may or
may not need to be inserted depending on whether other, possibly
optional, comparisons have been done. The 'sqlgroup' tag
automates the conditional insertion of boolean operators.
automates the conditional insertion of boolean operators.
The 'sqlgroup' tag is a block tag. It can
have any number of 'and' and 'or' continuation tags.
......@@ -26,7 +26,7 @@
The 'sqlgroup' tag has an optional attribure, 'required' to
specify groups that must include at least one test. This is
useful when you want to make sure that a query is qualified, but
want to be very flexible about how it is qualified.
want to be very flexible about how it is qualified.
Suppose we want to find people with a given first or nick name,
city or minimum and maximum age. Suppose we want all inputs to be
......@@ -62,15 +62,15 @@
'''
############################################################################
# Copyright
# Copyright
#
# Copyright 1996 Digital Creations, L.C., 910 Princess Anne
# Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
# rights reserved.
#
############################################################################
__rcs_id__='$Id: sqlgroup.py,v 1.8 2001/11/28 15:51:13 matt Exp $'
__version__='$Revision: 1.8 $'[11:-2]
############################################################################
__rcs_id__='$Id: sqlgroup.py,v 1.9 2002/08/14 21:50:59 mj Exp $'
__version__='$Revision: 1.9 $'[11:-2]
from DocumentTemplate.DT_Util import parse_params
str=__builtins__['str']
......@@ -102,7 +102,7 @@ class SQLGroup:
if s:
if r: r.append(tname)
r.append("%s\n" % s)
if r:
if len(r) > 1: r="(%s)\n" % join(r,' ')
else: r=r[0]
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''Inserting optional tests with 'sqlgroup'
It is sometimes useful to make inputs to an SQL statement
optinal. Doing so can be difficult, because not only must the
test be inserted conditionally, but SQL boolean operators may or
may not need to be inserted depending on whether other, possibly
optional, comparisons have been done. The 'sqlgroup' tag
automates the conditional insertion of boolean operators.
automates the conditional insertion of boolean operators.
The 'sqlgroup' tag is a block tag that has no attributes. It can
have any number of 'and' and 'or' continuation tags.
......@@ -55,17 +55,17 @@
'and' or 'or' tag, otherwise, no text is inserted.
'''
__rcs_id__='$Id: sqltest.py,v 1.17 2002/08/09 17:58:33 jshell Exp $'
__rcs_id__='$Id: sqltest.py,v 1.18 2002/08/14 21:50:59 mj Exp $'
############################################################################
# Copyright
# Copyright
#
# Copyright 1996 Digital Creations, L.C., 910 Princess Anne
# Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
# rights reserved.
#
############################################################################
__version__='$Revision: 1.17 $'[11:-2]
############################################################################
__version__='$Revision: 1.18 $'[11:-2]
import sys
from DocumentTemplate.DT_Util import ParseError, parse_params, name_param
......@@ -74,7 +74,7 @@ str=__builtins__['str']
from string import find, split, join, atoi, atof
from types import ListType, TupleType, StringType
class SQLTest:
class SQLTest:
name='sqltest'
optional=multiple=None
......@@ -83,14 +83,14 @@ class SQLTest:
multiple=1, optional=1, op=None)
name,expr = name_param(args,'sqlvar',1)
if expr is None:
expr=name
else: expr=expr.eval
self.__name__, self.expr = name, expr
if expr is None:
expr=name
else: expr=expr.eval
self.__name__, self.expr = name, expr
self.args=args
if not args.has_key('type'):
raise ParseError, ('the type attribute is required', 'sqltest')
raise ParseError, ('the type attribute is required', 'sqltest')
self.type=t=args['type']
if not valid_type(t):
......@@ -103,9 +103,9 @@ class SQLTest:
elif self.__name__ is None:
err = ' the column attribute is required if an expression is used'
raise ParseError, (err, 'sqltest')
else:
else:
self.column=self.__name__
# Deal with optional operator specification
op = '=' # Default
if args.has_key('op'):
......@@ -116,37 +116,37 @@ class SQLTest:
def render(self, md):
name=self.__name__
name=self.__name__
t=self.type
args=self.args
try:
expr=self.expr
if type(expr) is type(''):
v=md[expr]
else:
v=expr(md)
except KeyError:
if args.has_key('optional') and args['optional']:
return ''
expr=self.expr
if type(expr) is type(''):
v=md[expr]
else:
v=expr(md)
except KeyError:
if args.has_key('optional') and args['optional']:
return ''
raise 'Missing Input', 'Missing input variable, <em>%s</em>' % name
if type(v) in (ListType, TupleType):
if len(v) > 1 and not self.multiple:
raise 'Multiple Values', (
'multiple values are not allowed for <em>%s</em>'
% name)
else: v=[v]
vs=[]
for v in v:
if not v and type(v) is StringType and t != 'string': continue
if t=='int':
try:
if type(v) is StringType:
if v[-1:]=='L':
v=v[:-1]
atoi(v)
if v[-1:]=='L':
v=v[:-1]
atoi(v)
else: v=str(int(v))
except ValueError:
raise ValueError, (
......@@ -166,10 +166,10 @@ class SQLTest:
#v="'%s'" % v
vs.append(v)
if not vs and t=='nb':
if args.has_key('optional') and args['optional']:
return ''
else:
if not vs and t=='nb':
if args.has_key('optional') and args['optional']:
return ''
else:
err = 'Invalid empty string value for <em>%s</em>' % name
raise ValueError, err
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
'''Inserting values with the 'sqlvar' tag
......@@ -37,7 +37,7 @@
<dtml-sqlvar x type=nb optional>
if the value of 'x' is::
Let\'s do it
then the text inserted is:
......@@ -47,17 +47,17 @@
however, if x is ommitted or an empty string, then the value
inserted is 'null'.
'''
__rcs_id__='$Id: sqlvar.py,v 1.12 2001/11/28 15:51:13 matt Exp $'
__rcs_id__='$Id: sqlvar.py,v 1.13 2002/08/14 21:50:59 mj Exp $'
############################################################################
# Copyright
# Copyright
#
# Copyright 1996 Digital Creations, L.C., 910 Princess Anne
# Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
# rights reserved.
#
############################################################################
__version__='$Revision: 1.12 $'[11:-2]
############################################################################
__version__='$Revision: 1.13 $'[11:-2]
from DocumentTemplate.DT_Util import ParseError, parse_params, name_param
from string import find, split, join, atoi, atof
......@@ -65,7 +65,7 @@ StringType=type('')
str=__builtins__['str']
class SQLVar:
class SQLVar:
name='sqlvar'
def __init__(self, args):
......@@ -130,7 +130,7 @@ class SQLVar:
else:
raise ValueError, (
'Invalid empty string value for <em>%s</em>' % name)
v=md.getitem('sql_quote__',0)(v)
#if find(v,"\'") >= 0: v=join(split(v,"\'"),"''")
#v="'%s'" % v
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''$Id: __init__.py,v 1.8 2001/11/28 15:51:13 matt Exp $'''
__version__='$Revision: 1.8 $'[11:-2]
__doc__='''$Id: __init__.py,v 1.9 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.9 $'[11:-2]
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__version__='$Revision: 1.2 $'[11:-2]
__version__='$Revision: 1.3 $'[11:-2]
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
"""Provide conversion between Python pickles and XML
......@@ -65,7 +65,7 @@ def convert(S, find=string.find):
new=string.join(map(lambda s: reprs2.get(s,s), new), '')
return encoding, new
# Function unconvert takes a encoding and a string and
# Function unconvert takes a encoding and a string and
# returns the original string
def unconvert(encoding,S):
......@@ -96,7 +96,7 @@ def u64(v, unpack=struct.unpack):
class Global:
def __init__(self, module, name):
def __init__(self, module, name):
self.module=module
self.name=name
......@@ -111,7 +111,7 @@ class Scalar:
def __init__(self, v):
self._v=v
def value(self): return self._v
def __str__(self, indent=0):
......@@ -130,7 +130,7 @@ def xmlstr(v):
return v[1:-1]
class Int(Scalar): pass
class Long(Scalar):
class Long(Scalar):
def value(self):
result = str(self._v)
if result[-1:] == 'L':
......@@ -155,7 +155,7 @@ class String(Scalar):
class Wrapper:
def __init__(self, v): self._v=v
def value(self): return self._v
def __str__(self, indent=0):
......@@ -196,7 +196,7 @@ class Dictionary(Collection):
'%s<item>\n'
'%s'
'%s'
'%s</item>\n'
'%s</item>\n'
%
(ind,
Key(i[0]).__str__(indent),
......@@ -208,7 +208,7 @@ class Dictionary(Collection):
class Sequence(Collection):
def __init__(self, v=None):
def __init__(self, v=None):
if not v: v=[]
self._subs=v
......@@ -238,7 +238,7 @@ class Reference(Scalar):
def __str__(self, indent=0):
v=self._v
name=string.lower(self.__class__.__name__)
return '%s<%s id="%s"/>\n' % (' '*indent,name,v)
return '%s<%s id="%s"/>\n' % (' '*indent,name,v)
Get=Reference
......@@ -282,7 +282,7 @@ class ToXMLUnpickler(Unpickler):
def load_binint2(self):
self.append(Int(mloads('i' + self.read(2) + '\000\000')))
dispatch[BININT2] = load_binint2
def load_long(self):
self.append(Long(string.atol(self.readline()[:-1], 0)))
dispatch[LONG] = load_long
......@@ -358,11 +358,11 @@ class ToXMLUnpickler(Unpickler):
k = self.marker()
klass = stack[k + 1]
del stack[k + 1]
args = Tuple(stack[k + 1:])
args = Tuple(stack[k + 1:])
del stack[k:]
value=Object(klass,args)
self.append(value)
dispatch[OBJ] = load_obj
dispatch[OBJ] = load_obj
def load_global(self):
module = self.readline()[:-1]
......@@ -422,13 +422,13 @@ def ToXMLloads(str):
class NoBlanks:
def handle_data(self, data):
if string.strip(data): self.append(data)
def name(self, tag, data, join=string.join, strip=string.strip):
return strip(join(data[2:],''))
def start_pickle(self, tag, attrs):
self._pickleids={}
return [tag,attrs]
......@@ -490,7 +490,7 @@ class xmlUnpickler(NoBlanks, xyap):
'state': lambda self, tag, data: data[2],
'klass': lambda self, tag, data: data[2],
}
def save_int(self, tag, data):
binary=self.binary
if binary:
......@@ -584,7 +584,7 @@ def save_dict(self, tag, data):
def save_reference(self, tag, data):
binary=self.binary
a=data[1]
a=data[1]
id=a['id']
prefix=string.rfind(id,'.')
if prefix>=0: id=id[prefix+1:]
......@@ -600,7 +600,7 @@ def save_reference(self, tag, data):
get='j'
v=get+id
else: v=get+id+'\012'
return v
def save_object(self, tag, data):
......@@ -787,4 +787,3 @@ def test3():
if __name__ == '__main__':
test()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
from pyexpat import *
......@@ -9,8 +9,8 @@ _VERSION="1.3"
_URL="http://www.cwi.nl/~jack/pyexpatversion.txt"
try:
_myverbose=VERBOSE
_myverbose=VERBOSE
except NameError:
_myverbose=1
_myverbose=1
pyversioncheck.versioncheck(_PACKAGE, _URL, _VERSION, verbose=_myverbose)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
from dcpyexpat import *
......@@ -5,50 +5,50 @@ import sys
import os
class Outputter:
def __init__(self, verbose=0):
self.startcount = 0
self.endcount = 0
self.cdatacount = 0
self.instcount = 0
self.verbose = verbose
def __init__(self, verbose=0):
self.startcount = 0
self.endcount = 0
self.cdatacount = 0
self.instcount = 0
self.verbose = verbose
def startelt(self, name, attrs):
self.startcount = self.startcount + 1
if self.verbose:
print 'start', name
for i in range(0, len(attrs), 2):
print 'attr', attrs[i], attrs[i+1]
def startelt(self, name, attrs):
self.startcount = self.startcount + 1
if self.verbose:
print 'start', name
for i in range(0, len(attrs), 2):
print 'attr', attrs[i], attrs[i+1]
def endelt(self, name):
self.endcount = self.endcount + 1
if self.verbose:
print 'end', name
def endelt(self, name):
self.endcount = self.endcount + 1
if self.verbose:
print 'end', name
def cdata(self, data):
self.cdatacount = self.cdatacount + 1
if self.verbose:
print 'cdata', data
def cdata(self, data):
self.cdatacount = self.cdatacount + 1
if self.verbose:
print 'cdata', data
def inst(self, target, data):
self.instcount = self.instcount + 1
if self.verbose:
print 'inst', target, data
def inst(self, target, data):
self.instcount = self.instcount + 1
if self.verbose:
print 'inst', target, data
if len(sys.argv) > 1 and sys.argv[1] == '-v':
out = Outputter(verbose=1)
del sys.argv[1]
out = Outputter(verbose=1)
del sys.argv[1]
else:
out = Outputter()
out = Outputter()
if len(sys.argv) != 2:
if os.name == 'mac':
import macfs
fss, ok = macfs.StandardGetFile()
if not ok: sys.exit(0)
sys.argv.append(fss.as_pathname())
else:
print 'Usage: pyexpattest [-v] inputfile'
sys.exit(1)
if os.name == 'mac':
import macfs
fss, ok = macfs.StandardGetFile()
if not ok: sys.exit(0)
sys.argv.append(fss.as_pathname())
else:
print 'Usage: pyexpattest [-v] inputfile'
sys.exit(1)
parser = pyexpat.ParserCreate()
parser.StartElementHandler = out.startelt
parser.EndElementHandler = out.endelt
......@@ -61,10 +61,10 @@ rv = parser.Parse(data, 1)
print 'Parser returned', rv
if rv == 0:
print '** Error', parser.ErrorCode
print '** Line', parser.ErrorLineNumber
print '** Column', parser.ErrorColumnNumber
print '** Byte', parser.ErrorByteIndex
print '** Error', parser.ErrorCode
print '** Line', parser.ErrorLineNumber
print '** Column', parser.ErrorColumnNumber
print '** Byte', parser.ErrorByteIndex
print 'Summary of XML parser upcalls:'
print 'start elements:', out.startcount
print 'end elements:', out.endcount
......
......@@ -165,9 +165,9 @@ class XMLParser:
break
res = interesting.search(rawdata, i)
if res:
j = res.start(0)
j = res.start(0)
else:
j = n
j = n
if i < j:
if self.__at_start:
self.syntax_error('illegal data at start of file')
......
......@@ -62,7 +62,7 @@ class xyap:
append(top)
class NoBlanks:
def handle_data(self, data):
if string.strip(data): self.append(data)
......@@ -78,12 +78,12 @@ def name(self, tag, data, join=string.join, strip=string.strip):
def tuplef(self, tag, data): return tuple(data[2:])
class XYap(xyap, xmllib.XMLParser):
def __init__(self):
xmllib.XMLParser.__init__(self)
top=[]
self._stack=_stack=[top]
self.push=_stack.append
self.append=top.append
def __init__(self):
xmllib.XMLParser.__init__(self)
top=[]
self._stack=_stack=[top]
self.push=_stack.append
self.append=top.append
class xmlrpc(NoBlanks, XYap, xmllib.XMLParser):
end_handlers={
......@@ -117,7 +117,7 @@ class xmlrpc(NoBlanks, XYap, xmllib.XMLParser):
}
def test():
data="""<?xml version="1.0"?>
<methodCall>
<methodName>examples.getStateName
......@@ -154,7 +154,7 @@ def test():
</params>
</methodCall>
"""
data=string.split(data,'\n')
r=[]
for C in XYap, xmlrpc:
......@@ -163,9 +163,8 @@ def test():
p.feed(l)
p.close()
r.append(p._stack)
return r
if __name__=='__main__': print test()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
#
##############################################################################
__doc__='''$Id: __init__.py,v 1.6 2001/11/28 15:51:12 matt Exp $'''
__version__='$Revision: 1.6 $'[11:-2]
__doc__='''$Id: __init__.py,v 1.7 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.7 $'[11:-2]
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment