rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
ftplib.FTP.connect(host, port)
ftplib.FTP.connect(self, host, port)
def connect(self, host='', port=0): self.host=host self.port=port ftplib.FTP.connect(host, port)
port=0):
port=ftplib.FTP_PORT):
def __init__(self, host, username='', password='', acct='', passive=1, port=0): self._host=host self._port=port self._username=username self._password=password self._acct=acct self._passive=passive self._conn=FtpConnection() self._initconn()
'parse_spec']
'parse_cron']
def foo(): print "hi from foo()" raise "nougat"
child.__parent=self
child.parent=child.__parent=self
def addChild(self, *children): for child in children: if isinstance(child, XMLElement): child.__parent=self self.__children.append(child) # for convenience return self
beg = time.time()
if DEBUGIT(COMPONENT_TIMES): beg = time.time()
def _realRenderComponent( name, argDict, auxArgs, compType, srcModTime ): global topOfComponentStack DEBUG(COMPONENT, "_realRenderComponent") executable = Executables.getExecutable( name, compType, srcModTime ) if compType == DT_INCLUDE and componentStack: namespace = componentStack[topOfComponentStack].namespace else...
DEBUG(COMPONENT_TIMES, "execution of %s in %s" % ( name, time.time() - beg))
if DEBUGIT(COMPONENT_TIMES): DEBUG(COMPONENT_TIMES, "execution of %s in %s" % ( name, time.time() - beg))
def _realRenderComponent( name, argDict, auxArgs, compType, srcModTime ): global topOfComponentStack DEBUG(COMPONENT, "_realRenderComponent") executable = Executables.getExecutable( name, compType, srcModTime ) if compType == DT_INCLUDE and componentStack: namespace = componentStack[topOfComponentStack].namespace else...
LOG("no sessionStore defined: cannot load sessionHandler service")
import SkunkWeb.LogObj as lo lo.LOG("no sessionStore defined: cannot load sessionHandler service")
def __initSession(): import SkunkWeb.Configuration as Configuration if not Configuration.SessionStore: LOG("no sessionStore defined: cannot load sessionHandler service") else: import Session import SkunkWeb.constants as skc import SkunkWeb.Hooks as hk import requestHandler.requestHandler as rr hk.ServerStart.append(Ses...
chgfld = f.fields[ky]
chgfld = self.fields[ky]
def _setData(self, data): if self.setable: for ky in data.keys(): if self.fields.has_key(ky): chgfld = f.fields[ky] chgfld.value = data.get(ky)
if filter and filter(c):
if (filter and filter(c)) or not filter:
def walk(self, visitfunc, state=None, filter=None): for c in self.getChildren(): if filter and filter(c): visitfunc(c, state) if isinstance(c, XMLElement): c.walk(visitfunc, state, filter)
f = lambda x: int(float(x))
if item is None: f = lambda x: x else: f = lambda x: x is None and None or int(float(x))
def convertResultRows(self, colnames, attributes, rows): newresult = [] for row in rows: d = {} for item, desc in map(None, row, colnames): #do dbtype->python type conversions here a = attributes[desc] if _isDateKind(a): d[desc] = _dateConvertFromDB(item) elif _isNumber(a): if a in ('FLOAT4', 'FLOAT8'): f = float else:...
'SCRIPT_NAME' : match.group('path'),
'SCRIPT_NAME' : unquote(match.group('path')),
def _getEnv(self, sock, methodName, requestURI, httpVersion, headers): # parse the requestURI match=pathRE.match(requestURI) sockname=sock.getsockname() if isinstance(sockname, str): # unix socket; we'll set the serverPort to 0 serverPort=0 peeraddress='127.0.0.1' peerport=0 else: serverPort=sockname[1] peeraddress, p...
if _isString(dbtype):
if _isString(dbtype) and not val is None:
def sqlStringAndValue(self, val, attr, dbtype): newval = self.typeCheckAndConvert(val, attr, dbtype) if _isString(dbtype): newval = "'" + MySQLdb.escape_string(str(newval)) + "'" return str(newval), None
if _isString(dbtype):
if _isString(dbtype) and not val == None:
def sqlStringAndValue(self, val, attr, dbtype): newval = self.typeCheckAndConvert(val, attr, dbtype) if _isString(dbtype): newval = "'" + _escape(str(newval)) + "'" return str(newval), None
for addr in to_addrs + [from_addr]: if len(filter(lambda x: ord(x) > 127, list(addr))) > 0: raise MailError, "8bit character in address %s" % (addr) if string.find(addr, '@') == -1: raise MailError, "address '%s' is no FQDN" % (addr)
address_check(_addresscheck_level, to_addrs)
def sendmail ( to_addrs, subj, msg, from_addr = Configuration.FromAddress, **extended ): """** <p>The general-purpose sendmail function, which is called by the STML &lt;:sendmail:&gt; tag, or directly by Python code.</p> <p><tt>to_addrs</tt> should be a list or tuple of email address strings. <tt>subj</tt> must be a st...
else:
elif _method == 'sendmail':
def dispatch_to_send_method(to_addrs, messagetext,envelope_sender): # dispatch to correct function based on method if _method == 'relay': sendmail_smtp(to_addrs, messagetext, envelope_sender) elif _method == 'qmail': qmail_pipe(to_addrs, messagetext, envelope_sender) else: sendmail_pipe(to_addrs, messagetext, envelope_...
return return "'%s'" % string.replace(s, "'", "\\'")
return "'%s'" % string.replace(s, "'", "\\'")
def __escape(self, thing): """ this is somewhat inadequate, as it doesn't handle types beyond ints and strings; you'll need to perform your own escaping for dates and times (I can't tell what field is intended, whether you need a data or a time, etc.) """ if type(thing) in (types.StringType, types.UnicodeType): return ...
STATELIST = [
STATE_LIST = [
def validate(self, form=None): errorlist = [] if not self._address1.value and not self._address2.value: # at least one address line must be filled out s='Please enter at least one line of address information.' errorlist.append(FormErrorMessage(self,s )) if not self._city.value: errorlist.append(FormErrorMessage(self, '...
sys.stdout = cStringIO.StringIO()
outputIO = sys.stdout = cStringIO.StringIO()
def run( self ): if self.compType in ( DT_REGULAR, DT_INCLUDE ): sys.stdout = cStringIO.StringIO()
output = sys.stdout.getvalue()
output = outputIO.getvalue()
def run( self ): if self.compType in ( DT_REGULAR, DT_INCLUDE ): sys.stdout = cStringIO.StringIO()
sys.stdout = sys.__stdout__
sys.stdout = oldstdout
def run( self ): if self.compType in ( DT_REGULAR, DT_INCLUDE ): sys.stdout = cStringIO.StringIO()
sys.stdout = sys.__stdout__
sys.stdout = oldstdout
def run( self ): hns = copy.copy(_hidden_namespace) hns.OUTPUT = cStringIO.StringIO() sys.stdout = hns.OUTPUT try: return self.dt(self.namespace, self.namespace, hns, self.compType) finally: sys.stdout = sys.__stdout__
DEBUG(USERTRACKING, morsel) DEBUG(USERTRACKING, conn.responseCookie[cookiename])
DEBUG(USERTRACKING, str(morsel)) DEBUG(USERTRACKING, str(conn.responseCookie[cookiename]))
def _add_usertracking_cookie(conn, sessionDict): if Configuration.usertrackingOn: cookiename=Configuration.usertrackingCookieName if not _verify_cookie(conn, cookiename): f=Configuration.usertrackingGenUIDFunc if f is None: conn.responseCookie[cookiename]=uuid() else: conn.responseCookie[cookiename]=f(conn) morsel=conn...
'por': Portuguese}
'por': Portuguese, 'deu': German}
def _make_day_lookup(days): d = {} for i in range(len(days)): d[days[i]] = i d[i] = days[i] return d
def updatecache(filename):
def updatecache(filename, updcache=linecache.updatecache):
def updatecache(filename): # XXX Important - do not move to the top of the file, it will # get unloaded on restart then!!! import sys import os from stat import ST_MTIME, ST_SIZE if linecache.cache.has_key(filename): del linecache.cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullnam...
import sys
try: import sys except: return updcache(filename)
def updatecache(filename): # XXX Important - do not move to the top of the file, it will # get unloaded on restart then!!! import sys import os from stat import ST_MTIME, ST_SIZE if linecache.cache.has_key(filename): del linecache.cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullnam...
raise TimeException, s
raise TimeException, until
def untilString(until, curdate=None): if curdate is None: curdate = LocalDate() # if it looks like a "minutes after hour", # return current date slammed to next minutes. if until[0] == ':' and until[1] in _digits and until[2] in _digits: mins = int(until[1:]) if curdate.minute < mins: return (curdate + RDT(minute=mins,...
codestr+='print %s' % repr(s)
sl = s.split('\n') for si in sl: codestr+='print %s\n' % repr(si)
def psp_compile(s, name): """<% and %> are the code delimiters""" l = [] while 1: ci = s.find('<%') if ci == -1: l.append((LITERAL, s)) break l.append((LITERAL,s[:ci])) code = s[ci+2:] #print 'code is ', code ce = code.find('%>') if ce == -1: raise 'EOFError', 'End of file reached while in code' code = code[:ce] l.appe...
def get(self, key, default):
def get(self, key, default=None):
def get(self, key, default): return self.__data.get(key, default)
res=callComponent(comp_path,
res=callComponent(self.comp_path,
def __call__(self, form): res=callComponent(comp_path, argDict={'form' : form}, compType=DT_DATA, cache=NO) # should be a list of FormErrorMessage objects return res or []
class PseudoDict: def __init__(self): self.items = [] def _find(self, item): for i, (k,v) in zip(range(len(self.items)), self.items): if k == item: return i return -1 def __setitem__(self, item, value): i = self._find(item) if i == -1: self.items.append([item, value]) else: self.items[i][1] = value def get(self, ite...
def __init__(self, usernameSlot, authFile, loginPage): SessionAuthBase.__init__(self, usernameSlot) AuthFileBase.__init__(self, authFile) RespAuthBase.__init__(self, loginPage)
authorizer = Configuration.authAuthorizer if type(authorizer) == type(''): authorizer = Configuration.authAuthorizer = _getClass(authorizer)( *Configuration.authAuthorizerCtorArgs)
authorizer = getAuthorizer()
def checkAuthorization(conn, sessionDict): """ any, and sends a preemptive 401 response, if necessary. """ if not Configuration.authActivated: return DEBUG(AUTH, 'checking authorization') authorizer = Configuration.authAuthorizer if type(authorizer) == type(''): #if string, load module and replace authorizer = Config...
from SkunkWeb.LogObj import DEBUG
def __call__(self, jobName, *args, **kw): from SkunkWeb.LogObj import DEBUG for f in self._getFuncList(jobName): DEBUG(CORE, "calling %s with args (%s, %s)" % (str(f), str(args), str(kw))) try: retVal=f(*args, **kw) if retVal is not None: return retVal except: import sys, traceback, cStringIO x=cStringIO.StringIO() tra...
self.setable=setable
def __init__(self, name, description, default=None, multiple=1, setable=1, componentFields=None, componentFieldDelimiter='_', valueComposer=_defaultValueComposer): Field.__init__(self, name=name, description=description, default=default, multiple=multiple, setable=setable) self.delimiter = componentFieldDelimiter if co...
import skunklib._normpath _normpath = skunklib.normpath
def _getCompileCache(name, srcModTime, version): if srcModTime is None: srcModTime = _getDocRootModTime(name) cacheModTime = _getCompileCacheModTime(name) if cacheModTime > srcModTime or Configuration.runOutOfCache: try: ret, vsn = marshal.loads(_readCompileCacheRoot(name)) except ValueError: #marshal got bad shit ERRO...
return _normpath('%s/%s' % (root,path))
return '%s/%s' % (root,_normpath(path))
def _fixPath(root, path): return _normpath('%s/%s' % (root,path))
return self._get_fridge()['currentScopes']
return self._get_fridge()['currentScopes'].copy()
def currentScopes(self): return self._get_fridge()['currentScopes']
def reset():
def reset(self):
def reset():
def flush():
def flush(self):
def flush():
userModuleCleanupIgnore = []
userModuleCleanupIgnore = [], runInForeground=0
def _setConfigDefaults(): import confvars Configuration.mergeDefaults( numProcs = 15, maxKillTime = 5, pidFile = confvars.DEFAULT_PID_FILE, pollPeriod = 5, maxRequests = 256, userModuleCleanup = 0, userModuleCleanupIgnore = [] )
class ExtInPkgImporter(iu.Owner):
class ExtInPkgImporter(VFSOwner):
def getmod(self, nm): #print "PkgInVFSImporter.getmod %s -> %s" % (nm, self.name+'.'+nm) return self.owner.getmod(self.name+'.'+nm)
iu.Owner.__init__(self, path)
VFSOwner.__init__(self, path)
def __init__(self, path, prefix): iu.Owner.__init__(self, path) self.prefix = prefix
namespace[sig[_SIG_SPILLOVER]] = argDict[v]
namespace[sig[_SIG_SPILLOVER]] = argDict
def mergeNamespaces( self, namespace, argDict, auxVars ): sig = self.dt.meta().get(_SIG_META) if sig: #check the argument signature here if a <:compargs:> tag namespace.update(auxVars) for v in sig[_SIG_REQUIRED]: if not argDict.has_key(v) and not auxVars.has_key(v): raise SkunkStandardError, ( 'component %s: argument ...
import SkunkWeb.LogObj as LogObj DEBUG=LogObj.DEBUG
global DEBUG try: DEBUG except: import SkunkWeb.LogObj DEBUG=SkunkWeb.LogObj.DEBUG
def __call__(self, jobName, *args, **kw): # SkunkWeb will not bootstrap if this is imported at the top level import SkunkWeb.LogObj as LogObj DEBUG=LogObj.DEBUG for f in self._getFuncList(jobName): DEBUG(CORE, "calling %s with args (%s, %s)" % (str(f), str(args), str(kw))) try: retVal=f(*args, **kw) if retVal is not No...
if _users.has_key(connUser): raise SkunkStandardError, 'user %s already initialized!' % (connUser) _users[connUser] = connParams
if not _users.has_key(connUser): _users[connUser] = connParams
def initUser(connUser, connParams): """ Prior to using the module, you must call this function to add a user and associate it with a connect string. The function can be called more than once. """ if _users.has_key(connUser): raise SkunkStandardError, 'user %s already initialized!' % (connUser) _users[connUser] = conn...
class _dufus(_StaticBase): def __new__(self, name, bases, dict): return object.__new__(_StaticBase) class _static: pass
_static = object
def _updateMe(obj): import sys m = sys.modules.get(obj._modname) if not m: m = __import__(obj._modname, None, None, 1) if hasattr(m, obj._klass): co = getattr(m, obj._klass) if isinstance(co, _StaticBase): obj.__dict__.update(co.__dict__) return raise "static.error", 'cannot load static class %s' % obj._klass
_dufus = None
def __new__(self, name, bases, dict): return object.__new__(_StaticBase)
__metaclass__ = _dufus
__metaclass__ = _StaticBase
def __new__(self, name, bases, dict): return object.__new__(_StaticBase)
st=fs.ministat(path)
st=Configuration.documentRootFS.ministat(path)
def _getPathAndMinistat(name): path=_fixPath(Configuration.documentRoot, name) st=fs.ministat(path) return (path, st)
connObj.write( """Sorry the requested document (<tt>%s</tt>) is not available""" % connObj.uri)
connObj.write("Sorry the requested document is not available")
def fourOhFourHandler(connObj, sessionDict): #document not found, or shouldn't be seen connObj.setStatus(404) connObj.responseHeaders['Content-Type'] = 'text/html' if (hasattr(Configuration, 'notFoundTemplate') and Configuration.notFoundTemplate): connObj.write(AE.Component.callComponent( Configuration.notFoundTemplate...
return '%s/%s' % (root,_normpath(path))
return _normpath('%s/%s' % (root,_normpath(path)))
def _fixPath(root, path): ## basically, some insurance that we don't escape a given root # N.B.: the above comment used to be separated from the below line of code # by several lines. Then, in version 1.6 of this file, I moved # normpath so it applied to the whole string rather than just the path. # This resulted in ...
for f in self_getFuncList(jobName):
for f in self._getFuncList(jobName):
def __call__(self, jobName, *args, **kw): for f in self_getFuncList(jobName): retVal=f(*args, **kw) if retVal is not None: return retVal
self._mergeDefaultskw(kw)
self._mergeDefaultsKw(kw)
def mergeDefaults(self, *args, **kw): """ added for compatibility with the config object used by SkunkWeb """ self._mergeDefaultskw(kw) for dict in args: self._mergeDict(dict)
DEBUG(REQUESTHANDLER, 'response returned: %s' % rawResponse)
DEBUG(REQUESTHANDLER, 'response returned: %s' % str(rawResponse))
def _processRequest(sock, addr, protocolImpl): DEBUG(REQUESTHANDLER, "in _processRequest(%s, %s, %s)" % (sock, addr, protocolImpl)) requestData, responseData, sessionDict=None, None, {} _beginSession(sock, sessionDict) DEBUG(REQUESTHANDLER, "starting job: %s" % Configuration.job) # loop until connection is closed wh...
return map(self, results)
if type(results)==types.ListType: return map(self, results) else: return []
def static_getSome(self, **kw): """given the attribute/value pairs in kw, return a (potentially empty) list of data class instances representing the rows that fulfill the constraints in kw""" sql, values = apply( self.getSomeSQL, (), kw) if not kw: sql = sql[:-7] conn = self.getDBI() results = conn.execute(sql, values,...
_and=['AND', opTuple]
_and=opTuple and ['AND', opTuple] or []
def static_getTupleWhere(self, opTuple, **kw): if kw: _and=['AND', opTuple] for k, v in kw.items(): _and.append(('=', FIELD(k), v)) opTuple=tuple(_and) sql=operators.tupleToSQL(opTuple) return self.getSQLWhere(sql)
sql=operators.tupleToSQL(opTuple)
sql=opTuple and operators.tupleToSQL(opTuple) or ''
def static_getTupleWhere(self, opTuple, **kw): if kw: _and=['AND', opTuple] for k, v in kw.items(): _and.append(('=', FIELD(k), v)) opTuple=tuple(_and) sql=operators.tupleToSQL(opTuple) return self.getSQLWhere(sql)
namespace = ns_copy
def _realRenderComponent( name, argDict, auxArgs, compType, srcModTime ): global topOfComponentStack DEBUG(COMPONENT, "_realRenderComponent") executable = Executables.getExecutable( name, compType, srcModTime ) if compType == DT_INCLUDE and componentStack: namespace = componentStack[topOfComponentStack].namespace else...
print ( 'Answer has to be one of [%s]' % self.astr )
print ( 'Answer has to be one of [%s]' % astr )
def ask_quest ( self ): """ Ask the question, return the char the user chose. """ vals = list ( self._allowed ) for i in range ( 0, len(vals) ): if vals[i] == self._default: vals[i] = string.upper(vals[i]) astr = string.join ( vals, '/' )
DEBUG(AUTH, "cookie is %s" % responseCookie)
def authorize(username, password, responseCookie): """attempts to authorize. If succeeds, sets the cookie and returns a true value, otherwise, returns false""" DEBUG(AUTH, 'authing authorization') file = Configuration.cookieAuthFile DEBUG(AUTH, 'file = %s' % file) if not file: return authenticator = Authenticator.File...
for m in r.theirAttrs:
for m in r.myAttrs:
out.write(' def set%s(self, item):\n' % singular(oside))
ERROR("error writing to compile cache: %s" % sys.exc_info[1])
ERROR("error writing to compile cache: %s" % sys.exc_info()[1])
def _writeCompileCache( name, thing, serializeFunc): DEBUG(CACHE, "writing compile cache") path = _fixPath( Configuration.compileCacheRoot, name + "c" ) try: _writeDisk( path, serializeFunc( thing ) ) except: ERROR("error writing to compile cache: %s" % sys.exc_info[1])
print "self in metaclass __init__: %s" % self
def __init__(self, cl_name, bases, namespace): print "self in metaclass __init__: %s" % self for b in bases: try: b._classinit__() except AttributeError: pass try: self._classinit__() except AttributeError: pass
notFlag = '' if isinstance(v, NOT): notFlag = '!' v = v.val
def class_getSomeSQL(klass, **kw): """given the attribute/value pairs in kw, return sql statement, values to be used in a call to conn.execute. If kw is empty, the WHERE text in the sql statement will still be preseverved. """ sql = klass._baseSelect() + " WHERE " conn = klass.getDBI() where = [] values = [] for k, v i...
where.append("%s %s= %s" % ( k, notFlag, lit))
where.append("%s=%s" % ( k, lit))
def class_getSomeSQL(klass, **kw): """given the attribute/value pairs in kw, return sql statement, values to be used in a call to conn.execute. If kw is empty, the WHERE text in the sql statement will still be preseverved. """ sql = klass._baseSelect() + " WHERE " conn = klass.getDBI() where = [] values = [] for k, v i...
WARN ( 'URL %s: sendmail: %s' % ( AED._session._request.uri, str(val) ) )
WARN ( 'sendmail: %s' % str(val) )
def sendmail_smtp ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>Called by <code>sendmail</code> function, this function uses SMTP to send a mail message. Function raises a <code>MailError</code> if it cannot connect to the SMTP server; any other errors are merely sent as warnings to the AED e...
and self.responseHeaders['content-type'][:5] == 'text/'):
and str(self.responseHeaders.get('content-type'))[:5] == 'text/'):
def response(self): rawOutput = self._output.getvalue() headers = '' if Configuration.textCompression: ae = self.requestHeaders.get('accept-encoding', '').split(',') for i in ('gzip', 'x-gzip'): if (i in ae and self.responseHeaders['content-type'][:5] == 'text/'): rawOutput = _compressit(rawOutput) self.responseHeader...
return listdir(path, self.archive.paths.keys())
return listdir(path, self.paths.keys())
def listdir(self, path): return listdir(path, self.archive.paths.keys())
params, method=xmlrpclib.loads(sys.stdin)
params, method=xmlrpclib.loads(sys.stdin.read(bytelen))
def giveup(message, status=400): print "Status: %d" % status print print message sys.exit(0)
m=_vfskeyRE.match(vfsUrl) if not m: raise ValueError, "not a vfs url: %s" % vfsUrl self.fskey=m.group(1) path=m.group(2)
self.fskey, self.fspath=parseVFSUrl(vfsUrl)
def __init__(self, vfsUrl): m=_vfskeyRE.match(vfsUrl) if not m: raise ValueError, "not a vfs url: %s" % vfsUrl self.fskey=m.group(1) path=m.group(2) self.fs=vfs.VFSRegistry.get(self.fskey) if not self.fs: raise vfs.VFSException, "no fs registered by name %s" % self.fskey iu.Owner.__init__(self, path)
iu.Owner.__init__(self, path)
iu.Owner.__init__(self, vfsUrl)
def __init__(self, vfsUrl): m=_vfskeyRE.match(vfsUrl) if not m: raise ValueError, "not a vfs url: %s" % vfsUrl self.fskey=m.group(1) path=m.group(2) self.fs=vfs.VFSRegistry.get(self.fskey) if not self.fs: raise vfs.VFSException, "no fs registered by name %s" % self.fskey iu.Owner.__init__(self, path)
pth = os.path.join(self.path, nm)
pth = os.path.join(self.fspath, nm) pth=pth.replace('.', '/')
def getmod(self, nm, getsuffixes=imp.get_suffixes, loadco=marshal.loads, newmod=imp.new_module): # this is taken almost verbatim from # Gordon McMillan's iu.DirOwner.getmod, # except that vfs methods are used pth = os.path.join(self.path, nm) possibles = [(pth, 0, None)] if self.fs.isdir(pth): possibles.insert(0, (os....
mod.__path__ = [pkgpth] subimporter = iu.PathImportDirector(mod.__path__)
localpath=iu._os_path_dirname(self.fspath) vfspath="vfs://<%s>%s" % (self.fskey, localpath) mod.__path__ = [self.path, pkgpth, iu._os_path_dirname(mod.__file__)] subimporter = iu.PathImportDirector(mod.__path__, {self.path:PkgInVFSImporter(nm, self), vfspath:ExtInPkgImporter(vfspath, nm)}, [VFSOwner])
def getmod(self, nm, getsuffixes=imp.get_suffixes, loadco=marshal.loads, newmod=imp.new_module): # this is taken almost verbatim from # Gordon McMillan's iu.DirOwner.getmod, # except that vfs methods are used pth = os.path.join(self.path, nm) possibles = [(pth, 0, None)] if self.fs.isdir(pth): possibles.insert(0, (os....
class PkgInVFSImporter: def __init__(self, name, owner): self.name = name self.owner = owner def getmod(self, nm): return self.owner.getmod(self.name+'.'+nm) class ExtInPkgImporter(iu.Owner): def __init__(self, path, prefix): iu.Owner.__init__(self, path) self.prefix = prefix def getmod(self, nm): return VFSOwner.get...
def getmod(self, nm, getsuffixes=imp.get_suffixes, loadco=marshal.loads, newmod=imp.new_module): # this is taken almost verbatim from # Gordon McMillan's iu.DirOwner.getmod, # except that vfs methods are used pth = os.path.join(self.path, nm) possibles = [(pth, 0, None)] if self.fs.isdir(pth): possibles.insert(0, (os....
body = r.recv(cl)
body = sock.recv(cl)
def marshalRequest(self, sock, sessionDict): """ Sends a handshake byte, obtains the content length from the value of the first ten bytes read, and then reads no more than that amount, which it marshals with the 'marshal' module. Finally, returns the marshalled request data """
self.stale = exp_time >= Configuration.maxDeferStale + time.time()
self.stale = exp_time <= Configuration.maxDeferStale + time.time()
def __init__( self, exp_time, defer_time, output, full_key ): self.full_key = full_key self.exp_time = exp_time self.out = output self.stale = exp_time >= Configuration.maxDeferStale + time.time() self.ttl = self.exp_time - time.time() self.valid = self.ttl >= 0 if self.valid and defer_time != -1: self.valid = defer_ti...
def handleField(self, f, tr, table): msg=self.errors.get(f)
def handleField(self, f, tr, table, colspan=0, fromList=0): if not fromList: errTr = ecs.Tr() numErr = self.handleError(errTr, f) if numErr: table.addElement(errTr) if f.description: desTd = ecs.Td().addElement(f.description) vwTd = ecs.Td().addElement(f.getView()) desTd.setAttribute('valign', 'top') vwTd.setAttribut...
def handleField(self, f, tr, table): msg=self.errors.get(f) if msg: em=ecs.Em(msg).setAttribute('class', 'form_error') td=ecs.Td(em).setAttribute('colspan', '2') table.addElement(ecs.Tr().addElement(td))
table.addElement(ecs.Tr().addElement(td)) if f.description: tr.addElement(ecs.Td().addElement(f.description)) tr.addElement(ecs.Td().addElement(f.getView())) else: td=ecs.Td().addElement(f.getView()).setAttribute('colspan', '2')
def handleField(self, f, tr, table): msg=self.errors.get(f) if msg: em=ecs.Em(msg).setAttribute('class', 'form_error') td=ecs.Td(em).setAttribute('colspan', '2') table.addElement(ecs.Tr().addElement(td))
return numErrs
def handleField(self, f, tr, table): msg=self.errors.get(f) if msg: em=ecs.Em(msg).setAttribute('class', 'form_error') td=ecs.Td(em).setAttribute('colspan', '2') table.addElement(ecs.Tr().addElement(td))
if not results:
if results and type(results)==types.ListType: return map(self, results) else:
def static_getSQLWhere(self, sql, values=()): base=self._baseSelect() if sql: sql="%s WHERE %s" % (base, sql) else: sql=base conn = self.getDBI() results = conn.execute(sql, values, self.fieldDict) if not results: return [] return map(self, results)
return map(self, results)
def static_getSQLWhere(self, sql, values=()): base=self._baseSelect() if sql: sql="%s WHERE %s" % (base, sql) else: sql=base conn = self.getDBI() results = conn.execute(sql, values, self.fieldDict) if not results: return [] return map(self, results)
DEBUG(CACHE, "error storing component", val)
DEBUG(CACHE, "error storing component %s" % val)
def _storeCachedComponent( path, value, svr ): DEBUG(CACHE, "storing component output") try: _writeDisk(path, cPickle.dumps((value, COMPONENT_CACHEFILE_VERSION), 1)) os.chmod( path, NORMAL_MODE ) except IOError, val: DEBUG(CACHE, "error storing component", val) if val != errno.ENOENT: _serverFailover[ svr ] = time.time...
serverNo = string.atoi(md5[-4:], 16) % Configuration.numServers
serverNo = int(md5[-4:], 16) % Configuration.numServers
def _genCachedComponentPath( name, argDict ): d = argDict.copy() name = _fixPath('', name) md5, fullkey = cacheKey.cachekey.genCacheKey( d ) if Configuration.numServers: serverNo = string.atoi(md5[-4:], 16) % Configuration.numServers if _serverFailover.get(serverNo, 0) == 0: return "%s/%s/%s/%s/%s/%s.cache" % ( Config...
for format in ('%Y-%m-%d',
for format in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d',
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M', # hh:mm '%Y-%m'): # Y-M try: return DateTime.strptime(d, format) except: pass dashind = max(d.rfind('-'), d.rfind('+')) tz = d[dashind:] d = d[:dashind] #maybe it has a miliseconds ? dotind = ...
dashind = max(d.rfind('-'), d.rfind('+')) tz = d[dashind:] d = d[:dashind]
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M', # hh:mm '%Y-%m'): # Y-M try: return DateTime.strptime(d, format) except: pass dashind = max(d.rfind('-'), d.rfind('+')) tz = d[dashind:] d = d[:dashind] #maybe it has a miliseconds ? dotind = ...
d = d[:dotind] try: return DateTime.strptime(d, '%H:%M:%S'), tz except: pass if 1: return DateTime.strptime(d, '%Y-%m-%d %H:%M:%S')
dotless=d[:dotind] try: return DateTime.strptime(dotless, '%Y-%m-%d %H:%M:%S') except: pass else: dotless=None candidates=dotless is None and (d,) or (d, dotless) for dt in candidates: dashind = max(dt.rfind('-'), dt.rfind('+')) tz = dt[dashind:] dt = dt[:dashind] try: return DateTime.strptime(dt, '%H:%M:%S'), tz excep...
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M', # hh:mm '%Y-%m'): # Y-M try: return DateTime.strptime(d, format) except: pass dashind = max(d.rfind('-'), d.rfind('+')) tz = d[dashind:] d = d[:dashind] #maybe it has a miliseconds ? dotind = ...
STATE_LIST = [
STATELIST = [
def validate(self, form=None): errorlist = [] if not self._address1.value and not self._address2.value: # at least one address line must be filled out s='Please enter at least one line of address information.' errorlist.append(FormErrorMessage(self,s )) if not self._city.value: errorlist.append(FormErrorMessage(self, '...
('Arizona', 'AR'),
('Arizona', 'AZ'), ('Arkansas', 'AR'),
def validate(self, form=None): errorlist = [] if not self._address1.value and not self._address2.value: # at least one address line must be filled out s='Please enter at least one line of address information.' errorlist.append(FormErrorMessage(self,s )) if not self._city.value: errorlist.append(FormErrorMessage(self, '...
match=pathRE.match(urllib.unquote(requestURI))
match=pathRE.match(requestURI)
def _getEnv(self, sock, methodName, requestURI, httpVersion, headers): # parse the requestURI match=pathRE.match(urllib.unquote(requestURI)) sockname=sock.getsockname() if isinstance(sockname, str): # unix socket; we'll set the serverPort to 0 serverPort=0 peeraddress='127.0.0.1' peerport=0 else: serverPort=sockname[1...
hns = dummy()
hns = copy.copy(_hidden_namespace)
def run( self ): hns = dummy() hns.OUTPUT = cStringIO.StringIO() sys.stdout = hns.OUTPUT try: return self.dt(self.namespace, self.namespace, hns, self.compType) finally: sys.stdout = sys.__stdout__
codeout.write(indent, 'if type(%s) != DictType:' % argsarg)
codeout.write(indent, 'if type(%s) != __h.types.DictType:' % argsarg)
def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) #args=DTUtil.tagCall(tag, ['name', ('cache', 'no'), # ('defer', -1), ('__args__', None)], # kwcol='kw') args=DTUtil.tagCall(tag, ['name', ('cache', 'no'), ('__args__', None)], kwcol...
codeout.write(indent, 'if type(%s) != DictType:' % argsarg)
codeout.write(indent, 'if type(%s) != __h.types.DictType:' % argsarg)
def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) #pargs=args=DTUtil.tagCall(tag, [ 'var', 'name', # ( 'cache', 'no'), ('defer', -1), # ('__args__', None)], # kwcol='kw') pargs=args=DTUt...
return unPickled
return unPickled, 1, 1
def callComponent(self, callProtocol, name, argDict, cache, compType, srcModTime): """ client-side handler for remote component calls """ # we don't need the callProtocol argument in this case unPickled=None host, port, path=self.__parseComponentName(name) args = cPickle.dumps((path, argDict, cache, compType, srcModTim...
query = cgi.FieldStorage(fp = stdin, environ = env, keep_blank_values = 1) self.args=self._convertArgs(query) if Configuration.mergeQueryStringWithPostData and \
try: query = cgi.FieldStorage(fp = stdin, environ = env, keep_blank_values = 1) self.args=self._convertArgs(query) ok=1 except: logException() DEBUG(WEB, "content-type: %s" % self.requestHeaders.get("content-type")) self.args={} ok=0 if ok and Configuration.mergeQueryStringWithPostData and \
def _initArgs(self, requestData): stdin = cStringIO.StringIO(requestData['stdin']) env = requestData['environ'] query = cgi.FieldStorage(fp = stdin, environ = env, keep_blank_values = 1) self.args=self._convertArgs(query)
def __getpicklefile(self.path):
def __getpicklefile(self, path):
def __getpicklefile(self.path): return os.path.join(self.__picklepath, "p%s" % _slashre.sub('!', path))
picklefile=self.__getpicklefile(self.path)
picklefile=self.__getpicklefile(path) if not os.path.exists(picklefile): return {}
def __getproperties(self, path): picklefile=self.__getpicklefile(self.path) f=open(picklefile) fd=f.fileno() fcntl.flock(fd, fcntl.LOCK_SH) data=cPickle.load(f) fcntl.flock(fd, fcntl.LOCK_UN) f.close() return data
f=open(self.__getpicklefile(self.path), 'w')
f=open(self.__getpicklefile(path), 'w')
def __saveproperties(self, path, properties): f=open(self.__getpicklefile(self.path), 'w') fd=f.fileno() fcntl.flock(fd, fcntl.LOCK_EX) cPickle.dump, properties, f, 1) fcntl.flock(fd, fcntl.LOCK_UN) f.close()
cPickle.dump, properties, f, 1)
cPickle.dump(properties, f, 1)
def __saveproperties(self, path, properties): f=open(self.__getpicklefile(self.path), 'w') fd=f.fileno() fcntl.flock(fd, fcntl.LOCK_EX) cPickle.dump, properties, f, 1) fcntl.flock(fd, fcntl.LOCK_UN) f.close()
return self.properties(path)[property]
return self.properties(_normpath(path))[property]
def getproperty(self, path, property): return self.properties(path)[property]
return self.properties().has_key(property)
return self.properties(path).has_key(property)
def hasproperty(self, path, property): return self.properties().has_key(property)
not conn._db.closed or 1 / 0 conn.cursor().execute("select user();")
conn.ping() except MySQLdb.DatabaseError: return 0 else:
def SimpleQueryTest(conn): try: # poor man's assertion not conn._db.closed or 1 / 0 conn.cursor().execute("select user();") return 1 except: return 0