rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
log.msg( "WARNING: serializing ephemeral %s" % self ) | log.msg( "WARNING: serializing ephemeral %s" % self.__class__ ) | def __getstate__(self): log.msg( "WARNING: serializing ephemeral %s" % self ) return None |
self.file.close() self.file = None | if self.file is not None: self.file.close() self.file = None | def connectionLost(self, reason): if (self.action == 'STOR') and (self.file): self.pi.reply('fileok') elif self.file is not None: if self.file.tell() == self.filesize: self.pi.reply('fileok') else: self.pi.reply('getabort') self.file.close() self.file = None self.pi.queuedfile = None self.action = None if hasattr(self.... |
mtime = time.strftime("%b %d %H:%M", time.gmtime(os.path.getmtime(ff))) fsize = os.path.getsize(ff) | try: mtn = os.path.getmtime(ff) fsize = os.path.getsize(ff) except OSError: mtn = 0 fsize = 0 mtime = time.strftime("%b %d %H:%M", time.gmtime(mtn)) | def actionLIST(self, dir): """Prints outs the files in the given directory Note that the printout is very fake, and only gives the filesize, date, time and filename. """ list = os.listdir(dir) s = '' for a in list: ts = a ff = os.path.join(dir, ts) # the full filename mtime = time.strftime("%b %d %H:%M", time.gmtime(os... |
s = s + diracc+"r-xr-xr-x 1 twisted twisted %11d" % fsize+' '+mtime+' '+ts+'\n' | s = s + diracc+"r-xr-xr-x 1 twisted twisted %11d" % fsize+' '+mtime+' '+ts+'\r\n' | def actionLIST(self, dir): """Prints outs the files in the given directory Note that the printout is very fake, and only gives the filesize, date, time and filename. """ list = os.listdir(dir) s = '' for a in list: ts = a ff = os.path.join(dir, ts) # the full filename mtime = time.strftime("%b %d %H:%M", time.gmtime(os... |
from twisted.internet.reactor import callInThread | def __init__(self, data = None): from twisted.internet.reactor import callInThread self.data = data tunnel = _TunnelIterator(self) self._tunnel = tunnel callInThread(tunnel.process) | |
callInThread(tunnel.process) | def __init__(self, data = None): from twisted.internet.reactor import callInThread self.data = data tunnel = _TunnelIterator(self) self._tunnel = tunnel callInThread(tunnel.process) | |
ThreadedIterator.__init__(self) | def __init__(self, pool, sql, fetchall=0): self.curs = None self.sql = sql self.pool = pool self.data = None self.fetchall = fetchall ThreadedIterator.__init__(self) | |
def pongReceived(self, descriptorId, ttl, hops, ipAddress, port, numberOfFilesShared, kbShared) | def pongReceived(self, descriptorId, ttl, hops, ipAddress, port, numberOfFilesShared, kbShared): | def pongReceived(self, descriptorId, ttl, hops, ipAddress, port, numberOfFilesShared, kbShared) """ Override this to handle pong messages. |
mo = CONNSTRING.match(line): | mo = CONNSTRING.match(line) | def lineReceived(self, line): """ @precondition A GNUTELLA CONNECT must not already have been received.: not self.gothello: "line: %s" % str(line) """ assert not self.gothello, "precondition failure: A GNUTELLA CONNECT must not already have been received." + "--" + "line: %s" % str(line) mo = CONNSTRING.match(line): if... |
self.assertNotIn('hi hi', req.transport.getvalue()) | self.assertEquals(-1, req.transport.getvalue().find('hi hi')) | def testImplicitHead(self): req = self._getReq() req.requestReceived('HEAD', '/newrender', 'HTTP/1.0') self.assertEquals(req.code, 200) self.assertNotIn('hi hi', req.transport.getvalue()) |
('TCP', (80, self.f), {'interface':'', 'backlog':5})) | ('TCP', (80, self.f), {'interface':'', 'backlog':50})) | def testSimpleNumeric(self): self.assertEqual(strports.parse('80', self.f), ('TCP', (80, self.f), {'interface':'', 'backlog':5})) |
('TCP', (80, self.f), {'interface':'', 'backlog':5})) | ('TCP', (80, self.f), {'interface':'', 'backlog':50})) | def testSimpleTCP(self): self.assertEqual(strports.parse('tcp:80', self.f), ('TCP', (80, self.f), {'interface':'', 'backlog':5})) |
{'interface':'127.0.0.1', 'backlog':5})) | {'interface':'127.0.0.1', 'backlog':50})) | def testInterfaceTCP(self): self.assertEqual(strports.parse('tcp:80:interface=127.0.0.1', self.f), ('TCP', (80, self.f), {'interface':'127.0.0.1', 'backlog':5})) |
{'mode':0666, 'backlog':5})) | {'mode':0666, 'backlog':50})) | def testSimpleUnix(self): self.assertEqual(strports.parse('unix:/var/run/finger', self.f), ('UNIX', ('/var/run/finger', self.f), {'mode':0666, 'backlog':5})) |
{'mode':0660, 'backlog':5})) | {'mode':0660, 'backlog':50})) | def testModedUNIX(self): self.assertEqual(strports.parse('unix:/var/run/finger:mode=0660', self.f), ('UNIX', ('/var/run/finger', self.f), {'mode':0660, 'backlog':5})) |
('TCP', (80, self.f), {'interface':'', 'backlog':5})) | ('TCP', (80, self.f), {'interface':'', 'backlog':50})) | def testAllKeywords(self): self.assertEqual(strports.parse('port=80', self.f), ('TCP', (80, self.f), {'interface':'', 'backlog':5})) |
{'mode':0666, 'backlog':5})) | {'mode':0666, 'backlog':50})) | def testEscape(self): self.assertEqual(strports.parse(r'unix:foo\:bar\=baz\:qux\\', self.f), ('UNIX', ('foo:bar=baz:qux\\', self.f), {'mode':0666, 'backlog':5})) |
{'mode':0666, 'backlog':5})) | {'mode':0666, 'backlog':50})) | def testImpliedEscape(self): self.assertEqual(strports.parse(r'unix:address=foo=bar', self.f), ('UNIX', ('foo=bar', self.f), {'mode':0666, 'backlog':5})) |
relay.SMTPRelayer.sentMail(self, addresses) | def sentMail(self, addresses): """called when e-mail has been sent | |
def _finish(self, message): | def _finish(self, relay, message): self.managed[relay].remove(os.path.basename(message)) | def _finish(self, message): self.queue.done(message) |
self._finish(message) | self._finish(relay, message) | def notifySuccess(self, relay, message): """a relay sent a message successfully |
self._finish(message) | fp = self.queue.getEnvelopeFile(message) from_, to = cPickle.load(fp) fp.close() from_, to, bounce = bounce.generateBounceMessage(from_, to, open(self.queue.getPathFor(message)+'-D')) fp, message = self.queue.createNewMessage() cPickle.dump(fp, (from_, to)) fp.close() for line in string.split(bounce, '\n')[:-1]: messag... | def notifyFailure(self, relay, message): """Relaying the message has failed.""" log.msg("could not relay "+message) # Moshe - Bounce E-mail here # Be careful: if it's a bounced bounce, silently # discard it self._finish(message) |
self.queue.waiting(message) | self.queue.waiting[message] = 1 | def notifyDone(self, relay): """A relaying SMTP client is disconnected. |
return self.processNode(result.render(request)) | return self.processNode(request, result.render(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... |
from twisted.internet import defer | def failIfEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '==' operator. """ if first == second: raise self.failureException, (msg or '%s == %s' % (repr(first), repr(second))) | |
reactor.stop() | def cleanup(self, ignored=None): from twisted.internet import reactor self.testResult.stopTest(self) #reactor.runUntilCurrent() reactor.stop() if self.testResult.wasSuccessful(): self.testResult.addSuccess(self) | |
reactor.run() | reactor.runUntilCurrent() | def __call__(self, testResult=None): from twisted.internet import reactor if testResult is None: testResult = self.defaultTestResult() self.testResult = testResult self._runSetUp() reactor.run() |
See L{IDAVAccessControlList.principalCollections}. | (RFC 3744, section 5.8) @return: a sequence of URIs which refer to collection resources that contain the principal resources that may be used by the access control list for this resource. | def principalCollections(self): """ See L{IDAVAccessControlList.principalCollections}. """ return () |
See L{IDAVAccessControlList.accessControlList}. | @return: a L{davxml.ACL} element containing the access control list for this resource. | def accessControlList(self): """ See L{IDAVAccessControlList.accessControlList}. """ return allACL |
See L{IDAVAccessControlList.supportedPrivileges}. | @return: a L{davxml.SupportedPrivilegeSet} element describing the access control privileges which are supported by this resource. | def supportedPrivileges(self): """ See L{IDAVAccessControlList.supportedPrivileges}. """ return allPrivilegeSet |
davxml.Description("All access", **{"xml:lang": "en"}) | davxml.Description("all privileges", **{"xml:lang": "en"}) | def findChildren(self, depth): return () |
if sys.version_info[0:2] == (2,2): self.registry._clearAdapterRegistry() self._suite = None return | def tearDown(self): from twisted import trial trial.tbformat = self.oldtbformat if sys.version_info[0:2] == (2,2): self.registry._clearAdapterRegistry() self._suite = None return super(TestFailureFormatting, self).tearDown() | |
otherVersion = None | self.otherVersion = None | def __init__(self): self.buf = '' otherVersion = None # this gets set |
e = error.KeyNotFound(serviceName, perspectiveName) | e = KeyNotFound(serviceName, perspectiveName) | def requestPerspectiveForKey(self, serviceName, perspectiveName): """Get a perspective request (a Deferred) for the given key. |
TODO: * Login for IRCnets which require a PASS * Limit the length of messages sent (because the IRC server probably | @ivar nickname: Nickname the client will use. @ivar password: Password used to log on to the server. May be C{None}. @ivar realname: Supplied to the server during login as the \"Real name\" or \"ircname\". @ivar userinfo: Sent in reply to a X{USERINFO} CTCP query. If C{None}, no USERINFO reply will be sent. \"This i... | def irc_unknown(self, prefix, command, params): """Implement me!""" raise NotImplementedError |
* Add flood protection/rate limiting for my CTCP replies. * NickServ cooperation. (a mix-in?) | - Add flood protection/rate limiting for my CTCP replies. - NickServ cooperation. (a mix-in?) | def irc_unknown(self, prefix, command, params): """Implement me!""" raise NotImplementedError |
sourceHost = "twistedmatrix.com" sourceDir = "/downloads" sourceFiles = None | sourceURL = "http://twistedmatrix.com/downloads/" | def irc_unknown(self, prefix, command, params): """Implement me!""" raise NotImplementedError |
queue = None sendDelay = 0 | _queue = None _queueEmptying = None | def irc_unknown(self, prefix, command, params): """Implement me!""" raise NotImplementedError |
self.queue.append(line) if len(self.queue) == 1: delay, self.sendDelay = self.sendDelay, 0 reactor.callLater(delay, self._sendLine) | self._queue.append(line) if not self._queueEmptying: self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine) | def sendLine(self, line): if self.lineRate is None: basic.LineReceiver.sendLine(self, lowQuote(line)) else: self.queue.append(line) if len(self.queue) == 1: delay, self.sendDelay = self.sendDelay, 0 reactor.callLater(delay, self._sendLine) |
basic.LineReceiver.sendLine(self, lowQuote(self.queue.pop(0))) if len(self.queue): reactor.callLater(self.lineRate, self._sendLine) else: self.sendDelay = self.lineRate | if self._queue: basic.LineReceiver.sendLine(self, lowQuote(self._queue.pop(0))) self._queueEmptying = reactor.callLater(self.lineRate, self._sendLine) else: self._queueEmptying = None | def _sendLine(self): basic.LineReceiver.sendLine(self, lowQuote(self.queue.pop(0))) if len(self.queue): reactor.callLater(self.lineRate, self._sendLine) else: self.sendDelay = self.lineRate |
if self.sourceFiles: sourceFiles = string.join(self.sourceFiles, ' ') else: sourceFiles = '' self.ctcpMakeReply(nick, [('SOURCE', "%s:%s:%s" % (self.sourceHost, self.sourceDir, sourceFiles, )), ('SOURCE', None) ]) | self.ctcpMakeReply(nick, [('SOURCE', self.sourceURL), ('SOURCE', None)]) | def ctcpQuery_SOURCE(self, user, channel, data): if data is not None: self.quirkyMessage("Why did %s send '%s' with a SOURCE query?" % (user, data)) if self.sourceHost: nick = string.split(user,"!")[0] if self.sourceFiles: sourceFiles = string.join(self.sourceFiles, ' ') else: sourceFiles = '' self.ctcpMakeReply(nick, ... |
self.queue = [] | self._queue = [] | def connectionMade(self): self.queue = [] if self.performLogin: self.register(self.nickname) |
f.protocol = protocol.Protocol | f.protocol = NoopProtocol f.protocol.master = self self.serverConns = [] | def setUp(self): PortCleanerUpper.setUp(self) f = protocol.ServerFactory() f.protocol = protocol.Protocol self.listener = reactor.listenTCP(0, f, interface="127.0.0.1") self.ports.append(self.listener) self.clientF = f = protocol.ClientFactory() f.protocol = ConnectionLosingProtocol f.protocol.master = self def conne... |
selectable = selectables[fd] | try: selectable = selectables[fd] except KeyError: continue | def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log, POLLIN=select.POLLIN, POLLOUT=select.POLLOUT): """Poll the poller for new events.""" if timeout is not None: timeout = int(timeout * 1000) # convert seconds to milliseconds |
os.rename(testdir, os.path.abspath("_trial_temp_old%s" % random.randint(0, 99999999))) | print "caught OSError [Errno %s]: %s: could not remove path %s" % (e.errno,e.strerror,e.filename) try: os.rename(testdir, os.path.abspath("_trial_temp_old%s" % random.randint(0, 99999999))) except OSError, e: print "caught OSError [Errno %s]: %s: could not rename path %s" % (e.errno,e.strerror,e.filename) raise | def _setUpTestdir(): testdir = os.path.abspath("_trial_temp") if os.path.exists(testdir): try: shutil.rmtree(testdir) except OSError, e: # XXX Left-over debug print? This is a pretty-dodgy exception handler, # overall. Also, this block is also incorrectly indented. os.rename(testdir, os.path.abspath("_trial_temp_old%... |
result = apply(func, args, kw) | result = func(*args, **kw) | def _no_log_output(func, *args, **kw): io = StringIO.StringIO() old = sys.stdout sys.stdout = io try: result = apply(func, args, kw) return result, io.getvalue() finally: sys.stdout = old |
result = apply(func, args, kw) | result = func(*args, **kw) | def _log_output(func, *args, **kw): io = Output() logOwner.own(io) try: result = apply(func, args, kw) return result, io.getvalue() finally: logOwner.disown(io) |
return apply([_no_log_output, _log_output] [isinstance(sys.stdout, Log)], (func,)+args,kw) | if isinstance(sys.stdout, Log): return _log_output(func, *args, **kw) return _no_log_output(func, *args, **kw) | def output(func, *args, **kw): return apply([_no_log_output, _log_output] [isinstance(sys.stdout, Log)], (func,)+args,kw) |
x = self.owners.pop() assert x is owner, "Bad disown" | if self.owners: x = self.owners.pop() if x is not owner: warnings.warn("Bad disown: %r is not %r" % (x, owner)) else: warnings.warn("Bad disown: %r, owner stack is empty" % (owner,)) | def disown(self, owner): """Remove an object as owner of the log.""" if owner is not None: x = self.owners.pop() assert x is owner, "Bad disown" |
owners = self.ownersPerThread.get(i,[]) owners.append(owner) self.ownersPerThread[i] = owners | self.ownersPerThread.setdefault(i, []).append(owner) | def own(self, owner): """Set an object as owner of the log.""" if owner is not None: i = self.threadId() owners = self.ownersPerThread.get(i,[]) owners.append(owner) self.ownersPerThread[i] = owners |
apply(real_msg, stuff) | real_msg(*stuff) | def _threaded_msg(*stuff): loglock.acquire() apply(real_msg, stuff) loglock.release() |
try: util.untilConcludes(self.w.send, 'x') except OSError, e: if e.errno != errno.EAGAIN: raise | self.w.send('x') | def wakeUp(self): """Send a byte to my connection. """ try: util.untilConcludes(self.w.send, 'x') except OSError, e: if e.errno != errno.EAGAIN: raise |
try: util.untilConcludes(os.write, self.o, 'x') except OSError, e: if e.errno != errno.EAGAIN: raise | util.untilConcludes(os.write, self.o, 'x') | def wakeUp(self): """Write one byte to the pipe, and flush it. """ if self.o is not None: try: util.untilConcludes(os.write, self.o, 'x') except OSError, e: if e.errno != errno.EAGAIN: raise |
text=string.replace(text,'&','&') | def dehtml(text): text=string.replace(text,"<br>","\n") text=string.replace(text,"<BR>","\n") text=string.replace(text,"<Br>","\n") # XXX make this a regexp text=string.replace(text,"<bR>","\n") text=re.sub('<.*?>','',text) text=string.replace(text,'>','>') text=string.replace(text,'<','<') text=string.replace(te... | |
text=string.replace(text,'&','&') text=string.replace(text,'<','<') text=string.replace(text,'>','>') | text=string.replace(text,'&','&') text=string.replace(text,'<','<') text=string.replace(text,'>','>') | def html(text): text=string.replace(text,'"','"') text=string.replace(text,'&','&') text=string.replace(text,'<','<') text=string.replace(text,'>','>') text=string.replace(text,"\n","<br>") return '<html><body bgcolor="white"><font color="black">%s</font></body></html>'%text |
app = Application("pb-test") ident = identity.Identity("guest", app) | auth = authorizer.DefaultAuthorizer() appl = Application("pb-test") auth.setApplication(appl) ident = identity.Identity("guest", authorizer=auth) | def connectedServerAndClient(): """Returns a 3-tuple: (client, server, pump) """ c = pb.Broker() app = Application("pb-test") ident = identity.Identity("guest", app) ident.setPassword("guest") svc = DummyService("test", app) ident.addKeyForPerspective(svc.getPerspectiveNamed("any")) app.authorizer.addIdentity(ident) sv... |
svc = DummyService("test", app) | svc = DummyService("test", appl, authorizer=auth) | def connectedServerAndClient(): """Returns a 3-tuple: (client, server, pump) """ c = pb.Broker() app = Application("pb-test") ident = identity.Identity("guest", app) ident.setPassword("guest") svc = DummyService("test", app) ident.addKeyForPerspective(svc.getPerspectiveNamed("any")) app.authorizer.addIdentity(ident) sv... |
app.authorizer.addIdentity(ident) svr = pb.BrokerFactory(pb.AuthRoot(app)) | auth.addIdentity(ident) svr = pb.BrokerFactory(pb.AuthRoot(auth)) | def connectedServerAndClient(): """Returns a 3-tuple: (client, server, pump) """ c = pb.Broker() app = Application("pb-test") ident = identity.Identity("guest", app) ident.setPassword("guest") svc = DummyService("test", app) ident.addKeyForPerspective(svc.getPerspectiveNamed("any")) app.authorizer.addIdentity(ident) sv... |
self._connected = False | def __init__(self, port, proto, interface='', maxPacketSize=8192, reactor=None): """Initialize with a numeric port to listen on. """ assert isinstance(proto, protocol.DatagramProtocol) base.BasePort.__init__(self, reactor) self.port = port self.protocol = proto self.maxPacketSize = maxPacketSize self.interface = interf... | |
pass | if self._connectedAddr: self.protocol.connectionRefused() | def doRead(self): """Called when my socket is ready for reading.""" read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data, addr) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if ... |
if self._connected: | if self._connectedAddr: | def write(self, datagram, addr=None): """Write a datagram. |
if self._connected: | if self._connectedAddr: | def connect(self, host, port): """'Connect' to remote server.""" if self._connected: raise RuntimeError, "already connected, reconnecting is not currently supported" if not abstract.isIPAddress(host): raise ValueError, "please pass only IP addresses, not domain names" self._connected = True self._connectedAddr = (host,... |
self._connected = True | def connect(self, host, port): """'Connect' to remote server.""" if self._connected: raise RuntimeError, "already connected, reconnecting is not currently supported" if not abstract.isIPAddress(host): raise ValueError, "please pass only IP addresses, not domain names" self._connected = True self._connectedAddr = (host,... | |
elif se.args[0] in (EWOULDBLOCK, EINVAL, EINPROGRESS, EALREADY): | elif ((se.args[0] in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (se.args[0] == EINVAL and platform.getType() == "win32")): | def doConnect(self): """I connect the socket. |
@returns: an object that satisfies the IListeningPort interface @raise CannotListenError: as defined in twisted.internet.error, if it cannot listen on this port (e.g., it cannot bind to the required port number) | @param port: a port number on which to listen @param factory: a twisted.internet.protocol.ServerFactory instance @param backlog: size of the listen queue @param interface: the hostname to bind to, defaults to '' (all) @returns: an object that satisfies the IListeningPort interface @raise CannotListenError: as defi... | def listenTCP(self, port, factory, backlog=5, interface=''): """Connects a given protocol factory to the given numeric TCP/IP port. |
self.controller = self | if self.controller is None: self.controller = self | def __init__(self, model = None): Resource.__init__(self) View.__init__(self, model) self.controller = self self.model = model self.templateMethods = MethodLookup() self.setTemplateMethods( self.getTemplateMethods() ) self.outstandingCallbacks = 0 |
fname = os.path.splitext(href) node.setAttribute("href", fname[0] + ext) | fname, fext = os.path.splitext(href) fext = fext.replace('.html', ext) node.setAttribute("href", fname + fext) | def fixLinks(document, ext): for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") if '/' not in href: if href.endswith('.html') or href[:href.rfind('#')].endswith('.html'): fname = os.path.splitext(href) node.setAttribute("href", fname[0] + ext) |
or \"ircname\". | or \"ircname\". May be C{None}. @ivar username: Supplied to the server during login as the \"User name\". May be C{None} | def channelMode(self, user, channel, mode, *args): """ Send information about the mode of a channel. |
self.sendLine("USER %s foo bar :%s" % (nickname, self.realname)) | if self.username is None: self.username = nickname self.sendLine("USER %s foo bar :%s" % (self.username, self.realname)) | def register(self, nickname, hostname='foo', servername='bar'): if self.password is not None: self.sendLine("PASS %s" % self.password) self.setNick(nickname) self.sendLine("USER %s foo bar :%s" % (nickname, self.realname)) |
pdb.run("application.run(%d)" % (not config.opts['no_save'])) | pdb.run("application.run(%d)" % (not config.opts['no_save']), globals(), locals()) | def callMeAgain(self): reactor.callLater(0.1, self.callMeAgain) |
_1_RESPONSES = ('CAPABILITY', 'LIST', 'LSUB', 'STATUS', 'SEARCH') _2_RESPONSES = ('EXISTS', 'EXPUNGE', 'FETCH') | _1_RESPONSES = ('CAPABILITY', 'FLAGS', 'LIST', 'LSUB', 'STATUS', 'SEARCH') _2_RESPONSES = ('EXISTS', 'EXPUNGE', 'FETCH', 'RECENT') | def maybeDeferred(obj, cb, eb, cbArgs, ebArgs): if isinstance(obj, defer.Deferred): obj.addCallbacks(cb, eb, callbackArgs=cbArgs, errbackArgs=ebArgs) else: cb(obj, *cbArgs) |
def __init__(self, model): view.View.__init__(self, model) | def __init__(self, model, *args, **kwargs): view.View.__init__(self, model, *args, **kwargs) | def __init__(self, model): view.View.__init__(self, model) self.model.addView(self) # pretend self.foo is what the user now sees on their screen self.foo = self.model.foo self.random = self.model.random |
_res = getattr(res, fn)(*args, **kwargs) res = _res is None and res or _res | if fn == '__getitem__' and isinstance(res, list) and isinstance(args[0], types.SliceType): res = res[args[0].start:args[0].stop] else: _res = getattr(res, fn)(*args, **kwargs) res = _res is None and res or _res | def __call__(self, res): for fn, args, kwargs in self.callstack: if isinstance(fn, Recipe): res = fn(res) else: _res = getattr(res, fn)(*args, **kwargs) res = _res is None and res or _res return res |
if collection is not None: | configurator = coil.getConfigurator(entity) if collection or configurator: | def displayTreeElement(self, write, inName, inPath, collection, indentLevel=0): subIndent = indentLevel + 1 for name, entity in collection.listStaticEntities(): collection = coil.getCollection(entity) if collection is not None: write('%s + <a href="%s/%s">%s</a> <br>' % (indentLevel * ' ', inPath, name, name)) sel... |
self.displayTreeElement(write, name, '%s/%s' % (inPath, name), collection, subIndent) | if collection: self.displayTreeElement(write, name, '%s/%s' % (inPath, name), collection, subIndent) | def displayTreeElement(self, write, inName, inPath, collection, indentLevel=0): subIndent = indentLevel + 1 for name, entity in collection.listStaticEntities(): collection = coil.getCollection(entity) if collection is not None: write('%s + <a href="%s/%s">%s</a> <br>' % (indentLevel * ' ', inPath, name, name)) sel... |
isLeaf = 1 | def wmfactory_form(self, request): if self.formModel: return self.formModel else: return guard.newLoginSignature.method(None) | |
isLeaf = 1 | def wchild_stuff(self, request): return self | |
self.write('') | if len(self.client.buf)>1: b = self.client.buf[1:] self.client.buf = '' self.write(b) | def channelOpen(self, specificData): log.msg('opened forwarding channel %s' % self.id) self.write('') # send the buffer |
self.channel.write(data) | if self.buf: self.buf += data else: self.channel.write(data) | def dataReceived(self, data): self.channel.write(data) |
return "<DelayedCall [%ds] called=%s cancelled=%s %s%s>" % (self.time - time(), self.called, self.cancelled, func, reflect.safe_repr(self.args)) | return "<DelayedCall %s [%ss] called=%s cancelled=%s %s%s>" % ( id(self), self.time - time(), self.called, self.cancelled, func, reflect.safe_repr(self.args)) | def __str__(self): try: func = self.func.func_name try: func = self.func.im_class.__name__ + '.' + func except: func = self.func if hasattr(func, 'func_code'): func = func.func_code # func_code's repr sometimes has more useful info except: func = reflect.safe_repr(self.func) return "<DelayedCall [%ds] called=%s cancell... |
_implList = [IReactorCore, IReactorTime, IReactorPluggableResolver] if platform.supportsThreads(): _implList.append(IReactorThreads) implements(*_implList) del _implList | implements(IReactorCore, IReactorTime, IReactorPluggableResolver) | def getHostByName(self, name, timeout = (1, 3, 11, 45)): try: address = socket.gethostbyname(name) except socket.error: msg = "address %r not found" % (name,) err = error.DNSLookupError(msg) return defer.fail(err) else: return defer.succeed(address) |
reactor.callLater(0.1, self.stop) reactor.run() reactor.callLater(0.1, self.stop) reactor.run() | reactor.callLater(0.1, self.crash) reactor.run() reactor.callLater(0.1, self.crash) reactor.run() | def testRun(self): """Test that reactor.stop terminates reactor.run""" reactor.callLater(0.1, self.stop) reactor.run() # returns once .stop is called reactor.callLater(0.1, self.stop) reactor.run() # returns once .stop is called |
t = reactor.callLater(10, self.stop) | t = reactor.callLater(10, self.crash) | def testIterate(self): """Test that reactor.iterate(0) doesn't block""" start = time.time() # twisted timers are distinct from the underlying event loop's # timers, so this fail-safe probably won't keep a failure from # hanging the test t = reactor.callLater(10, self.stop) reactor.iterate(0) # shouldn't block stop = ti... |
def testStop(self): """reactor.stop should fire shutdown triggers""" self.counter = 0 self.problem = 0 self.addTrigger("before", "shutdown", self.count) self.addTimer(0.1, self.stop) t = self.addTimer(5, self.timeout) reactor.run() self.failUnless(self.counter == 1, "reactor.stop didn't invoke shutdown triggers") self... | def testStop(self): """reactor.stop should fire shutdown triggers""" # make sure shutdown triggers are run when the reactor is stopped self.counter = 0 self.problem = 0 self.addTrigger("before", "shutdown", self.count) self.addTimer(0.1, self.stop) t = self.addTimer(5, self.timeout) reactor.run() self.failUnless(self.c... | |
self.protocol.makeConnection(self) | def __init__(self, protocol, deviceNameOrPortNumber, reactor, baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE, stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0): self._serial = serial.Serial(deviceNameOrPortNumber, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=None, xonxoff... | |
newNode = self.getPattern('item') | newNode = self.getPattern('item', _RAISE) | def generateDOM(self, request, node): node = Widget.generateDOM(self, request, node) domhelpers.clearNode(node) if self.end: listSize = self.end - self.start if listSize > len(self.getData()): listSize = len(self.getData()) else: listSize = len(self.getData()) for itemNum in range(listSize): if itemNum % self.columns ... |
if not newNode.getAttribute("view"): newNode.setAttribute("view", "DefaultWidget") | def generateDOM(self, request, node): node = Widget.generateDOM(self, request, node) domhelpers.clearNode(node) if self.end: listSize = self.end - self.start if listSize > len(self.getData()): listSize = len(self.getData()) else: listSize = len(self.getData()) for itemNum in range(listSize): if itemNum % self.columns ... | |
class WhatchuTalkinBoutWillisError(Exception): | class ArgumentError(Exception): | def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self) |
except WhatchuTalkinBoutWillisError: | except ArgumentError: | def _handleFile(self, filename): m = None if osp.isfile(filename): try: mname = reflect.filenameToModuleName(filename) self._tryNamedAny(mname) except WhatchuTalkinBoutWillisError: # okay, not in PYTHONPATH... path, fullname = osp.split(filename) name, ext = osp.splitext(fullname) m = new.module(name) sourcestring = fi... |
raise WhatchuTalkinBoutWillisError | raise ArgumentError | def _tryNamedAny(self, arg): try: n = reflect.namedAny(arg) except ValueError: raise WhatchuTalkinBoutWillisError except: f = failure.Failure() f.printTraceback() self['_couldNotImport'][arg] = f return |
raise WhatchuTalkinBoutWillisError, "could not figure out how to use %s" % arg | raise ArgumentError, "could not figure out how to use %s" % arg | def _tryNamedAny(self, arg): try: n = reflect.namedAny(arg) except ValueError: raise WhatchuTalkinBoutWillisError except: f = failure.Failure() f.printTraceback() self['_couldNotImport'][arg] = f return |
except WhatchuTalkinBoutWillisError: | except ArgumentError: | def _dbg(msg): if self._logObserver is not None: log.msg(iface=ITrialDebug, parseargs=msg) |
print "can't figure out what to do with argument %r, continuing" % (arg,) continue | raise ArgumentError, ("argument %r appears to be " "invalid, rather than doing something incredibly stupid, " "I'm blowing up" % (arg,)) | def _dbg(msg): if self._logObserver is not None: log.msg(iface=ITrialDebug, parseargs=msg) |
if hasattr(ob, '__class__'): fixClassImplements(ob.__class__) | def _hook(iface, ob, lookup=globalRegistry.lookup1): # FIXME: Workaround zope.interface bug: # Once you look up something in AdapterRegistry, # any further 'classProvides(Only)' statements will not work. # Until this is fixed, make *sure* fixClassImplements was # called before looking anything up in AdapterRegistry. # ... | |
def __init__(self): | def __init__(self, homeDir): | def __init__(self): avatar.ConchUser.__init__(self) self.channelLookup['session'] = session.SSHSession self.subsystemLookup['sftp'] = filetransfer.FileTransferServer |
return os.path.join(os.getcwd(), 'sftp_test') | return os.path.join(os.getcwd(), self.homeDir) | def getHomeDir(self): return os.path.join(os.getcwd(), 'sftp_test') |
try: os.mkdir('sftp_test') except OSError, e: if e.args[0] == 17: pass try: os.mkdir('sftp_test/testDirectory') except OSError, e: if e.args[0] == 17: pass f=file('sftp_test/testfile1','w') | self.test_dir = self.mktemp() os.makedirs(os.path.join(self.test_dir, 'testDirectory')) f = file(os.path.join(self.test_dir, 'testfile1'),'w') | def setUp(self): try: os.mkdir('sftp_test') except OSError, e: if e.args[0] == 17: pass try: os.mkdir('sftp_test/testDirectory') except OSError, e: if e.args[0] == 17: pass |
os.chmod('sftp_test/testfile1', 0644) file('sftp_test/testRemoveFile', 'w').write('a') file('sftp_test/testRenameFile', 'w').write('a') file('sftp_test/.testHiddenFile', 'w').write('a') def tearDown(self): for f in ['testfile1', 'testRemoveFile', 'testRenameFile', 'testRenamedFile', 'testLink', 'testfile2', '.testHid... | os.chmod(os.path.join(self.test_dir, 'testfile1'), 0644) file(os.path.join(self.test_dir, 'testRemoveFile'), 'w').write('a') file(os.path.join(self.test_dir, 'testRenameFile'), 'w').write('a') file(os.path.join(self.test_dir, '.testHiddenFile'), 'w').write('a') | def setUp(self): try: os.mkdir('sftp_test') except OSError, e: if e.args[0] == 17: pass try: os.mkdir('sftp_test/testDirectory') except OSError, e: if e.args[0] == 17: pass |
self.avatar = FileTransferTestAvatar() | SFTPTestBase.setUp(self) self.avatar = FileTransferTestAvatar(self.test_dir) | def setUp(self): self.avatar = FileTransferTestAvatar() self.server = filetransfer.FileTransferServer(avatar=self.avatar) clientTransport = loopback.LoopbackRelay(self.server) |
SFTPTestBase.setUp(self) | def _(serverVersion, extData): self._serverVersion = serverVersion self._extData = extData |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.