rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
def receiveDirectMessage(self, sender, message): | def receiveDirectMessage(self, sender, message, metadata=None): | def receiveDirectMessage(self, sender, message): """Pass this message through tendril to my IRC counterpart. """ self.tendril.msgFromWords(self.nickname, sender, message) |
sender, message) | sender, message, metadata) | def receiveDirectMessage(self, sender, message): """Pass this message through tendril to my IRC counterpart. """ self.tendril.msgFromWords(self.nickname, sender, message) |
versionNum = '$Revision: 1.13 $'[11:-2] | versionNum = '$Revision: 1.14 $'[11:-2] | def receiveDirectMessage(self, sender, message): """Pass this message through tendril to my IRC counterpart. """ self.tendril.msgFromWords(self.nickname, sender, message) |
def receiveGroupMessage(self, sender, group, message): | def receiveGroupMessage(self, sender, group, message, metadata=None): | def receiveGroupMessage(self, sender, group, message): """Pass a message from the Words group on to IRC. |
def msgFromWords(self, toNick, sender, message): | def msgFromWords(self, toNick, sender, message, metadata=None): | def msgFromWords(self, toNick, sender, message): """Deliver a directMessage as a privmsg over IRC. """ if message[0] != irc.X_DELIM: self.msg(toNick, '<%s> %s' % (sender, message)) else: # If there is a CTCP delimeter at the beginning of the # message, let's leave it there to accomidate not-so- # tolerant clients. dcc_... |
self.pbCallback, self.connectionFailed, | def __init__(self,im,server=None,port=None,username=None,password=None,service=None): self.im=im self.service=service self.username=username self.attached=0 self.ref=WordsGateway(username) pb.connect( self.pbCallback, self.connectionFailed, server, int(port), username, password, service, username, # need to fix this, m... | |
) | ).addCallback(self.pbCallback, self.connectionFailed) | def __init__(self,im,server=None,port=None,username=None,password=None,service=None): self.im=im self.service=service self.username=username self.attached=0 self.ref=WordsGateway(username) pb.connect( self.pbCallback, self.connectionFailed, server, int(port), username, password, service, username, # need to fix this, m... |
listener.startListening() | def buildProtocol(self, connection): # This is a bit hackish -- we already have a Protocol instance, # so just return it instead of making a new one # FIXME: Reject connections from the wrong address/port # (potential security problem) self.protocol.factory = self self.port.loseConnection() return self.protocol | |
self.failUnless(sf.done, "Never finished reading all lines") | self.failUnless(sf.done, "Never finished reading all lines: %s" % sf.lines) | def testTLS(self): cf = protocol.ClientFactory() cf.protocol = UnintelligentProtocol cf.client = 1 |
if node.hasChildNodes(): while len(node.childNodes): node.removeChild(node.lastChild()) | node.childNodes[:] = [] | def clearNode(node): """ Remove all children from the given node. """ if node.hasChildNodes(): while len(node.childNodes): node.removeChild(node.lastChild()) |
chunk of XML that you want to insert into the DOM, but you don't want to incur the cost of parsing it, you can construct one of these and insert it into the DOM. This will most certainly only work with minidom as the API for converting nodes to xml is different in every DOM implementation. | chunk of XML that you want to insert into the DOM, but you don't want to incur the cost of parsing it, you can construct one of these and insert it into the DOM. This will most certainly only work with microdom as the API for converting nodes to xml is different in every DOM implementation. | def gatherTextNodes(iNode): childNodes = iNode.childNodes[:] gathered = [] while childNodes: node = childNodes.pop(0) if node.childNodes: childNodes.extend(node.childNodes) if hasattr(node, 'nodeValue'): gathered.append(node.nodeValue) return ''.join(gathered) |
if not hasattr(parent, 'childNodes'): | if not parent.hasChildNodes(): | def findNodes(parent, matcher, accum=None): if accum is None: accum = [] if not hasattr(parent, 'childNodes'): return accum for child in parent.childNodes: # print child, child.nodeType, child.nodeName if matcher(child): accum.append(child) findNodes(child, matcher, accum) return accum |
def getMethods(self, klass, prefix): testMethodNames = [ name for name in dir(klass) if name[:len(prefix)] == prefix ] testMethodNames.sort() testMethods = [ getattr(klass, name) for name in testMethodNames if type(getattr(klass, name)) is types.MethodType ] return testMethods | def __init__(self): self.testClasses = {} self.numTests = 0 self.couldNotImport = {} self.testMethods = [] | |
methods = self.getMethods(testClass, self.methodPrefix) | methods = [getattr(testClass, "%s%s" % (self.methodPrefix, name)) for name in reflect.prefixedMethodNames(testClass, self.methodPrefix)] | def addTestClass(self, testClass): methods = self.getMethods(testClass, self.methodPrefix) self.testClasses[testClass] = methods self.numTests += len(methods) |
reactor.connectTCP(self.host, self.port, factory) | reactor.connectTCP(host, port, factory) | def doSCGI(request, host, port): if request.stream.length is None: return http.Response(responsecode.LENGTH_REQUIRED) factory = SCGIClientProtocolFactory(request) reactor.connectTCP(self.host, self.port, factory) return factory.deferred |
return xmlrpc.Fault(12) | return xmlrpc.Fault(12, "hello") | def xmlrpc_fault(self): return xmlrpc.Fault(12) |
d = self.proxy().callRemote("fail").addErrback(l.append) | d = self.proxy().callRemote(methodName).addErrback(l.append) | def testErrors(self): for methodName in "fail", "deferFail", "fault", "noSuchMethod": l = [] d = self.proxy().callRemote("fail").addErrback(l.append) while not l: reactor.iterate() l[0].trap(xmlrpc.Fault) log.flushErrors(RuntimeError) |
log.msg('FORWARdING PROCESS OPEN') | reactor.callLater(1, self._connect) def _connect(self): self.connected = 1 | def connectionMade(self): log.msg('FORWARdING PROCESS OPEN') cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self) reactor.callLater(1, cc.connectTCP, 'localhost', self.port) |
reactor.callLater(1, cc.connectTCP, 'localhost', self.port) | d = cc.connectTCP('127.0.0.1', self.port) d.addErrback(self._ebConnect) def _ebConnect(self, f): log.msg('ERROR CONNECTING TO %s' % self.port) log.err(f) log.flushErrors() reactor.callLater(1, self._connect) | def connectionMade(self): log.msg('FORWARdING PROCESS OPEN') cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self) reactor.callLater(1, cc.connectTCP, 'localhost', self.port) |
log.msg('FORWARDING PORT OPEN') | def connectionMade(self): log.msg('FORWARDING PORT OPEN') self.proto.fac.proto.expectedLoseConnection = 1 self.buf = '' self.transport.write(self.data) | |
log.msg('FORWARDING PORT CLOSED %s' % repr(self.buf)) | def connectionLost(self, reason): log.msg('FORWARDING PORT CLOSED %s' % repr(self.buf)) unittest.failUnlessEqual(self.buf, self.data) | |
d = defer.maybeDeferred(self.fac.proto.transport.loseConnection) | self.fac.proto.transport.loseConnection() reactor.iterate() d = self.server.stopListening() if d: | def tearDown(self): try: self.fac.proto.done = 1 except AttributeError: pass else: d = defer.maybeDeferred(self.fac.proto.transport.loseConnection) util.wait(d) d = defer.maybeDeferred(self.server.stopListening) util.wait(d) |
d = defer.maybeDeferred(self.server.stopListening) util.wait(d) | def tearDown(self): try: self.fac.proto.done = 1 except AttributeError: pass else: d = defer.maybeDeferred(self.fac.proto.transport.loseConnection) util.wait(d) d = defer.maybeDeferred(self.server.stopListening) util.wait(d) | |
util.spinWhile(lambda: not p.done) | util.spinWhile(lambda: not p.done, timeout=10) | def execute(self, args, p, preargs = ''): cmdline = ('ssh -2 -l testuser -p %i ' '-oUserKnownHostsFile=kh_test ' '-oPasswordAuthentication=no ' # Always use the RSA key, since that's the one in kh_test. '-oHostKeyAlgorithms=ssh-rsa ' '-a ' '-i dsa_test ') + preargs + \ ' localhost ' + args port = self.server.getHost().... |
reactor.spawnProcess(p, sys.executable, cmds, env=None) | reactor.spawnProcess(p, sys.executable, cmds, env={}) | def execute(self, args, p, preargs=''): if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" port = self.server.getHost().port cmd = ('-p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '-a -I ' '-K direct ' '-i d... |
util.spinWhile(lambda: not p.done) | util.spinWhile(lambda: not p.done, timeout=10) | def execute(self, args, p, preargs=''): if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" port = self.server.getHost().port cmd = ('-p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '-a -I ' '-K direct ' '-i d... |
connect.connect(o['host'], int(o['port']), o, vhk, uao) util.spinWhile(lambda: not p.done) | d = connect.connect(o['host'], int(o['port']), o, vhk, uao) d.addErrback(lambda f: unittest.fail('Failure connecting to test server: %s' % f)) util.spinWhile(lambda: not p.done, timeout=10) | def _(host, *args): o['host'] = host |
process[controller.submodel] = data | process[node.getAttribute('name')] = data | def handleSuccesses(self, request, successes): print "There were successes: ", successes process = {} for controller, data, node in successes: process[controller.submodel] = data return process |
DIRTY_REACTOR_MSG = "reactor left in unclean state, the following Selectables were left over: " | DIRTY_REACTOR_MSG = "THIS WILL BECOME AN ERROR SOON! reactor left in unclean state, the following Selectables were left over: " | def __init__(self, original): self.value = [original] |
raise DirtyReactorError, s | warnings.warn(s, DirtyReactorError) | def do_cleanReactor(cls): s = None if interfaces.IReactorCleanup.providedBy(reactor): junk = reactor.cleanup() if junk: s = DIRTY_REACTOR_MSG + repr([repr(obj) for obj in junk]) if s is not None: raise DirtyReactorError, s |
self._adapterCache[interfaceClass] = adapterClass() | self._adapterCache[interfaceClass] = adapterClass(self) def removeComponent(self, interfaceClass): del self._adapterCache[interfaceClass] | def setAdapter(self, interfaceClass, adapterClass): self._adapterCache[interfaceClass] = adapterClass() |
txt = data.getSubmodel("text").getData(request) | txt = data.getSubmodel(request, "text").getData(request) | def setUp(self, request, node, data): # TODO: we ought to support Deferreds here for both text and href! if isinstance(data, StringType): node.tagName = self.tagName node.attributes["href"] = data else: data = self.model txt = data.getSubmodel("text").getData(request) if not isinstance(txt, Node): txt = document.create... |
lnk = data.getSubmodel("href").getData(request) | lnk = data.getSubmodel(request, "href").getData(request) | def setUp(self, request, node, data): # TODO: we ought to support Deferreds here for both text and href! if isinstance(data, StringType): node.tagName = self.tagName node.attributes["href"] = data else: data = self.model txt = data.getSubmodel("text").getData(request) if not isinstance(txt, Node): txt = document.create... |
timeout = main.runUntilCurrent() if timeout is not None: _simtag = gtk.timeout_add(timeout * 1010, simulate) | timeout = main.runUntilCurrent() or 0.1 _simtag = gtk.timeout_add(timeout * 1010, simulate) | def simulate(): """Run simulation loops and reschedule callbacks. """ global _simtag if _simtag is not None: gtk.timeout_remove(_simtag) timeout = main.runUntilCurrent() if timeout is not None: _simtag = gtk.timeout_add(timeout * 1010, simulate) # grumble |
childNodes = iNode.childNodes[:] gathered = [] while childNodes: node = childNodes.pop(0) if node.childNodes: [childNodes.insert(0, ch_node) for ch_node in node.childNodes] if hasattr(node, 'nodeValue') and node.nodeValue is not None: gathered.append(node.nodeValue) gathered.reverse() | gathered=[] slice=[iNode] while len(slice)>0: c=slice.pop(0) if hasattr(c, 'nodeValue') and c.nodeValue is not None: gathered.append(c.nodeValue) slice=c.childNodes+slice | def gatherTextNodes(iNode): """Visit each child node and collect its text data, if any, into a string. |
os.path.walk(basePath, self.addFiles, None) def addFiles(self, arg, path, files): path = path.replace(self.basePath, '') for file in files: file = os.path.join(path, file) module = (file.replace('.py.html', '') .replace('/', '.')) self.stuff[module] = self.baseURL + file | for file in glob.glob(os.path.join(basePath, "*.html")): file = os.path.basename(file) module = file[:-len('.html')].split('.') for i in range(len(module)-1): self.stuff['.'.join(module[i:])] = self.baseURL+file | def __init__(self, basePath, baseURL): self.stuff = {} self.basePath = basePath self.baseURL = baseURL os.path.walk(basePath, self.addFiles, None) |
if not '.' in name: raise ValueError("Gimme more than just *%s* to work with, " "will ya?!?" % name) name = '.*' + name.replace('.', '\.') + "\.html$" pat = re.compile(name) for k,v in self.stuff.items(): if pat.match(k): return v | ret = self.stuff.get(name) if ret: return ret parts = name.split('.') if len(parts)>1: return self.stuff.get('.'.join(parts[:-1])) | def match(self, name): """ I take a fully-qualified *or* relative module or class-name, and return an URL to the Twisted API documentation for that name. """ # Evil is fun. if not '.' in name: raise ValueError("Gimme more than just *%s* to work with, " "will ya?!?" % name) name = '.*' + name.replace('.', '\.') + "\.htm... |
if not (href.startswith("http://") or href.startswith("mailto:")): | if '/' not in href and href.endswith('.html'): | def fixLinks(document, ext): for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") if not (href.startswith("http://") or href.startswith("mailto:")): fname = os.path.splitext(href) if len(fname) == 2 and fname[1] == '.html': node.setAttribute("href", fname[0] + ext) |
if len(fname) == 2 and fname[1] == '.html': node.setAttribute("href", fname[0] + ext) | node.setAttribute("href", fname[0] + ext) | def fixLinks(document, ext): for node in domhelpers.findElementsWithAttribute(document, 'href'): href = node.getAttribute("href") if not (href.startswith("http://") or href.startswith("mailto:")): fname = os.path.splitext(href) if len(fname) == 2 and fname[1] == '.html': node.setAttribute("href", fname[0] + ext) |
hosts, hostKeyType, encodedKey = line.split() | try: hosts, hostKeyType, encodedKey = line.split() except ValueError: continue | def isInKnownHosts(self, host, pubKey): """checks to see if host is in the known_hosts file for the user. returns 0 if it isn't, 1 if it is and is the same, 2 if it's changed. """ keyType = common.getNS(pubKey)[0] retVal = 0 try: known_hosts = open(os.path.expanduser('~/.ssh/known_hosts')) except IOError: return 0 for ... |
return "<pre>"+escapehtml(text)+"</pre>" | return "<pre>"+escape(text)+"</pre>" | def PRE(text): "Wrap <pre> tags around some text and escape it with web.escapehtml." return "<pre>"+escapehtml(text)+"</pre>" |
if namespace != self.namespace: | if namespace != self.namespace and self.namespace: | def writexml(self, stream, indent='', addindent='', newl='', strip=0, nsprefixes={}, namespace=''): # write beginning ALLOWSINGLETON = ('img', 'br', 'hr', 'base', 'meta', 'link', 'param', 'area', 'input', 'col', 'basefont', 'isindex', 'frame') BLOCKELEMENTS = ('html', 'head', 'body', 'noscript', 'ins', 'del', 'h1', 'h2... |
output.reportError(testClass, method, e) | def runOneTest(self, testClass, testCase, method, output): ok = 0 try: testCase.setUp() method(testCase) except AssertionError, e: output.reportFailure(testClass, method, sys.exc_info()) except KeyboardInterrupt: raise except SkipTest: output.reportSkip(testClass, method, sys.exc_info()) except: output.reportError(test... | |
newQueue.append(seconds - now, func, args, kw) | newQueue.append([seconds - now, func, args, kw]) | def __getstate__(self): """Save state by storing all callback timeouts as differences from the current time. """ now = time() newQueue = [] for seconds, func, args, kw in self.queue: newQueue.append(seconds - now, func, args, kw) return {'queue': newQueue} |
for fn in filter(lambda n: callable(getattr(self,n)) and n.startswith('decode_'), dir(self)): setattr(self, fn.replace('decode','handle'), self.resultHarvester) | for fn in reflect.prefixedMethodNames(self.__class__, 'decode_'): setattr(self, 'handle_' + fn, self.resultHarvester) | def connectionMade(self): self.resultHarvester = ResultHarvester() for fn in filter(lambda n: callable(getattr(self,n)) and n.startswith('decode_'), dir(self)): setattr(self, fn.replace('decode','handle'), self.resultHarvester) |
options['gid'] = pwd.getpwnam(options['gid'])[3] | options['gid'] = grp.getgrnam(options['gid'])[2] | def run(): tapLookup = loadPlugins() options = GeneralOptions(tapLookup) if hasattr(os, 'getgid'): options['uid'] = os.getuid() options['gid'] = os.getgid() try: options.parseOptions(sys.argv[1:]) # XXX - Yea, this is FILTH FILTH FILTH if options['debug'] or options['progress']: tapLookup = loadPlugins(options['debug']... |
setup_args = {"scripts": [scriptfile], | setup_args = {"service": [serviceModule], "scripts": [scriptfile], | def run(argv = sys.argv): setup_args = {"scripts": [scriptfile], "data_files": [("", [configfile]), ], } orig_argv = sys.argv sys.argv = argv setup(**setup_args) sys.argv = orig_argv |
service=%(name)s_ServiceControl | def run(argv = sys.argv): setup_args = {"scripts": [scriptfile], "data_files": [("", [configfile]), ], } orig_argv = sys.argv sys.argv = argv setup(**setup_args) sys.argv = orig_argv | |
version_productversion = %(package_version)s icon = %(icon)s version_filedescription = %(description)s version_productname = %(display_name)s | description = %(description)s | def run(argv = sys.argv): setup_args = {"scripts": [scriptfile], "data_files": [("", [configfile]), ], } orig_argv = sys.argv sys.argv = argv setup(**setup_args) sys.argv = orig_argv |
scr.collect(os.path.join("dist", "%(name)ssvc")) | scr.collect('dist') | def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) from twisted.internet import reactor reactor.callFromThread(reactor.stop) |
host = string.lower(request.getHeader('host')) | host = string.split(string.lower(request.getHeader('host')),':')[0] | 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("host %s not in vhost map" % repr(host))) |
for callback, errback in self.awaitingPerspectives.values(): | for perspective, username, password, referenced, callback, errback in self.expq: | def connectionFailed(self): """The connection failed; bail on any awaiting perspective requests. """ for callback, errback in self.awaitingPerspectives.values(): try: errback() except: traceback.print_exc(file=log.logfile) |
self.waitingForAnswers = None | def connectionLost(self): """The connection was lost. """ self.disconnected = 1 # nuke potential circular references. for perspective, client in self.perspectives.values(): try: perspective.detached(client) except: log.msg("Exception in perspective detach ignored:") traceback.print_exc(file=log.logfile) self.perspectiv... | |
exitCode = self.status >> 8 | exitCode = os.WEXITSTATUS(self.status) | def maybeCallProcessEnded(self): if self.lostProcess == 2: try: if self.status != -1: exitCode = self.status >> 8 else: exitCode = None # wonder when this happens if exitCode: self.proto.processEnded(failure.Failure(error.ProcessTerminated(exitCode))) else: self.proto.processEnded(failure.Failure(error.ProcessDone())) ... |
raise ConchError('could not get next service: %s'%self.nextService) | raise error.ConchError('could not get next service: %s' % self.nextService) | def _cbFinishedAuth(self, (interface, avatar, logout)): self.transport.isAuthorized = True service = self.transport.factory.getService(self.transport, self.nextService) if not service: raise ConchError('could not get next service: %s'%self.nextService) log.msg('%s authenticated with %s' % (self.user, self.method)) if s... |
if self.context.pending(): self.context.iteration(0) | if gtk.events_pending(): gtk.main_iteration(0) | def doIteration(self, delay): # flush some pending events, return if there was something to do # don't use the usual "while self.context.pending(): self.context.iteration()" # idiom because lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system', event=... |
self.context.iteration(1) | gtk.main_iteration(1) | def doIteration(self, delay): # flush some pending events, return if there was something to do # don't use the usual "while self.context.pending(): self.context.iteration()" # idiom because lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system', event=... |
if sys.modules.has_key("gtk"): | if True: | def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) self.simulate() if sys.modules.has_key("gtk"): import gtk self.__crash = gtk.main_quit gtk.main() else: self.__crash = self.loop.quit self.loop.run() |
zope.interface(portal.IRealm) | implements(portal.IRealm) | def perspective_watch(self, identifier): """Watch the object obtained by evaluating the identifier. |
def getObject(self): if self.path: testOb = PathReferenceContext([self.path[0]], self.root).getObject() if testOb.__module__ == 'twisted.web.error': self.path.pop(0) return self.request.site.getResourceFor(self) | def getObject(self): # fix for t.w.distrib, where the first path segment doesn't point to a file on disk if self.path: testOb = PathReferenceContext([self.path[0]], self.root).getObject() if testOb.__module__ == 'twisted.web.error': self.path.pop(0) # Use the loop in site.getRequestFor # It may implement caching in the... | |
raise SkipTest("This test runs an external process. " "This reactor doesn't support it.") | raise unittest.SkipTest("This test runs an external process. " "This reactor doesn't support it.") | def test_actuallyRuns(self): from twisted.internet import interfaces, reactor if not interfaces.IReactorProcess.providedBy(reactor): raise SkipTest("This test runs an external process. " "This reactor doesn't support it.") import test_output, os d = test_output.runTrialWithEnv(os.environ, '--testmodule', sibpath('modul... |
if e.errno != errno.EAGAIN: | if e.errno != errno.WSAEWOULDBLOCK: | 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 |
self.q.put(o) | def dispatch(self, owner, func, *args, **kw): """Dispatch a function to be a run in a thread. owner must be a loggable object. """ assert isinstance(owner, log.Logger), "owner isn't logger" if self.joined: return o=(owner,func,args,kw) self._startSomeWorkers() self.q.put(o) | |
signal.signal(signal.SIGINT, lambda *args: pdb.set_trace()) | signal.signal(signal.SIGUSR2, lambda *args: reactor.callLater(0, pdb.set_trace)) | def runReactorWithLogging(config, oldstdout, oldstderr): from twisted.internet import reactor try: if config['profile']: p = profile.Profile() p.runcall(reactor.run) if config['savestats']: p.dump_stats(config['profile']) else: # XXX - omfg python sucks tmp, sys.stdout = sys.stdout, open(config['profile'], 'a') p.print... |
"(implies nodaemon), sending SIGINT will drop into debugger"], | "(implies nodaemon), sending SIGUSR2 will drop into debugger"], | def reportProfile(report_profile, name): if not report_profile: return if name: from twisted.python.dxprofile import report log.msg("Sending DXP stats...") report(report_profile, name) log.msg("DXP stats sent.") else: log.err("--report-profile specified but application has no " "name (--appname unspecified)") |
inst = Dummy() setInstanceState(inst, self.d) self.protocol.setObject(self.count, inst) self.deferred.callback(inst) return inst | obj = self.factory() obj.setCopyableState(self.d) self.protocol.setObject(self.count, obj) self.deferred.callback(obj) return obj | def receiveClose(self): # TODO: TASTE HERE IF YOU WANT TO LIVE! inst = Dummy() #inst.__classname__ = self.classname setInstanceState(inst, self.d) self.protocol.setObject(self.count, inst) self.deferred.callback(inst) return inst |
def __init__(self, reactor, proc, name, fileno): | def __init__(self, reactor, proc, name, fileno, forceReadHack=False): | def __init__(self, reactor, proc, name, fileno): """Initialize, specifying a Process instance to connect to. """ abstract.FileDescriptor.__init__(self, reactor) fdesc.setNonBlocking(fileno) self.proc = proc self.name = name self.fd = fileno |
try: os.read(self.fileno(), 0) except OSError: | if forceReadHack: | def __init__(self, reactor, proc, name, fileno): """Initialize, specifying a Process instance to connect to. """ abstract.FileDescriptor.__init__(self, reactor) fdesc.setNonBlocking(fileno) self.proc = proc self.name = name self.fd = fileno |
writer = ProcessWriter(reactor, self, childFD, parentFD) | writer = ProcessWriter(reactor, self, childFD, parentFD, forceReadHack=True) | def __init__(self, reactor, command, args, environment, path, proto, uid=None, gid=None, childFDs=None): """Spawn an operating-system process. |
node.setAttribute("href", linkrel+node.getAttribute("href")) | href = node.getAttribute('href') if not href.startswith('http'): node.setAttribute("href", linkrel+node.getAttribute("href")) | def fixRelativeLinks(document, linkrel): for node in domhelpers.findElementsWithAttribute(document, "href"): node.setAttribute("href", linkrel+node.getAttribute("href")) |
if se.args[0] == EISCONN: | if se.args[0] in (EISCONN, EINPROGRESS, EALREADY): | def doConnect(self): """I connect the socket. |
elif se.args[0] in (EINPROGRESS, EWOULDBLOCK, EALREADY, EINVAL): | elif se.args[0] in (EWOULDBLOCK, EINVAL): | def doConnect(self): """I connect the socket. |
self.passwd = params | def ftp_Pass(self, params): """Authorize the USER and the submitted password """ if not self.user: self.reply('nouser') return self.passwd = params if self.user == self.factory.useranonymous: self.reply('guestok') else: # Authing follows if self.factory.otp: otp = self.factory.userdict[self.user]["otp"] try: otp.authen... | |
anonymous = 0 | anonymous = 1 | def lineReceived(self, line): "Process the input from the client" line = string.strip(line) print repr(line) command = string.split(line) if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = string.capitalize(command)... |
otp = 1 root = '/usr/bin/local' | otp = 0 root = '/var/www' | def lineReceived(self, line): "Process the input from the client" line = string.strip(line) print repr(line) command = string.split(line) if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = string.capitalize(command)... |
fixLinks(document, ext) | def munge(document, template, linkrel, d, fullpath, ext, url, config): fixRelativeLinks(template, linkrel) addMtime(template, fullpath) removeH1(document) fixAPI(document, url) fontifyPython(document) addPyListings(document, d) addHTMLListings(document, d) addPlainListings(document, d) fixLinks(document, ext) putInToC(... | |
resource = guardResource(SimpleResource(), checker, anon))) | resource = guardResource(SimpleResource(), [checker, anon]))) | def render(self, request): auth = request.getComponent(Authenticated) if auth: return "hello my friend "+auth.name else: return """ I don't think we've met <a href="perspective-init">login</a> """ |
inet, addr, port = self.getHost() | port = self.getHost().port | def prePathURL(self): inet, addr, port = self.getHost() if self.isSecure(): default = 443 else: default = 80 if port == default: hostport = '' else: hostport = ':%d' % port return quote('http%s://%s%s/%s' % ( self.isSecure() and 's' or '', self.getRequestHostname(), hostport, string.join(self.prepath, '/')), "/:") |
self.transport.write("Authentication failed\n") | self.transport.write("\nAuthentication failed\n") | def _ebLogin(self, failure): self.transport.write("Authentication failed\n") self.transport.write("Username: ") return "User" |
return "User" | self.state = "User" | def _ebLogin(self, failure): self.transport.write("Authentication failed\n") self.transport.write("Username: ") return "User" |
class _ReferenceableProducerWrapper(pb.Referenceable): def __init__(self, producer): self.producer = producer def remote_resumeProducing(self): self.producer.resumeProducing() def remote_pauseProducing(self): self.producer.pauseProducing() def remote_stopProducing(self): self.producer.stopProducing() class OldReque... | def getSession(self, sessionInterface = None): # Session management if not self.session: # FIXME: make sitepath be something cookiename = string.join(['TWISTED_SESSION'] + self.sitepath, "_") sessionCookie = self.getCookie(cookiename) if sessionCookie: try: self.session = self.site.getSession(sessionCookie) except KeyE... | |
dirwidget = DirectoryListing(self.path) return widgets.RenderSession(dirwidget.display(request), request) | dirListingPage = WidgetPage(DirectoryListing(self.path)) return dirListingPage.render(request) | def render(self, request): "You know what you doing." mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime =\ os.stat(self.path) |
except NameError: | except (NameError, ValueError): | def initThreads(): global theScheduler, thread, schedule import thread # Sibling Imports import main # there may already be a registered scheduler, so we need to get # rid of it. try: main.removeDelayed(theScheduler) except NameError: pass theScheduler = ThreadedScheduler() schedule = theScheduler.addTask main.addDe... |
theScheduler = Scheduler() schedule = theScheduler.addTask | def initThreads(): global theScheduler, thread, schedule import thread # Sibling Imports import main # there may already be a registered scheduler, so we need to get # rid of it. try: main.removeDelayed(theScheduler) except NameError: pass theScheduler = ThreadedScheduler() schedule = theScheduler.addTask main.addDe... | |
theScheduler = Scheduler() schedule = theScheduler.addTask | def initThreads(): global theScheduler, thread, schedule import thread # Sibling Imports import main # there may already be a registered scheduler, so we need to get # rid of it. try: main.removeDelayed(theScheduler) except NameError: pass theScheduler = ThreadedScheduler() schedule = theScheduler.addTask main.addDe... | |
Precondition: descriptorId must be a string of length DESCRIPTORLENGTH.: (type(descriptorId) is types.StringType) and (len(descriptorId) == DESCRIPTORLENGTH): "descriptorId: %s :: %s" % (repr(descriptorId), str(type(descriptorId)),) | def pongReceived(self, descriptorId, ttl, hops, ipAddress, port, numberOfFilesShared, kbShared): """ Override this to handle pong messages. | |
raise error.Unauthorized("Malformed Response - not base64") | raise IllegalClientResponse("Malformed Response - not base64") | def __cbAuthChunk(self, result, chal, tag): try: uncoded = base64.decodestring(result) except binascii.Error: raise error.Unauthorized("Malformed Response - not base64") |
raise error.Unauthorized("Malformed Response - wrong number of parts") | raise IllegalClientResponse("Malformed Response - wrong number of parts") | def __cbAuthChunk(self, result, chal, tag): try: uncoded = base64.decodestring(result) except binascii.Error: raise error.Unauthorized("Malformed Response - not base64") |
self.sendNegativeResponse(tag, 'No such mailbox: ' + parts[1]) | self.sendNegativeResponse(tag, 'No such mailbox: ' + mailbox) | def do_COPY(self, tag, messages, mailbox, uid=0): mailbox = self._parseMbox(mailbox) mbox = self.account.select(mailbox) if not mbox: self.sendNegativeResponse(tag, 'No such mailbox: ' + parts[1]) else: maybeDeferred( self.mbox.fetch, messages, ['BODY', [], 'INTERNALDATE', 'FLAGS'], uid=uid ).addCallbacks( self.__cbCop... |
parts = uncoded.split(None, 1) if len(parts) != 2: self.sendCode(501, "Invalid challenge response") return self.challenger.username = parts[0] self.challenger.response = parts[1] self.portal.login(self.challenger, None, IMessageDelivery ).addCallback(self._cbAuthenticated ).addCallback(lambda _: self.sendCode(235, 'Au... | self.challenger.setResponse(uncoded) if self.challenger.moreChallenges(): self.authenticate(self.challenger) else: self.portal.login(self.challenger, None, IMessageDelivery ).addCallback(self._cbAuthenticated ).addCallback(lambda _: self.sendCode(235, 'Authentication successful.') ).addErrback(self._ebAuthenticated ) | def state_AUTH(self, rest): self.mode = COMMAND if rest == '*': self.sendCode(501, 'Authentication aborted') self.challenger.abort() self.challenger = None return |
self._fixupNAT(m, addr) | def datagramReceived(self, data, addr): self.parser.dataReceived(data) self.parser.dataDone() for m in self.messages: if self.debug: log.msg("Received %r from %r" % (m, addr)) self._fixupNAT(m, addr) if isinstance(m, Request): self.handle_request(m, addr) else: self.handle_response(m, addr) self.messages[:] = [] | |
if senderVia.port != srcPort: senderVia.rport = srcPort if senderVia.received is not None or senderVia.rport is not None: | if senderVia.port != srcPort: senderVia.rport = srcPort | def _fixupNAT(self, message, (srcHost, srcPort)): # RFC 2543 6.40.2 senderVia = parseViaHeader(message.headers["via"][0]) if senderVia.host != srcHost: senderVia.received = srcHost if senderVia.port != srcPort: senderVia.rport = srcPort if senderVia.received is not None or senderVia.rport is not None: message.headers["... |
algo = self.fields.get('algorithm') qop = self.fields.get('qop-options') | algo = self.fields.get('algorithm', 'MD5') qop = self.fields.get('qop-options', 'auth') | def checkPassword(self, password): |
'digest': DigestAuthorizer(), | def decode(self, response): response = ' '.join(response.splitlines()) parts = response.split(',') auth = dict([(k.strip(), unq(v.strip())) for (k, v) in [p.split('=', 1) for p in parts]]) try: username = auth['username'] except KeyError: raise SIPError(401) try: return DigestedCredentials(username, auth, self.outstand... | |
for weakref in self.views: | for weakref in list(self.views): | def removeView(self, view): """ Remove a view that the model no longer should keep track of. """ for weakref in self.views: ref = weakref() if ref is view or ref is None: self.views.remove(weakref) |
for view in self.views: | for view in list(self.views): | def notify(self, changed=None): """ Notify all views that something was changed on me. Passing a dictionary of {'attribute': 'new value'} in changed will pass this dictionary to the view for increased performance. If you don't want to do this, don't, and just use the traditional MVC paradigm of querying the model for t... |
for item in value: | for item in list(value): | def notify(self, changed=None): """ Notify all views that something was changed on me. Passing a dictionary of {'attribute': 'new value'} in changed will pass this dictionary to the view for increased performance. If you don't want to do this, don't, and just use the traditional MVC paradigm of querying the model for t... |
self.views.remove(view) | value.remove(item) | def notify(self, changed=None): """ Notify all views that something was changed on me. Passing a dictionary of {'attribute': 'new value'} in changed will pass this dictionary to the view for increased performance. If you don't want to do this, don't, and just use the traditional MVC paradigm of querying the model for t... |
self.client.buf = '' | def channelOpen(self, specificData): log.msg('opened forwarding channel %s' % self.id) if len(self.client.buf)>1: b = self.client.buf[1:] self.client.buf = '' self.write(b) | |
print ftp_reply[key] % s + '\r\n' | if self.debug: print ftp_reply[key] % s + '\r\n' | def reply(self, key, s = ''): if string.find(ftp_reply[key], '%s') > -1: print ftp_reply[key] % s + '\r\n' self.transport.write(ftp_reply[key] % s + '\r\n') else: print ftp_reply[key] + '\r\n' self.transport.write(ftp_reply[key] + '\r\n') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.