rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
digest.appendChild(microdom.Text(cgi.escape(self.getResource()))) self.sendIQ(type='set', query=query).addCallbackAndError(
resource.appendChild(microdom.Text(cgi.escape(self.getResource()))) query.appendChild(username) query.appendChild(digest) query.appendChild(resource) self.sendIQ(type='set', from_=None, to=None, query=query)[1].addCallbacks(
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...
def loginSuccess(self): raise NotImplementedError def loginFailure(self):
def loginSuccess(self, arg): raise NotImplementedError def loginFailure(self, arg):
def loginSuccess(self): raise NotImplementedError
if se.args[0] == 0:
if se.args[0] in (0, 2):
def doSelect(timeout, # Since this loop should really be as fast as possible, # I'm caching these global attributes so the interpreter # will hit them in the local namespace. reads=reads, writes=writes, rhk=reads.has_key, whk=writes.has_key): """Run one iteration of the I/O monitor loop. This will run all selectables ...
default), or whose errback is invoked if there is an error.
default), to additional information, or whose errback is invoked if there is an error.
def fetchMessage(self, messages, uid=0): """Retrieve one or more entire messages
self.sendFlap(2,"toc_set_caps %s" % (SEND_FILE_UID,)
self.sendFlap(2,"toc_set_caps %s" % (SEND_FILE_UID,))
def signon(self): """ called to finish the setup, and signon to the network """ self.sendFlap(2,"toc_init_done") self.sendFlap(2,"toc_set_caps %s" % (SEND_FILE_UID,) # GET_FILE_UID))
signal.signal(signal.SIGINT, shutDown) signal.signal(signal.SIGTERM, shutDown) if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, shutDown) if platform.getType() == 'posix': signal.signal(signal.SIGCHLD, process.reapProcess)
handleSignals()
def run(installSignalHandlers=1): """Run input/output and dispatched/delayed code. This call never returns. It is the main loop which runs delayed timers (see twisted.python.delay and addDelayed), and the I/O monitor (doSelect). """ global running running = 1 threadable.registerAsIOThread() if installSignalHandlers: ...
firstLine = '%s %s HTTP/%' %(
firstLine = '%s %s HTTP/%s' %(
def emit(self, eventDict): if eventDict.get('interface') is not iweb.IRequest: return
def _callProtocolWithDeferred(protocol, executable, args=(), env={}, path='.'):
def _callProtocolWithDeferred(protocol, executable, args, env, path, reactor):
def _callProtocolWithDeferred(protocol, executable, args=(), env={}, path='.'): d = defer.Deferred() p = protocol(d) reactor.spawnProcess(p, executable, (executable,)+args, env, path) return d
def lookupSubmodel(name): """Get a submodel out of this model by name. """ def setSubmodel(name, value): """Set the named submodel on this model to the given value. """ def getData(): """ @return: The actual data (or a L{twisted.internet.defer.Deferred} resulting in the actual data) represented by this Model, if this...
def lookupSubmodel(name): """Get a submodel out of this model by name. """
['verbose', 'v', 'verbose color output (default)'],
['verbose', 'v', 'verbose color output'],
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
['text', 't', 'terse text output'],
['text', 't', 'terse text output (default reporter)'],
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
fallbackReporter = reporter.TreeReporter
fallbackReporter = reporter.VerboseTextReporter
def remove(self): if self in log.theLogPublisher.observers: log.removeObserver(self)
mname = reflect.filenameToModuleName(arg) _dbg("modulename: %s" % (mname,)) if mname: self['modules'].append(mname) continue
_dbg("osp.exists, appending '%s' to self['modules']" % (modstr,)) self['modules'].append(mod) continue
def _dbg(msg): if self._logObserver is not None: log.msg(iface=ITrialDebug, parseargs=msg)
raise SystemExit, "testing"
def run(): _monkeyPatchPyunit() if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error, ue: raise SystemExit, "%s: %s" % (sys.argv[0], ue) _setUpAdapters() _initialDebugSetup(config) suite = _getSuite(config) _setUpTestdir() _setUpLogging(config) raise Sys...
return self.hosts.get(host, error.NoResource())
return self.hosts.get(host, error.NoResource("host %s not in vhost map" % repr(host)))
def _getResourceForRequest(self, request): """(Internal) Get the appropriate resource for the given host. """ host = string.lower(request.getHeader('host')) return self.hosts.get(host, error.NoResource())
"""Call a function from within another (i.e. non-reactor) thread.
"""Cause a function to be executed by the reactor thread.
def callFromThread(callable, *args, **kw): """Call a function from within another (i.e. non-reactor) thread.
self.protocol.processEnded(failure.Failure(error.ProcessEnded(exitCode)))
if exitCode == 0: err = error.ProcessDone() else: err = error.ProcessTerminated(exitCode) self.protocol.processEnded(failure.Failure(err))
def connectionLost(self, reason=None): """Shut down resources.""" exitCode = win32process.GetExitCodeProcess(self.hProcess) self.reactor.removeEvent(self.hProcess) abstract.FileDescriptor.connectionLost(self, reason) self.protocol.processEnded(failure.Failure(error.ProcessEnded(exitCode)))
print 'Entering state_' + self.state[-1] + ' with', repr(s)
def parseString(self, s): s = self.remaining + s try: while s or self.state: print 'Entering state_' + self.state[-1] + ' with', repr(s) state = self.state.pop() try: s = s[getattr(self, 'state_' + state)(s):] except: self.state.append(state) raise finally: self.remaining = s
self.assertEquals(p.outF.getvalue(), "hello, worldabc123")
self.assertEquals(p.outF.getvalue(), "hello, worldabc123", p.errF.getvalue())
def testStdio(self): """twisted.internet.stdio test.""" exe = sys.executable scriptPath = util.sibpath(__file__, "process_twisted.py") p = Accumulator() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], None, None) p.transport.write("hello, world") p.transport.write("abc") p.transport.write("123") p.transport.close...
class OldCircularReferenceTestCase(test_newjelly.CircularReferenceTestCase):
class CircularReferenceTestCase(test_newjelly.CircularReferenceTestCase):
def persistentLoad(pidstr, unj, perst = perst): pid = int(pidstr) return perst[0][pid]
testCases = [OldJellyTestCase, OldCircularReferenceTestCase]
testCases = [JellyTestCase, CircularReferenceTestCase]
def persistentLoad(pidstr, unj, perst = perst): pid = int(pidstr) return perst[0][pid]
@intervals: The intervals between instants.
@param intervals: The intervals between instants.
def __init__(self, intervals, default=60): """ @type intervals: C{list} of C{int}, C{long}, or C{float} param @intervals: The intervals between instants.
def connectionFailed(self): log.msg("Connection Failed! %s" % self) self.stopKeepAlive()
def connectionFailed(self): log.msg("Connection Failed! %s" % self) self.stopKeepAlive()
c = serviceClasses[service](self, cookie, d) reactor.clientTCP(ip, 5190, c) self.services[service] = c
c = protocol.ClientCreator(reactor, serviceClasses[service], self, cookie, d) def addService(x): self.services[service] = x c.connectTCP(ip, 5190).addCallback(addService)
def oscar_01_05(self, snac, d = None): """ data for a new service connection d might be a deferred to be called back when the service is ready """ tlvs = readTLVs(snac[3][2:]) service = struct.unpack('!H',tlvs[0x0d])[0] ip = tlvs[5] cookie = tlvs[6] c = serviceClasses[service](self, cookie, d) reactor.clientTCP(ip, 519...
def connectionLost(self, reason): for k,v in self.bos.services.items(): if v == self: del self.bos.services[k] SNACBased.connectionLost(self, reason) def connectionFailed(self): for k,v in self.bos.services.items(): if v == self: del self.bos.services[k] SNACBased.connectionFailed(self)
def connectionLost(self, reason): for k,v in self.bos.services.items(): if v == self: del self.bos.services[k] SNACBased.connectionLost(self, reason)
bos=self.BOSClass(self.username,self.cookie) if self.deferred: self.deferred.callback(bos) reactor.clientTCP(server,int(port),bos)
c = protocol.ClientCreator(reactor, self.BOSClass, self.username, self.cookie) d = c.connectTCP(server, int(port)) d.addErrback(lambda x: log.msg("Connection Failed! Reason: %s" % x)) d.chainDeferred(self.deferred)
def oscar_Cookie(self,data): snac=readSNAC(data[1]) if self.icq: i=snac[5].find("\000") snac[5]=snac[5][i:] tlvs=readTLVs(snac[5]) if tlvs.has_key(6): self.cookie=tlvs[6] server,port=string.split(tlvs[5],":") bos=self.BOSClass(self.username,self.cookie) if self.deferred: self.deferred.callback(bos) reactor.clientTCP(se...
'unkown class %s' %element.getAttribute('class'))
'unknown class %s' %element.getAttribute('class'))
def matcher(element, self=self): if not self.allowedClasses.has_key(element.tagName): return 0 if not element.hasAttribute('class'): return 0 checker = self.allowedClasses[element.tagName] return not checker(element.getAttribute('class'))
Binray, Boolean, DateTime, Deferreds, or Handler instances.
Binary, Boolean, DateTime, Deferreds, or Handler instances.
def run(self, *args): # event driven equivalent of 'raise UnimplementedError' self.result.errback(NotImplementedError("Implement run() in subclasses"))
mutable = [None]
_mutable = [None]
def retrieve(self, command, protocol): """Retrieves a file or listing generated by the given command, feeding it to the given protocol.
self=self, mutable=mutable, protocol=protocol):
self=self, mutable=_mutable, protocol=protocol):
def doPassive(response, self=self, mutable=mutable, protocol=protocol): """Connect to the port specified in the response to PASV""" line = response[-1]
cmd.deferred.addCallbacks(lambda result, mutable=mutable: mutable[0].loseConnection() or result, lambda result: mutable[0].loseConnection())
cmd.deferred.addCallbacks( lambda result, mutable=_mutable: mutable[0].loseConnection() or result, lambda result, mutable=_mutable: mutable[0].loseConnection())
abcdef = re.sub('[^0-9, ]', '', line[4:])
Mailbox
IMailbox
def authenticateUserPASS(self, user, password): """Perform authentication of a username/password login. @type user: C{str} @param user: The name of the user attempting to log in. @type password: C{str} @param password: The password to attempt to authenticate with. @rtype: C{Deferred} @return: A deferred whose callba...
d.addCallback(self._resultCallback) t = reactor.callLater(1, self._timeout) while not self.done: reactor.iterate() self.failUnless(self.gotResult, "timeout") if t.active(): t.cancel()
return d.addCallback(self.assertEquals, 7)
def testDeferredResult(self): d = threads.deferToThread(lambda x, y=5: x + y, 3, y=4) d.addCallback(self._resultCallback) t = reactor.callLater(1, self._timeout) while not self.done: reactor.iterate() self.failUnless(self.gotResult, "timeout") if t.active(): t.cancel()
def raiseError(): raise TypeError
class NewError(Exception): pass def raiseError(): raise NewError
def raiseError(): raise TypeError
d.addErrback(self._resultErrback) t = reactor.callLater(1, self._timeout) while not self.done: reactor.iterate() self.failUnless(self.gotResult, "timeout") if t.active(): t.cancel()
return assertions.assertFailure(d, NewError)
def raiseError(): raise TypeError
def _updateRegisteration(self, fd):
def _updateRegistration(self, fd):
def _updateRegisteration(self, fd): """Register/unregister an fd with the poller.""" try: poller.unregister(fd) except KeyError: pass
self._updateRegisteration(fd)
self._updateRegistration(fd)
def _dictRemove(self, selectable, mdict): try: # the easy way fd = reader.fileno() except: # the hard way: necessary because fileno() may disappear at any # moment, thanks to python's underlying sockets impl for fd, fdes in selectables.items(): if selectable is fdes: break else: # Hmm, maybe not the right course of act...
self._updateRegisteration(fd)
self._updateRegistration(fd)
def addReader(self, reader): """Add a FileDescriptor for notification of data available to read. """ fd = reader.fileno() if not reads.has_key(fd): selectables[fd] = reader reads[fd] = 1 self._updateRegisteration(fd)
self._updateRegisteration(fd)
self._updateRegistration(fd)
def addWriter(self, writer, writes=writes, selectables=selectables): """Add a FileDescriptor for notification of data available to write. """ fd = writer.fileno() if not writes.has_key(fd): selectables[fd] = writer writes[fd] = 1 self._updateRegisteration(fd)
def makeService(mod, s, options):
def makeService(mod, options):
def makeService(mod, s, options): if hasattr(mod, 'updateApplication'): ser = service.MultiService() mod.updateApplication(compat.IOldApplication(ser), options) else: ser = mod.makeService(options) return ser
a = service.Application(append, uid, gid)
a = service.Application(name, uid, gid)
def addToApplication(ser, name, append, procname, type, encrypted, uid, gid): if append and os.path.exists(append): a = service.loadApplication(append, 'pickle', None) else: a = service.Application(append, uid, gid) if procname: service.IProcess(a).processName = procname ser.setServiceParent(service.IServiceCollection(...
text = escapingRE.sub(lambda x: (x.group()=='\\' and '$\\backslash$') or (x.group()=='~' and '\\~{}') or '\\'+x.group(), text)
text = escapingRE.sub(_escapeMatch, text)
def latexEscape(text): text = escapingRE.sub(lambda x: (x.group()=='\\' and '$\\backslash$') or (x.group()=='~' and '\\~{}') or '\\'+x.group(), text) return text.replace('\n', ' ')
0: {'RFC822': 'Header: Value\r\nBODY TEXT\r\n'}
0: {'RFC822': 'Header: Value\r\n\r\nBODY TEXT\r\n'}
def testFetchMessage(self, uid=0): self.function = self.client.fetchMessage self.messages = '1,3,7,10101' self.msgObjs = [ FakeyMessage({'Header': 'Value'}, (), '', 'BODY TEXT\r\n', 91, None), ] self.expected = { 0: {'RFC822': 'Header: Value\r\nBODY TEXT\r\n'} } self._fetchWork(uid)
0: {'RFC822.HEADER': imap4._formatHeaders({'H1': 'V1', 'H2': 'V2'}) + '\r\n'},
0: {'RFC822.HEADER': imap4._formatHeaders({'H1': 'V1', 'H2': 'V2'})},
def testFetchHeaders(self, uid=0): self.function = self.client.fetchHeaders self.messages = '9,6,2' self.msgObjs = [ FakeyMessage({'H1': 'V1', 'H2': 'V2'}, (), '', '', 99, None), ] self.expected = { 0: {'RFC822.HEADER': imap4._formatHeaders({'H1': 'V1', 'H2': 'V2'}) + '\r\n'}, } self._fetchWork(uid)
method = getattr(self, 'handle_'+self.command, self.handle_default) method(line)
self._dispatch(self.command, self.handle_default, line)
def lineReceived(self, line): if self.mode == SHORT or self.mode == FIRST_LONG: self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command, self.handle_default) method(line) elif self.mode == LONG: if line == '.': self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command+'_end', None) if ...
method = getattr(self, 'handle_'+self.command+'_end', None) if method is not None: method()
self._dispatch(self.command+'_end', None)
def lineReceived(self, line): if self.mode == SHORT or self.mode == FIRST_LONG: self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command, self.handle_default) method(line) elif self.mode == LONG: if line == '.': self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command+'_end', None) if ...
method = getattr(self, 'handle_'+self.command+'_continue', None) if method is not None: method(line)
self._dispatch(self.command+"_continue", None, line)
def lineReceived(self, line): if self.mode == SHORT or self.mode == FIRST_LONG: self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command, self.handle_default) method(line) elif self.mode == LONG: if line == '.': self.mode = NEXT[self.mode] method = getattr(self, 'handle_'+self.command+'_end', None) if ...
if isinstance(obj, domish.Element):
if domish.IElement.providedBy(obj):
def send(self, obj): """ Send data over the stream.
self.type = MimeType.fromString(self.type)
self.type = http_headers.MimeType.fromString(self.type)
def __init__(self, data, type): self.data = data self.type = MimeType.fromString(self.type) self.created_time = time.time()
return MimeType.fromString(self._type)
return http_headers.MimeType.fromString(self._type)
def contentType(self): if not hasattr(self, "_type"): self._initTypeAndEncoding() return MimeType.fromString(self._type)
def do_LIST(self, subcmd = ''):
def do_LIST(self, subcmd = '', *dummy):
def do_LIST(self, subcmd = ''): subcmd = subcmd.strip().lower() if subcmd == 'newsgroups': # XXX - this could use a real implementation, eh? self.sendLine('215 Descriptions in form "group description"') self.sendLine('.') elif subcmd == 'overview.fmt': defer = self.factory.backend.overviewRequest() defer.addCallbacks(s...
html.PRE(failure.getBriefTraceback())).
html.PRE(failure)).
def failed(self, failure): self.request.write( error.ErrorPage(http.INTERNAL_SERVER_ERROR, "Server Connection Lost", "Connection to distributed server lost:" + html.PRE(failure.getBriefTraceback())). render(self.request)) self.request.finish() log.msg(failure.getBriefTraceback())
log.msg(failure.getBriefTraceback())
log.msg(failure)
def failed(self, failure): self.request.write( error.ErrorPage(http.INTERNAL_SERVER_ERROR, "Server Connection Lost", "Connection to distributed server lost:" + html.PRE(failure.getBriefTraceback())). render(self.request)) self.request.finish() log.msg(failure.getBriefTraceback())
Idiomatic usage would look like:
Idiomatic usage would look like::
def whenReady(d): """ Wrap a deferred returned from a pb method in another deferred that expects a RemotePublished as a result. This will allow you to wait until the result is really available. Idiomatic usage would look like: publish.whenReady(serverObject.getMeAPublishable()).addCallback(lookAtThePublishable) """ ...
mapStart_dl = mapStart_ul = '\\begin{description}\n' mapEnd_dl = mapEnd_ul = '\\end{description}\n'
mapStart_dl = '\\begin{description}\n' mapEnd_dl = '\\end{description}\n' mapStart_ul = '\\begin{itemize}\n' mapEnd_ul = '\\end{itemize}\n'
def visitNode_table(self, node): # All of my children should be <tr> elements numCols = 0 for child in node.childNodes: numCols = max(numCols, len(child.childNodes)) numCols += 1 self.writer('\\begin{table}[ht]\\begin{center}') self.writer('\\begin{tabular}{@{}'+'l'*numCols+'@{}}') for child in node.childNodes: th = 0 ...
mapStart_li = '\\item ' mapEnd_li = '\n'
mapStart_li = mapStart_ul = '\\item ' mapEnd_li = mapEnd_ul = '\n'
def visitNode_table(self, node): # All of my children should be <tr> elements numCols = 0 for child in node.childNodes: numCols = max(numCols, len(child.childNodes)) numCols += 1 self.writer('\\begin{table}[ht]\\begin{center}') self.writer('\\begin{tabular}{@{}'+'l'*numCols+'@{}}') for child in node.childNodes: th = 0 ...
def __init__(self):
def __init__(self, prefix="event_"): self.prefix = prefix
def __init__(self): self.callbacks = {}
reflect.accumulateMethods(obj, d, 'event_')
reflect.accumulateMethods(obj, d, self.prefix)
def autoRegister(self, obj): from twisted.python import reflect d = {} reflect.accumulateMethods(obj, d, 'event_') for k,v in d.items(): self.registerHandler(k, v)
conn = reactor.connectTCP(port.getHost().host, port.getHost().port, cf)
if H == '0.0.0.0': H = '127.0.0.1' conn = reactor.connectTCP('127.0.0.1', P, cf)
def testStartTLS(self): sf = TLSServerFactory() sf.protocol.output = [ ['+OK'], # Server greeting ['+OK', 'STLS', '.'], # CAPA response ['+OK'], # STLS response ['+OK', '.'], # Second CAPA response ['+OK'] # QUIT response ] sf.protocol.context = ServerTLSContext() port = reactor.listenTCP(0, sf)
self.account.create(args.strip())
self.account.create(name[0])
def auth_CREATE(self, tag, args): try: self.account.create(args.strip()) except MailboxCollision, c: self.sendNegativeResponse(tag, str(c)) else: self.sendPositiveResponse(tag, 'Mailbox created')
self.account.delete(args.strip())
self.account.delete(name[0])
def auth_DELETE(self, tag, args): try: self.account.delete(args.strip()) except MailboxException, m: self.sendNegativeResponse(tag, str(m)) else: self.sendPositiveResponse(tag, 'Mailbox deleted')
self.account.rename(*args.strip().split())
self.account.rename(*names)
def auth_RENAME(self, tag, args): try: self.account.rename(*args.strip().split()) except TypeError: self.sendBadResponse(tag, 'Invalid command syntax') except MailboxException, m: self.sendNegativeResponse(tag, str(m)) else: self.sendPositiveResponse(tag, 'Mailbox renamed')
self.account.subscribe(args.strip())
self.account.subscribe(name[0])
def auth_SUBSCRIBE(self, tag, args): try: self.account.subscribe(args.strip()) except MailboxError, m: self.sendNegativeResponse(tag, str(m)) else: self.sendPositiveResponse(tag, 'Subscribed')
self.account.unsubscribe(args.strip())
self.account.unsubscribe(name[0])
def auth_UNSUBSCRIBE(self, tag, args): try: self.account.unsubscribe(args.strip()) except MailboxError, m: self.sendNegativeResponse(tag, str(m)) else: self.sendPositiveResponse(tag, 'Unsubscribed')
if 2 >= len(parts) >= 3:
if 2 <= len(parts) <= 3:
def select_STORE(self, tag, args, uid=0): parts = parseNestedParens(args) if 2 >= len(parts) >= 3: messages = parseIdList(parts[0], self.mbox.getUIDNext()) mode = parts[1].upper() if len(parts) == 3: flags = parts[2] else: flags = () else: raise IllegalClientResponse, args
raise IllegalClientResponse, args
raise IllegalClientResponse, ('Wrong number of arguments', args) if uid: topPart = ~(self.mbox.getUIDValidity() << 16) messages = map(topPart.__and__, messages)
def select_STORE(self, tag, args, uid=0): parts = parseNestedParens(args) if 2 >= len(parts) >= 3: messages = parseIdList(parts[0], self.mbox.getUIDNext()) mode = parts[1].upper() if len(parts) == 3: flags = parts[2] else: flags = () else: raise IllegalClientResponse, args
reactor.iterate() reactor.iterate() reactor.iterate() self.assertEquals(f.protocol.data, "hello") self.assertEquals(f.protocol.closed, True)
d = self._delayDeferred(0.2, f.protocol) d.addCallback(lambda x : self.assertEqual(f.protocol.data, 'hello')) d.addCallback(lambda x : self.assertEqual(f.protocol.closed, True)) return d
def testNoNotification(self): client = self.client f = self.f client.transport.write("hello") w = client.transport.write client.transport.loseWriteConnection() reactor.iterate() reactor.iterate() reactor.iterate() self.assertEquals(f.protocol.data, "hello") self.assertEquals(f.protocol.closed, True)
@ivar jitter: percentage of randomness to introduce into the delay lengh
@ivar jitter: percentage of randomness to introduce into the delay length
def connectTCP(self, host, port, timeout=30, bindAddress=None): """Connect to remote host, return Deferred of resulting protocol instance.""" d = defer.Deferred() f = _InstanceFactory(self.reactor, self.protocolClass(*self.args, **self.kwargs), d) self.reactor.connectTCP(host, port, f, timeout=timeout, bindAddress=bind...
p = self.protocol(self.domain, len(self.toEmail)*2+2)
p = self.protocol(self.domain, self.nEmails*2+2)
def buildProtocol(self, addr): p = self.protocol(self.domain, len(self.toEmail)*2+2) p.factory = self return p
def _errback(self, ignored): print 'FAILED: ERRBACKED: ', ignored
def _errback(self, ignored): print 'FAILED: ERRBACKED: ', ignored
testHashedPasswords.skip = "crypt module not available"
skip = "crypt module not available"
def _errback(self, ignored): print 'FAILED: ERRBACKED: ', ignored
module = namedModule(string.join(classSplit[:-1]))
module = namedModule(string.join(classSplit[:-1], '.'))
def namedClass(name): classSplit = string.split(name, '.') module = namedModule(string.join(classSplit[:-1])) return getattr(module, classSplit[-1])
from twisted.python import components
def wchild_more(self, request): return self
def callback(model): return Here()
class ConstantResource: def __init__(self, resource): self.resource = resource def __call__(self, _): return self.resource class TemplateDirResource: def __init__(self, resource, templateDir): self.resource = resource self.templateDir = templateDir def __call__(self, model): r = self.resource(model) r.templateDir ...
def callback(model): return Here()
a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Authenticated()
c = Authenticated() c.templateDir = self.templateDir return c
def wchild_secret(self, request): a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Authenticated()
a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Another()
c = Another() c.templateDir = self.templateDir return c
def wchild_another(self, request): a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Another()
self.errback(failure.Failure(AttributeError("prcoessAnswer_%s" %
self.errback(failure.Failure(AttributeError("processAnswer_%s" %
def getAnswer(self, message): self.done = 1 self.removeAll() if not message.answers: self.errback(failure.Failure(ValueError("No answers"))) return process = getattr(self, 'processAnswer_%d' % self.type, None) if process is None: self.errback(failure.Failure(AttributeError("prcoessAnswer_%s" % self.type))) return proce...
args = args.split()
args = parseNestedParens(args)
def unauth_LOGIN(self, tag, args): args = args.split() if len(args) != 2: self.sendBadResponse(tag, 'Wrong number of arguments') else: d = self.authenticateLogin(*args) maybeDeferred(d, self._cbLogin, self._ebLogin, (tag,), (tag,))
mbox = self.account.select(args)
args = parseNestedParens(args) if len(args) != 1: raise IllegalClientResponse, args mbox = self.account.select(args[0])
def auth_SELECT(self, tag, args): mbox = self.account.select(args) if mbox is None: self.sendNegativeResponse(tag, 'No such mailbox') else: self.state = 'select'
mbox = self.account.select(args, 0)
args = parseNestedParens(args) if len(args) != 1: raise IllegalClientResponse, args mbox = self.account.select(args[0], 0)
def auth_EXAMINE(self, tag, args): mbox = self.account.select(args, 0) if mbox is None: self.sendNegativeResponse(tag, 'No such mailbox') else: self.state = 'select'
messages = parseIdList(messages)
messages = parseIdList(messages, self.mbox.getUIDNext())
def select_FETCH(self, tag, args, uid=0): parts = args.split(None, 1) if len(parts) != 2: raise IllegalClientResponse, args messages, args = parts messages = parseIdList(messages) query = parseNestedParens(args) if uid: topPart = self.mbox.getUIDValidity() << 16 messages = map(topPart.__or__, messages) d = self.mbox.fe...
for (portion, value) in parts.items(): if uid: topPart = self.mbox.getUIDValidity() << 16 value.extend(['UID', str(mId | topPart)]) self.sendUntaggedResponse( '%d %s %s' % (mId, portion, collapseNestedLists(value)) )
if parts: for (portion, value) in parts.items(): if uid: topPart = self.mbox.getUIDValidity() << 16 value.extend(['UID', str(mId | topPart)]) self.sendUntaggedResponse( '%d %s %s' % (mId, portion, collapseNestedLists(value)) )
def _cbFetch(self, results, tag, uid): for (mId, parts) in results.items(): for (portion, value) in parts.items(): if uid: topPart = self.mbox.getUIDValidity() << 16 value.extend(['UID', str(mId | topPart)]) self.sendUntaggedResponse( '%d %s %s' % (mId, portion, collapseNestedLists(value)) ) self.sendPositiveResponse(t...
messages = parseIdList(parts[0])
messages = parseIdList(parts[0], self.mbox.getUIDNext())
def select_STORE(self, tag, args, uid=0): parts = parseNestedParens(args) if 2 >= len(parts) >= 3: messages = parseIdList(parts[0]) mode = parts[1].upper() if len(parts) == 3: flags = parts[2] else: flags = () else: raise IllegalClientResponse, args
messages = parseIdList(parts[0])
messages = parseIdList(parts[0], self.mbox.getUIDNext())
def select_COPY(self, tag, args, uid=0): parts = args.split(None, 1) if len(parts) != 2: raise IllegalClientResponse, args messages = parseIdList(parts[0]) mbox = self.account.select(parts[1]) if not mbox: self.sendNegativeResponse(tag, 'No such mailbox: ' + parts[1]) else: if uid: topPart = self.mbox.getUIDValidity() ...
def parseIdList(s):
def parseIdList(s, topValue):
def parseIdList(s): res = [] parts = s.split(',') for p in parts: if ':' in p: low, high = p.split(':', 1) try: low = int(low) high = int(high) + 1 except ValueError: raise IllegalIdentifierError, p else: res.extend(range(low, high)) else: try: res.append(int(p)) except ValueError: raise IllegalIdentifierError, p retur...
high = int(high) + 1
if high == '*': high = topValue else: high = int(high) + 1
def parseIdList(s): res = [] parts = s.split(',') for p in parts: if ':' in p: low, high = p.split(':', 1) try: low = int(low) high = int(high) + 1 except ValueError: raise IllegalIdentifierError, p else: res.extend(range(low, high)) else: try: res.append(int(p)) except ValueError: raise IllegalIdentifierError, p retur...
class LimitConnectionsByPeerProtocol(ProtocolWrapper): """Stability: Unstable""" def connectionLost(self): self.factory.peerDisconnected(self) self.wrappedProtocol.connectionLost(self)
def write(self, data): log.msg("Sending: %r" % data) ProtocolWrapper.write(self,data)
protocol = LimitConnectionsByPeerProtocol
def connectionLost(self): self.factory.peerDisconnected(self) self.wrappedProtocol.connectionLost(self)
peerHost = addr[1]
peerHost = addr[0]
def buildProtocol(self, addr): peerHost = addr[1] connectionCount = self.peerConnections.get(peerHost, 0) if connectionCount >= self.maxConnectionsPerPeer: return None self.peerConnections[peerHost] = connectionCount + 1 return WrappingFactory.buildProtocol(self, addr)
if se.args[0] in (EISCONN, EALREADY):
if se.args[0] == EISCONN:
def doConnect(self): """I connect the socket.
elif se.args[0] in (EWOULDBLOCK, EINVAL, EINPROGRESS):
elif se.args[0] in (EWOULDBLOCK, EINVAL, EINPROGRESS, EALREADY):
def doConnect(self): """I connect the socket.
self.assertEquals(str(p.result[0]), 'BODY.PEEK')
self.assertEquals(str(p.result[0]), 'BODY')
def testFetchParserBody(self): P = imap4._FetchParser p = P() p.parseString('BODY') self.assertEquals(len(p.result), 1) self.failUnless(isinstance(p.result[0], p.Body)) self.assertEquals(p.result[0].peek, False) self.assertEquals(p.result[0].header, None) self.assertEquals(str(p.result[0]), 'BODY')
self.assertEquals(str(p.result[0]), 'BODY.PEEK[HEADER]')
self.assertEquals(str(p.result[0]), 'BODY[HEADER]')
def testFetchParserBody(self): P = imap4._FetchParser p = P() p.parseString('BODY') self.assertEquals(len(p.result), 1) self.failUnless(isinstance(p.result[0], p.Body)) self.assertEquals(p.result[0].peek, False) self.assertEquals(p.result[0].header, None) self.assertEquals(str(p.result[0]), 'BODY')
self.assertEquals(str(p.result[0]), 'BODY.PEEK[HEADER.FIELDS (Subject Cc Message-Id)]')
self.assertEquals(str(p.result[0]), 'BODY[HEADER.FIELDS (Subject Cc Message-Id)]')
def testFetchParserBody(self): P = imap4._FetchParser p = P() p.parseString('BODY') self.assertEquals(len(p.result), 1) self.failUnless(isinstance(p.result[0], p.Body)) self.assertEquals(p.result[0].peek, False) self.assertEquals(p.result[0].header, None) self.assertEquals(str(p.result[0]), 'BODY')
self.assertEquals(str(p.result[0]), 'BODY.PEEK[HEADER.FIELDS.NOT (Subject Cc Message-Id)]')
self.assertEquals(str(p.result[0]), 'BODY[HEADER.FIELDS.NOT (Subject Cc Message-Id)]')
def testFetchParserBody(self): P = imap4._FetchParser p = P() p.parseString('BODY') self.assertEquals(len(p.result), 1) self.failUnless(isinstance(p.result[0], p.Body)) self.assertEquals(p.result[0].peek, False) self.assertEquals(p.result[0].header, None) self.assertEquals(str(p.result[0]), 'BODY')
self.assertEquals(str(p.result[0]), 'BODY.PEEK[1.3.9.11.HEADER.FIELDS.NOT (Message-Id Date)]<103.69>')
self.assertEquals(str(p.result[0]), 'BODY[1.3.9.11.HEADER.FIELDS.NOT (Message-Id Date)]<103.69>')
def testFetchParserBody(self): P = imap4._FetchParser p = P() p.parseString('BODY') self.assertEquals(len(p.result), 1) self.failUnless(isinstance(p.result[0], p.Body)) self.assertEquals(p.result[0].peek, False) self.assertEquals(p.result[0].header, None) self.assertEquals(str(p.result[0]), 'BODY')
def _fetchWork(self, fetch, uid):
def _fetchWork(self, uid):
def _fetchWork(self, fetch, uid): if uid: for (i, msg) in zip(range(len(self.msgObjs)), self.msgObjs): self.expected[i]['UID'] = str(msg.getUID()) def result(R): self.result = R self.connected.addCallback(strip(fetch) ).addCallback(result ).addCallback(self._cbStopClient ).addErrback(self._ebGeneral) loopback.loopba...
self.connected.addCallback(strip(fetch)
self.connected.addCallback(lambda _: self.function(self.messages, uid)
def result(R): self.result = R
def fetch(): return self.client.fetchUID(self.messages)
self.function = lambda m, u: self.client.fetchUID(m)
def fetch(): return self.client.fetchUID(self.messages)
self._fetchWork(fetch, 0)
self._fetchWork(0)
def fetch(): return self.client.fetchUID(self.messages)