bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): ts_results = name_re.match_group(headers[i], (1,2)) if ts_results: k, v = ts_results[1] v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
2,000
def __init__(self, index_dictionary = None, synstop = None): 'Create an inverted index' if (synstop is None): synstop = {} for key, value in default_stop_words: synstop[key] = value self.synstop = synstop
def __init__(self, index_dictionary = None, synstop = None): 'Create an inverted index' if (synstop is None): synstop = {} for key, value in default_stop_words.items(): synstop[key] = value self.synstop = synstop
2,001
def appendCookie(self, name, value):
def appendCookie(self, name, value):
2,002
def expireCookie(self, name):
def expireCookie(self, name):
2,003
def setCookie(self,name, value=None,
def setCookie(self,name, value=None,
2,004
def _cookie_list(self):
def _cookie_list(self):
2,005
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. If calling manage_pasteObjects from python code, pass the result of a previous call to manage_cutObjects or manage_copyObjects as the first argument.""" cp=None if cb_copy_data is not None: cp=cb_copy_data else: if REQUEST and REQUEST.has_key('__cp'): cp=REQUEST['__cp'] if cp is None: raise CopyError, eNoData try: cp=_cb_decode(cp) except: raise CopyError, eInvalid
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. If calling manage_pasteObjects from python code, pass the result of a previous call to manage_cutObjects or manage_copyObjects as the first argument.""" cp=None if cb_copy_data is not None: cp=cb_copy_data else: if REQUEST and REQUEST.has_key('__cp'): cp=REQUEST['__cp'] if cp is None: raise CopyError, eNoData try: cp=_cb_decode(cp) except: raise CopyError, eInvalid
2,006
def _read_and_report(file, rpt=None, fromEnd=0, both=0, n=99999999, show=0): """\ Read a file's index up to the given time. """ first=1 seek=file.seek read=file.read unpack=struct.unpack split=string.split join=string.join find=string.find seek(0,2) file_size=file.tell() gmtime=time.gmtime if fromEnd: pos=file_size else: pos=newpos=len(packed_version) tlast=0 err=0 tnamelast='' while 1: if fromEnd: seek(pos-4) l=unpack(">i", read(4))[0] if l==0: b=pos p=pos-4 while l==0: p=p-4 seek(p) l=unpack(">i", read(4))[0] pos=p+4 error("nulls skipped from %s to %s" % (pos,b)) p=pos-l if p < 0: error('Corrupted data before %s' % pos) if show > 0: p=pos-show if p < 0: p=0 seek(p) p=read(pos-p) else: p='' error(p,1) pos=p else: pos=newpos seek(pos) h=read(24) # 24=header_size if not h: break if len(h) != 24: break oid,prev,start,tlen,plen=unpack(">iidii",h) if (prev < 0 or prev >= pos or start < tlast or plen > tlen or plen < 0 or oid < -999): __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: error(read(show)) err=1 break newpos=pos+tlen if newpos > file_size: error('Truncated data record at %s' % pos) if show > 0: error(read(show)) err=1 break seek(newpos-4) if read(4) != h[16:20]: __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: seek(pos+24) error(read(show)) err=1 break tlast=start-100 if rpt is None: continue n=n-1 if n < 1: break seek(pos+24) if plen > 0: p=read(plen) if p[-1:] != '.': error('Corrupted pickle at %s %s %s' % (pos,plen,len(p))) if show > 0: seek(pos+24) error(read(show)) err=1 break else: p='' t=split(read(tlen-plen-28),'\t') tname, user = (t+[''])[:2] t=join(t[2:],'\t') start,f=divmod(start,1) y,m,d,h,mn,s=gmtime(start)[:6] s=s+f start="%.4d-%.2d-%.2d %.2d:%.2d:%.3f" % (y,m,d,h,mn,s) rpt(pos,oid,start,tname,user,t,p,first,tname!=tnamelast) first=0 tnamelast=tname if err and both and not fromEnd: _read_and_report(file, rpt, 1, 0, n, show) rpt(None, None, None, None, None, None, None, None, None)
def _read_and_report(file, rpt=None, fromEnd=0, both=0, n=99999999, show=0): """\ Read a file's index up to the given time. """ first=1 seek=file.seek read=file.read unpack=struct.unpack split=string.split join=string.join find=string.find seek(0,2) file_size=file.tell() gmtime=time.gmtime if fromEnd: pos=file_size else: pos=newpos=len(packed_version) tlast=0 err=0 tnamelast=None while 1: if fromEnd: seek(pos-4) l=unpack(">i", read(4))[0] if l==0: b=pos p=pos-4 while l==0: p=p-4 seek(p) l=unpack(">i", read(4))[0] pos=p+4 error("nulls skipped from %s to %s" % (pos,b)) p=pos-l if p < 0: error('Corrupted data before %s' % pos) if show > 0: p=pos-show if p < 0: p=0 seek(p) p=read(pos-p) else: p='' error(p,1) pos=p else: pos=newpos seek(pos) h=read(24) # 24=header_size if not h: break if len(h) != 24: break oid,prev,start,tlen,plen=unpack(">iidii",h) if (prev < 0 or prev >= pos or start < tlast or plen > tlen or plen < 0 or oid < -999): __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: error(read(show)) err=1 break newpos=pos+tlen if newpos > file_size: error('Truncated data record at %s' % pos) if show > 0: error(read(show)) err=1 break seek(newpos-4) if read(4) != h[16:20]: __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: seek(pos+24) error(read(show)) err=1 break tlast=start-100 if rpt is None: continue n=n-1 if n < 1: break seek(pos+24) if plen > 0: p=read(plen) if p[-1:] != '.': error('Corrupted pickle at %s %s %s' % (pos,plen,len(p))) if show > 0: seek(pos+24) error(read(show)) err=1 break else: p='' t=split(read(tlen-plen-28),'\t') tname, user = (t+[''])[:2] t=join(t[2:],'\t') start,f=divmod(start,1) y,m,d,h,mn,s=gmtime(start)[:6] s=s+f start="%.4d-%.2d-%.2d %.2d:%.2d:%.3f" % (y,m,d,h,mn,s) rpt(pos,oid,start,tname,user,t,p,first,tname!=tnamelast) first=0 tnamelast=tname if err and both and not fromEnd: _read_and_report(file, rpt, 1, 0, n, show) rpt(None, None, None, None, None, None, None, None, None)
2,007
def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t))
def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t))
2,008
def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t))
def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t))
2,009
def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search):
def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search):
2,010
def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search):
def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search):
2,011
def doc_strong(self, s, expr = re.compile(r'\s*\*\*([ \n%s0-9]+)\*\*' % lettpunc).search ):
def doc_strong(self, s, expr = re.compile(r'\s*\*\*([ \n%s0-9]+)\*\*' % lettpunc).search ):
2,012
def finish_starttag(self, tag, attrs): self.scan_xmlns(attrs) if tag in EMPTY_HTML_TAGS: self.pop_xmlns() elif BLOCK_CLOSING_TAG_MAP.has_key(tag): blocks_to_close = BLOCK_CLOSING_TAG_MAP[tag] close_to = -1 for i in range(len(self.tagstack)): t = self.tagstack[i] if t in blocks_to_close: close_to = i elif t in BLOCK_LEVEL_HTML_TAGS: close_to = -1 self.close_to_level(close_to) self.tagstack.append(tag) elif tag in PARA_LEVEL_HTML_TAGS + BLOCK_LEVEL_HTML_TAGS: close_to = -1 for i in range(len(self.tagstack)): if self.tagstack[i] in BLOCK_LEVEL_HTML_TAGS: close_to = -1 elif self.tagstack[i] in PARA_LEVEL_HTML_TAGS: if close_to == -1: close_to = i self.close_to_level(close_to) self.tagstack.append(tag) else: self.tagstack.append(tag) attrlist, taldict, metaldict = self.extract_attrs(attrs) self.gen.emitStartElement(tag, attrlist, taldict, metaldict, self.getpos())
def finish_starttag(self, tag, attrs): self.scan_xmlns(attrs) if tag in EMPTY_HTML_TAGS: self.pop_xmlns() elif BLOCK_CLOSING_TAG_MAP.has_key(tag): blocks_to_close = BLOCK_CLOSING_TAG_MAP[tag] close_to = -1 for i in range(len(self.tagstack)): t = self.tagstack[i] if t in blocks_to_close: close_to = i elif t in BLOCK_LEVEL_HTML_TAGS: close_to = -1 self.close_to_level(close_to) self.tagstack.append(tag) elif tag in PARA_LEVEL_HTML_TAGS + BLOCK_LEVEL_HTML_TAGS: close_to = -1 for i in range(len(self.tagstack)): if self.tagstack[i] in BLOCK_LEVEL_HTML_TAGS: close_to = -1 elif self.tagstack[i] in PARA_LEVEL_HTML_TAGS: if close_to == -1: close_to = i self.close_to_level(close_to) self.tagstack.append(tag) else: self.tagstack.append(tag) attrlist, taldict, metaldict = self.extract_attrs(attrs) self.gen.emitStartElement(tag, attrlist, taldict, metaldict, self.getpos())
2,013
def manage_edit(self, title, module, function, REQUEST=None):
def manage_edit(self, title, module, function, REQUEST=None):
2,014
def getFunction(self):
def getFunction(self):
2,015
def getFunction(self):
def getFunction(self):
2,016
def __cmp__(self,other):
def __cmp__(self,other):
2,017
def __init__(self, blocks): tname, args, section = blocks[0]
def __init__(self, blocks): tname, args, section = blocks[0]
2,018
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except DTReturn: raise except: # but an error occurs.. save the info. t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t else: errname = t.__name__
def render(self, md): # first we try to render the first block try: result = render_blocks(self.section, md) except DTReturn: raise except: # but an error occurs.. save the info. t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t else: errname = t.__name__
2,019
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except DTReturn: raise except: # but an error occurs.. save the info. t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t else: errname = t.__name__
def else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result render(self, else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result md): else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result # else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result first else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result we else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result try else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result to else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result render else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result the else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result first else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result block else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result try: else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result return else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result render_blocks(self.section, else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result md) else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result except else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result DTReturn: else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result raise else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result except: else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result # else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result but else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result an else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result error else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result occurs.. else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result save else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result the else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result info. else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result t,v else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result = else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result sys.exc_info()[:2] else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result if else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result type(t)==type(''): else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result errname else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result = else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result t else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result else: else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result errname else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result = else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result t.__name__
2,020
def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=regex.compile(':[a-zA-Z][a-zA-Z0-9_]+$').search, rfind=string.rfind, ): """Process request inputs
def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=regex.compile(':[a-zA-Z][a-zA-Z0-9_]+$').search, rfind=string.rfind, ): """Process request inputs
2,021
def __getitem__(self,index):
def __getitem__(self,index):
2,022
def __getitem__(self,index):
def __getitem__(self,index):
2,023
def manage_importObject(self, file, REQUEST=None): """Import an object from a file""" dirname, file=os.path.split(file) if dirname: raise 'Bad Request', 'Invalid file name %s' % file file=os.path.join(INSTANCE_HOME, 'import', file) if not os.path.exists(file): raise 'Bad Request', 'File does not exist: %s' % file ob=self._p_jar.importFile(file) if REQUEST: self._verifyObjectPaste(ob, REQUEST) id=ob.id if hasattr(id, 'im_func'): id=id() self._setObject(id, ob) if REQUEST is not None: return MessageDialog( title='Object imported', message='<EM>%s</EM> sucessfully imported' % id, action='manage_main' )
def manage_importObject(self, file, REQUEST=None): """Import an object from a file""" dirname, file=os.path.split(file) if dirname: raise 'Bad Request', 'Invalid file name %s' % file file=os.path.join(INSTANCE_HOME, 'import', file) if not os.path.exists(file): raise 'Bad Request', 'File does not exist: %s' % file connection=self._p_jar obj=self while connection is None: obj=obj.aq_parent connection=obj._p_jar ob=connection.importFile(file) if REQUEST: self._verifyObjectPaste(ob, REQUEST) id=ob.id if hasattr(id, 'im_func'): id=id() self._setObject(id, ob) if REQUEST is not None: return MessageDialog( title='Object imported', message='<EM>%s</EM> sucessfully imported' % id, action='manage_main' )
2,024
def parse2(q, default_operator, operator_dict = {AndNot: AndNot, And: And, Or: Or, Near: Near}, ListType=type([]), ): '''Find operators and operands''' i = 0 isop=operator_dict.has_key while (i < len(q)): if (type(q[i]) is ListType): q[i] = parse2(q[i], default_operator) # every other item, starting with the first, should be an operand if ((i % 2) != 0): # This word should be an operator; if it is not, splice in # the default operator. if isop(q[i]): q[i] = operator_dict[q[i]] else: q[i : i] = [ default_operator ] i = i + 1 return q
def parse2(q, default_operator, operator_dict = {AndNot: AndNot, And: And, Or: Or, Near: Near}, ListType=type([]), ): '''Find operators and operands''' i = 0 isop=operator_dict.has_key while (i < len(q)): if (type(q[i]) is ListType): q[i] = parse2(q[i], default_operator) # every other item, starting with the first, should be an operand 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 ] i = i + 1 return q
2,025
def __bobo_traverse__(self, REQUEST, name=None):
def __bobo_traverse__(self, REQUEST, name=None):
2,026
def clear(self):
def clear(self):
2,027
def __call__(self, *args, **kw): """Call an ExternalMethod
def __call__(self, *args, **kw): """Call an ExternalMethod
2,028
def _delDB(): transaction.abort() del stuff['db']
def _delDB(): transaction.abort() del stuff['db']
2,029
def testSubcommit(self): sd = self.app.session_data_manager.getSessionData() sd.set('foo', 'bar') # TODO: this is used to test that transaction.commit(1) returned # None, but transaction.commit(whatever) always returns None (unless # there's an exception). What is this really trying to test? transaction.savepoint(optimistic=True)
def testSubcommit(self): sd = self.app.session_data_manager.getSessionData() sd.set('foo', 'bar') # TODO: this is used to test that transaction.commit(1) returned # None, but transaction.commit(whatever) always returns None (unless # there's an exception). What is this really trying to test? transaction.savepoint(optimistic=True)
2,030
def testAqWrappedObjectsFail(self): a = Foo() b = Foo() aq_wrapped = a.__of__(b) sd = self.app.session_data_manager.getSessionData() sd.set('foo', aq_wrapped) self.assertRaises(TypeError, transaction.commit)
def testAqWrappedObjectsFail(self): a = DummyAqImplicit() b = DummyAqImplicit() aq_wrapped = a.__of__(b) sd = self.app.session_data_manager.getSessionData() sd.set('foo', aq_wrapped) self.assertRaises(TypeError, transaction.commit)
2,031
def boboTraverseAwareSimpleTraverse(object, path_items, econtext): """A slightly modified version of zope.tales.expressions.simpleTraverse that interacts correctly with objects requiring.""" request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if ITraversable.providedBy(object): try: object = object.restrictedTraverse(name) except (NotFound, Unauthorized), e: # OFS.Traversable.restrictedTraverse spits out # NotFound or Unauthorized (the Zope 2 versions) which # Zope 3's ZPT implementation obviously doesn't know # as exceptions indicating failed traversal. Perhaps # the Zope 2's versions should be replaced with their # Zope 3 equivalent at some point. For the time # being, however, we simply convert them into # LookupErrors: raise LookupError(*e.args) else: object = traversePathElement(object, name, path_items, request=request) return object
def boboTraverseAwareSimpleTraverse(object, path_items, econtext): """A slightly modified version of zope.tales.expressions.simpleTraverse that interacts correctly with objects providing OFS.interfaces.ITraversable. """ request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if ITraversable.providedBy(object): try: object = object.restrictedTraverse(name) except (NotFound, Unauthorized), e: # OFS.Traversable.restrictedTraverse spits out # NotFound or Unauthorized (the Zope 2 versions) which # Zope 3's ZPT implementation obviously doesn't know # as exceptions indicating failed traversal. Perhaps # the Zope 2's versions should be replaced with their # Zope 3 equivalent at some point. For the time # being, however, we simply convert them into # LookupErrors: raise LookupError(*e.args) else: object = traversePathElement(object, name, path_items, request=request) return object
2,032
def do_adduser(self, arg): try: name, password = arg.split() except: print "usage: adduser <name> <password>" return cmdline = self.get_startup_cmd( self.options.python , 'import Zope2; app=Zope2.app();' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []);' 'transaction.commit()' ) % (name, password) os.system(cmdline)
def do_adduser(self, arg): try: name, password = arg.split() except: print "usage: adduser <name> <password>" return cmdline = self.get_startup_cmd( self.options.python , 'import Zope2; ' 'app = Zope2.app(); ' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []); ' 'import transaction; ' 'transaction.commit(); ' ) % (name, password) os.system(cmdline)
2,033
def get(self, pattern): """ Query the lexicon for words matching a pattern.""" wc_set = [self.multi_wc, self.single_wc]
def get(self, pattern): """ Query the lexicon for words matching a pattern.""" wc_set = [self.multi_wc, self.single_wc]
2,034
def _check_context(self, object): # Check that 'object' exists in the acquisition context of # the parent of the acl_users object containing this user, # to prevent "stealing" access through acquisition tricks. # Return true if in context, false if not or if context # cannot be determined (object is not wrapped). parent = getattr(self, 'aq_parent', None) context = getattr(parent, 'aq_parent', None) if context is not None: if object is None: 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, so return false. return 0 if object.aq_inContextOf(context, 1): return 1 # This is lame, but required to keep existing behavior. return 1
def _check_context(self, object): # Check that 'object' exists in the acquisition context of # the parent of the acl_users object containing this user, # to prevent "stealing" access through acquisition tricks. # Return true if in context, false if not or if context # cannot be determined (object is not wrapped). parent = getattr(self, 'aq_parent', None) context = getattr(parent, 'aq_parent', None) if context is not None: if object is None: 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, so return false. return 0 return object.aq_inContextOf(context, 1) # This is lame, but required to keep existing behavior. return 1
2,035
def searchResults(self, REQUEST=None, used=None, query_map={ type(regex.compile('')): Query.Regex, type([]): orify, type(''): Query.String, }, **kw):
def searchResults(self, REQUEST=None, used=None, query_map={ type(regex.compile('')): Query.Regex, type([]): orify, type(''): Query.String, }, **kw):
2,036
def and_not(self, x): result = {} dict = self._dict xdict = x._dict xhas = xdict.has_key for id, score in dict.items(): if not xhas(id): result[id] = xdict[id]+score return self.__class__(result, self._words, self._index)
def and_not(self, x): result = {} dict = self._dict xdict = x._dict xhas = xdict.has_key for id, score in dict.items(): if not xhas(id): result[id] = score return self.__class__(result, self._words, self._index)
2,037
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,038
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,039
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,040
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,041
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,042
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,043
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,044
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,045
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,046
def field2tuple(v): if type(v) is not ListType: v=(v,) return tuple(v)
def field2tuple(v): if type(v) is not ListType: v=(v,) return tuple(v)
2,047
def str(self,name): dict=getattr(self,name) return "%s:\n\t%s\n\n" % ( name, join( map(lambda k, d=dict: "%s: %s" % (k, `d[k]`), dict.keys()), "\n\t" ) )
def str(self,name): dict=getattr(self,name) return "%s:\n\t%s\n\n" % ( name, join( map(lambda k, d=dict: "%s: %s" % (k, `d[k]`), dict.keys()), "\n\t" ) )
2,048
def old_validation(groups, HTTP_AUTHORIZATION, roles=UNSPECIFIED_ROLES): global base64 if base64 is None: import base64 if lower(HTTP_AUTHORIZATION[:6]) != 'basic ': return None [name,password] = string.splitfields( base64.decodestring( split(HTTP_AUTHORIZATION)[-1]), ':') if roles is None: return name keys=None try: keys=groups.keys except: try: groups=groups() # Maybe it was a method defining a group keys=groups.keys except: pass if keys is not None: # OK, we have a named group, so apply the roles to the named # group. if roles is UNSPECIFIED_ROLES: roles=keys() g=[] for role in roles: if groups.has_key(role): g.append(groups[role]) groups=g for d in groups: if d.has_key(name) and d[name]==password: return name if keys is None: # Not a named group, so don't go further raise 'Forbidden', ( """<strong>You are not authorized to access this resource""") return None
def old_validation(groups, HTTP_AUTHORIZATION, roles=UNSPECIFIED_ROLES): global base64 if base64 is None: import base64 if lower(HTTP_AUTHORIZATION[:6]) != 'basic ': if roles is None: return '' return None [name,password] = string.splitfields( base64.decodestring( split(HTTP_AUTHORIZATION)[-1]), ':') if roles is None: return name keys=None try: keys=groups.keys except: try: groups=groups() # Maybe it was a method defining a group keys=groups.keys except: pass if keys is not None: # OK, we have a named group, so apply the roles to the named # group. if roles is UNSPECIFIED_ROLES: roles=keys() g=[] for role in roles: if groups.has_key(role): g.append(groups[role]) groups=g for d in groups: if d.has_key(name) and d[name]==password: return name if keys is None: # Not a named group, so don't go further raise 'Forbidden', ( """<strong>You are not authorized to access this resource""") return None
2,049
def parse_text(s): if find('\\') < 0 or (find('\\t') < 0 and find('\\n') < 0): return s r=[] for x in split(s,'\\\\'): x=join(split(x,'\\n'),'\n') r.append(join(split(x,'\\t'),'\t')) return join(r,'\\')
def parse_text(s): if find(s,'\\') < 0 or (find(s,'\\t') < 0 and find(s,'\\n') < 0): return s r=[] for x in split(s,'\\\\'): x=join(split(x,'\\n'),'\n') r.append(join(split(x,'\\t'),'\t')) return join(r,'\\')
2,050
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,051
def publish(self, module_name, after_list, published='web_objects',
def publish(self, module_name, after_list, published='web_objects',
2,052
def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10)
def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10)
2,053
def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10)
def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10)
2,054
def traverse(self, path, response=None, validated_hook=None): """Traverse the object space
def traverse(self, path, response=None, validated_hook=None): """Traverse the object space
2,055
def _cached_result(self, DB__, query):
def _cached_result(self, DB__, query):
2,056
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ else: realm=module_name # Check whether tracebacks should be hidden: if (hasattr(module,'__bobo_hide_tracebacks__') and not module.__bobo_hide_tracebacks__): CGIResponse._tbopen, CGIResponse._tbclose = '<PRE>', '</PRE>' if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ else: realm=module_name # Check whether tracebacks should be hidden: if (hasattr(module,'__bobo_hide_tracebacks__') and not module.__bobo_hide_tracebacks__): CGIResponse._tbopen, CGIResponse._tbclose = '<PRE>', '</PRE>' if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
2,057
def StructuredText(paragraphs, delimiter=re.compile(para_delim)): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = expandtabs(paragraphs) paragraphs = '%s%s%s' % ('\n\n', paragraphs, '\n\n') paragraphs = delimiter.split(paragraphs) paragraphs = filter(strip, paragraphs) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindet = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
def StructuredText(paragraphs, delimiter=re.compile(para_delim)): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = expandtabs(paragraphs) paragraphs = '%s%s%s' % ('\n\n', paragraphs, '\n\n') paragraphs = delimiter.split(paragraphs) paragraphs = filter(strip, paragraphs) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindent = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
2,058
def validate( self, *args, **kw ): return self._lambdas[ 0 ]( *args, **kw )
def validate( self, *args, **kw ): return self._lambdas[ 0 ]( *args, **kw )
2,059
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
2,060
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
2,061
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
2,062
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
def __init__(self,id,title=None): self.id=id self.title=title self._ztable=ZTablesCore.ZTable(id)
2,063
def reindexIndex(self, name, REQUEST): if isinstance(name, str): name = (name,) for p in self._catalog.uids.keys(): obj = self.resolve_path(p) if not obj: obj = self.resolve_url(p, REQUEST) if obj is None: LOG.error('reindexIndex could not resolve ' 'an object from the uid %r.' % (uid)) else: # don't update metadata when only reindexing a single # index via the UI try: self.catalog_object(obj, p, idxs=name, update_metadata=0) except TypeError: # Fall back to Zope 2.6.2 interface. This is necessary for # products like CMF 1.4.2 and earlier that subclass from # ZCatalog and don't support the update_metadata argument. # May be removed some day. from warnings import warn warn('catalog_object interface of %s not up to date' % self.__class__.__name__, DeprecationWarning) self.catalog_object(obj, p, idxs=name)
def reindexIndex(self, name, REQUEST): if isinstance(name, str): name = (name,) for p in self._catalog.uids.keys(): obj = self.resolve_path(p) if not obj: obj = self.resolve_url(p, REQUEST) if obj is None: LOG.error('reindexIndex could not resolve ' 'an object from the uid %r.' % p) else: # don't update metadata when only reindexing a single # index via the UI try: self.catalog_object(obj, p, idxs=name, update_metadata=0) except TypeError: # Fall back to Zope 2.6.2 interface. This is necessary for # products like CMF 1.4.2 and earlier that subclass from # ZCatalog and don't support the update_metadata argument. # May be removed some day. from warnings import warn warn('catalog_object interface of %s not up to date' % self.__class__.__name__, DeprecationWarning) self.catalog_object(obj, p, idxs=name)
2,064
def _getCurrentBucket(self): """ Do housekeeping if necessary, then return the 'current' bucket. """ self.lock.acquire() try: # do in-place upgrade of old "ring-based" instances if # we've just upgraded from Zope 2.5.X if self._data is None: self._upgrade()
def _getCurrentBucket(self): """ Do housekeeping if necessary, then return the 'current' bucket. """ self.lock.acquire() try: # do in-place upgrade of old "ring-based" instances if # we've just upgraded from Zope 2.5.X if self._data is None: self._upgrade()
2,065
def dav__allprop(self, propstat=propstat ): # DAV helper method - return one or more propstat elements # indicating property names and values for all properties. result=[] for item in self._propertyMap(): name, type=item['id'], item.get('type','string') value=self.getProperty(name)
def dav__allprop(self, propstat=propstat ): # DAV helper method - return one or more propstat elements # indicating property names and values for all properties. result=[] for item in self._propertyMap(): name, type=item['id'], item.get('type','string') value=self.getProperty(name)
2,066
def dav__allprop(self, propstat=propstat ): # DAV helper method - return one or more propstat elements # indicating property names and values for all properties. result=[] for item in self._propertyMap(): name, type=item['id'], item.get('type','string') value=self.getProperty(name)
def dav__allprop(self, propstat=propstat ): # DAV helper method - return one or more propstat elements # indicating property names and values for all properties. result=[] for item in self._propertyMap(): name, type=item['id'], item.get('type','string') value=self.getProperty(name)
2,067
def dav__propstat(self, name, result, propstat=propstat, propdesc=propdesc): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop='<n:%s xmlns:n="%s"/>\n' % (name, xml_id) code='404 Not Found' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=' '.join(str(value)) elif type=='lines': value='\n'.join(str(value)) # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=''.join(attrs) else: # quote non-xml items here? attrs='' prop='<n:%s%s xmlns:n="%s">%s</n:%s>\n' % ( name, attrs, xml_id, value, name) code='200 OK' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return
def dav__propstat(self, name, result, propstat=propstat, propdesc=propdesc): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop='<n:%s xmlns:n="%s"/>\n' % (name, xml_id) code='404 Not Found' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=' '.join(map(str, value)) elif type=='lines': value='\n'.join(str(value)) # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=''.join(attrs) else: # quote non-xml items here? attrs='' prop='<n:%s%s xmlns:n="%s">%s</n:%s>\n' % ( name, attrs, xml_id, value, name) code='200 OK' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return
2,068
def dav__propstat(self, name, result, propstat=propstat, propdesc=propdesc): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop='<n:%s xmlns:n="%s"/>\n' % (name, xml_id) code='404 Not Found' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=' '.join(str(value)) elif type=='lines': value='\n'.join(str(value)) # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=''.join(attrs) else: # quote non-xml items here? attrs='' prop='<n:%s%s xmlns:n="%s">%s</n:%s>\n' % ( name, attrs, xml_id, value, name) code='200 OK' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return
def dav__propstat(self, name, result, propstat=propstat, propdesc=propdesc): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop='<n:%s xmlns:n="%s"/>\n' % (name, xml_id) code='404 Not Found' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=' '.join(str(value)) elif type=='lines': value='\n'.join(map(str, value)) # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=''.join(attrs) else: # quote non-xml items here? attrs='' prop='<n:%s%s xmlns:n="%s">%s</n:%s>\n' % ( name, attrs, xml_id, value, name) code='200 OK' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return
2,069
def sighandler(signum, frame): signame = zdaemon.Daemon.get_signal_name(signum) zLOG.LOG('Z2', zLOG.INFO , "Caught signal %s" % signame)
def sighandler(signum, frame): signame = zdaemon.Daemon.get_signal_name(signum) zLOG.LOG('Z2', zLOG.INFO , "Caught signal %s" % signame)
2,070
def doc_emphasize( self, s, expr = re.compile(r'\s*\*([ \na-zA-Z0-9.:/;,\'\"\?\-\_\/\=]+)\*(?!\*|-)').search ):
def doc_emphasize( self, s, expr = re.compile(r'\s*\*([ \na-zA-Z0-9.:/;,\'\"\?\-\_\/\=\-\>\<\(\)]+)\*(?!\*|-)').search ):
2,071
def register_loop_callback(callback, args=(), kw=None): _loop_lock.acquire() try: if _looping: apply(cb, (map,)+args, kw or {}) else: _loop_callbacks.append((callback, args, kw)) finally: _loop_lock.release()
def register_loop_callback(callback, args=(), kw=None): _loop_lock.acquire() try: if _looping: apply(callback, (map,)+args, kw or {}) else: _loop_callbacks.append((callback, args, kw)) finally: _loop_lock.release()
2,072
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
2,073
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
2,074
def load_config_text(self, text): # We have to create a directory of our own since the existence # of the directory is checked. This handles this in a # platform-independent way. schema = Zope.Startup.getSchema() sio = cStringIO.StringIO( text.replace("<<INSTANCE_HOME>>", TEMPNAME)) os.mkdir(TEMPNAME) os.mkdir(TEMPPRODUCTS) try: conf, handler = ZConfig.loadConfigFile(schema, sio) finally: os.rmdir(TEMPPRODUCTS) os.rmdir(TEMPNAME) self.assertEqual(conf.instancehome, TEMPNAME) return conf
def load_config_text(self, text): # We have to create a directory of our own since the existence # of the directory is checked. This handles this in a # platform-independent way. schema = self.schema sio = cStringIO.StringIO( text.replace("<<INSTANCE_HOME>>", TEMPNAME)) os.mkdir(TEMPNAME) os.mkdir(TEMPPRODUCTS) try: conf, handler = ZConfig.loadConfigFile(schema, sio) finally: os.rmdir(TEMPPRODUCTS) os.rmdir(TEMPNAME) self.assertEqual(conf.instancehome, TEMPNAME) return conf
2,075
def test_load_config_template(self): schema = Zope.Startup.getSchema() cfg = getConfiguration() fn = os.path.join(cfg.zopehome, "skel", "etc", "zope.conf.in") f = open(fn) text = f.read() f.close() self.load_config_text(text)
def test_load_config_template(self): schema = self.schema cfg = getConfiguration() fn = os.path.join(cfg.zopehome, "skel", "etc", "zope.conf.in") f = open(fn) text = f.read() f.close() self.load_config_text(text)
2,076
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('Z_REALM'): realm=os.environ['Z_REALM'] elif os.environ.has_key('BOBO_REALM'): realm=os.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode debug_mode=None if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ else: z1 = os.environ.get('Z_DEBUG_MODE',None) z2 = os.environ.get('BOBO_DEBUG_MODE',None) if z1.lower() in ('yes','y') or z1.isdigit(): debug_mode = 1 elif z2.lower() in ('yes','y') or z2.isdigit(): debug_mode = 1 if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None if hasattr(module,'bobo_application'): object=module.bobo_application elif hasattr(module,'web_objects'): object=module.web_objects else: object=module error_hook=getattr(module,'zpublisher_exception_hook', None) validated_hook=getattr(module,'zpublisher_validated_hook', None) transactions_manager=getattr( module,'zpublisher_transactions_manager', None) if not transactions_manager: try: get_transaction() except: pass else: # Create a default transactions manager for use # by software that uses ZPublisher and ZODB but # not the rest of Zope. transactions_manager = DefaultTransactionsManager() info= (bobo_before, bobo_after, object, realm, debug_mode, error_hook, validated_hook, transactions_manager) modules[module_name]=modules[module_name+'.cgi']=info return info except: t,v,tb=sys.exc_info() v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('Z_REALM'): realm=os.environ['Z_REALM'] elif os.environ.has_key('BOBO_REALM'): realm=os.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode debug_mode=None if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ else: z1 = os.environ.get('Z_DEBUG_MODE','') z2 = os.environ.get('BOBO_DEBUG_MODE','') if z1.lower() in ('yes','y') or z1.isdigit(): debug_mode = 1 elif z2.lower() in ('yes','y') or z2.isdigit(): debug_mode = 1 if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None if hasattr(module,'bobo_application'): object=module.bobo_application elif hasattr(module,'web_objects'): object=module.web_objects else: object=module error_hook=getattr(module,'zpublisher_exception_hook', None) validated_hook=getattr(module,'zpublisher_validated_hook', None) transactions_manager=getattr( module,'zpublisher_transactions_manager', None) if not transactions_manager: try: get_transaction() except: pass else: # Create a default transactions manager for use # by software that uses ZPublisher and ZODB but # not the rest of Zope. transactions_manager = DefaultTransactionsManager() info= (bobo_before, bobo_after, object, realm, debug_mode, error_hook, validated_hook, transactions_manager) modules[module_name]=modules[module_name+'.cgi']=info return info except: t,v,tb=sys.exc_info() v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
2,077
def pt_upload(self, REQUEST, file=''): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV"
def pt_upload(self, REQUEST, file=''): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV"
2,078
def manage_test(self, REQUEST): ' '
def manage_test(self, REQUEST): ' '
2,079
def manage_test(self, REQUEST): ' '
def manage_test(self, REQUEST): ' '
2,080
def manage_test(self, REQUEST): ' '
def manage_test(self, REQUEST): ' '
2,081
def __setattr__(self, name, v): klass=self._k setattr(klass, name, v) if not klass._p_changed: get_transaction().register(klass) klass._p_changed=1
def __setattr__(self, name, v): klass=self._k setattr(klass, name, v) if not getattr(klass,'_p_changed',None): get_transaction().register(klass) klass._p_changed=1
2,082
def __delattr__(self, name): klass=self._k delattr(klass, name) if not klass._p_changed: get_transaction().register(klass) klass._p_changed=1
def __delattr__(self, name): klass=self._k delattr(klass, name) if not getattr(klass,'_p_changed',None): get_transaction().register(klass) klass._p_changed=1
2,083
def manage_setPermissionMapping(self, permission_names=[], class_permissions=[], REQUEST=None): "Change property sheet permissions" ips=self.getClassAttr('propertysheets') ips=getattr(ips, self.id)
def manage_setPermissionMapping(self, permission_names=[], class_permissions=[], REQUEST=None): "Change property sheet permissions" ips=self.getClassAttr('propertysheets') ips=getattr(ips, self.id)
2,084
def manage_setPermissionMapping(self, permission_names=[], class_permissions=[], REQUEST=None): "Change property sheet permissions" ips=self.getClassAttr('propertysheets') ips=getattr(ips, self.id)
def manage_setPermissionMapping(self, permission_names=[], class_permissions=[], REQUEST=None): "Change property sheet permissions" ips=self.getClassAttr('propertysheets') ips=getattr(ips, self.id)
2,085
def rclass(klass): if klass._p_changed==0: get_transaction().register(klass) klass._p_changed=1
def rclass(klass): if not getattr(klass, '_p_changed', 0): get_transaction().register(klass) klass._p_changed=1
2,086
def _delOb(self, id): delattr(self, id) pc=self.aq_inner.aq_parent.aq_parent._zclass_propertysheets_class delattr(pc,id) pc.__propset_attrs__=tuple(map(lambda o: o['id'], self._objects)) rclass(pc)
def _delOb(self, id): delattr(self, id) pc=self.aq_inner.aq_parent.aq_parent._zclass_propertysheets_class try: delattr(pc,id) except: pass pc.__propset_attrs__=tuple(map(lambda o: o['id'], self._objects)) rclass(pc)
2,087
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. If calling manage_pasteObjects from python code, pass the result of a previous call to manage_cutObjects or manage_copyObjects as the first argument.""" cp=None if cb_copy_data is not None: cp=cb_copy_data else: if REQUEST and REQUEST.has_key('__cp'): cp=REQUEST['__cp'] if cp is None: raise CopyError, eNoData try: cp=_cb_decode(cp) except: raise CopyError, eInvalid
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. If calling manage_pasteObjects from python code, pass the result of a previous call to manage_cutObjects or manage_copyObjects as the first argument.""" cp=None if cb_copy_data is not None: cp=cb_copy_data else: if REQUEST and REQUEST.has_key('__cp'): cp=REQUEST['__cp'] if cp is None: raise CopyError, eNoData try: cp=_cb_decode(cp) except: raise CopyError, eInvalid
2,088
def _changeUser(self,name,password,confirm,roles,domains,REQUEST=None): if not name: return MessageDialog( title ='Illegal value', message='A username must be specified', action ='manage_main')
def _changeUser(self,name,password,confirm,roles,domains,REQUEST=None): if not name: return MessageDialog( title ='Illegal value', message='A username must be specified', action ='manage_main')
2,089
def runTest(self): sys.stdout.write(os.path.basename(self.__file) + " ") sys.stdout.flush() sys.argv = ["", "-Q", self.__file] pwd = os.getcwd() try: try: os.chdir(self.__dir) runtest.main() finally: os.chdir(pwd) except SystemExit, what: if what.code: self.fail("output for %s didn't match" % self.__file)
def runTest(self): basename = os.path.basename(self.__file) sys.stdout.write(basename + " ") sys.stdout.flush() sys.argv = ["", "-Q", self.__file] pwd = os.getcwd() try: try: os.chdir(self.__dir) runtest.main() finally: os.chdir(pwd) except SystemExit, what: if what.code: self.fail("output for %s didn't match" % self.__file)
2,090
def runTest(self): sys.stdout.write(os.path.basename(self.__file) + " ") sys.stdout.flush() sys.argv = ["", "-Q", self.__file] pwd = os.getcwd() try: try: os.chdir(self.__dir) runtest.main() finally: os.chdir(pwd) except SystemExit, what: if what.code: self.fail("output for %s didn't match" % self.__file)
def runTest(self): sys.stdout.write(os.path.basename(self.__file) + " ") sys.stdout.flush() if basename[:10] == 'test_metal': sys.argv = ["", "-Q", "-m", self.__file] else: sys.argv = ["", "-Q", self.__file] pwd = os.getcwd() try: try: os.chdir(self.__dir) runtest.main() finally: os.chdir(pwd) except SystemExit, what: if what.code: self.fail("output for %s didn't match" % self.__file)
2,091
def getPath(prefix, name, checkProduct=1, suffixes=('',)): """Find a file in one of several relative locations Arguments: prefix -- The location, relative to some home, to look for the file name -- The name of the file. This must not be a path. checkProduct -- a flag indicating whether product directories should be used as additional hope ares to be searched. This defaults to a true value. If this is true and the name contains a dot, then the text before the dot is treated as a product name and the product package directory is used as anothe rhome. suffixes -- a sequences of file suffixes to check. By default, the name is used without a suffix. The search takes on multiple homes which are INSTANCE_HOME, the directory containing the directory containing SOFTWARE_HOME, and possibly product areas. """ d,n = path_split(name) if d: raise ValueError, ( 'The file name, %s, should be a simple file name' % name) sw=path_split(path_split(SOFTWARE_HOME)[0])[0] for home in (INSTANCE_HOME, sw): if checkProduct: l=find(name, '.') if l > 0: p=name[:l] n=name[l+1:] r=_getPath(home, "Products/%s/%s/" % (p,prefix), n, suffixes) if r is not None: return r r=_getPath(home, prefix, name, suffixes) if r is not None: return r
def getPath(prefix, name, checkProduct=1, suffixes=('',)): """Find a file in one of several relative locations Arguments: prefix -- The location, relative to some home, to look for the file name -- The name of the file. This must not be a path. checkProduct -- a flag indicating whether product directories should be used as additional hope ares to be searched. This defaults to a true value. If this is true and the name contains a dot, then the text before the dot is treated as a product name and the product package directory is used as anothe rhome. suffixes -- a sequences of file suffixes to check. By default, the name is used without a suffix. The search takes on multiple homes which are INSTANCE_HOME, the directory containing the directory containing SOFTWARE_HOME, and possibly product areas. """ d,n = path_split(name) if d: raise ValueError, ( 'The file name, %s, should be a simple file name' % name) sw=path_split(path_split(SOFTWARE_HOME)[0])[0] for home in (INSTANCE_HOME, sw): if checkProduct: l=find(name, '.') if l > 0: p=name[:l] n=name[l+1:] r=_getPath(home, "lib/python/Products/%s/%s/" % (p,prefix), n, suffixes) if r is not None: return r r=_getPath(home, prefix, name, suffixes) if r is not None: return r
2,092
def getObject(module, name, reload=0, # The use of a mutable default is intentional here, # because modules is a module cache. modules={} ): # The use of modules here is not thread safe, however, there is # no real harm in a rece condition here. If two threads # update the cache, then one will have simply worked a little # harder than need be. So, in this case, we won't incur # the expense of a lock. if modules.has_key(module): old=modules[module] if old.has_key(name) and not reload: return old[name] else: old=None if module[-3:]=='.py': p=module[:-3] elif module[-4:]=='.pyp': p=module[:-4] else: p=module p=getPath('Extensions', p, suffixes=('','py','pyp')) if p is None: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be found." % module) __traceback_info__=p, module if p[-4:]=='.pyp': data=zlib.decompress( rotor.newrotor(d+' shshsh').decrypt(open(p,'rb').read()) ) execsrc=compile(data,module,'exec') else: try: execsrc=open(p) except: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be opened." % module) m={} exec execsrc in m try: r=m[name] except KeyError: raise 'Invalid Object Name', ( "The specified object, <em>%s</em>, was not found in module, " "<em>%s</em>." % (name, module)) if old: for k, v in m.items(): old[k]=v else: modules[module]=m return r
def getObject(module, name, reload=0, # The use of a mutable default is intentional here, # because modules is a module cache. modules={} ): # The use of modules here is not thread safe, however, there is # no real harm in a rece condition here. If two threads # update the cache, then one will have simply worked a little # harder than need be. So, in this case, we won't incur # the expense of a lock. if modules.has_key(module): old=modules[module] if old.has_key(name) and not reload: return old[name] else: old=None if module[-3:]=='.py': p=module[:-3] elif module[-4:]=='.pyp': p=module[:-4] else: p=module p=getPath('Extensions', p, suffixes=('','py','pyp')) if p is None: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be found." % module) __traceback_info__=p, module if p[-4:]=='.pyp': data=zlib.decompress( rotor.newrotor(prod_id +' shshsh').decrypt(open(p,'rb').read()) ) execsrc=compile(data,module,'exec') else: try: execsrc=open(p) except: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be opened." % module) m={} exec execsrc in m try: r=m[name] except KeyError: raise 'Invalid Object Name', ( "The specified object, <em>%s</em>, was not found in module, " "<em>%s</em>." % (name, module)) if old: for k, v in m.items(): old[k]=v else: modules[module]=m return r
2,093
def getObject(module, name, reload=0, # The use of a mutable default is intentional here, # because modules is a module cache. modules={} ): # The use of modules here is not thread safe, however, there is # no real harm in a rece condition here. If two threads # update the cache, then one will have simply worked a little # harder than need be. So, in this case, we won't incur # the expense of a lock. if modules.has_key(module): old=modules[module] if old.has_key(name) and not reload: return old[name] else: old=None if module[-3:]=='.py': p=module[:-3] elif module[-4:]=='.pyp': p=module[:-4] else: p=module p=getPath('Extensions', p, suffixes=('','py','pyp')) if p is None: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be found." % module) __traceback_info__=p, module if p[-4:]=='.pyp': data=zlib.decompress( rotor.newrotor(d+' shshsh').decrypt(open(p,'rb').read()) ) execsrc=compile(data,module,'exec') else: try: execsrc=open(p) except: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be opened." % module) m={} exec execsrc in m try: r=m[name] except KeyError: raise 'Invalid Object Name', ( "The specified object, <em>%s</em>, was not found in module, " "<em>%s</em>." % (name, module)) if old: for k, v in m.items(): old[k]=v else: modules[module]=m return r
def getObject(module, name, reload=0, # The use of a mutable default is intentional here, # because modules is a module cache. modules={} ): # The use of modules here is not thread safe, however, there is # no real harm in a rece condition here. If two threads # update the cache, then one will have simply worked a little # harder than need be. So, in this case, we won't incur # the expense of a lock. if modules.has_key(module): old=modules[module] if old.has_key(name) and not reload: return old[name] else: old=None if module[-3:]=='.py': p=module[:-3] elif module[-4:]=='.pyp': p=module[:-4] else: p=module p=getPath('Extensions', p, suffixes=('','py','pyp')) if p is None: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be found." % module) __traceback_info__=p, module if p[-4:]=='.pyp': data=zlib.decompress( rotor.newrotor(d+' shshsh').decrypt(open(p,'rb').read()) ) execsrc=compile(data, module, 'exec') else: try: execsrc=open(p) except: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be opened." % module) m={} exec execsrc in m try: r=m[name] except KeyError: raise 'Invalid Object Name', ( "The specified object, <em>%s</em>, was not found in module, " "<em>%s</em>." % (name, module)) if old: for k, v in m.items(): old[k]=v else: modules[module]=m return r
2,094
def tpValuesIds(self, branches, args, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): # This should build the ids of subitems which are # expandable (non-empty). Leaves should never be # in the state - it will screw the colspan counting. r=[] idattr=args['id'] try: try: items=getattr(self, branches)() except AttributeError: items=() for item in items: try: if getattr(item, branches)(): if hasattr(self, idattr): id=getattr(self, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) e=tpValuesIds(item, branches) if e: id=[id,e] else: id=[id] r.append(id) except: pass except: pass return r
def tpValuesIds(self, branches, args, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): # This should build the ids of subitems which are # expandable (non-empty). Leaves should never be # in the state - it will screw the colspan counting. r=[] idattr=args['id'] try: try: items=getattr(self, branches)() except AttributeError: items=() for item in items: try: if getattr(item, branches)(): if hasattr(self, idattr): id=getattr(self, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) e=tpValuesIds(item, branches, args) if e: id=[id,e] else: id=[id] r.append(id) except: pass except: pass return r
2,095
def manage_cache_age(self,value,REQUEST): "set cache age" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_age=value self._p_jar.db().setVersionCacheDeactivateAfter(value) else: self._cache_age=value self._p_jar.db().setCacheDeactivateAfter(value) return
def manage_cache_age(self,value,REQUEST): "set cache age" try: v=self._p_jar.getVersion() except: if self._p_jar.db is not Globals.Bobobase._jar.db: raise 'Version Error', ( '''You may not change the database cache age while working in a <em>version</em>''') self._cache_age=Globals.Bobobase._jar.cache.cache_age=value else: if v: self._vcache_age=value self._p_jar.db().setVersionCacheDeactivateAfter(value) else: self._cache_age=value self._p_jar.db().setCacheDeactivateAfter(value) return
2,096
def manage_cache_age(self,value,REQUEST): "set cache age" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_age=value self._p_jar.db().setVersionCacheDeactivateAfter(value) else: self._cache_age=value self._p_jar.db().setCacheDeactivateAfter(value) return
def manage_cache_age(self,value,REQUEST): "set cache age" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_age=value self._p_jar.db().setVersionCacheDeactivateAfter(value) else: self._cache_age=value self._p_jar.db().setCacheDeactivateAfter(value) return
2,097
def manage_cache_size(self,value,REQUEST): "set cache size" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_size=value self._p_jar.db().setVersionCacheSize(value) else: self._cache_size=value self._p_jar.db().setCacheSize(value) return
def manage_cache_size(self,value,REQUEST): "set cache size" try: v=self._p_jar.getVersion() except: if self._p_jar.db is not Globals.Bobobase._jar.db: raise 'Version Error', ( '''You may not change the database cache size while working in a <em>version</em>''') self._cache_size=Globals.Bobobase._jar.cache.cache_size=value else: if v: self._vcache_size=value self._p_jar.db().setVersionCacheSize(value) else: self._cache_size=value self._p_jar.db().setCacheSize(value) return
2,098
def manage_cache_size(self,value,REQUEST): "set cache size" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_size=value self._p_jar.db().setVersionCacheSize(value) else: self._cache_size=value self._p_jar.db().setCacheSize(value) return
def manage_cache_size(self,value,REQUEST): "set cache size" try: v=self._p_jar.getVersion() except: pass else: if v: self._vcache_size=value self._p_jar.db().setVersionCacheSize(value) else: self._cache_size=value self._p_jar.db().setCacheSize(value) return
2,099