rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
__version__='$Revision: 1.41 $'[11:-2]
__version__='$Revision: 1.42 $'[11:-2]
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
try: return d[key] except: if string.upper(key) == 'HTTP_AUTHORIZATION': try: return d['HTTP_CGI_AUTHORIZATION'] except: return '' return ''
try: return d[key] except: return ''
def env(key,d=environ): try: return d[key] except: if string.upper(key) == 'HTTP_AUTHORIZATION': try: return d['HTTP_CGI_AUTHORIZATION'] except: return '' return ''
return index[key]
return List(index[key])
def __getitem__(self, key): '''\ Get the ResultList objects for the inverted key, key. The key may be a regular expression, in which case a regular expression match is done. The key may be a string, in which case an case-insensitive match is done. ''' index = self._index_object synstop = self.synstop List = self.list_class if (type(key) == RegexType): dict = {} for k in index.keys(): if (key.search(k) >= 0): try: while (type(index[k]) == StringType): k = index[k] except KeyError: continue if (index[k] is None): continue dict[index[k]] = 1 Lists = dict.keys() if (not len(Lists)): return List() return reduce(lambda x, y: x | y, Lists) key = lower(key) while (1): try: key = synstop[key] except KeyError: break if (key is None): return List()
$Id: InvertedIndex.py,v 1.34 1997/04/23 16:53:27 chris Exp $'''
$Id: InvertedIndex.py,v 1.35 1997/04/23 16:56:31 chris Exp $'''
def highlight(self, text, positions, before, after): ws = WordSequence(text, self.synstop) positions.sort() positions.reverse()
__version__='$Revision: 1.34 $'[11:-2]
__version__='$Revision: 1.35 $'[11:-2]
def highlight(self, text, positions, before, after): ws = WordSequence(text, self.synstop) positions.sort() positions.reverse()
try: length = len(result) except: result = result.keys() length = len(result) assert length == len( expectedValues ), \
assert len(result) == len( expectedValues ), \
def _checkApply( self, req, expectedValues ): result, used = self._index._apply_index( req ) assert used == ( 'foo', ) try: length = len(result) except: result = result.keys() length = len(result) assert length == len( expectedValues ), \ '%s | %s' % ( map( None, result ), map(lambda x: x[0], expectedValues )) for k, v in expectedValues: assert k in result
unittest.TextTestRunner().run( test_suite() )
if len(sys.argv) > 1: globals()[sys.argv[1]]() else: main()
def test_suite(): return unittest.makeSuite( TestCase )
rot=rotor.newrotor('\357\261\390\247\357\362\306\216\226', 13) dat=rot.decrypt(dat) dat=list(dat) dat.reverse() dat=join(dat,'') dat=marshal.loads(dat) del rot
dat=lcd(dat) if dat is None: return 0
def lic_check(product_name): path_join =os.path.join product_dir=path_join(SOFTWARE_HOME,'lib/python/Products') package_dir=path_join(product_dir, product_name) bobobase =Globals.Bobobase try: f=open(path_join(package_dir,'%s.lic' % product_name), 'rb') except: try: product=getattr(__import__("Products.%s" % product_name), product_name) for s in pgetattr(product, 'classes', ()): p=rfind(s,'.') m='Products.%s.%s' % (product_name, s[:p]) c=s[p+1:] __import__(m) setattr(sys.modules[m], c, Expired) except: pass return 0 dat=f.read() f.close() rot=rotor.newrotor('\357\261\390\247\357\362\306\216\226', 13) dat=rot.decrypt(dat) dat=list(dat) dat.reverse() dat=join(dat,'') dat=marshal.loads(dat) del rot name=dat[0] val =dat[1] if name != product_name: return 0 if val is None: return 1 else: if not bobobase.has_key('_t_'): bobobase['_t_']={} t=bobobase['_t_'] if not t.has_key(product_name): t[product_name]=time.time() bobobase['_t_']=t if (t[product_name] + (86400.0 * val)) < time.time(): product=getattr(__import__("Products.%s" % product_name), product_name) for s in pgetattr(product, 'classes', ()): p=rfind(s,'.') m='Products.%s.%s' % (product_name, s[:p]) c=s[p+1:] try: __import__(m) except: m=s[:p] __import__(m) setattr(sys.modules[m], c, Expired) return 0 return 1
if len(stdout) > 0: conn.send(stdout) conn.send('%010d' % len(stderr)) if len(stderr) > 0: conn.send(stderr)
to_send=stdout_len if to_send > 0: while 1: sent = conn.send(stdout) if sent == to_send: break else: to_send = to_send - sent stdout = stdout[sent:] stderr_len=len(stderr) conn.send('%010d' % stderr_len) to_send=stderr_len if to_send > 0: while 1: sent = conn.send(stderr) if sent == to_send: break else: to_send = to_send - sent stderr = stderr[sent:]
def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10)
self.fail('Expected DeprecationWarning, none given')
self.fail('Unexpected DeprecationWarning, ' 'no warnings expected here')
def testAllowed(self): """hasRole is an alias for allowed, which should be unaffected.""" try: self.userObject.allowed(None) except DeprecationWarning: self.fail('Expected DeprecationWarning, none given') else: pass
all=callable(self.all_meta_types) and self.all_meta_types() or \ self.all_meta_types
if callable(self.all_meta_types): all=self.all_meta_types() else: all=self.all_meta_types
def filtered_meta_types(self, user): "Those meta types for which a user has adequite permissions." meta_types=[] all=callable(self.all_meta_types) and self.all_meta_types() or \ self.all_meta_types for meta_type in all: if meta_type.has_key('permission'): if user.has_permission(meta_type['permission'],self): meta_types.append(meta_type) else: meta_types.append(meta_type) return meta_types
self.useBrains(self._v_brains)
def __getitem__(self, index): """ returns instances of self._v_brains, or whatever is passed into self.useBrains. """ self.useBrains(self._v_brains) r=self._v_result_class(self.data[index]).__of__(self.aq_parent) r.data_record_id_ = index return r
for key, value in self.schema.items(): scopy[key]=value
scopy = self.schema.copy()
def has_key(self, key): return self.__record_schema__.has_key(key)
mybrains.__theCircularGottaCoverUpABugRefOfJoy = mybrains
def has_key(self, key): return self.__record_schema__.has_key(key)
self.useBrains(self._v_brains)
def instantiate(self, record): self.useBrains(self._v_brains)
self.useBrains(self._v_brains)
def searchResults(self, REQUEST=None, used=None, query_map={ type(regex.compile('')): Query.Regex, type([]): orify, type(''): Query.String, }, **kw):
try:
src="Could not render the query template!" result=() try: src=self(REQUEST,1)
def manage_test(self, REQUEST):
'<hr><strong>Error, <em>%s</em>:</strong> %s'
'<strong>Error, <em>%s</em>:</strong> %s'
def manage_test(self, REQUEST):
'<!-- % r)
'<!-- '<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>/n<hr>\n' '</body></html>' % (r,src))
def manage_test(self, REQUEST):
def __call__(self, REQUEST=None, **kw):
def __call__(self, REQUEST=None, src__=0, **kw):
def __call__(self, REQUEST=None, **kw):
else: isHTML = split(headers.get('content-type', ''), ';')[0] == 'text/html' if isHTML and end_of_header_search(self.body) < 0: lhtml=html_search(body) if lhtml >= 0: lhtml=lhtml+6 body='%s<head></head>\n%s' % (body[:lhtml],body[lhtml:]) elif contHTML: body='<html><head></head>\n' + body else: body='<html><head></head>\n' + body + '\n</html>\n' self.setBody(body) body=self.body
def __str__(self, html_search=regex.compile('<html>',regex.casefold).search, ): if self._wrote: return '' # Streaming output was used.
raise TALESError("unknown variable: %s", expr)
raise TALESError("unknown variable: %s" % `expr`)
def evaluate(self, expression): expression = self.uncompile(expression) m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "path" expr = expression if type in ("string", "str"): return expr if type in ("path", "var", "global", "local"): expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] elif self.globals.has_key(expr): return self.globals[expr] else: raise TALESError("unknown variable: %s", expr) if type == "not": v = self.evaluate(expr) return not v if type == "exists": return self.locals.has_key(expr) or self.globals.has_key(expr) if type == "python": try: return eval(expr, self.globals, self.locals) except: t, v, tb = info = sys.exc_info() raise TALESError("evaluation error in %s" % `expr`, info=sys.exc_info()) raise TALESError("unrecognized expression: " + `expression`)
text, encoding = convertToUnicode(state['_text'], state['content_type'])
text, encoding = convertToUnicode(state['_text'], state.get('content_type', 'text/html'))
def __setstate__(self, state): # Perform on-the-fly migration to unicode. # Perhaps it might be work with the 'generation' module here? if not isinstance(state['_text'], unicode): text, encoding = convertToUnicode(state['_text'], state['content_type']) state['_text'] = text state['output_encoding'] = encoding self.__dict__.update(state)
def testExpandsionMap(self):
def testExpansionMap(self):
def testExpandsionMap(self): treeroot = self.tm.tree(self.root, self.expansionmap)
if folder_permissions.has_key[permission]:
if folder_permissions.has_key(permission):
def productItems(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']=='Image': n=i['name'] t.append((n,getattr(self,n))) return t
for name in self._catalog.indexes.keys():
for name in self._catalog.schema.keys():
def _searchable_result_columns(self): r = [] for name in self._catalog.indexes.keys(): i = {} i['name'] = name i['type'] = 's' i['parser'] = str i['width'] = 8 r.append(i) r.append({'name': 'data_record_id_', 'type': 's', 'parser': str, 'width': 8}) return r
list(self._getProductRegistryData(type))
list(self.aq_acquire('_getProductRegistryData')(type))
def _manage_add_product_data(self, type, product, id, **data): values=filter( lambda d, product=product, id=id: not (d['product']==product and d['id']==id), list(self._getProductRegistryData(type)) )
self._setProductRegistryData(type, tuple(values))
self.aq_acquire('_setProductRegistryData')(type, tuple(values))
def _manage_add_product_data(self, type, product, id, **data): values=filter( lambda d, product=product, id=id: not (d['product']==product and d['id']==id), list(self._getProductRegistryData(type)) )
self._getProductRegistryData(type)
self.aq_acquire('_getProductRegistryData')(type)
def _manage_remove_product_data(self, type, product, id): values=filter( lambda d, product=product, id=id: not (d['product']==product and d['id']==id), self._getProductRegistryData(type) )
self._setProductRegistryData(type, tuple(values))
self.aq_acquire('_setProductRegistryData')(type, tuple(values))
def _manage_remove_product_data(self, type, product, id): values=filter( lambda d, product=product, id=id: not (d['product']==product and d['id']==id), self._getProductRegistryData(type) )
expr = re.compile(r"'([%s%s%s\s]+)'[%s]+" % (letters, digits, literal_punc, phrase_delimiters)).search):
expr = re.compile(r"(\W+|^)'([%s%s%s\s]+)'([%s]+|$)" % (letters, digits, literal_punc, phrase_delimiters)).search,):
def doc_literal( self, s, expr = re.compile(r"'([%s%s%s\s]+)'[%s]+" % (letters, digits, literal_punc, phrase_delimiters)).search):
start, end = r.span(1)
start, end = r.span(2)
def doc_literal( self, s, expr = re.compile(r"'([%s%s%s\s]+)'[%s]+" % (letters, digits, literal_punc, phrase_delimiters)).search):
if ts_reults:
if ts_results:
def parse(text, result=None, keys=None, unparmre=ts_regex.compile( '\([\0- ]*\([^\0- =\"]+\)\)'), parmre=ts_regex.compile( '\([\0- ]*\([^\0- =\"]+\)=\([^\0- =\"]+\)\)'), qparmre=ts_regex.compile( '\([\0- ]*\([^\0- =\"]+\)="\([^"]*\)\"\)'), ): if result is None: result = {} keys=[] __traceback_info__=text ts_results = parmre.match_group(text, (1,2,3)) if ts_results: start, grps = ts_results name=grps[1] value={'default':grps[2]} l=len(grps[0]) else: ts_results = qparmre.match_group(text, (1,2,3)) if ts_results: start, grps = ts_results name=grps[1] value={'default':grps[2]} l=len(grps[0]) else: ts_results = unparmre.match_group(text, (1,2)) if ts_reults: start, grps = ts_results name=grps[1] l=len(grps[0]) value={} else: if not text or not strip(text): return Args(result,keys) raise InvalidParameter, text lt=string.find(name,':') if lt > 0: value['type']=name[lt+1:] name=name[:lt] result[name]=value keys.append(name) return parse(text[l:],result,keys)
base_re=regex.compile('<base[\0- ]+[^>]+>\)',
base_re=regex.compile('\(<base[\0- ]+[^>]+>\)',
def insertBase(self, base_re=regex.compile('<base[\0- ]+[^>]+>\)', regex.casefold) ): if (self.headers.has_key('content-type') and self.headers['content-type']!='text/html'): return
return self._d
return self.__dict__['_d']
def Destination(self): "Return the destination for factory output" return self._d
self._v_f = None
self._v_ft = None
def __setstate__(self, state): Script.__setstate__(self, state) if (getattr(self, 'Python_magic', None) != Python_magic or getattr(self, 'Script_magic', None) != Script_magic): global _log_complaint if _log_complaint: LOG(self.meta_type, INFO, _log_complaint) _log_complaint = 0 # Changes here won't get saved, unless this Script is edited. body = self._body.rstrip() if body: self._body = body + '\n' self._compile() self._v_change = 1 elif self._code is None: self._v_f = None else: self._newfun(marshal.loads(self._code))
self._v_f = None
self._v_ft = None
def _compile(self): r = self._compiler(self._params, self._body or 'pass', self.id, self.meta_type) code = r[0] errors = r[1] self.warnings = tuple(r[2]) if errors: self._code = None self._v_f = None self._setFuncSignature((), (), 0) # Fix up syntax errors. filestring = ' File "<string>",' for i in range(len(errors)): line = errors[i] if line.startswith(filestring): errors[i] = line.replace(filestring, ' Script', 1) self.errors = errors return
self._v_f = f = l.values()[0]
f = l.values()[0] self._v_ft = (f.func_code, g, f.func_defaults or ())
def _newfun(self, code): g = {'__debug__': __debug__, '__builtins__': safe_builtins, '_getattr_': guarded_getattr, '_getitem_': guarded_getitem, '_write_': full_write_guard, '_print_': RestrictedPython.PrintCollector, } l = {} exec code in g, l self._v_f = f = l.values()[0] return f
if getattr(self, '_v_f', None) is not None:
if getattr(self, '_v_ft', None) is not None:
def _editedBindings(self): if getattr(self, '_v_f', None) is not None: self._makeFunction()
f = self._v_f if f is None:
ft = self._v_ft if ft is None:
def _exec(self, bound_names, args, kw): """Call a Python Script
f.func_globals.update(bound_names) f.func_globals['__traceback_supplement__'] = (
g.update(bound_names) g['__traceback_supplement__'] = (
def _exec(self, bound_names, args, kw): """Call a Python Script
try: r=apply(HTML.__call__, (self, client, REQUEST), kw) except: if self.id()=='standard_error_message': raise sys.exc_type, sys.exc_value, sys.exc_traceback error_type=sys.exc_type error_value=sys.exc_value if lower(error_type) in ('redirect',): raise error_type, error_value, sys.exc_traceback if regex.search('[a-zA-Z]>', error_value) > 0: error_message=error_value else: error_message='' tb=sys.exc_traceback error_tb=pretty_tb(error_type, error_value, tb) if client is not None: c=client else: c=self.aq_parent try: s=getattr(c, 'standard_error_message') v=HTML.__call__(s, c, REQUEST, error_type=error_type, error_value=error_value, error_tb=error_tb, error_traceback=error_tb, error_message=error_message)
try: try: r=apply(HTML.__call__, (self, client, REQUEST), kw)
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
v='Sorry, an error occured' sys.exc_traceback=tb tb=None raise error_type, v, sys.exc_traceback
if self.id()=='standard_error_message': raise sys.exc_type, sys.exc_value, sys.exc_traceback error_type=sys.exc_type error_value=sys.exc_value tb=sys.exc_traceback if lower(error_type) in ('redirect',): raise error_type, error_value, tb if (type(error_value) is type('') and regex.search('[a-zA-Z]>', error_value) > 0): error_message=error_value else: error_message='' error_tb=pretty_tb(error_type, error_value, tb) if client is not None: c=client else: c=self.aq_parent try: s=getattr(c, 'standard_error_message') v=HTML.__call__(s, c, REQUEST, error_type=error_type, error_value=error_value, error_tb=error_tb, error_traceback=error_tb, error_message=error_message) except: v='Sorry, an error occured' raise error_type, v, tb finally: tb=None
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
if action > 1 and not self.showtal:
if action == 1 or (action > 1 and not self.showtal):
def attrAction(self, item): name, value, action = item[:3] if action > 1 and not self.showtal: return 0, name, value ok = 1 if action == 2 and self.metal: i = rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] ##self.dumpMacroStack(prefix, suffix, value) what, macroName, slots = self.macroStack[-1] if suffix == "define-macro": if what == "use-macro": name = prefix + "use-macro" value = macroName else: assert what == "define-macro" i = self.macroContext("use-macro") if i >= 0: j = self.macroContext("define-slot") if j > i: name = prefix + "use-macro" else: return 0, name, value elif suffix == "define-slot": assert what == "define-slot" if self.macroContext("use-macro") >= 0: name = prefix + "fill-slot"
return self.manage_main(self,REQUEST,title=title,__str__=data, dtpref_cols=cols,dtpref_rows=rows)
return self.manage_main( self,REQUEST,title=title,__str__=self.quotedHTML(data), dtpref_cols=cols,dtpref_rows=rows)
def _er(self,data,title,SUBMIT,dtpref_cols,dtpref_rows,REQUEST): dr,dc = self._size_changes[SUBMIT] rows=max(1,atoi(dtpref_rows)+dr) cols=max(40,atoi(dtpref_cols)+dc) e='Friday, 31-Dec-99 23:59:59 GMT' resp=REQUEST['RESPONSE'] resp.setCookie('dtpref_rows',str(rows),path='/',expires=e) resp.setCookie('dtpref_cols',str(cols),path='/',expires=e) return self.manage_main(self,REQUEST,title=title,__str__=data, dtpref_cols=cols,dtpref_rows=rows)
except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f))
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, '__import_error__'): ie=productp.__import_error__ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return old except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=app._p_jar.importFile(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: app._manage_remove_product_meta_type(product) products._delObject(name) for id, v in old.objectValues(): try: product._setObject(id, v) except: pass products._setObject(name, product) #product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, ) return product
class ZopeEngine(ExpressionEngine): def getContext(self, contexts=None, **kwcontexts): if contexts is not None: if kwcontexts: kwcontexts.update(contexts) else: kwcontexts = contexts return ZopeContext(self, kwcontexts)
class ZopeEngine(zope.app.pagetemplate.engine.ZopeEngine): _create_context = ZopeContext
def translate(self, msgid, domain=None, mapping=None, default=None): context = self.contexts.get('context') return getGlobalTranslationService().translate( domain, msgid, mapping=mapping, context=context, default=default)
if (headers is None) and (not content_type): raise 'Bad Request', 'No content type specified.' if headers and headers.has_key('content-type'):
data=(headers is None) and file or file.read() if headers and headers.has_key('content-type') and (not content_type):
def __init__(self, id, title, file, content_type='', precondition=''): self.__name__=id self.title=title self.precondition=precondition headers=hasattr(file, 'headers') and file.headers or None if (headers is None) and (not content_type): raise 'Bad Request', 'No content type specified.' if headers and headers.has_key('content-type'): content_type=headers['content-type'] if not content_type: raise 'Bad Request', 'No content type specified.' data=(headers is None) and file or file.read() self.update_data(data, content_type)
raise 'Bad Request', 'No content type specified.' data=(headers is None) and file or file.read()
content_type, enc=mimetypes.guess_type(id) if not content_type: if content_types.find_binary(data) >= 0: content_type='application/octet-stream' else: content_type=content_types.text_type(data) content_type=string.lower(content_type)
def __init__(self, id, title, file, content_type='', precondition=''): self.__name__=id self.title=title self.precondition=precondition headers=hasattr(file, 'headers') and file.headers or None if (headers is None) and (not content_type): raise 'Bad Request', 'No content type specified.' if headers and headers.has_key('content-type'): content_type=headers['content-type'] if not content_type: raise 'Bad Request', 'No content type specified.' data=(headers is None) and file or file.read() self.update_data(data, content_type)
if file.headers.has_key('content-type'): content_type=file.headers['content-type'] else: content_type=None self.update_data(file.read(), content_type)
headers=hasattr(file, 'headers') and file.headers or None data=(headers is None) and file or file.read() if headers and headers.has_key('content-type'): content_type=headers['content-type'] if not content_type: content_type, enc=mimetypes.guess_type(self.id()) if not content_type: if content_types.find_binary(data) >= 0: content_type='application/octet-stream' else: content_type=content_types.text_type(data) content_type=string.lower(content_type) self.update_data(data, content_type)
def manage_upload(self,file='',REQUEST=None): """ Replaces the current contents of the File or Image object with file.
value = item[1]
value = evalue
def startTagCommon(self, name, attrList, end): if not attrList: self.stream_write("<%s%s" % (name, end)) return self.stream_write("<" + name) align = self.col+1 for item in attrList: name, value = item[:2] if len(item) > 2: try: action = self.actionIndex(item[2]) except ValueError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: continue if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.CancelAction: if action == 1: # Cancelled insert continue elif not evalue: continue else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.CancelAction: if action == 1: # Cancelled insert continue else: value = item[1] if value is None: continue elif (action == 2 and self.currentMacro and name[-13:] == ":define-macro" and self.metal): name = name[:-13] + ":use-macro" value = self.currentMacro if value is None: s = name else: s = "%s=%s" % (name, quote(value)) if (self.wrap and self.col >= align and self.col + 1 + len(s) > self.wrap): self.stream_write("\n" + " "*align + s) else: self.stream_write(" " + s) self.stream_write(end)
return map(lambda dict: dict.copy(), self._objects)
return tuple(map(lambda dict: dict.copy(), self._objects))
def objectMap(self): # Return a tuple of mappings containing subobject meta-data return map(lambda dict: dict.copy(), self._objects)
def test_csv_table_file_option_raise(self):
def test_csv_table_url_option_raise(self):
def test_csv_table_file_option_raise(self):
tname, args, section = blocks[0]
tname, args, section = blocks[-1]
def __init__(self, blocks):
raise (ValueError, 'The object with the id "%s" does not exist.' % id)
raise ValueError('The object with the id "%s" does not exist.' % id)
def moveObjectsByDelta(self, ids, delta): """ Move specified sub-objects by delta. """ if type(ids) is StringType: ids = (ids,) min_position = 0 objects = list(self._objects) obj_dict = {} for obj in self._objects: obj_dict[ obj['id'] ] = obj # unify moving direction if delta > 0: ids = list(ids) ids.reverse() objects.reverse() counter = 0
raise ValueError, 'The object with the id "%s" does not exist.' % id
raise ValueError('The object with the id "%s" does not exist.' % id)
def getObjectPosition(self, id): """ Get the position of an object by its id. """ ids = self.objectIds() if id in ids: return ids.index(id) raise ValueError, 'The object with the id "%s" does not exist.' % id
base=find_class(self, b) bases.append(base)
raise 'Invalid class', b
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) else: base=find_class(self, b) bases.append(base) Z=ZClass(id, title, bases, zope_object=zope_object) if meta_type: Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) self.manage_addDTMLMethod( id+'_add', id+' constructor', addDefault % {'id': id}, ) self.manage_addPermission( id+'_add_permission', id+' constructor permission', 'Add %ss' % meta_type ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', 'Add %ss' % meta_type ) Z=self._getOb(id) Z.propertysheets.permissions.manage_edit( selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type] ) if REQUEST is not None: return self.manage_main(self,REQUEST, update_menu=1)
if meta_type: Z._zclass_.meta_type=meta_type
Z._zclass_.meta_type=meta_type
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) else: base=find_class(self, b) bases.append(base) Z=ZClass(id, title, bases, zope_object=zope_object) if meta_type: Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) self.manage_addDTMLMethod( id+'_add', id+' constructor', addDefault % {'id': id}, ) self.manage_addPermission( id+'_add_permission', id+' constructor permission', 'Add %ss' % meta_type ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', 'Add %ss' % meta_type ) Z=self._getOb(id) Z.propertysheets.permissions.manage_edit( selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type] ) if REQUEST is not None: return self.manage_main(self,REQUEST, update_menu=1)
def manage_subclassableClassNames(self): r={} r.update(Products.meta_class_info) while 1: if not hasattr(self, 'objectItems'): break for k, v in self.objectItems(): if hasattr(v,'_zclass_') and not r.has_key(k): r[k]=v.title_and_id() if not hasattr(self, 'aq_parent'): break self=self.aq_parent r=r.items() r.sort() return r
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) else: base=find_class(self, b) bases.append(base) Z=ZClass(id, title, bases, zope_object=zope_object) if meta_type: Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) self.manage_addDTMLMethod( id+'_add', id+' constructor', addDefault % {'id': id}, ) self.manage_addPermission( id+'_add_permission', id+' constructor permission', 'Add %ss' % meta_type ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', 'Add %ss' % meta_type ) Z=self._getOb(id) Z.propertysheets.permissions.manage_edit( selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type] ) if REQUEST is not None: return self.manage_main(self,REQUEST, update_menu=1)
product=self.aq_inner.aq_parent.id,
product=product,
def _register(self):
product=self.aq_inner.aq_parent.id,
product=product,
def _unregister(self):
singledots=re.compile('^\.$')
singledots=re.compile('^\.$', re.M)
def Send(host, port, localhost, timeout, from_, to, subject, body): SendMail(host, port, localhost, timeout).send(from_, to, subject, body)
replace=string.replace
bfile = StringIO(body) mo=rfc822.Message(bfile) for k, v in mo.items(): self.conn.send('%s: %s\015\012' % (string.capitalize(k), v)) if not mo.has_key('Mime-Version'): self.conn.send('Mime-Version: 1.0\015\012') if not mo.has_key('Content-Type'): self.conn.send( 'Content-Type: text/plain; charset="iso-8859-1"\015\012') if not mo.has_key('Content-Transfer-Encoding'): self.conn.send( 'Content-Transfer-Encoding: quoted-printable\015\012') self.conn.send('\015\012') body=bfile.read()
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\015\012" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\015\012" % person) self._check() else: self.conn.send("rcpt to:<%s>\015\012" % mto) self._check() self.conn.send("data\015\012") self._check() replace=string.replace body=self.singledots.sub('..', body) body=replace(body, '\r\n', '\n') body=replace(body, '\r', '\n')
body=replace(body, '\r\n', '\n') body=replace(body, '\r', '\n') body=replace(body, '\n', '\015\012')
body=string.replace(body, '\r\n', '\n') body=string.replace(body, '\r', '\n') body=encode(body, 0) body=string.replace(body, '\n', '\015\012')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\015\012" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\015\012" % person) self._check() else: self.conn.send("rcpt to:<%s>\015\012" % mto) self._check() self.conn.send("data\015\012") self._check() replace=string.replace body=self.singledots.sub('..', body) body=replace(body, '\r\n', '\n') body=replace(body, '\r', '\n')
$Id: Publish.py,v 1.7 1996/07/11 19:39:07 jfulton Exp $"""
$Id: Publish.py,v 1.8 1996/07/18 14:59:54 jfulton Exp $"""
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
__version__='$Revision: 1.7 $'[11:-2]
__version__='$Revision: 1.8 $'[11:-2]
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
object=getattr(dict,published)
object=getattr(theModule,published)
def publish(self, module_name, published='web_objects',
if not path: path = ['help']
try: doc=object.__doc__ except: try: doc=object['__doc__'] except: doc=None if not path: for entry_name in 'index_html', 'index.html': try: if hasattr(object,entry_name): path=[entry_name] break except: pass try: if object.has_key(entry_name): path=[entry_name] break except: pass if not path: path = ['help']
def publish(self, module_name, published='web_objects',
self._setObject('UserFolder', i)
self._setObject('acl_users', i)
def manage_addUserFolder(self,dtself,REQUEST): """ """ i=UserFolder() i._init() self._setObject('UserFolder', i) self.__allow_groups__=self.UserFolder return self.manage_main(self,REQUEST)
print '+2'
def save_tuple(self, object):
print '+3'
def save_tuple(self, object):
args = getattr(getattr(meth, 'func_code', None), 'co_argcount', 2)
args = getattr(getattr(aq_base(meth), 'func_code', None), 'co_argcount', 2)
def __call__(self, container, request): try: meth = getattr(container, self.name) except AttributeError: return
$Id: Publish.py,v 1.6 1996/07/10 22:53:54 jfulton Exp $"""
$Id: Publish.py,v 1.7 1996/07/11 19:39:07 jfulton Exp $"""
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
if not hasattr(object, 'aq_parent'): break object=object.aq_parent
if hasattr(object, 'aq_parent'): object=object.aq_parent continue if hasattr(object, 'im_self'): object=object.im_self continue break
def getRolesInContext(self, object): """Return the list of roles assigned to the user, including local roles assigned in context of the passed in object.""" name=self.getUserName() roles=self.getRoles() local={} while 1: if hasattr(object, '__ac_local_roles__'): dict=object.__ac_local_roles__ or {} for r in dict.get(name, []): local[r]=1 if not hasattr(object, 'aq_parent'): break object=object.aq_parent joined=rolejoin(roles, local.keys()) return joined
finished = {}
finished = []
def analyze(f, top, sortf, start=None, end=None, mode='cumulative'): beginrequests = {} cumulative = {} finished = {} unfinished = {} while 1: line = f.readline() if not line: break line = string.strip(line) tup = parsebigmlogline(line) if tup is None: print "Could not interpret line: %s" % line continue code, id, timestr, desc = tup timestr = string.strip(timestr) fromepoch = getdate(timestr) if start is not None and fromepoch < start: continue if end is not None and fromepoch > end: break request = unfinished.get(id) if request is None: if code != "B": continue # garbage at beginning of file request = Request() unfinished[id] = request request.put(code, int(fromepoch), desc) if request.isfinished(): del unfinished[id] finished[id] = request request.active = len(unfinished) finished.update(unfinished) requests = finished.values() if mode == 'cumulative': for request in requests: url = request.url stats = cumulative.get(url) if stats is None: stats = Cumulative(url) cumulative[url] = stats stats.put(request) cumulative = cumulative.values() if mode == 'cumulative': dict = cumulative elif mode == 'detailed': dict = requests else: raise "Invalid mode." dict.sort(sortf) write(dict, top)
finished[id] = request
finished.append(request)
def analyze(f, top, sortf, start=None, end=None, mode='cumulative'): beginrequests = {} cumulative = {} finished = {} unfinished = {} while 1: line = f.readline() if not line: break line = string.strip(line) tup = parsebigmlogline(line) if tup is None: print "Could not interpret line: %s" % line continue code, id, timestr, desc = tup timestr = string.strip(timestr) fromepoch = getdate(timestr) if start is not None and fromepoch < start: continue if end is not None and fromepoch > end: break request = unfinished.get(id) if request is None: if code != "B": continue # garbage at beginning of file request = Request() unfinished[id] = request request.put(code, int(fromepoch), desc) if request.isfinished(): del unfinished[id] finished[id] = request request.active = len(unfinished) finished.update(unfinished) requests = finished.values() if mode == 'cumulative': for request in requests: url = request.url stats = cumulative.get(url) if stats is None: stats = Cumulative(url) cumulative[url] = stats stats.put(request) cumulative = cumulative.values() if mode == 'cumulative': dict = cumulative elif mode == 'detailed': dict = requests else: raise "Invalid mode." dict.sort(sortf) write(dict, top)
finished.update(unfinished) requests = finished.values()
finished.extend(unfinished.values()) requests = finished
def analyze(f, top, sortf, start=None, end=None, mode='cumulative'): beginrequests = {} cumulative = {} finished = {} unfinished = {} while 1: line = f.readline() if not line: break line = string.strip(line) tup = parsebigmlogline(line) if tup is None: print "Could not interpret line: %s" % line continue code, id, timestr, desc = tup timestr = string.strip(timestr) fromepoch = getdate(timestr) if start is not None and fromepoch < start: continue if end is not None and fromepoch > end: break request = unfinished.get(id) if request is None: if code != "B": continue # garbage at beginning of file request = Request() unfinished[id] = request request.put(code, int(fromepoch), desc) if request.isfinished(): del unfinished[id] finished[id] = request request.active = len(unfinished) finished.update(unfinished) requests = finished.values() if mode == 'cumulative': for request in requests: url = request.url stats = cumulative.get(url) if stats is None: stats = Cumulative(url) cumulative[url] = stats stats.put(request) cumulative = cumulative.values() if mode == 'cumulative': dict = cumulative elif mode == 'detailed': dict = requests else: raise "Invalid mode." dict.sort(sortf) write(dict, top)
transaction().abort()
transaction.abort()
def install_product(app, product_dir, product_name, meta_types, folder_permissions, raise_exc=0, log_exc=1): path_join=os.path.join isdir=os.path.isdir exists=os.path.exists global_dict=globals() silly=('__doc__',) if 1: # Preserve indentation for diff :-) package_dir=path_join(product_dir, product_name) __traceback_info__=product_name if not isdir(package_dir): return if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): if not exists(path_join(package_dir, '__init__.pyo')): return try: product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) # Install items into the misc_ namespace, used by products # and the framework itself to store common static resources # like icon images. misc_=pgetattr(product, 'misc_', {}) if misc_: if isinstance(misc_, dict): misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Here we create a ProductContext object which contains # information about the product and provides an interface # for registering things like classes and help topics that # should be associated with that product. Products are # expected to implement a method named 'initialize' in # their __init__.py that takes the ProductContext as an # argument. productObject=App.Product.initializeProduct( product, product_name, package_dir, app) context=ProductContext(productObject, app, product) # Look for an 'initialize' method in the product. If it does # not exist, then this is an old product that has never been # updated. In that case, we will analyze the product and # build up enough information to do initialization manually. initmethod=pgetattr(product, 'initialize', None) if initmethod is not None: initmethod(context) # Support old-style product metadata. Older products may # define attributes to name their permissions, meta_types, # constructors, etc. permissions={} new_permissions={} if pgetattr(product, '__ac_permissions__', None) is not None: warn('__init__.py of %s has a long deprecated ' '\'__ac_permissions__\' attribute. ' '\'__ac_permissions__\' will be ignored by ' 'install_product in Zope 2.10. Please use registerClass ' 'instead.' % product.__name__, DeprecationWarning) for p in pgetattr(product, '__ac_permissions__', ()): permission, names, default = ( tuple(p)+('Manager',))[:3] if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() if pgetattr(product, 'meta_types', None) is not None: warn('__init__.py of %s has a long deprecated \'meta_types\' ' 'attribute. \'meta_types\' will be ignored by ' 'install_product in Zope 2.10. Please use registerClass ' 'instead.' % product.__name__, DeprecationWarning) for meta_type in pgetattr(product, 'meta_types', ()): # Modern product initialization via a ProductContext # adds 'product' and 'permission' keys to the meta_type # mapping. We have to add these here for old products. pname=permissions.get(meta_type['action'], None) if pname is not None: meta_type['permission']=pname meta_type['product']=productObject.id meta_type['visibility'] = 'Global' meta_types.append(meta_type) if pgetattr(product, 'methods', None) is not None: warn('__init__.py of %s has a long deprecated \'methods\' ' 'attribute. \'methods\' will be ignored by ' 'install_product in Zope 2.10. Please use registerClass ' 'instead.' % product.__name__, DeprecationWarning) for name,method in pgetattr( product, 'methods', {}).items(): if not hasattr(Folder.Folder, name): setattr(Folder.Folder, name, method) if name[-9:]!='__roles__': # not Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key( permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.Folder.__ac_permissions__=tuple( list(Folder.Folder.__ac_permissions__)+new_permissions) if not doInstall(): transaction().abort() else: transaction.get().note('Installed product '+product_name) transaction.commit() except: if log_exc: LOG('Zope',ERROR,'Couldn\'t install %s' % product_name, error=sys.exc_info()) transaction.abort() if raise_exc: raise
td_reg=re.compile(r'[ \t\n]*\|\|([^\0x00|]*)')
td_reg=re.compile(r'[ \t\n]*\|\|([^\0|]*)')
def create(self,aPar, td_reg=re.compile(r'[ \t\n]*\|\|([^\0x00|]*)') ): '''parses a table and returns nested list representing the table''' self.table=[] text=filter(None,aPar.split('\n')) for line in text: row=[] while 1: mo = td_reg.match(line) if not mo: return 0 pos = mo.end(1) row.append(mo.group(1)) if pos==len(line):break line=line[pos:] self.table.append(row) return 1
rc=referenceCount_get(roid, 0)
rc=referenceCount_get(roid, 0) - 1
def _takeOutGarbage(self, oid): # take out the garbage. referenceCount=self._referenceCount referenceCount_get=referenceCount.get
referenceCount[roid] = rc - 1
referenceCount[roid] = rc
def _takeOutGarbage(self, oid): # take out the garbage. referenceCount=self._referenceCount referenceCount_get=referenceCount.get
status = _("An error occured.")
status = _("An error occurred.")
def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status
self.update_status = _("An error occured.")
self.update_status = _("An error occurred.")
def update(self): if self.update_status is not None: # We've been called before. Just return the previous result. return self.update_status
if not isInContext(ucontext, object):
if not object.aq_inContextOf(ucontext, 1):
def allowed(self, object, object_roles=None): """Check whether the user has access to object, assuming that object.__roles__ is the given roles.""" if object_roles is None or 'Anonymous' in object_roles: return 1 usr_roles=self.getRolesInContext(object) for role in object_roles: if role in usr_roles: # The user apparently has one of the necessary # roles, but first make sure the object exists # in the context of the parent of the acl_users # folder. ufolder = getattr(self, 'aq_parent', None) ucontext = getattr(ufolder, 'aq_parent', None) if ucontext is not None: if object is None: # This is a strange rule, though # it doesn't cause any security holes. SDH return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # object is not wrapped, therefore we # can't determine context. # Fail the access attempt. Otherwise # this would be a security hole. return None # ----------------------------------------------------- # FIXME: this is a workaround for broken aq_inContextOf # ----------------------------------------------------- # if not object.aq_inContextOf(ucontext, 1): if not isInContext(ucontext, object): if 'Shared' in object_roles: # Damn, old role setting. Waaa object_roles=self._shared_roles(object) if 'Anonymous' in object_roles: return 1 return None
from Acquisition import aq_base, aq_inner, aq_parent def isInContext(fixed, variable): fixed = aq_base(fixed) while variable is not None: v = aq_base(variable) if v is fixed: return 1 variable = aq_parent(aq_inner(variable)) return 0
def reqattr(request, attr): try: return request[attr] except: return None
expr=re.compile(r"\_([%s0-9\s\.,\?]+)\_" % letters).search):
expr=re.compile(r"\s*\_([%s0-9\s\.,\?]+)\_" % letters).search):
def doc_underline(self, s, expr=re.compile(r"\_([%s0-9\s\.,\?]+)\_" % letters).search): result = expr(s) if result: start,end = result.span(1) st,e = result.span() return (StructuredTextUnderline(s[start:end]),st,e) else: return None
def manage_addZCatalog(self, id, title, vocab='', vocab_id='', REQUEST=None):
def manage_addZCatalog(self,id,title,REQUEST=None):
def manage_addZCatalog(self, id, title, vocab='', vocab_id='', REQUEST=None): """Add a ZCatalog object """ c=ZCatalog(id, title, vocab, vocab_id, self) self._setObject(id, c) if REQUEST is not None: return self.manage_main(self, REQUEST)
c=ZCatalog(id, title, vocab, vocab_id, self) self._setObject(id, c)
c=ZCatalog(id,title) self._setObject(id,c)
def manage_addZCatalog(self, id, title, vocab='', vocab_id='', REQUEST=None): """Add a ZCatalog object """ c=ZCatalog(id, title, vocab, vocab_id, self) self._setObject(id, c) if REQUEST is not None: return self.manage_main(self, REQUEST)
return self.manage_main(self, REQUEST) def VocabularyIDs(self): """ returns a list of acquireable vocabularies. Stole this from ZSQLMethods """ ids={} have_id=ids.has_key StringType=type('') while self is not None: if hasattr(self, 'objectValues'): for o in self.objectValues(): if (hasattr(o,'_isAVocabulary') and o._isAVocabulary and hasattr(o,'id')): id=o.id if type(id) is not StringType: id=id() if not have_id(id): if hasattr(o,'title_and_id'): o=o.title_and_id() else: o=id ids[id]=id if hasattr(self, 'aq_parent'): self=self.aq_parent else: self=None ids=map(lambda item: (item[1], item[0]), ids.items()) ids.sort() return ids
return self.manage_main(self,REQUEST)
def manage_addZCatalog(self, id, title, vocab='', vocab_id='', REQUEST=None): """Add a ZCatalog object """ c=ZCatalog(id, title, vocab, vocab_id, self) self._setObject(id, c) if REQUEST is not None: return self.manage_main(self, REQUEST)
_v_vocabulary = None def __init__(self, id, title='', vocab=0, vocab_id='', container=None):
def __init__(self,id,title=''):
def VocabularyIDs(self): """ returns a list of acquireable vocabularies. Stole this from ZSQLMethods """ ids={} have_id=ids.has_key StringType=type('') while self is not None: if hasattr(self, 'objectValues'): for o in self.objectValues(): if (hasattr(o,'_isAVocabulary') and o._isAVocabulary and hasattr(o,'id')): id=o.id if type(id) is not StringType: id=id() if not have_id(id): if hasattr(o,'title_and_id'): o=o.title_and_id() else: o=id ids[id]=id if hasattr(self, 'aq_parent'): self=self.aq_parent else: self=None ids=map(lambda item: (item[1], item[0]), ids.items()) ids.sort() return ids
self.vocab_id = vocab_id
def __init__(self, id, title='', vocab=0, vocab_id='', container=None): self.id=id self.title=title self.vocab_id = vocab_id self.threshold = 10000 self._v_total = 0
if not vocab: v = Vocabulary('Vocabulary', 'Vocabulary', globbing=1) self._setObject('Vocabulary', v) v = 'Vocabulary' else: v = vocab_id self._catalog = Catalog(vocabulary=v)
self._catalog = Catalog()
def __init__(self, id, title='', vocab=0, vocab_id='', container=None): self.id=id self.title=title self.vocab_id = vocab_id self.threshold = 10000 self._v_total = 0
self._catalog.addColumn('absolute_url') self._catalog.addIndex('absolute_url', 'FieldIndex') def getVocabulary(self): """ more ack! """ return getattr(self, self.vocab_id)
def __init__(self, id, title='', vocab=0, vocab_id='', container=None): self.id=id self.title=title self.vocab_id = vocab_id self.threshold = 10000 self._v_total = 0
for b in klass.__bases__: _ii(b)
for b in klass.__bases__: _ii(b, items)
def _ii(klass, items): for k, v in klass.__dict__.items(): if type(v) is not FunctionType or not v.__doc__: continue if k[:1]=='_' and not (k[:2]=='__' and k[-2:]=='__'): continue items[k]=v for b in klass.__bases__: _ii(b) return items
return getattr(self,suffix)(data[prefix+'-index'])
try: v=data[prefix+'-index'] except: pass else: return getattr(self,suffix)(v)
def __getitem__(self,key, special_prefixes=special_prefixes, special_prefix=special_prefixes.has_key ): data=self.data if data.has_key(key): return data[key]
__builtins__.__debug__=DEBUG
def server_info(old, v, offset=0): # interpret v as a port or address/port and get new value if v == '-': v='' l=string.find(v, ':') if l >= 0: a=v[:l] v=v[l+1:] else: a=IP_ADDRESS if not v: return v try: v=string.atoi(v) if v < 0: raise 'Invalid port', v v=v+offset except: raise 'Invalid port', v if type(old) is type(0): old=[(a,v)] else: old.append((a,v)) return old
if hasattr(aq_base(ob), 'isTopLevelPrincipiaApplicationObject'):
if hasattr(aq_base(ob), 'isTopLevelPrincipiaApplicationObject') and \ ob.isTopLevelPrincipiaApplicationObject:
def is_acquired(ob, hasattr=hasattr, aq_base=aq_base, absattr=absattr): # Return true if this object is not a direct # subobject of its aq_parent object. if not hasattr(ob, 'aq_parent'): return 0 if hasattr(aq_base(ob.aq_parent), absattr(ob.id)): return 0 if hasattr(aq_base(ob), 'isTopLevelPrincipiaApplicationObject'): return 0 return 1
while path and path[0]=='/': path=path[1:] while path and path[-1]=='/': path=path[:-1] req=REQUEST.clone() rsp=req.response req['PATH_INFO']=path object=None try: object=req.traverse(path) except: pass if object is not None: if hasattr(object, 'id'): if callable(object.id): name=object.id() else: name=object.id elif hasattr(object, '__name__'): name=object.__name__ else: name='' if name != os.path.split(path)[-1]: result = req.PARENTS[0] req.close() return result req.close() return object req.close() raise rsp.errmsg, sys.exc_value
script=REQUEST.script if string.find(path, script) != 0: path='%s/%s' % (script, path) try: return REQUEST.resolve_url(path) except: return None
def resolve_url(self, path, REQUEST): """ """ while path and path[0]=='/': path=path[1:] while path and path[-1]=='/': path=path[:-1] req=REQUEST.clone() rsp=req.response req['PATH_INFO']=path object=None try: object=req.traverse(path) except: # Do NOT call rsp.exception here! pass if object is not None: if hasattr(object, 'id'): if callable(object.id): name=object.id() else: name=object.id elif hasattr(object, '__name__'): name=object.__name__ else: name='' if name != os.path.split(path)[-1]: result = req.PARENTS[0] req.close() return result req.close() return object req.close() raise rsp.errmsg, sys.exc_value
print >> _log_dest, "s: %s" % error[:2]
print >> _log_dest, "%s: %s" % error[:2]
def log(self, subsystem, severity, summary, detail, error): if _log_dest is None or severity < _log_level: return