rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print ftp_reply[key] + '\r\n'
if self.debug: print ftp_reply[key] + '\r\n'
def reply(self, key, s = ''): if string.find(ftp_reply[key], '%s') > -1: print ftp_reply[key] % s + '\r\n' self.transport.write(ftp_reply[key] % s + '\r\n') else: print ftp_reply[key] + '\r\n' self.transport.write(ftp_reply[key] + '\r\n')
print repr(line)
if self.debug: print repr(line)
def lineReceived(self, line): "Process the input from the client" line = string.strip(line) print repr(line) command = string.split(line) if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = string.capitalize(command)...
print "-"+command+"-"
if self.debug: print "-"+command+"-"
def lineReceived(self, line): "Process the input from the client" line = string.strip(line) print repr(line) command = string.split(line) if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = string.capitalize(command)...
def decode(file, data): log.msg('Loading %s...' % (file,)) d = {'__file__': pyfile}
def decode(filename, data): log.msg('Loading %s...' % (filename,)) d = {'__file__': filename}
def decode(file, data): log.msg('Loading %s...' % (file,)) d = {'__file__': pyfile} exec data in d, d try: return d['application'] except KeyError: log.msg("Error - python file %s must set a variable named 'application', an instance of twisted.internet.app.Application. No such variable was found!" % (repr(file),)) sys....
log.msg("Error - python file %s must set a variable named 'application', an instance of twisted.internet.app.Application. No such variable was found!" % (repr(file),))
log.msg("Error - python file %s must set a variable named 'application', an instance of twisted.internet.app.Application. No such variable was found!" % (repr(filename),))
def decode(file, data): log.msg('Loading %s...' % (file,)) d = {'__file__': pyfile} exec data in d, d try: return d['application'] except KeyError: log.msg("Error - python file %s must set a variable named 'application', an instance of twisted.internet.app.Application. No such variable was found!" % (repr(file),)) sys....
file = os.path.abspath(config.opts['python'])
filename = os.path.abspath(config.opts['python'])
def decode(file, data): log.msg('Loading %s...' % (file,)) d = {'__file__': pyfile} exec data in d, d try: return d['application'] except KeyError: log.msg("Error - python file %s must set a variable named 'application', an instance of twisted.internet.app.Application. No such variable was found!" % (repr(file),)) sys....
def decode(file, data):
def decode(filename, data):
def decode(file, data): from twisted.persisted.marmalade import unjellyFromXML log.msg('<Loading file="%s" />' % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromXML(StringIO(data)) application.persistStyle = 'xml' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
log.msg('<Loading file="%s" />' % (file,))
log.msg('<Loading file="%s" />' % (filename,))
def decode(file, data): from twisted.persisted.marmalade import unjellyFromXML log.msg('<Loading file="%s" />' % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromXML(StringIO(data)) application.persistStyle = 'xml' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
file = config.opts['xml']
filename = config.opts['xml']
def decode(file, data): from twisted.persisted.marmalade import unjellyFromXML log.msg('<Loading file="%s" />' % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromXML(StringIO(data)) application.persistStyle = 'xml' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
def decode(file, data):
def decode(filename, data):
def decode(file, data): from twisted.persisted.aot import unjellyFromSource log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromSource(StringIO(data)) application.persistStyle = 'aot' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
log.msg("Loading %s..." % (file,))
log.msg("Loading %s..." % (filename,))
def decode(file, data): from twisted.persisted.aot import unjellyFromSource log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromSource(StringIO(data)) application.persistStyle = 'aot' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
file = config.opts['source']
filename = config.opts['source']
def decode(file, data): from twisted.persisted.aot import unjellyFromSource log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = unjellyFromSource(StringIO(data)) application.persistStyle = 'aot' sys.modules['__main__'] = mainMod styles.doUpgrade() return application
def decode(file, data): log.msg("Loading %s..." % (file,))
def decode(filename, data): log.msg("Loading %s..." % (filename,))
def decode(file, data): log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = loads(data) sys.modules['__main__'] = mainMod styles.doUpgrade() return application
file = config.opts['file']
filename = config.opts['file']
def decode(file, data): log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = loads(data) sys.modules['__main__'] = mainMod styles.doUpgrade() return application
data = open(file, 'rb').read()
data = open(filename, 'rb').read()
def decode(file, data): log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = loads(data) sys.modules['__main__'] = mainMod styles.doUpgrade() return application
application = decode(file, data)
application = decode(filename, data)
def decode(file, data): log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = loads(data) sys.modules['__main__'] = mainMod styles.doUpgrade() return application
data = open(file, mode).read() application = decode(file, data)
data = open(filename, mode).read() application = decode(filename, data)
def decode(file, data): log.msg("Loading %s..." % (file,)) sys.modules['__main__'] = EverythingEphemeral() application = loads(data) sys.modules['__main__'] = mainMod styles.doUpgrade() return application
err = error.ProcessDone()
err = error.ProcessDone(exitCode)
def connectionLost(self, reason=None): """Shut down resources.""" exitCode = win32process.GetExitCodeProcess(self.hProcess) self.reactor.removeEvent(self.hProcess) abstract.FileDescriptor.connectionLost(self, reason) if exitCode == 0: err = error.ProcessDone() else: err = error.ProcessTerminated(exitCode) self.protocol...
strio.write(data)
strio.write(self.data)
def encode(self, strio, compDict=None): self.name.encode(strio, compDict) strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, len( self.data))) strio.write(data)
len(self.queries), 0, 0, 0))
len(self.queries), len(self.answers), len(self.ns), len(self.add)))
def encode(self, strio): compDict = {} body_tmp = StringIO.StringIO() for q in self.queries: q.encode(body_tmp, compDict) body = body_tmp.getvalue() size = len(body) + self.headerSize if self.maxSize and size > self.maxSize: self.trunc = 1 body = body[:maxSize - self.headerSize] byte3 = (( ( self.answer & 1 ) << 7 ) | ...
"""SecurityOptions.allowInstances(klass, klass, ...): allow instances of the specified classes This will also allow the 'instance', 'class', and 'module' types, as well as basic types.
"""SecurityOptions.allowInstances(klass, klass, ...): allow instances of the specified classes This will also allow the 'instance', 'class' (renamed 'classobj' in Python 2.3), and 'module' types, as well as basic types.
def allowInstancesOf(self, *classes): """SecurityOptions.allowInstances(klass, klass, ...): allow instances of the specified classes This will also allow the 'instance', 'class', and 'module' types, as well as basic types. """ self.allowBasicTypes() self.allowTypes("instance", "class", "module") for klass in classes: s...
self.allowTypes("instance", "class", "module")
self.allowTypes("instance", "class", "classobj", "module")
def allowInstancesOf(self, *classes): """SecurityOptions.allowInstances(klass, klass, ...): allow instances of the specified classes This will also allow the 'instance', 'class', and 'module' types, as well as basic types. """ self.allowBasicTypes() self.allowTypes("instance", "class", "module") for klass in classes: s...
port is C{tcp}, but passing a non-C{None} value as C{default} will
type is C{tcp}, but passing a non-C{None} value as C{default} will
def parse(description, factory, default=None): """Parse a description of a reliable virtual circuit server @type description: C{str} @type factory: C{twisted.internet.interfaces.IProtocolFactory} @type default: C{str} or C{None} @rtype: C{tuple} @return: a tuple of string, tuple and dictionary. The string is the name ...
def __init__(self, pool, connection=None):
def __init__(self, pool, connection):
def __init__(self, pool, connection=None): self._pool = pool self._connection = connection self.reopen()
if self._connection is None: self.reconnect()
def reopen(self): if self._connection is None: self.reconnect()
if self._connection is not None: self._pool.disconnect(self._connection) self._connection = self._pool.connect()
self._connection.reconnect()
def reconnect(self): if self._connection is not None: self._pool.disconnect(self._connection) self._connection = self._pool.connect() self._cursor = None
def runWithConnection(self, func, *args, **kw): return self._deferToThread(self._runWithConnection, func, *args, **kw) def _runWithConnection(self, func, *args, **kw): conn = Connection(self) try: result = func(conn, *args, **kw) conn.commit() return result except: conn.rollback() raise
def start(self): """Start the connection pool.
trans = Transaction(self)
conn = Connection(self) trans = Transaction(self, conn)
def _runInteraction(self, interaction, *args, **kw): trans = Transaction(self) try: result = interaction(trans, *args, **kw) trans.close() trans._connection.commit() return result except: self._rollback(trans) raise
trans._connection.commit()
conn.commit()
def _runInteraction(self, interaction, *args, **kw): trans = Transaction(self) try: result = interaction(trans, *args, **kw) trans.close() trans._connection.commit() return result except: self._rollback(trans) raise
self._rollback(trans)
conn.rollback()
def _runInteraction(self, interaction, *args, **kw): trans = Transaction(self) try: result = interaction(trans, *args, **kw) trans.close() trans._connection.commit() return result except: self._rollback(trans) raise
def _rollback(self, trans): if not self.reconnect: trans._connection.rollback() return try: trans._connection.rollback() trans.reopen() trans.execute(self.good_sql) trans.close() trans._connection.commit() return except: pass self.disconnect(trans._connection) if self.noisy: log.msg('Connection lost.') raise Connec...
def _rollback(self, trans): if not self.reconnect: trans._connection.rollback() return
"""This returns a Deferred which files when the eventual-send queue is
"""This returns a Deferred which fires when the eventual-send queue is
def flushEventualQueue(): """This returns a Deferred which files when the eventual-send queue is finally empty. This is useful to wait upon as the last step of a Trial test method. """ return _theSimpleQueue.flush()
for r in ans:
for r in answers:
def extractRecord(resolver, name, answers, level = 10): if not level: return None for r in answers: if r.name == name and r.type == dns.A6: return socket.inet_ntop(socket.AF_INET6, r.payload.address) for r in ans: if r.name == name and r.type == dns.AAAA: return socket.inet_ntop(socket.AF_INET6, r.payload.address) for ...
dcctype = data.split(None, 1).upper()
if not data: return dcctype = data.split(None, 1)[0].upper()
def ctcpQuery_DCC(self, user, channel, data): """Initiate a Direct Client Connection """
real_cb(real_s, condition)
return real_cb(real_s, condition)
def wrapper(source, condition, real_s=source, real_cb=callback): real_cb(real_s, condition)
return 1
def callback(self, source, condition): methods = [] cbNames = []
parts.insert(-1, '')
parts.insert(len(parts) - 1, '')
def inet_ntop(af, addr): if af == socket.AF_INET: return socket.inet_ntoa(addr) elif af == socket.AF_INET6: if len(addr) != 16: raise ValueError("address length incorrect") parts = struct.unpack('!8H', addr) curBase = bestBase = None for i in range(8): if not parts[i]: if curBase is None: curBase = i curLen = 0 curLen ...
return self.keyring[serviceName] = Key(serviceName, perspectiveName, self)
self.keyring[serviceName] = Key(serviceName, perspectiveName, self)
def setKey(self, serviceName, perspectiveName): """Set a key on my keyring.
channel = params[-1]
channel = params[0]
def irc_PART(self, prefix, params): nick = string.split(prefix,'!')[0] channel = params[-1] if nick == self.nickname: self.left(channel) else: self.userLeft(nick, channel)
self.nickname = params[0]
self.nickChanged(params[0])
def irc_NICK(self, prefix, params): nick = string.split(prefix,'!',0)[0] if nick == self.nickname: self.nickname = params[0] else: self.userRenamed(nick, params[0])
except VauleError:
except ValueError:
def dcc_CHAT(self, user, channel, data): data = text.splitQuoted(data) if len(data) < 3: raise IRCBadMessage, "malformed DCC CHAT request: %r" % (data,)
if '/' not in href and href.endswith('.html'): fname = os.path.splitext(href) node.setAttribute("href", fname[0] + ext)
if '/' not in href: if href.endswith('.html') or href[:href.rfind(' fname = os.path.splitext(href) node.setAttribute("href", fname[0] + ext)
def fixLinks(document, ext): for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") if '/' not in href and href.endswith('.html'): fname = os.path.splitext(href) node.setAttribute("href", fname[0] + ext)
end_h2 = end_h3 = end_h4 = '</title>' start_title, end_title = '<section><title>', '</title>'
end_h2 = end_h3 = end_h4 = '</title><para />' start_title, end_title = '<section><title>', '</title><para />'
def visitNode_a_name(self, node): self.visitNodeDefault(node)
start_strong, end_strong = start_em, end_emp = '<emphasis>', '</emphasis>' start_span_footnote, end_span_footnote = '<footnote>', '</footnote>'
start_strong, end_strong = start_em, end_em = '<emphasis>', '</emphasis>' start_span_footnote, end_span_footnote = '<footnote><para>', '</para></footnote>'
def visitNode_a_name(self, node): self.visitNodeDefault(node)
start_pre = end_pre = '<programlisting>', '</programlisting>' start_div_note, end_div_note = '<note>', '</note>' start_li, end_li = '<listitem>', '</listitem>'
start_pre, end_pre = '<programlisting>', '</programlisting>' start_div_note, end_div_note = '<note><para>', '</para></note>' start_li, end_li = '<listitem><para>', '</para></listitem>'
def visitNode_a_name(self, node): self.visitNodeDefault(node)
start_dd, end_dd = '<listitem>', '</listitem></varlistentry>'
start_dd, end_dd = '<listitem><para>', '</para></listitem></varlistentry>'
def visitNode_a_name(self, node): self.visitNodeDefault(node)
isTypeOrClass = issubclass(o, type) or isinstance(o, ClassType)
isTypeOrClass = isinstance(o, (ClassType, type))
def topClasses(N=25): d = {} for o in gc.get_objects(): try: isTypeOrClass = issubclass(o, type) or isinstance(o, ClassType) except TypeError: pass else: if isTypeOrClass: s = getattr(o, '__name__', str(o)) for i in gc.get_referrers(o): if isinstance(i, o): d[s] = d.get(s, 0) + 1 counts = [(v, k) for (k, v) in d.iterit...
If a rowClass doesnt have a containerMethod, then a list attribute "childRows"
If a rowClass does not have a containerMethod, then a list attribute "childRows"
def addToParent(self, parentRow, rows, tableName): """util method used by reflectors. adds these rows to the parent row object. If a rowClass doesnt have a containerMethod, then a list attribute "childRows" will be used. """ parentInfo = self.getTableInfo(parentRow) relationship = parentInfo.getRelationshipFor(tableNam...
continue
def dataReceived(self, data): self.buf += data while len(self.buf) > 5: length, kind = struct.unpack('!LB', self.buf[:5]) if len(self.buf) < 4 + length: return data, self.buf = self.buf[5:4+length], self.buf[4+length:] packetType = self.packetTypes.get(kind, None) if not packetType: print 'no packet type for', kind #XX...
return
reqId = struct.unpack('!L', data[:4])[0] self._sendStatus(reqId, FX_OP_UNSUPPORTED, "don't understand %s" % packetType)
def dataReceived(self, data): self.buf += data while len(self.buf) > 5: length, kind = struct.unpack('!LB', self.buf[:5]) if len(self.buf) < 4 + length: return data, self.buf = self.buf[5:4+length], self.buf[4+length:] packetType = self.packetTypes.get(kind, None) if not packetType: print 'no packet type for', kind #XX...
print 'ext', extended_type, extended_data
def _parseAttributes(self, data): flags = struct.unpack('!L', data[:4])[0] attrs = {} data = data[4:] if flags & FILEXFER_ATTR_SIZE == FILEXFER_ATTR_SIZE: size = struct.unpack('!Q', data[:8])[0] attrs['size'] = size data = data[8:] if flags & FILEXFER_ATTR_OWNERGROUP == FILEXFER_ATTR_OWNERGROUP: uid, gid = struct.unpac...
data = struct.pack('!2L', requestId, len(result))
data = ''
def _cbScanDirectory(self, result, requestId): data = struct.pack('!2L', requestId, len(result)) for (filename, longname, attrs) in result: data += NS(filename) data += NS(longname) data += self._packAttributes(attrs) self.sendPacket(FXP_NAME, data)
self.sendPacket(FXP_NAME, data)
self.sendPacket(FXP_NAME, struct.pack('!2L', requestId, len(result))+data)
def _cbScanDirectory(self, result, requestId): data = struct.pack('!2L', requestId, len(result)) for (filename, longname, attrs) in result: data += NS(filename) data += NS(longname) data += self._packAttributes(attrs) self.sendPacket(FXP_NAME, data)
print reason
def _ebStatus(self, reason, requestId, msg = "request failed"): print reason code = FX_FAILURE message = msg if reason.type in (IOError, OSError): if reason.value.errno == errno.ENOENT: # no such file code = FX_NO_SUCH_FILE message = reason.value.strerror elif reason.value.errno == errno.EACCES: # permission denied cod...
""" if len(opaqueId) > 1: raise EOFError
No more than 250 files should be returned at once, as some clients cannot handle packets that large. """ if len(opaqueId) > 2: raise EOFError
def scanDirectory(self, opaqueId): """ Scan the directory represented by the opaqueId.
for f in self._runAsUser(os.listdir, path):
d = self._runAsUser(os.listdir, path)[start:] for f in d[:250]:
def scanDirectory(self, opaqueId): """ Scan the directory represented by the opaqueId.
opaqueId.append(1)
if len(d) > 250: start += 250 if len(opaqueId) == 2: opaqueId[1] = start else: opaqueId.append(start) else: opaqueId.append(1) opaqueId.append(1)
def scanDirectory(self, opaqueId): """ Scan the directory represented by the opaqueId.
['verbose', 'v', 'verbose color output'],
['verbose', 'v', 'verbose color output (default)'],
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
['text', 't', 'terse text output (default reporter)'],
['text', 't', 'terse text output'],
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
fallbackReporter = reporter.VerboseTextReporter
fallbackReporter = reporter.TreeReporter
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
warnings.warn("""Your twisted plugins are broken for some reason. Please tell slyphon you saw this message! Using default: TextReporter""", PluginWarning)
def getReporter(self): """return the class of the selected reporter @param config: a usage.Options instance after parsing options """ if not hasattr(self, 'optToQual'): self._loadReporters() for opt, qual in self.optToQual.iteritems(): if self[opt]: nany = reflect.namedAny(qual) log.msg(iface=ITrialDebug, reporter="rep...
_dbg("osp.exists, appending '%s' to self['modules']" % (modstr,)) self['modules'].append(mod) continue
mname = reflect.filenameToModuleName(arg) _dbg("modulename: %s" % (mname,)) if mname: self['modules'].append(mname) continue
def _dbg(msg): if self._logObserver is not None: log.msg(iface=ITrialDebug, parseargs=msg)
Extension("twisted.inetd.portmap", ["twisted/inetd/portmap.c"], define_macros=define_macros), Extension("twisted.internet.cReactor", ["twisted/internet/cReactor/cReactorModule.c", "twisted/internet/cReactor/cReactor.c", "twisted/internet/cReactor/cReactorTime.c", "twisted/internet/cReactor/cReactorTCP.c", "twisted/inte...
def _detect_modules(self): """ Determine which extension modules we should build on this system. """
adict.update(getattr(classObj, attr, {}))
adict.update(classObj.__dict__.get(attr, {}))
def accumulateClassDict(classObj, attr, adict, baseClass=None): """Accumulate all attributes of a given name in a class heirarchy into a single dictionary. Assuming all class attributes of this name are dictionaries. If any of the dictionaries being accumulated have the same key, the one highest in the class heirarchy...
listObj.extend(getattr(classObj, attr, []))
listObj.extend(classObj.__dict__.get(attr, []))
def accumulateClassList(classObj, attr, listObj, baseClass=None): """Accumulate all attributes of a given name in a class heirarchy into a single list. Assuming all class attributes of this name are lists. """ for base in classObj.__bases__: accumulateClassList(base, attr, listObj) if baseClass is None or baseClass in...
groupID = item.group.group.findIDFor(item.group)
if isinstance(item, SSIGroup): groupID = 0 else: groupID = item.group.group.findIDFor(item.group)
def addItemSSI(self, item, groupID = None, buddyID = None): """ add an item to the SSI server. if buddyID == 0, then this should be a group. this gets a callback when it's finished, but you can probably ignore it. """ if groupID is None: groupID = item.group.group.findIDFor(item.group) if buddyID is None: buddyID = it...
groupID = item.group.group.findIDFor(item.group)
if isinstance(item, SSIGroup): groupID = 0 else: groupID = item.group.group.findIDFor(item.group)
def modifyItemSSI(self, item, groupID = None, buddyID = None): if groupID is None: groupID = item.group.group.findIDFor(item.group) if buddyID is None: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x09, item.oscarRep(groupID, buddyID))
groupID = item.group.group.findIDFor(item.group)
if isinstance(item, SSIGroup): groupID = 0 else: groupID = item.group.group.findIDFor(item.group)
def delItemSSI(self, item, groupID = None, buddyID = None): if groupID is None: groupID = item.group.group.findIDFor(item.group) if buddyID is None: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x0A, item.oscarRep(groupID, buddyID))
data = open(filename, mode).read() + '\n'
data = open(filename, mode).read()
def loadValueFromFile(filename, variable, passphrase=None): """Load the value of a variable in a Python file. Run the contents of the file, after decrypting if C{passphrase} is given, in a namespace and return the result of the variable named C{variable}. @param filename: string @param variable: string @param passphr...
raise NotImplementedError
def registerProducer(self, producer, streaming): """Register to receive data from a producer.
raise NotImplementedError
def unregisterProducer(self): """Stop consuming data from a producer, without disconnecting. """ raise NotImplementedError
raise NotImplementedError
def write(self, data): """The producer will write data by calling this method.""" raise NotImplementedError
raise NotImplementedError
def resumeProducing(self): """Resume producing data. This tells a producer to re-add itself to the main loop and produce more data for its consumer. """ raise NotImplementedError
raise NotImplementedError
def pauseProducing(self): """Pause producing data. Tells a producer that it has produced too much data to process for the time being, and to stop until resumeProducing() is called. """ raise NotImplementedError
raise NotImplementedError
def stopProducing(self): """Stop producing data. This tells a producer that its consumer has died, so it must stop producing data for good. """ raise NotImplementedError
transportFactory = None protocol = None factory = None def __init__(self, host, portno, protocolFactory, timeout=30): raise NotImplementedError def connectionFailed(self): raise NotImplementedError def connectionLost(self): raise NotImplementedError def startConnecting(self): raise NotImplementedError
def stopProducing(self): """Stop producing data. This tells a producer that its consumer has died, so it must stop producing data for good. """ raise NotImplementedError
raise NotImplementedError class ISelectable(Interface): """An object that can be registered with the networking event loop. Selectables more or less correspond to object that can be passed to select(). This is platform dependant, and not totally accurate, since the main event loop may not be using select(). Select...
def getProtocol(self): """Get the current protocol instance.""" raise NotImplementedError
for name in changed.keys(): handler = getattr(self, 'update_' + name, None) if handler: handler(changed[name])
request = changed.get('request', None) oldNode = self.node newNode = self.generate(request, oldNode) returnNode = self.dispatchResult(request, oldNode, newNode) self.handleNewNode(request, returnNode) self.handleOutstanding(request) self.controller.domChanged(request, self, returnNode)
def modelChanged(self, changed): """Dispatch changed messages to any update_* methods which may have been defined, then pass the update notification on to the controller. """ for name in changed.keys(): handler = getattr(self, 'update_' + name, None) if handler: handler(changed[name])
return self.lookupTemplate(request).childNodes[0]
newNode = self.lookupTemplate(request).childNodes[0] newNode.setAttribute('id', 'woven_id_%s' % id(self)) self.node = newNode return newNode
def generate(self, request, node): """Allow a view to be used like a widget. Will look up the template file and return it in place of the incoming node. """ return self.lookupTemplate(request).childNodes[0]
factory.protocol = wire.Echo
factory.protocol = TestEcho TestEcho.d = defer.Deferred()
def testTCP(self): s = service.MultiService() s.startService() factory = protocol.ServerFactory() factory.protocol = wire.Echo t = internet.TCPServer(0, factory) t.setServiceParent(s) num = t._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write('lalala\r\n') def lineReceive...
factory.protocol = wire.Echo
factory.protocol = TestEcho TestEcho.d = defer.Deferred()
def testPrivileged(self): factory = protocol.ServerFactory() factory.protocol = wire.Echo t = internet.TCPServer(0, factory) t.privileged = 1 t.privilegedStartService() num = t._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write('lalala\r\n') def lineReceived(self, line): ...
internet.TCPClient('localhost', num, factory).startService()
c = internet.TCPClient('localhost', num, factory) c.startService()
def lineReceived(self, line): self.factory.line = line
factory.protocol = wire.Echo
factory.protocol = TestEcho TestEcho.d = defer.Deferred()
def testUNIX(self): if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" s = service.MultiService() s.startService() factory = protocol.ServerFactory() factory.protocol = wire.Echo t = internet.UNIXServer('echo.skt', factory) t.setServiceParent(s) c...
d = s.stopService() l = [] d.addCallback(l.append) util.spinWhile(lambda :not l)
util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d) TestEcho.d = defer.Deferred()
def lineReceived(self, line): self.factory.line = line
d = s.stopService() l = [] d.addCallback(l.append) util.spinWhile(lambda :not l)
util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d)
def lineReceived(self, line): self.factory.line = line
import warnings warnings.warn("You almost certainly want to be using interface->interface adapters. " "If you do not, modify your desire.", DeprecationWarning, stacklevel=3)
def getAdapterClassWithInheritance(self, klass, interfaceClass, default): """Return registered adapter for a given class and interface. """ import warnings warnings.warn("You almost certainly want to be using interface->interface adapters. " "If you do not, modify your desire.", DeprecationWarning, stacklevel=3) adapte...
self.endLine(['ERROR'], self.RED)
self.endLine('[ERROR]', self.RED)
def upDownError(self, method, error, warn, printStatus): self.write(self.color(" %s" % method, self.RED)) if printStatus: self.endLine(['ERROR'], self.RED) super(TreeReporter, self).upDownError(method, error, warn, printStatus)
raise DBError("Stub class must be derived from RowClass")
raise DBError("Stub class (%s) is not derived from RowObject" % str(stubClass))
def _transPopulateClasses(self, transaction): """Used to construct the row classes in a single interaction. """ for (stubClass, tableName, keyColumns) in self.stubs: # log.msg( "retrieving class %s for table %s" %(repr(stubClass), tableName)) if not issubclass(stubClass, RowObject): raise DBError("Stub class must be de...
dns.RRHeader(name, dns.A, dns.IN, self.ttl)
[dns.RRHeader(name, dns.A, dns.IN, self.ttl)], (), ()
def lookupAddress(self, name, timeout = None): res = searchFileFor(self.file, name) if res: return defer.succeed([ dns.RRHeader(name, dns.A, dns.IN, self.ttl) ]) return defer.fail(failure.Failure(dns.DomainError(name)))
s = os.stat(testdir) from pprint import pformat print "os.stat(%s): %s" % (testdir, pformat(dict([(name, getattr(s, name)) for name in dir(s) if not name.startswith('__')])))
def _setUpTestdir(): testdir = osp.normpath(osp.abspath("_trial_temp")) if osp.exists(testdir): try: shutil.rmtree(testdir) except OSError, e: print "could not remove path, caught OSError [Errno %s]: %s" % (e.errno,e.strerror) s = os.stat(testdir) from pprint import pformat print "os.stat(%s): %s" % (testdir, pformat(d...
methods = reflect.prefixedMethods('notifyConnectionMade_') for m in methods: m()
def connectionMade(self): XMLStream.connectionMade(self) methods = reflect.prefixedMethods('notifyConnectionMade_') for m in methods: m()
return {'to': self.getGlobalTo(self)}
return {'to': self.getGlobalTo()}
def getGlobalAttributes(self): return {'to': self.getGlobalTo(self)}
def _getElementNamedOrNone(self, element, name):
def _getElementNamedOrNone(element, name):
def _getElementNamedOrNone(self, element, name): return (microdom.getElementsByTagName(element, name) or [None])[0]
self.gotMessageDefault(type, from, to, id, subject, body, thread)
self.gotMessageDefault(type, from_, to, id, subject, body, thread)
def gotMessageUnknown(self, type, from_, to, id, message): body = _getElementNamedOrNone(message, 'body') subject = _getElementNamedOrNone(message, 'subject') thread = _getElementNamedOrNone(message, 'thread') self.gotMessageDefault(type, from, to, id, subject, body, thread)
for k, v in [('from', from_), ('to', to), ('type', type)]:
for k, v in [('from', from_), ('to', to), ('type', type), ('id', id)]:
def sendIQ(self, type, from_, to, query): id = str(self.lastID) self.lastID += 1 deferred = defer.Deferred() attributes = [] for k, v in [('from', from_), ('to', to), ('type', type)]: if v: attributes.append('%s="%s"' % (k, v)) attributes = " ".join(attributes) self.transport.write('<iq %s>" % attributes) query.writexm...
self.transport.write('<iq %s>" % attributes)
self.transport.write("<iq %s>" % attributes)
def sendIQ(self, type, from_, to, query): id = str(self.lastID) self.lastID += 1 deferred = defer.Deferred() attributes = [] for k, v in [('from', from_), ('to', to), ('type', type)]: if v: attributes.append('%s="%s"' % (k, v)) attributes = " ".join(attributes) self.transport.write('<iq %s>" % attributes) query.writexm...
del self.requests[id]
def gotElement_iq(self, element): type = element.attributes['type'] id = element.attributes.get('id') from_ = element.attributes.get('from') to = element.attributes.get('to') if type == 'result' or type == 'error': if not self.requests.has_key(id): return # ignore results for cancelled/non-existing requests if type == ...
'to': from, type: 'error'})
'to': from_, type: 'error'})
def _(query): myTo, myFrom = from_, to e = microdom.Element('iq', {'id': id, 'from': to, 'to': from, type: 'error'}) e.appendChild(query) self.writeElement(e)
'to': from, type: 'result'})
'to': from_, type: 'result'})
def _(failure): failure.trap(IQFailure) code, text = failure.value myTo, myFrom = from_, to e = microdom.Element('iq', {'id': id, 'from': to, 'to': from, type: 'result'}) error = microdom.Element('error', {'code': code}) error.appendChild(microdom.Text(cgi.escape(text))) e.appendChild(error) self.writeElement(e)
query = microdom.Element('query', xmlns="jabber:iq:auth")
query = microdom.Element('query', {'xmlns':"jabber:iq:auth"})
def notifyConnectionMade_IQ(self): JabberIQMixin.notifyConnectionMade_IQ(self) query = microdom.Element('query', xmlns="jabber:iq:auth") username = microdom.Element('username') username.appendChild(microdom.Text(cgi.escape(self.getUsername()))) digest = microdom.Element('digest') digest.appendChild(microdom.Text(cgi.es...