rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if self._from is None or (not self._to and not self._user_to):
if self._from is None or (not self._to):
def do_DATA(self, rest): if self._from is None or (not self._to and not self._user_to): self.sendCode(503, 'Must have valid receiver and originator') return assert self.delivery self.mode = DATA helo, origin, user_recipients = self._helo, self._from, self._user_to recipients = self._to self._from = None self._to = [] ...
helo, origin, user_recipients = self._helo, self._from, self._user_to
helo, origin = self._helo, self._from
def do_DATA(self, rest): if self._from is None or (not self._to and not self._user_to): self.sendCode(503, 'Must have valid receiver and originator') return assert self.delivery self.mode = DATA helo, origin, user_recipients = self._helo, self._from, self._user_to recipients = self._to self._from = None self._to = [] ...
self._user_to = []
def do_DATA(self, rest): if self._from is None or (not self._to and not self._user_to): self.sendCode(503, 'Must have valid receiver and originator') return assert self.delivery self.mode = DATA helo, origin, user_recipients = self._helo, self._from, self._user_to recipients = self._to self._from = None self._to = [] ...
if user_recipients: try: self.__messages = self.startMessage(user_recipients) except SMTPServerError, e: self.sendCode(e.code, e.resp) self.mode = COMMAND return rcvdhdr = self.delivery.receivedHeader( helo, origin, map(str, user_recipients)) else: try: self.__messages = [f() for (u, f) in recipients] except SMTPServer...
try: self.__messages = [f() for (u, f) in recipients] except SMTPServerError, e: self.sendCode(e.code, e.resp) self.mode = COMMAND return except: log.err() self.sendCode(550, "Internal server error") self.mode = COMMAND return rcvdhdr = self.delivery.receivedHeader( helo, origin, [u for (u, f) in recipients])
def do_DATA(self, rest): if self._from is None or (not self._to and not self._user_to): self.sendCode(503, 'Must have valid receiver and originator') return assert self.delivery self.mode = DATA helo, origin, user_recipients = self._helo, self._from, self._user_to recipients = self._to self._from = None self._to = [] ...
log.msg(fmt % (origin, map(str, [u for (u, f) in recipients] or user_recipients)))
log.msg(fmt % (origin, [str(u) for (u, f) in recipients]))
def do_DATA(self, rest): if self._from is None or (not self._to and not self._user_to): self.sendCode(503, 'Must have valid receiver and originator') return assert self.delivery self.mode = DATA helo, origin, user_recipients = self._helo, self._from, self._user_to recipients = self._to self._from = None self._to = [] ...
self._user_to = []
def do_RSET(self, rest): self._from = None self._to = [] self._user_to = [] self.sendCode(250, 'I remember nothing.')
else: self.sendCode(451, 'Requested action aborted: error in processing')
elif reason.check(SMTPAddressError): self.sendCode(reason.value.code, reason.value.resp) else: self.sendCode(451, 'Requested action aborted: local error in processing')
def _ebAuthenticated(self, reason): self.challenge = None if reason.check(cred.error.UnauthorizedLogin): self.sendCode(535, 'Authentication failed') else: self.sendCode(451, 'Requested action aborted: error in processing') log.err(reason)
try: self.sentMail(code, resp, len(self.successAddresses), self.toAddressesResult, self.log) except TypeError: if self.sentMail.func_code.co_argcount == 2: warnings.warn( 'File "%s", line %d, in %s\n' ' %s.sentMail call syntax has changed!\n' ' Please update your code!' % (self.sentMail.func_code.co_filename, self.se...
self.sentMail(code, resp, len(self.successAddresses), self.toAddressesResult, self.log)
def smtpState_msgSent(self, code, resp): if self._from is not None: # If there was a pending message try: self.sentMail(code, resp, len(self.successAddresses), self.toAddressesResult, self.log) except TypeError: if self.sentMail.func_code.co_argcount == 2: warnings.warn( 'File "%s", line %d, in %s\n' ' %s.sentMail cal...
self._user_to = []
def do_EHLO(self, rest): peer = self.transport.getPeer()[1] self._helo = (rest, peer) self._from = None self._to = [] self._user_to = [] ext = self.extensions() self.sendCode( 250, '%s\n%s Hello %s, nice to meet you' % ( self.listExtensions(), self.host, peer ) )
ttyGID = os.stat(self.ptyTuple[2])[5] os.chown(self.ptyTuple[2], uid, ttyGID)
if self.ptyTuple: ttyGID = os.stat(self.ptyTuple[2])[5] os.chown(self.ptyTuple[2], uid, ttyGID)
def request_exec(self, data): command = common.getNS(data)[0] user = self.conn.transport.authenticatedUser uid, gid = user.getUserGroupID() homeDir = user.getHomeDir() shell = user.getShell() or '/bin/sh' command = [shell, '-c', command] peerHP = tuple(self.conn.transport.transport.getPeer()[1:]) hostP = (self.conn.tra...
if hasattr(self, 'pty'):
if self.pty is not None:
def dataReceived(self, data): if not hasattr(self, 'client'): #self.conn.sendClose(self) self.buf += data return if hasattr(self, 'pty'): import tty attr = tty.tcgetattr(self.pty.fileno())[3] if not attr & tty.ECHO and attr & tty.ICANON: # no echo self.conn.transport.sendIgnore('\x00' * (8+len(data))) self.client.dataR...
"""we got a global request. pretty much, this is just used by the client
""" We got a global request. pretty much, this is just used by the client
def gotGlobalRequest(self, requestType, data): """we got a global request. pretty much, this is just used by the client to request that we forward a port from the server to the client. returns either: 1: request accepted 1, <data>: request accepted with request specific data 0: request denied """ return 0
1: request accepted 1, <data>: request accepted with request specific data 0: request denied
- 1: request accepted - 1, <data>: request accepted with request specific data - 0: request denied
def gotGlobalRequest(self, requestType, data): """we got a global request. pretty much, this is just used by the client to request that we forward a port from the server to the client. returns either: 1: request accepted 1, <data>: request accepted with request specific data 0: request denied """ return 0
del sys.modules[modname]
del sys.modules['twisted.trial.test.importErrors']
def testImportError(self): self.failIfImportErrors = False # Add a module that fails to import if modname in sys.modules: # Previous tests might leave this hanging around in Python < 2.4. del sys.modules[modname] self.suite.addModule('twisted.trial.test.importErrors') self.suite.run()
("content-encoding", self.contentType()),
("content-encoding", self.contentEncoding()),
def setHeaders(response): for (header, value) in ( ("content-length", self.contentLength()), ("content-type", self.contentType()), ("content-encoding", self.contentType()), ): if value is not None: response.headers.setHeader(header, value)
This callback will be called with one method, this instance.
This callback will be called with one argument, this instance.
def notifyOnDisconnect(self, callback): """Register a callback to be called if our broker gets disconnected.
Argument.__init__(self, name, default=None, shortDesc=None, longDesc=None, hints=None, allowNone=1)
Argument.__init__(self, name, default=default, shortDesc=shortDesc, longDesc=longDesc, hints=hints, allowNone=allowNone)
def __init__(self, name, default=None, shortDesc=None, longDesc=None, hints=None, allowNone=1, min=0, max=None): Argument.__init__(self, name, default=None, shortDesc=None, longDesc=None, hints=None, allowNone=1) self.min = min self.max = max
request.write(oldwidgets.formatFailure(fail))
request.write(webutil.formatFailure(fail))
def renderFailure(fail, request): if not fail: fail = failure.Failure() log.err(fail) request.write(oldwidgets.formatFailure(fail)) #request.finish()
(self.namespace, self.streamHost)
(self.namespace, self.streamHost.encode('utf-8'))
def connectionMade(self): # Generate stream header if self.version == 1.0: sh = "<stream:stream xmlns='%s' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>" % \ (self.namespace) else: sh = "<stream:stream xmlns='%s' xmlns:stream='http://etherx.jabber.org/streams' to='%s'>" % \ (self.namespace, self.stream...
if not isinstance(view, widgets.DefaultWidget):
if model is not peek(self.viewStack).model and not isinstance(view, widgets.DefaultWidget):
def handleNode(self, request, node): submodelName = node.attributes.get('model') if submodelName is None: submodelName = "" model = self.getNodeModel(request, node, submodelName) view = self.getNodeView(request, node, submodelName, model) controller = self.getNodeController(request, node, submodelName, model) if view o...
curId = id(view) theId = "woven_id_" + str(curId)
theId = "woven_id_%d" % id(view)
def handleNode(self, request, node): submodelName = node.attributes.get('model') if submodelName is None: submodelName = "" model = self.getNodeModel(request, node, submodelName) view = self.getNodeView(request, node, submodelName, model) controller = self.getNodeController(request, node, submodelName, model) if view o...
readAndDiscard(self, truncater)
readAndDiscard(truncater)
def notifyClosed(self, truncater): if self.closed: # we are closed, have first half really close truncater.postTruncater = None truncater.close() elif self.sentInitialSegment: # We are trying to read, read up first half readAndDiscard(self, truncater) else: # Idle, store closed info. self.truncaterClosed = truncater
'BufferedStream', 'readStream', 'ProcessStreamer']
'BufferedStream', 'readStream', 'ProcessStreamer', 'readIntoFile']
def split(self, offset): off = offset - len(self.data) pre, post = self.stream.split(max(0, off)) pre = BufferedStream(pre) post = BufferedStream(post) if off < 0: pre.data = self.data[:-off] post.data = self.data[-off:] else: pre.data = self.data return pre, post
raise AssertionError, (msg or '%s != %s' % (first, second))
raise AssertionError, (msg or '%r != %r' % (first, second))
def failUnlessEqual(self, first, second, msg=None): if not first == second: raise AssertionError, (msg or '%s != %s' % (first, second))
raise AssertionError, (msg or '%s == %s' % (first, second))
raise AssertionError, (msg or '%r == %r' % (first, second))
def failIfEqual(self, first, second, msg=None): if not first != second: raise AssertionError, (msg or '%s == %s' % (first, second))
l = traceback.extract_tb(tb, limit) return ['%s:%s:%s\n' % x[:-1] for x in l]
l = extract_tb(tb, limit) return ['%s:%s:%s\n' % (filename, lineno, method) for filename, lineno, method, _ in l]
def emacs_format_exception(eType, eValue, tb, limit=None): """Compact traceback formatting, parseable by emacs compile-mode. """ # TODO: hide trial frames like plain_format_exception l = traceback.extract_tb(tb, limit) return ['%s:%s:%s\n' % x[:-1] for x in l]
self._exception = exception
self._exception = e
def _doAction(self, function, *args, **kwargs): """Run the action whose result we are. Should only be called by the scheduler.""" try: result = apply(function, args, kwargs) except Exception, e: self._exception = exception else: self._result = result self._finished = 1
The method used to fetch the next value
The method used to fetch the next value, make sure to return a list of rows, not just a row
def next(self): ''' The method used to fetch the next value ''' raise StopIteration
callFromThread(self.buff.append,val)
callFromThread(self.buff.extend,val)
def process(self): ''' This is called in the 'source' thread, and just basically sucks the iterator, appending items back to the main thread. ''' from twisted.internet.reactor import callFromThread try: while 1: val = self.source.next() callFromThread(self.buff.append,val) except StopIteration: callFromThread(self.stop...
def __init__(self, pool, sql):
def __init__(self, pool, sql, fetchall=0):
def __init__(self, pool, sql): FlowIterator.__init__(self) self.curs = None self.sql = sql self.pool = pool self.data = None
self.simulate()
def addReader(self, reader): if not hasReader(reader): reads[reader] = gtk.input_add(reader, gtk.GDK.INPUT_READ, self.callback) self.simulate()
self.port2 = reactor.connectMulticast("127.0.0.1", self.server.transport.getHost().port, self.client) reactor.iterate() reactor.iterate()
self.port2 = reactor.listenMulticast(0, self.client) reactor.iterate() reactor.iterate() self.client.transport.connect("127.0.0.1", self.server.transport.getHost().port)
def setUp(self): self.server = Server() self.client = Client() # multicast won't work if we listen over loopback, apparently self.port1 = reactor.listenMulticast(0, self.server) self.port2 = reactor.connectMulticast("127.0.0.1", self.server.transport.getHost().port, self.client) reactor.iterate() reactor.iterate()
self.o.write('x') self.o.flush()
try: self.o.write('x') self.o.flush() except ValueError: pass
def wakeUp(self): """Write one byte to the pipe, and flush it. """ self.o.write('x') self.o.flush()
self.handshake = "start"
self.initiator = false self.handshake = "start"
def __init__(self): self.handshake = "start" # state transitions: "start" -> "hesaidhello", "hesaidhello" -> "completed", "start" -> "isaidhello", "isaidhello" -> "completed" self.gotver = None self.secret = "geheim"
self.secret = "geheim"
def __init__(self): self.handshake = "start" # state transitions: "start" -> "hesaidhello", "hesaidhello" -> "completed", "start" -> "isaidhello", "isaidhello" -> "completed" self.gotver = None self.secret = "geheim"
def setSecret(self, secret): self.secret = secret
def __init__(self): self.handshake = "start" # state transitions: "start" -> "hesaidhello", "hesaidhello" -> "completed", "start" -> "isaidhello", "isaidhello" -> "completed" self.gotver = None self.secret = "geheim"
def abortConnection(self, logmsg):
def initiateConnection(self, ipAddress, port): assert self.handshake == "start" assert self.initiator == false self.initiator = true def connectionMade(self): if self.initiator: self.transport.write(CONNSTRING) self.handshake = "initiatorsaidhello" def _abortConnection(self, logmsg):
def abortConnection(self, logmsg): log.msg(logmsg + ", self: %s" % str(self)) self.transport.loseConnection() return
self.abortConnection("Received non-empty Ping payload. Closing connection. payload: %s" % str(payload))
self._abortConnection("Received non-empty Ping payload. Closing connection. payload: %s" % str(payload))
def handlePing(self, descriptorId, ttl, hops, payload): """ A ping message has arrived. """ if payload != '': self.abortConnection("Received non-empty Ping payload. Closing connection. payload: %s" % str(payload)) return
self.abortConnection("Received ill-formatted Pong payload. Closing connection. payload: %s" % str(payload))
self._abortConnection("Received ill-formatted Pong payload. Closing connection. payload: %s" % str(payload))
def handlePong(self, descriptorId, ttl, hops, payload): try: (port, ipA0, ipA1, ipA2, ipA3, numberOfFilesShared, kbShared,) = struct.unpack(PONGPAYLOADENCODING, payload) except struct.error, le: self.abortConnection("Received ill-formatted Pong payload. Closing connection. payload: %s" % str(payload)) return
self.abortConnection("Received ill-formatted Query payload. Closing connection. payload: %s" % str(payload))
self._abortConnection("Received ill-formatted Query payload. Closing connection. payload: %s" % str(payload))
def handleQuery(self, descriptorId, ttl, hops, payload): try: (minimumSpeed,) = struct.unpack("<H", payload[:2]) except struct.error, le: self.abortConnection("Received ill-formatted Query payload. Closing connection. payload: %s" % str(payload)) return searchCriteria = payload[2:] self.queryReceived(descriptorId, tt...
self.abortConnection("Received ill-formatted QueryHit payload. Closing connection. payload: %s" % str(payload))
self._abortConnection("Received ill-formatted QueryHit payload. Closing connection. payload: %s" % str(payload))
def handleQueryHit(self, descriptorId, ttl, hops, payload): try: (numberOfHits, port, ipA0, ipA1, ipA2, ipA3, speed,) = struct.unpack(PARTIALQUERYHITPAYLOADENCODING, payload[:PARTIALQUERYHITPAYLOADLENGTH]) except struct.error, le: self.abortConnection("Received ill-formatted QueryHit payload. Closing connection. payl...
self.abortConnection("Received ill-formatted partial QueryHit result. Closing connection. partial query hit result: %s" % str(payload[i:i+PARTIALQUERYHITRESULTLENGTH]))
self._abortConnection("Received ill-formatted partial QueryHit result. Closing connection. partial query hit result: %s" % str(payload[i:i+PARTIALQUERYHITRESULTLENGTH]))
def handleQueryHit(self, descriptorId, ttl, hops, payload): try: (numberOfHits, port, ipA0, ipA1, ipA2, ipA3, speed,) = struct.unpack(PARTIALQUERYHITPAYLOADENCODING, payload[:PARTIALQUERYHITPAYLOADLENGTH]) except struct.error, le: self.abortConnection("Received ill-formatted QueryHit payload. Closing connection. payl...
self.abortConnection("Received ill-formatted QueryHit payload. Closing connection. i: %s, ill-formed part of query hit payload: %s" % (str(i), str(payload[i:]),))
self._abortConnection("Received ill-formatted QueryHit payload. Closing connection. i: %s, ill-formed part of query hit payload: %s" % (str(i), str(payload[i:]),))
def handleQueryHit(self, descriptorId, ttl, hops, payload): try: (numberOfHits, port, ipA0, ipA1, ipA2, ipA3, speed,) = struct.unpack(PARTIALQUERYHITPAYLOADENCODING, payload[:PARTIALQUERYHITPAYLOADLENGTH]) except struct.error, le: self.abortConnection("Received ill-formatted QueryHit payload. Closing connection. payl...
self.abortConnection("Received ill-formatted Push payload. Closing connection. i: %s, ill-formed part of query hit payload: %s" % (str(i), str(payload[i:]),))
self._abortConnection("Received ill-formatted Push payload. Closing connection. i: %s, ill-formed part of query hit payload: %s" % (str(i), str(payload[i:]),))
def handlePush(self, descriptorId, ttl, hops, payload): try: (serventIdentifer, fileIndex, ipA0, ipA1, ipA2, ipA3, port,) = struct.unpack(PUSHPAYLOADENCODING, payload) except struct.error, le: self.abortConnection("Received ill-formatted Push payload. Closing connection. i: %s, ill-formed part of query hit payload: %...
self.abortConnection("Received ill-formatted descriptor. Closing connection. payload: %s" % str(descriptor))
self._abortConnection("Received ill-formatted descriptor. Closing connection. payload: %s" % str(descriptor))
def descriptorReceived(self, descriptor): """ A Gnutella descriptor has arrived.
self.abortConnection("Received unrecognized payload descriptor. Closing connection. payloadDescriptor: %s" % str(payloadDescriptor))
self._abortConnection("Received unrecognized payload descriptor. Closing connection. payloadDescriptor: %s" % str(payloadDescriptor))
def descriptorReceived(self, descriptor): """ A Gnutella descriptor has arrived.
@precondition We must be expecting a GNUTELLA CONNECT handshake move.: self.handshake in ("start", "isaidhello",): "self.handshake: %s, line: %s" % (str(self.handshake), str(line),) """ assert self.handshake in ("start", "isaidhello",), "precondition failure: We must be expecting a GNUTELLA CONNECT handshake move." + "...
@precondition We must be expecting a GNUTELLA CONNECT handshake move.: (self.initiator and (self.handshake == "initiatorsaidhello")) or ((not self.initiator) and (self.handshake == "start")): "self.initiator: %s, self.handshake: %s, line: %s" % (str(self.initiator), str(self.handshake), str(line),) """ assert (self.ini...
def lineReceived(self, line): """ @precondition We must be expecting a GNUTELLA CONNECT handshake move.: self.handshake in ("start", "isaidhello",): "self.handshake: %s, line: %s" % (str(self.handshake), str(line),) """ assert self.handshake in ("start", "isaidhello",), "precondition failure: We must be expecting a GNU...
self.abortConnection("Received incorrect GNUTELLA HELLO. Closing connection. line: %s" % str(line))
self._abortConnection("Received incorrect GNUTELLA HELLO. Closing connection. line: %s" % str(line))
def lineReceived(self, line): """ @precondition We must be expecting a GNUTELLA CONNECT handshake move.: self.handshake in ("start", "isaidhello",): "self.handshake: %s, line: %s" % (str(self.handshake), str(line),) """ assert self.handshake in ("start", "isaidhello",), "precondition failure: We must be expecting a GNU...
self.setRawMode() else: assert self.handshake == "isaidhello" if line != ACKSTRING: self.abortConnection("Received incorrect GNUTELLA OK. Closing connection. line: %s" % str(line)) return self.handshake = "completed"
def lineReceived(self, line): """ @precondition We must be expecting a GNUTELLA CONNECT handshake move.: self.handshake in ("start", "isaidhello",): "self.handshake: %s, line: %s" % (str(self.handshake), str(line),) """ assert self.handshake in ("start", "isaidhello",), "precondition failure: We must be expecting a GNU...
self.abortConnection("Received ill-formatted raw data. Closing connection. self.buf: %s" % str(self.buf))
self._abortConnection("Received ill-formatted raw data. Closing connection. self.buf: %s" % str(self.buf))
def rawDataReceived(self, data): self.buf += data # XXX opportunity for future optimization --Zooko 2002-07-15 if len(self.buf) >= HEADERLENGTH: try: (payloadLength,) = struct.unpack(PAYLOADENCODING, self.buf[PAYLOADLENGTHOFFSET:HEADERLENGTH]) except struct.error, le: self.abortConnection("Received ill-formatted raw d...
self.abortConnection("Received payload > %d KB or < than 0 in size. Closing connection. payloadLength: %s" % ((OURMAXPAYLOADLENGTH / 2**10), str(payloadLength),))
self._abortConnection("Received payload > %d KB or < than 0 in size. Closing connection. payloadLength: %s" % ((OURMAXPAYLOADLENGTH / 2**10), str(payloadLength),))
def rawDataReceived(self, data): self.buf += data # XXX opportunity for future optimization --Zooko 2002-07-15 if len(self.buf) >= HEADERLENGTH: try: (payloadLength,) = struct.unpack(PAYLOADENCODING, self.buf[PAYLOADLENGTHOFFSET:HEADERLENGTH]) except struct.error, le: self.abortConnection("Received ill-formatted raw d...
test, error = self.errorInfo[selected]
test, failure = self.errorInfo[selected] s = StringIO.StringIO() failure.printTraceback(s) tracebackText = s.getvalue()
def showSelectedError(self): selection = self.errorListbox.curselection() if not selection: return selected = int(selection[0]) txt = self.errorListbox.get(selected) window = tk.Toplevel(self.root) window.title(txt) window.protocol('WM_DELETE_WINDOW', window.quit) test, error = self.errorInfo[selected] tk.Label(window,...
tracebackLines = apply(traceback.format_exception, error + (10,)) tracebackText = string.join(tracebackLines,'')
def showSelectedError(self): selection = self.errorListbox.curselection() if not selection: return selected = int(selection[0]) txt = self.errorListbox.get(selected) window = tk.Toplevel(self.root) window.title(txt) window.protocol('WM_DELETE_WINDOW', window.quit) test, error = self.errorInfo[selected] tk.Label(window,...
self.call = reactor.callLater(self.delay, self._getPage)
if not self.call: self.call = reactor.callLater(self.delay, self._getPage)
def gotMD5(self, md5): if not self.working: return if md5 != self.md5: self.reportChange(self.md5, md5) self.md5 = md5 else: self.reportNoChange() self.call = reactor.callLater(self.delay, self._getPage)
articles = string.split(text, '-')
articles = text.split('-')
def parseRange(text): # FIXME: should cope with '1-', '-443' and even '-' articles = string.split(text, '-') if len(articles) == 1: try: a = int(articles[0]) return a, a except: return None, None elif len(articles) == 2: try: if len(articles[0]): l = int(articles[0]) else: l = None if len(articles[1]): h = int(articles...
except:
except ValueError, e:
def parseRange(text): # FIXME: should cope with '1-', '-443' and even '-' articles = string.split(text, '-') if len(articles) == 1: try: a = int(articles[0]) return a, a except: return None, None elif len(articles) == 2: try: if len(articles[0]): l = int(articles[0]) else: l = None if len(articles[1]): h = int(articles...
if l is h is None: self.sendLine('501 command syntax error') else: defer = self.factory.backend.xoverRequest(self.currentGroup, l, h) defer.addCallbacks(self._gotXOver, self._errXOver)
defer = self.factory.backend.xoverRequest(self.currentGroup, l, h) defer.addCallbacks(self._gotXOver, self._errXOver)
def do_XOVER(self, parts): if self.currentGroup is None: self.sendLine('412 No news group currently selected') else: if not len(parts): self.sendLine('501 command syntax error') return l, h = parseRange(parts[0]) if l is h is None: self.sendLine('501 command syntax error') else: defer = self.factory.backend.xoverReques...
self.transport.write(body + '\r\n')
self.transport.write(body.replace('\r\n..', '\r\n.') + '\r\n')
def _gotBody(self, parts): index, id, body = parts self.currentIndex = index self.sendLine('221 %d %s article retrieved' % (index, id)) self.transport.write(body + '\r\n') self.sendLine('.')
self.setHeader("content-length", "0")
def redirect(self, url): """Utility function that does a redirect.
listConn = True
lostConn = True
def testManyRecords(self): self.auth.addresses['test.domain'] = [ 'mx1.test.domain', 'mx2.test.domain', 'mx3.test.domain' ] mx = unittest.deferredResult(self.mx.getMX('test.domain')) self.failUnless(str(mx.exchange).split('.', 1)[0] in ('mx1', 'mx2', 'mx3')) self.mx.markBad(mx) nextMX = unittest.deferredResult(self....
sup.__init__(self)
def __init__(self): sup.__init__(self) self.xml = gtk.glade.XML(util.sibpath(__file__,"gladereactor.glade")) d = {} for m in reflect.prefixedMethods(self, "on_"): d[m.im_func.__name__] = m self.xml.signal_autoconnect(d) self.xml.get_widget('window1').connect('destroy', lambda w: self.stop()) self.servers = self.xml.get...
method = getattr(self, "irc_%s" % command, None) try: if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params) except: log.deferr()
self.handleCommand(command, prefix, params) def handleCommand(self, command, prefix, params): """Determine the function to call for the given command and call it with the given arguments. """ method = getattr(self, "irc_%s" % command, None) try: if method is not None: method(prefix, params) else: self.irc_unknown(pre...
def dataReceived(self, data): """This hack is to support mIRC, which sends LF only, even though the RFC says CRLF. (Also, the flexibility of LineReceiver to turn "line mode" on and off was not required.) """ self.buffer = self.buffer + data lines = string.split(self.buffer, LF) # Put the (possibly empty) element after...
method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params)
self.handleCommand(command, prefix, params)
def lineReceived(self, line): line = lowDequote(line) try: prefix, command, params = parsemsg(line) if numeric_to_symbolic.has_key(command): command = numeric_to_symbolic[command] method = getattr(self, "irc_%s" % command, None) if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, param...
from xml.dom.minidom import Element
from twisted.web.microdom import Element
def unjellyFromDOM_2(self, unjellier, element): self.integer = int(element.getAttribute("integer")) self.name = element.getAttribute("name")
iterateFunc()
try: iterateFunc() except: log.err()
def iterateReactor_(self, iterateFunc): iterateFunc()
from twisted.python import log
def reactorNotification_(self, iterateFunc): pool = NSAutoreleasePool.alloc().init() self.performSelectorOnMainThread_withObject_waitUntilDone_('iterateReactor:', iterateFunc, False) del pool
if self.method == "HEAD":
if self.method == "HEAD" or response.code in NO_BODY_CODES: response.stream.close() self._finished(None)
def writeResponse(self, response): """ Write a response. """ if self.stream.doStartReading is not None: # Expect: 100-continue was requested, but 100 response has not been # sent, and there's a possibility that data is still waiting to be # sent. # # Ideally this means the remote side will not send any data. # However,...
if response.code in NO_BODY_CODES: return
def writeResponse(self, response): """ Write a response. """ if self.stream.doStartReading is not None: # Expect: 100-continue was requested, but 100 response has not been # sent, and there's a possibility that data is still waiting to be # sent. # # Ideally this means the remote side will not send any data. # However,...
not (code in NO_BODY_CODES)):
self.command != "HEAD" and code not in NO_BODY_CODES):
def _writeHeaders(self, code, headers, addConnectionHeaders): # HTTP 0.9 doesn't have headers. if self.version[0] == 0: return l = [] code_message = responsecode.RESPONSES.get(code, "Unknown Status") l.append('%s %s %s\r\n' % (self.out_version, code, code_message)) if headers is not None: for name, valuelist in heade...
from twisted.trial.util import deferredResult
def encodeTokens(obj, debug=0): from twisted.trial.util import deferredResult b = TokenStorageBanana() b.debug = debug d = b.send(obj) deferredResult(d) return b.tokens
deferredResult(d) return b.tokens
d.addCallback(lambda res: b.tokens) return d
def encodeTokens(obj, debug=0): from twisted.trial.util import deferredResult b = TokenStorageBanana() b.debug = debug d = b.send(obj) deferredResult(d) return b.tokens
class NDeferred: def __init__(self, n, deferred): self.n = n self.deferred = deferred self.done = 0 def callback(self, arg): if self.done: return self.n = self.n - 1 if self.n == 0: self.deferred.callback(arg) self.done = 1 def errback(self, arg): if self.done: return self.deferred.errback(arg) self.done = 1
def quoteaddr(addr): """Turn an email address, possibly with realname part etc, into a form suitable for and SMTP envelope. """ if isinstance(addr, Address): return '<%s>' % str(addr) res = rfc822.parseaddr(addr) if res == (None, None): # It didn't parse, use it as-is return '<%s>' % str(addr) else: return '<%s>' % ...
deferred = defer.Deferred() deferred.addCallback(self._messageHandled) deferred.addErrback(self._messageNotHandled) ndeferred = NDeferred(len(self.__messages), deferred) for message in self.__messages: deferred = message.eomReceived() deferred.addCallback(ndeferred.callback) deferred.addErrback(ndeferred.errback)
defer.DeferredList([ m.eomReceived() for m in self.__messages ]).addCallback(self._messageHandled ).addErrback(self._messageNotHandled)
def dataLineReceived(self, line): if line[:1] == '.': if line == '.': self.mode = COMMAND if self.datafailed: self.sendCode(self.datafailed.code, self.datafailed.resp) return if not self.__messages: self._messageHandled("thrown away") return deferred = defer.Deferred() deferred.addCallback(self._messageHandled) deferre...
fcntl.ioctl(pty.fileno(), tty.TIOCSWINSZ,
fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
def openShell(self, proto): import fcntl, tty if not self.ptyTuple: # we didn't get a pty-req log.msg('tried to get shell without pty, failing') raise error.ConchError("no pty") #proto = wrapProtocol(proto) uid, gid = self.avatar.getUserGroupId() homeDir = self.avatar.getHomeDir() shell = self.avatar.getShell() self.en...
prefix, s = string.split(s[1:], maxsplit=1)
prefix, s = string.split(s[1:], ' ', 1)
def parsemsg(s): prefix = '' trailing = [] if s[0] == ':': prefix, s = string.split(s[1:], maxsplit=1) if string.find(s,':') != -1: s, trailing = string.split(s, ':', 1) args = string.split(s) args.append(trailing) else: args = string.split(s) command = args.pop(0) return prefix, command, args
yield STRING, current yield OP, n
yield _STRING, current yield _OP, n
def _tokenize(description): current = '' ops = ':=' nextOps = {':': ':=', '=': ':'} description = iter(description) for n in description: if n in ops: yield STRING, current yield OP, n current = '' ops = nextOps[n] elif n=='\\': current += description.next() else: current += n yield STRING, current
yield STRING, current
yield _STRING, current
def _tokenize(description): current = '' ops = ':=' nextOps = {':': ':=', '=': ':'} description = iter(description) for n in description: if n in ops: yield STRING, current yield OP, n current = '' ops = nextOps[n] elif n=='\\': current += description.next() else: current += n yield STRING, current
if type is STRING: so_far += (value,) elif type is OP and value==':':
if type is _STRING: sofar += (value,) elif value==':':
def add(sofar): if len(sofar)==1: args.append(sofar[0]) else: kw[sofar[0]] = sofar[1]
def listStaticNames(self): n = [] for i in xrange(len(self.app.connectors)): c = self.app.connectors[i] n.append("%s:%s,%d" % (c.host, c.portno, i)) return n def listStaticEntities(self): return map(None, self.listStaticNames(), self.app.connectors[:])
def __init__(self, app): coil.ConfigCollection.__init__(self) self.app = app
return self.processNode(request, result.render(request), node)
return self.processNode(request, result.generateDOM(request), node)
def dispatchResult(self, request, node, result): """ Check a given result from handling a node and hand it to a process* method which will convert the result into a node and insert it into the DOM tree. Return the new node. """ if isinstance(result, widgets.Widget): return self.processWidget(request, result, node) elif...
raise unittest.FailTest, "Deferred did not fail: %r" % result
raise unittest.FailTest, "Deferred did not fail: %r" % (result,)
def deferredError(d, timeout=None): """Waits for deferred to fail, and it returns the Failure. If the deferred succeeds, raises FailTest. """ result = _getDeferredResult(d, timeout) if isinstance(result, failure.Failure): return result else: raise unittest.FailTest, "Deferred did not fail: %r" % result
def render(self): return error.NoResource.render()
def render(self, request): return error.NoResource().render(request)
def render(self): return error.NoResource.render()
<ul id="blah" view="List"> <li id="listItem" view="Text">Foo</li> </ul>
| <ul id="blah" view="List"> | <li id="listItem" view="Text">Foo</li> | </ul>
def generateDOM(self, request, node): href = self.baseHREF params = urllib.urlencode(self.parameters) if params: href = href + '?' + params self['href'] = href or self.getData() + '/' data = self.getData() if data is None: data = "" self.add(Text(data, self.raw)) return Widget.generateDOM(self, request, node)
<table model="blah" view="List"> <tr class="listHeader"><th>A</th><th>B</th></tr> <tr class="listItem"> <td><span view="Text" model="1" /</td> <td><span view="Text" model="2" /</td> </tr> </table> Where blah is the name of a list on the model; eg self.model.blah = ['foo', 'bar']
| <table model="blah" view="List"> | <tr class="listHeader"><th>A</th><th>B</th></tr> | <tr class="listItem"> | <td><span view="Text" model="1" /> | <td><span view="Text" model="2" /> | </tr> | </table> Where blah is the name of a list on the model; eg: | self.model.blah = ['foo', 'bar']
def generateDOM(self, request, node): href = self.baseHREF params = urllib.urlencode(self.parameters) if params: href = href + '?' + params self['href'] = href or self.getData() + '/' data = self.getData() if data is None: data = "" self.add(Text(data, self.raw)) return Widget.generateDOM(self, request, node)
self.path = path or '/'
if path == '/': path = '' self.path = path
def __init__(self, scheme='', netloc='localhost', path='', query='', fragment=''): self.scheme = scheme or 'http' self.netloc = netloc self.path = path or '/' self.query = query self.fragment = fragment
def _pathMod(self, newpath, keepQuery):
def _pathMod(self, newpathsegs, keepQuery):
def _pathMod(self, newpath, keepQuery): if keepQuery: query = self.query else: query = '' return URLPath(self.scheme, self.netloc, newpath, query)
newpath,
'/'.join(newpathsegs),
def _pathMod(self, newpath, keepQuery): if keepQuery: query = self.query else: query = '' return URLPath(self.scheme, self.netloc, newpath, query)
newpath = '/'.join(l) return self._pathMod(path, keepQuery)
return self._pathMod(l, keepQuery)
def sibling(self, path, keepQuery=0): l = self.pathList() l[-1] = path newpath = '/'.join(l) return self._pathMod(path, keepQuery)
l.append(path) newpath = '/'.join(l) return self._pathMod(path, keepQuery)
if l[-1] == '': l[-1] = path else: l.append(path) return self._pathMod(l, keepQuery)
def child(self, path, keepQuery=0): l = self.pathList() l.append(path) newpath = '/'.join(l) return self._pathMod(path, keepQuery)
l[-2:] = [] newpath = '/'.join(l) return self._pathMod(newpath, keepQuery)
if l[-1] == '': del l[-2] else: l.pop() return self._pathMod(l, keepQuery) def here(self, keepQuery=0): l = self.pathList() if l[-1] != '': l.pop() return self._pathMod(l, keepQuery)
def parent(self, keepQuery=0): l = self.pathList() l[-2:] = [] newpath = '/'.join(l) return self._pathMod(newpath, keepQuery)
basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
self._reallySendLine(line)
def sendLine(self, line): if self.lineRate is None: basic.LineReceiver.sendLine(self, lowQuote(line) + '\r') else: self._queue.append(line) if not self._queueEmptying: self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine)
self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine)
self._sendLine()
def sendLine(self, line): if self.lineRate is None: basic.LineReceiver.sendLine(self, lowQuote(line) + '\r') else: self._queue.append(line) if not self._queueEmptying: self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine)
basic.LineReceiver.sendLine(self, lowQuote(self._queue.pop(0)) + '\r')
self._reallySendLine(self._queue.pop(0))
def _sendLine(self): if self._queue: basic.LineReceiver.sendLine(self, lowQuote(self._queue.pop(0)) + '\r') self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine) else: self._queueEmptying = None
pass
self.startWriting()
def doConnect(self): """I connect the socket. Then, call the protocol's makeConnection, and start waiting for data. """ try: self.socket.connect(self.addr) except socket.error, se: if se.args[0] in (EWOULDBLOCK, EALREADY, EINPROGRESS): pass else: self.protocol.connectionFailed() return CONNECTION_LOST # If I have reac...
return CONNECTION_LOST
self.stopWriting()
def doConnect(self): """I connect the socket. Then, call the protocol's makeConnection, and start waiting for data. """ try: self.socket.connect(self.addr) except socket.error, se: if se.args[0] in (EWOULDBLOCK, EALREADY, EINPROGRESS): pass else: self.protocol.connectionFailed() return CONNECTION_LOST # If I have reac...
removeReader(self)
self.stopReading()
def loseConnection(self): """ Stop accepting connections on this port.
self._properties = DeadPropertyStore(self) return self._properties
self._dead_properties = DeadPropertyStore(self) return self._dead_properties
def getDeadProperties(self): if not hasattr(self, "_dead_properties"): self._properties = DeadPropertyStore(self) return self._properties
what = error.getBriefTraceback()
what = itrial.IFormattedFailure(error)
def formatImportError(name, error): if isinstance(error, failure.Failure): what = error.getBriefTraceback() elif type(error) == types.TupleType: what = error.args[0] else: what = "%s\n" % error ret = "Could not import %s: %s\n" % (name, what) return ret
ret = "Could not import %s: %s\n" % (name, what) return ret
ret.append("Could not import %s: \n%s\n" % (name, what)) return ''.join(ret)
def formatImportError(name, error): if isinstance(error, failure.Failure): what = error.getBriefTraceback() elif type(error) == types.TupleType: what = error.args[0] else: what = "%s\n" % error ret = "Could not import %s: %s\n" % (name, what) return ret
return "fake", "fake", "fake"
return address.IPv4Address("TCP", "fake", "fake")
def getPeer(self): return "fake", "fake", "fake"