rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
from twisted.internet.reactor import callFromThread | def process(self): """ This is called in the 'source' thread, and just basically sucks the iterator, appending items back to the main thread. """ try: self.source.init() except: self.failure = failure.Failure() from twisted.internet.reactor import callFromThread try: while 1: val = self.source.next() if self.extend: se... | |
callFromThread(self.stop) | self.stop = 1 | def process(self): """ This is called in the 'source' thread, and just basically sucks the iterator, appending items back to the main thread. """ try: self.source.init() except: self.failure = failure.Failure() from twisted.internet.reactor import callFromThread try: while 1: val = self.source.next() if self.extend: se... |
def setFailure(self, failure): self.failure = failure def stop(self): self.isFinished = 1 | def setFailure(self, failure): self.failure = failure | |
if self.isFinished: | if self.stop: | def next(self): if self.buff: return self.buff.pop(0) if self.isFinished: raise StopIteration if self.failure: raise self.failure raise Cooperate() |
interface = '' backlog = 5 | def getHost(self): """ Returns a tuple of ('INET', hostname, port), indicating the servers address """ return ('INET',)+self.socket.getsockname() | |
def __setstate__(self, dct): if not dct.has_key('backlog'): dct['backlog'] = 5 self.__dict__.update(dct) | def __setstate__(self, dct): if not dct.has_key('backlog'): dct['backlog'] = 5 self.__dict__.update(dct) | |
if not val: print "val is null; key is '%s'" % key | assert val is not None | 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... |
if not val: print "val is null; attr is '%s'" % attr | assert val is not None | 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... |
host = string.split(string.lower(request.getHeader('host')),':')[0] | hostHeader = request.getHeader('host') if hostHeader == None: return self.default or error.NoResource() else: host = string.split(string.lower(hostHeader),':')[0] | def _getResourceForRequest(self, request): """(Internal) Get the appropriate resource for the given host. """ host = string.split(string.lower(request.getHeader('host')),':')[0] return self.hosts.get(host, error.NoResource("host %s not in vhost map" % repr(host))) |
why = getattr(selectable, method)() handfn = getattr(selectable, 'fileno', None) if not handfn: why = error.ConnectionFdescWentAway('Handler has no fileno method') elif handfn() == -1: why = error.ConnectionFdescWentAway('Filedescriptor went away') except: log.deferr() why = sys.exc_value if why: self.removeReader(sele... | def doSelect(self, 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. | |
selectable.connectionLost(failure.Failure(why)) | why = getattr(selectable, method)() handfn = getattr(selectable, 'fileno', None) if not handfn: why = _NO_FILENO elif handfn() == -1: why = _NO_FILEDESC | def doSelect(self, 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. |
log.logOwner.disown(selectable) | why = sys.exc_value if why: self.removeReader(selectable) self.removeWriter(selectable) try: selectable.connectionLost(failure.Failure(why)) except: log.deferr() finally: log.logOwner.disown(selectable) | def doSelect(self, 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. |
failed, or lost - see L{ClientFactory<twisted.internet.protocol.ServerFactory>} docs for details. | failed, or lost - see L{ClientFactory<twisted.internet.protocol.ClientFactory>} docs for details. | def connectTCP(self, host, port, factory, timeout=30, bindAddress=None): """Connect a TCP client. |
return Todo(reason=str(value.value)) | return Todo(reason=value.getErrorMessage()) | def makeTodo(value): if isinstance(value, str): return Todo(reason=value) if isinstance(value, tuple): errors, reason = value try: errors = list(errors) except TypeError: errors = [errors] return Todo(reason=reason, errors=errors) if isinstance(value, failure.Failure): return Todo(reason=str(value.value)) |
warnings.warn(("Do not raise unittest.SkipTest or " "unittest.TodoTest with no arguments! Give a reason " "for skipping tests!"), | warnings.warn(("Do not raise unittest.SkipTest with no " "arguments! Give a reason for skipping tests!"), | def _getReason(self, f): if len(f.value.args) > 0: reason = f.value.args[0] else: warnings.warn(("Do not raise unittest.SkipTest or " "unittest.TodoTest with no arguments! Give a reason " "for skipping tests!"), stacklevel=2) reason = f return reason |
def pong(self, user, secs): """Called with the results of a CTCP PING query. | def topicUpdated(self, user, channel, newTopic): """In channel, user changed the topic to newTopic. Also called when first joining a channel. | def pong(self, user, secs): """Called with the results of a CTCP PING query. """ pass |
def signedOn(self): """Called after sucessfully signing on to the server. | def userRenamed(self, oldname, newname): """A user changed their name from oldname to newname. | def signedOn(self): """Called after sucessfully signing on to the server. """ pass |
def kickedFrom(self, channel, kicker, message): """Called when I am kicked from a channel. """ pass def userKicked(self, kickee, channel, kicker, message): | def receivedMOTD(self, motd): """I recieved a message-of-the-day banner from the server. motd is a list of strings, where each string was sent as a seperate message from the server. To display, you might want to use string.join(motd, '\n') to get a nicely formatted string. """ | def kickedFrom(self, channel, kicker, message): """Called when I am kicked from a channel. """ pass |
def topic(self, channel, topic): | def topic(self, channel, topic=None): """Attempt to set the topic of the given channel, or ask what it is. If topic is None, then I sent a topic query instead of trying to set the topic. The server should respond with a TOPIC message containing the current topic of the given channel. """ | def topic(self, channel, topic): # << TOPIC #xtestx :fff if channel[0] not in '&#!+': channel = '#' + channel self.sendLine("TOPIC %s :%s" % (channel, topic)) |
self.sendLine("TOPIC %s :%s" % (channel, topic)) | if topic != None: self.sendLine("TOPIC %s :%s" % (channel, topic)) else: self.sendLine("TOPIC %s" % (channel,)) | def topic(self, channel, topic): # << TOPIC #xtestx :fff if channel[0] not in '&#!+': channel = '#' + channel self.sendLine("TOPIC %s :%s" % (channel, topic)) |
self.joined(params[-1]) | self.joined(channel) else: self.userJoined(nick, channel) def irc_PART(self, prefix, params): nick = string.split(prefix,'!')[0] channel = params[-1] if nick == self.nickname: self.left(channel) else: self.userLeft(nick, channel) | def irc_JOIN(self, prefix, params): nick = string.split(prefix,'!')[0] if nick == self.nickname: self.joined(params[-1]) |
if nick == self.nickname: self.nickname = params[0] | if nick == self.nickname: self.nickname = params[0] else: self.userRenamed(nick, params[0]) | def irc_NICK(self, prefix, params): nick = string.split(prefix,'!',0)[0] if nick == self.nickname: self.nickname = params[0] |
__all__ = ['dict', 'inet_pton', 'inet_ntop', 'isinstance'] | __all__ = ['dict', 'inet_pton', 'inet_ntop', 'isinstance', 'True', 'False', 'bool'] | def isinstance(object, class_or_type_or_tuple): if type(class_or_type_or_tuple) == types.TupleType: for t in class_or_type_or_tuple: if __builtin__.isinstance(object, t): return 1 return 0 else: return __builtin__.isinstance(object, class_or_type_or_tuple) |
print 'Making ', os.path.join(dir, subdir) | def initializeMaildir(dir): if not os.path.isdir(dir): os.mkdir(dir) for subdir in ['new', 'cur', 'tmp', '.Trash']: print 'Making ', os.path.join(dir, subdir) os.mkdir(os.path.join(dir, subdir)) for subdir in ['new', 'cur', 'tmp']: print 'Making ', os.path.join(dir, '.Trash', subdir) os.mkdir(os.path.join(dir, '.Trash'... | |
print 'Making ', os.path.join(dir, '.Trash', subdir) | def initializeMaildir(dir): if not os.path.isdir(dir): os.mkdir(dir) for subdir in ['new', 'cur', 'tmp', '.Trash']: print 'Making ', os.path.join(dir, subdir) os.mkdir(os.path.join(dir, subdir)) for subdir in ['new', 'cur', 'tmp']: print 'Making ', os.path.join(dir, '.Trash', subdir) os.mkdir(os.path.join(dir, '.Trash'... | |
reactor.addSystemEventTrigger('after', 'startup', self.start) | main.callWhenRunning(self.start) | def __init__(self, *args, **kwargs): apply(threadpool.ThreadPool.__init__, (self,) + args, kwargs) reactor.addSystemEventTrigger('after', 'startup', self.start) self._callbacks = [] |
theDispatcher = ThreadDispatcher(0) | theDispatcher = ThreadDispatcher() | def stop(self): log.msg("stopping thread dispatcher " +str(self)) threadpool.ThreadPool.stop(self) |
return self._reportError(filename, dom, 'not exactly one title') | return self._reportError(filename, doc, 'not exactly one title') | def check_title(self, dom, filename): title = domhelpers.findNodesNamed(dom, 'title') if len(title)!=1: return self._reportError(filename, dom, 'not exactly one title') h1 = domhelpers.findNodesNamed(dom, 'h1') if len(h1)!=1: return self._reportError(filename, dom, 'not exactly one h1') if domhelpers.getNodeText(h1[0])... |
return self._reportError(filename, dom, 'not exactly one h1') | return self._reportError(filename, doc, 'not exactly one h1') | def check_title(self, dom, filename): title = domhelpers.findNodesNamed(dom, 'title') if len(title)!=1: return self._reportError(filename, dom, 'not exactly one title') h1 = domhelpers.findNodesNamed(dom, 'h1') if len(h1)!=1: return self._reportError(filename, dom, 'not exactly one h1') if domhelpers.getNodeText(h1[0])... |
r'(?P<date>.*)\s+(?P<filename>.*)\r?$' | r'(?P<date>... .. ..:..)\s+(?P<filename>.*?)\r?$' | def lineReceived(self, line): """(Private) Parses the response messages from the FTP server.""" # Add this line to the current response if self.debug: log.msg('--> %s' % line) line = string.rstrip(line) self.response.append(line) |
dirListingPage = WidgetPage(DirectoryListing(self.path)) | dirListingPage = widgets.WidgetPage(DirectoryListing(self.path)) | def render(self, request): "You know what you doing." mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime =\ os.stat(self.path) |
log.msg('real path for %s is %s' % (path, self._absPath(path))) | def realPath(self, path): log.msg('real path for %s is %s' % (path, self._absPath(path))) return self._absPath(path) | |
log.msg("%s %i" % (directory, len(self.files))) | def __init__(self, server, directory): self.server = server self.files = server.avatar._runAsUser(os.listdir, directory) log.msg("%s %i" % (directory, len(self.files))) self.dir = directory | |
| ['menu', 'How to greet?', 'how', ['cheerfully', 'with a smile', | 'sullenly', 'without enthusiasm', | 'spontaneously', 'on the spur of the moment']]] | | ['menu', 'How to greet?', 'how', [('cheerfully', 'with a smile'), | ('sullenly', 'without enthusiasm'), | ('spontaneously', 'on the spur of the moment')]]] | def htmlFor_checkgroup(write, name, value): "A check-group." for optionName, displayName, checked in value: checked = (checked and 'checked') or '' write('<INPUT TYPE="checkbox" NAME="%s" VALUE="%s" %s>%s<br>\n' % (name, optionName, checked, displayName)) |
log.msg('touching %s' % self) | def touch(self): log.msg('touching %s' % self) f = open(self.filename, 'w') f.seek(0) if self.writePID: f.write(str(os.getpid())) else: f.write("a") f.close() # keep the lock fresh | |
log.msg('removing %s' % self) | def remove(self): log.msg('removing %s' % self) self.touchLoop.stop() os.remove(self.filename) | |
callback(string) or errback(string) | callback(string) or errback(error) | def eomReceived(self): """handle end of message |
skip = "Crypto requirements missing, can't run historic recvline tests over ssh" | skip = "Crypto requirements missing, can't run manhole tests over ssh" | ">>> def deferLater(n):", |
self.prefixes["http://www.w3.org/XML/1998/namespace"] = "xml" | self.prefixes.update(G_PREFIXES) | def __init__(self, prefixes = None): self.cio = StringIO.StringIO() self.prefixes = prefixes or {} self.prefixes["http://www.w3.org/XML/1998/namespace"] = "xml" self.prefixCounter = 0 |
if not os.path.isdir(dir): os.mkdir(dir) for subdir in ['new', 'cur', 'tmp', '.Trash']: os.mkdir(os.path.join(dir, subdir)) for subdir in ['new', 'cur', 'tmp']: os.mkdir(os.path.join(dir, '.Trash', subdir)) fp=open(os.path.join(dir, '.Trash', 'maildirfolder'), 'w') fp.close() | def userDirectory(self, name): """Get the directory for a user | |
print "password is", repr(self.opts['password']) | def postOptions(self): if not self.opts.has_key('password'): self.opt_password('-') print "password is", repr(self.opts['password']) | |
testReadEmptyInput.timeout = 5 | def testReadEmptyInput(self): cgiFilename = os.path.abspath(self.mktemp()) cgiFile = file(cgiFilename, 'wt') cgiFile.write(READINPUT_CGI) cgiFile.close() | |
testReadInput.timeout = 5 | def testReadInput(self): cgiFilename = os.path.abspath(self.mktemp()) cgiFile = file(cgiFilename, 'wt') cgiFile.write(READINPUT_CGI) cgiFile.close() | |
testRealAllInput.timeout = 5 | def testRealAllInput(self): cgiFilename = os.path.abspath(self.mktemp()) cgiFile = file(cgiFilename, 'wt') cgiFile.write(READALLINPUT_CGI) cgiFile.close() | |
testScriptsExecute.timeout=10 | def _cleanup(res): d = self.p.stopListening() d.addCallback(lambda ign: res) return d | |
self.assertEquals(unittest.wait(d), "End") | self.assertEquals(util.wait(d), "End") | def _cbDoWait(self, result): self.assertEquals(result, "Beginning") d = defer.succeed("End") self.assertEquals(unittest.wait(d), "End") |
self.assertRaises(util.WaitIsNotReentrantError, unittest.wait, d) | self.assertRaises(util.WaitIsNotReentrantError, util.wait, d) | def testReturnedDeferredThenWait(self): d = self._returnedDeferredThenWait() self.assertRaises(util.WaitIsNotReentrantError, unittest.wait, d) |
d1.addCallback(lambda ignored: unittest.wait(d2)) unittest.wait(d1) | d1.addCallback(lambda ignored: util.wait(d2)) util.wait(d1) | def threadedOperation(n): time.sleep(n) return n |
if len(conn.channels) == 1 and not (options['fork'] and options['nocache']): | if len(conn.channels) == 1 and not (options['fork'] and not options['nocache']): | def closed(self): self.unix.sendMessage('closed', self.id) if len(conn.channels) == 1 and not (options['fork'] and options['nocache']): # just us left reactor.stop() |
log.msg(str(self.conn.channels)) log.msg(str(options['fork'])) log.msg(str(options['nocache'])) if len(self.conn.channels) == 1 and not (options['fork'] and options['nocache']): | if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']): | def closed(self): log.msg('closed %s' % self) log.msg(str(self.conn.channels)) log.msg(str(options['fork'])) log.msg(str(options['nocache'])) if len(self.conn.channels) == 1 and not (options['fork'] and options['nocache']): # just us left reactor.stop() |
if len(self.conn.channels) == 1 and not (options['fork'] and options['nocache']): | if len(self.conn.channels) == 1 and not (options['fork'] and not options['nocache']): | def closed(self): forwarding.SSHListenClientForwardingChannel.closed(self) if len(self.conn.channels) == 1 and not (options['fork'] and options['nocache']): # just us left reactor.stop() |
else: for node in slots: node.removeAttribute('pattern') else: for node in slots: node.removeAttribute(name + 'Of') | def getPattern(self, name, default=missingPattern, clone=1, deep=1): """Get a named slot from the incoming template node. Returns a copy of the node and all its children. If there was more than one node with the same slot identifier, they will be returned in a round-robin fashion. """ #print self.templateNode.toxml() i... | |
config['nodaemon'] = config['nodaemon'] and not config['debug'] | config['nodaemon'] = config['nodaemon'] or config['debug'] | def runApp(config): passphrase = app.getPassphrase(config['encrypted']) app.installReactor(config['reactor']) config['nodaemon'] = config['nodaemon'] and not config['debug'] oldstdout = sys.stdout oldstderr = sys.stderr startLogging(config['logfile'], config['syslog'], config['prefix'], config['nodaemon']) app.initialL... |
else: msg = flow.wrap(lookupAddress(soFar, authority, p)) yield msg msg = msg.next() records = msg.answers + msg.authority + msg.additional addresses = [r for r in records if r.type == dns.A] if addresses: authority = addresses[0].payload.dottedQuad() else: raise IOError("Resolution error") | def discoverAuthority(host, roots, cache=None, p=None): if cache is None: cache = {} rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar = '' for part in parts: soFar = part + '.' + soFar msg = flow.wrap(lookupNameservers(soFar, authority, p)) yield msg msg... | |
return "InstanceMethod(%r, %r, \n\t%s)" % (self.name, self.klass, prettify(self.instance)) | return "InstanceMethod(%r, %r, \n\0%s)" % (self.name, self.klass, prettify(self.instance)) | def getSource(self): return "InstanceMethod(%r, %r, \n\t%s)" % (self.name, self.klass, prettify(self.instance)) |
pass | return "Instance(%r, %s)" % (self.klass, prettify(stateDict)) | def getSource(self): #XXX make state be foo=bar instead of a dict. if self.stateIsDict: stateDict = self.state elif isinstance(self.state, Ref) and isinstance(self.state.obj, types.DictType): stateDict = self.state.obj else: stateDict = None if stateDict is not None: try: return "Instance(%r, %s)" % (self.klass, dictTo... |
return "Ref(%d, \n\t%s)" % (self.refnum, prettify(self.obj)) | return "Ref(%d, \n\0%s)" % (self.refnum, prettify(self.obj)) | def getSource(self): if self.obj is None: raise RuntimeError("Don't try to display me before setting an object on me!") if self.refnum: return "Ref(%d, \n\t%s)" % (self.refnum, prettify(self.obj)) return prettify(self.obj) |
raise NonFormattableDict(d) | raise NonFormattableDict("%r ain't a string" % k) if not r.match(k): raise NonFormattableDict("%r ain't an identifier" % k) | def dictToKW(d): out = [] items = d.items() items.sort() for k,v in items: if not isinstance(k, types.StringType): raise NonFormattableDict(d) out.append( "\n\t%s=%s," % (k, prettify(v)) ) return string.join(out, '') |
"\n\t%s=%s," % (k, prettify(v)) | "\n\0%s=%s," % (k, prettify(v)) | def dictToKW(d): out = [] items = d.items() items.sort() for k,v in items: if not isinstance(k, types.StringType): raise NonFormattableDict(d) out.append( "\n\t%s=%s," % (k, prettify(v)) ) return string.join(out, '') |
out.append('\n\t%s: %s,' % (prettify(k), prettify(v))) out.append(len(obj) and '\n\t}' or '}') | out.append('\n\0%s: %s,' % (prettify(k), prettify(v))) out.append(len(obj) and '\n\0}' or '}') | def prettify(obj): if hasattr(obj, 'getSource'): return obj.getSource() else: #basic type t = type(obj) if t in [types.StringType, types.UnicodeType, types.IntType, types.FloatType, types.LongType, types.NoneType]: return repr(obj) elif t is types.DictType: out = ['{'] for k,v in obj.items(): out.append('\n\t%s: %s,'... |
out.append('\n\t%s,' % prettify(x)) out.append(len(obj) and '\n\t]' or ']') | out.append('\n\0%s,' % prettify(x)) out.append(len(obj) and '\n\0]' or ']') | def prettify(obj): if hasattr(obj, 'getSource'): return obj.getSource() else: #basic type t = type(obj) if t in [types.StringType, types.UnicodeType, types.IntType, types.FloatType, types.LongType, types.NoneType]: return repr(obj) elif t is types.DictType: out = ['{'] for k,v in obj.items(): out.append('\n\t%s: %s,'... |
out.append('\n\t%s,' % prettify(x)) out.append(len(obj) and '\n\t)' or ')') | out.append('\n\0%s,' % prettify(x)) out.append(len(obj) and '\n\0)' or ')') | def prettify(obj): if hasattr(obj, 'getSource'): return obj.getSource() else: #basic type t = type(obj) if t in [types.StringType, types.UnicodeType, types.IntType, types.FloatType, types.LongType, types.NoneType]: return repr(obj) elif t is types.DictType: out = ['{'] for k,v in obj.items(): out.append('\n\t%s: %s,'... |
for ch in s: if ch in ['[', '(', '{']: stack.append(ch) elif ch in [']', ')', '}']: | def eater(type, val, r, c, l, out=out, stack=stack): if val in ['[', '(', '{']: stack.append(val) elif val in [']', ')', '}']: | def indentify(s): out = [] stack = [] for ch in s: if ch in ['[', '(', '{']: stack.append(ch) elif ch in [']', ')', '}']: stack.pop() if ch == '\t': out.append(' '*len(stack)) else: out.append(ch) return string.join(out, '') |
if ch == '\t': | if val == '\0': | def indentify(s): out = [] stack = [] for ch in s: if ch in ['[', '(', '{']: stack.append(ch) elif ch in [']', ')', '}']: stack.pop() if ch == '\t': out.append(' '*len(stack)) else: out.append(ch) return string.join(out, '') |
out.append(ch) | out.append(val) l = ['', s] tokenize.tokenize(l.pop, eater) | def indentify(s): out = [] stack = [] for ch in s: if ch in ['[', '(', '{']: stack.append(ch) elif ch in [']', ')', '}']: stack.pop() if ch == '\t': out.append(' '*len(stack)) else: out.append(ch) return string.join(out, '') |
def accumulateMethods(obj, dict, prefix=''): | def accumulateMethods(obj, dict, prefix='', curClass=None): | def accumulateMethods(obj, dict, prefix=''): """Raped'n'pasted from addMethodNamesToDict. This takes an *instance* object, and accumulates a dict of methname: *instance*MethObj pairs. """ for base in obj.__class__.__bases__: accumulateMethods(obj, dict, prefix) for name, method in obj.__class__.__dict__.items(): optNa... |
for base in obj.__class__.__bases__: accumulateMethods(obj, dict, prefix) for name, method in obj.__class__.__dict__.items(): | if not curClass: curClass = obj.__class__ for base in curClass.__bases__: accumulateMethods(obj, dict, prefix, base) for name, method in curClass.__dict__.items(): | def accumulateMethods(obj, dict, prefix=''): """Raped'n'pasted from addMethodNamesToDict. This takes an *instance* object, and accumulates a dict of methname: *instance*MethObj pairs. """ for base in obj.__class__.__bases__: accumulateMethods(obj, dict, prefix) for name, method in obj.__class__.__dict__.items(): optNa... |
cmd.deferred.addBoth(close) d = DeferredList([cmd.deferred, protocol.deferred], fireOnOneErrback=1) | d.addBoth(close) | def close(x, m=_mutable): m[0] and m[0].disconnect() return x |
self.running = 1 | self.running = 0 | def stopService(self): self.running = 1 |
print 'false is open' | def channelOpen(self, ignored): print 'false is open' d = self.conn.sendRequest(self, 'exec', common.NS('false'), 1) d.addErrback(self._ebRequestFailed) log.msg('opened false') | |
def datagramReceived(self, datagram): | def datagramReceived(self, datagram, host): | def datagramReceived(self, datagram): print 'Datagram received: ', repr(datagram) self.sendDatagram() |
protocol = ConnectedEchoClientDatagramProtocol() reactor.connectUDP('localhost', 8000, protocol) | protocol = EchoClientDatagramProtocol() t = reactor.listenUDP(0, protocol) | def main(): protocol = ConnectedEchoClientDatagramProtocol() reactor.connectUDP('localhost', 8000, protocol) reactor.run() |
ret = f(*args, **kwargs) | return f(*args, **kwargs) | exec """def %s(*args, **kwargs): |
return ret | exec """def %s(*args, **kwargs): | |
d.addErrback(self.receiveDirectMessage, sender.name, message, None) | if d: d.addErrback(self.receiveDirectMessage, sender.name, message, None) | def receiveDirectMessage(self, sender, message, metadata): if self.client: if metadata: d = self.client.receiveDirectMessage(sender.name, message, metadata) #If the client doesn't support metadata, call this function #again with no metadata, so none is sent d.addErrback(self.receiveDirectMessage, sender.name, message, ... |
d.addErrback(self.receiveGroupMessage, sender, group, message, None) | if d: d.addErrback(self.receiveGroupMessage, sender, group, message, None) | def receiveGroupMessage(self, sender, group, message, metadata): if sender is not self and self.client: if metadata: d = self.client.receiveGroupMessage(sender.name, group.name, message, metadata) d.addErrback(self.receiveGroupMessage, sender, group, message, None) else: self.client.receiveGroupMessage(sender.name, gro... |
def runProcess(self, env, request): | def runProcess(self, env, request, qargs=[]): | def runProcess(self, env, request): p = CGIProcessProtocol(request) reactor.spawnProcess(p, self.filter, [self.filter, self.filename], env, os.path.dirname(self.filename)) |
reactor.spawnProcess(p, self.filter, [self.filter, self.filename], env, os.path.dirname(self.filename)) | reactor.spawnProcess(p, self.filter, [self.filter, self.filename]+qargs, env, os.path.dirname(self.filename)) | def runProcess(self, env, request): p = CGIProcessProtocol(request) reactor.spawnProcess(p, self.filter, [self.filter, self.filename], env, os.path.dirname(self.filename)) |
if not [n.tagName in ('pre', 'code') for n in parents]: | if not [1 for n in parents if n.tagName in ('pre', 'code')]: | def writeNodeData(self, node): buf = StringIO() getLatexText(node, buf.write, latexEscape) parents = domhelpers.getParents(node.parentNode)[:-1] text = buf.getvalue() if not [n.tagName in ('pre', 'code') for n in parents]: text = text.replace('<', '$<$').replace('>', '$>$') self.writer(text) |
if ftp_reply[key].find('%s') > -1: | if string.find(ftp_reply[key], '%s') > -1: | def reply(self, key, s = ''): if ftp_reply[key].find('%s') > -1: self.transport.write(ftp_reply[key] % s + '\r\n') else: self.transport.write(ftp_reply[key] + '\r\n') |
wd = wd.replace('\\','/') while wd.find('//') > -1: wd = wd.replace('//','/') | wd = string.replace(wd,'\\','/') while string.find(wd, '//') > -1: wd = string.replace(wd, '//','/') | def ftp_Cwd(self, params): if self.checkauth(): return wd = os.path.normpath(params) if not os.path.isabs(wd): wd = os.path.normpath(self.wd + '/' + wd) wd = wd.replace('\\','/') while wd.find('//') > -1: wd = wd.replace('//','/') # '..', '\\', and '//' is there just to prevent stop hacking :P if (not os.path.isdir(sel... |
if (not os.path.isdir(self.root + wd)) or (wd.find('..') > 0) or \ (wd.find('\\') > 0) or (wd.find('//') > 0): | if (not os.path.isdir(self.root + wd)) or (string.find(wd,'..') > 0) or \ (string.find(wd,'\\') > 0) or (string.find(wd,'//') > 0): | def ftp_Cwd(self, params): if self.checkauth(): return wd = os.path.normpath(params) if not os.path.isabs(wd): wd = os.path.normpath(self.wd + '/' + wd) wd = wd.replace('\\','/') while wd.find('//') > -1: wd = wd.replace('//','/') # '..', '\\', and '//' is there just to prevent stop hacking :P if (not os.path.isdir(sel... |
wd = wd.replace('\\','/') | wd = string.replace(wd,'\\','/') | def ftp_Cwd(self, params): if self.checkauth(): return wd = os.path.normpath(params) if not os.path.isabs(wd): wd = os.path.normpath(self.wd + '/' + wd) wd = wd.replace('\\','/') while wd.find('//') > -1: wd = wd.replace('//','/') # '..', '\\', and '//' is there just to prevent stop hacking :P if (not os.path.isdir(sel... |
if line.count(' ') > 0: | if string.count(line,' ') > 0: | def processLine(self, line): "Process the input from the client" line = string.strip(line) command = string.split(line) if command == []: self.reply('unknown') return 0 commandTmp, command = command[0], '' for c in commandTmp: if ord(c) < 128: command = command + c command = string.capitalize(command) print "-"+command... |
name = params[-1] | name = params[0] | def irc_WHO(self, prefix, params): #<< who #python #>> :benford.openprojects.net 352 glyph #python aquarius pc-62-31-193-114-du.blueyonder.co.uk forward.openprojects.net Aquarius H :3 Aquarius # ... #>> :benford.openprojects.net 352 glyph #python foobar europa.tranquility.net benford.openprojects.net skreech H :0 skree... |
self.transport.write(record.encode()) | self.write(record.encode()) def dataReceived(self, data): print 'Received', repr(data) ImplicitStateProtocol.dataReceived(self, data) | def send(self, record): self.transport.write(record.encode()) |
def __init__(self, target): | def __init__(self, target, logFile=None): | def __init__(self, target): self.target = target |
self.request.write(self.file.read(abstract.FileDescriptor.bufferSize)) | buffer = self.file.read(abstract.FileDescriptor.bufferSize) self.request.write(buffer) | def resumeProducing(self): if (self.request is None) or (self.file.closed): return self.request.write(self.file.read(abstract.FileDescriptor.bufferSize)) if self.file.tell() == self.filesize: self.stopProducing() |
self.file = open(queuedfile, "rb") self.filesize = os.path.getsize(queuedfile) | if self.file is None: self.file = open(queuedfile, "rb") self.filesize = os.path.getsize(queuedfile) | def actionRETR(self, queuedfile): "Send the given file to the peer" self.file = open(queuedfile, "rb") self.filesize = os.path.getsize(queuedfile) producer = SendFileTransfer(self.file, self.filesize, self.makeRETRTransport()) producer.resumeProducing() |
list = os.listdir(dir) | list = os.listdir(dir) s = '' | 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) for a in list: s = a ff = os.path.join(dir, s) # the full filename mtime = time.strftime("%b %d %H:%M", time.gmtime(os.path.get... |
self.transport.write(diracc+"r-xr-xr-x 1 twisted twisted %11d" % fsize+' '+mtime+' '+s+'\r\n') self.pi.reply('fileok') self.pi.queuedfile = None self.transport.loseConnection() | s = s + diracc+"r-xr-xr-x 1 twisted twisted %11d" % fsize+' '+mtime+' '+s+'\r\n' self.action = 'RETR' self.file = StringIO.StringIO(s) self.filesize = len(s) reactor.callLater(0.1, self.executeAction) | 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) for a in list: s = a ff = os.path.join(dir, s) # the full filename mtime = time.strftime("%b %d %H:%M", time.gmtime(os.path.get... |
self.reactor.removeReader(w) self.reactor.removeWriter(w) | def read(self, sock): why = None w = self.watcher try: why = w.doRead() except: why = sys.exc_value log.msg('Error in %s.doRead()' % w) log.deferr() if why: try: w.connectionLost(failure.Failure(why)) except: log.deferr() self.reactor.removeReader(w) self.reactor.removeWriter(w) self.reactor.simulate() | |
self.reactor.removeReader(w) self.reactor.removeWriter(w) | def write(self, sock): why = None w = self.watcher self.setEnabled(0) try: why = w.doWrite() except: why = sys.exc_value log.msg('Error in %s.doWrite()' % w) log.deferr() if why: try: w.connectionLost(failure.Failure(why)) except: log.deferr() self.reactor.removeReader(w) self.reactor.removeWriter(w) elif self.watcher:... | |
return long(gmpy.mpz(n, 256)), i[4+l:] | return long(gmpy.mpz(n+'\x00', 256)), i[4+l:] | def _fastgetMP(i): l = struct.unpack('!L', i[:4])[0] n = i[4:l+4][::-1] return long(gmpy.mpz(n, 256)), i[4+l:] |
getLatexText(node, buf.write, entities=entities) self.writer(buf.getvalue()) | getLatexText(node, buf.write, entities=hacked_entities) self.writer(buf.getvalue().rstrip()) | def writeNodeData(self, node): buf = StringIO() getLatexText(node, buf.write, entities=entities) self.writer(buf.getvalue()) |
text = domhelpers.getNodeText(node) lines = text.split('\n') self.writer('%font "typewriter", size 4\n') | buf = StringIO() getLatexText(node, buf.write, entities=entities) data = buf.getvalue() data = text.removeLeadingTrailingBlanks(data) lines = data.split('\n') | def visitNode_pre(self, node): # TODO: Syntax highlighting text = domhelpers.getNodeText(node) lines = text.split('\n') self.writer('%font "typewriter", size 4\n') self.fontStack.append(('typewriter', 4)) for line in lines: self.writer(' ' + line + '\n') del self.fontStack[-1] self.writer('%' + self.fontName() + '\n') |
return 'font "%s" size %d' % (name, size) | return 'font "%s", size %d' % (name, size) | def fontName(self): names = [x[0] for x in self.fontStack] if 'typewriter' in names: name = 'typewriter' else: name = '' |
end_h2 = '\n\n%font "typewriter", size 2\n\n%font "standard"\n' start_li = "\t" | end_h2 = '\n\n\n' _start_ul = '\n' _start_li = "\t" | def fontName(self): names = [x[0] for x in self.fontStack] if 'typewriter' in names: name = 'typewriter' else: name = '' |
from twisted.internet import base self.original = base.seconds | from twisted.internet import base, task from twisted.python import runtime self.base_original = base.seconds self.task_original = task.seconds self.runtime_original = runtime.seconds | def install(self): # Violation is fun. from twisted.internet import base self.original = base.seconds base.seconds = self |
from twisted.internet import base base.seconds = self.original | from twisted.internet import base, task from twisted.python import runtime base.seconds = self.base_original runtime.seconds = self.runtime_original task.seconds = self.task_original | def uninstall(self): from twisted.internet import base base.seconds = self.original |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.