rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
d.addCallback(keyValidated) d.addErrback(result.errback) | def keyValidated(x=None): d = defer.maybeDeferred(f, *args) d.chainDeferred(result) d.addBoth(self.logProtectedCall, path, args, user) | |
return result | def logProtectedCall(self, result, path, args, user, allowed=True): """This should be called when a protected call was attempted, successful or not. It logs the attempt and its results in the audit_trail database. This audit trail can be used for several things- listing recently updated metadata (perhaps for a 'whats n... | |
penVector = (self.width-1, (self.height-1) * (1-channel)) | penVector = (self.width-1, int((self.height-1) * (1-channel))) | def graphChannels(self): """Graph the current values of each channel. Called each time the graph is scrolled and/or the channel values are changed. """ for i in range(len(self.channels)): channel = self.channels[i] if channel is not None: # Calculate a current pen position, always at the right side of the graph penVect... |
def keyValidated(x=None): d = defer.maybeDeferred(f, *args) d.addBoth(self.logProtectedCall, path, args, user) d.chainDeferred(result) | def keyValidated(validationResult): if validationResult is None: d = defer.maybeDeferred(f, *args) d.addBoth(self.logProtectedCall, path, args, user) d.chainDeferred(result) else: self.logProtectedCall(validationResult, path, args, user, allowed=False) result.errback(validationResult) | def keyValidated(x=None): d = defer.maybeDeferred(f, *args) d.addBoth(self.logProtectedCall, path, args, user) d.chainDeferred(result) |
user = Security.User(key=key) | user = Security.User(key=str(key)) | def keyValidated(x=None): d = defer.maybeDeferred(f, *args) d.addBoth(self.logProtectedCall, path, args, user) d.chainDeferred(result) |
d.addErrback(self.logProtectedCall, path, args, user, allowed=False) d.addCallbacks(keyValidated, result.errback) | d.addCallbacks(keyValidated) | def keyValidated(x=None): d = defer.maybeDeferred(f, *args) d.addBoth(self.logProtectedCall, path, args, user) d.chainDeferred(result) |
_rootInterface = None | if '_rootInterface' not in globals(): global _rootInterface _rootInterface = None | def makeDefaultCaps(self, path): """Create a default list of acceptable capability IDs for the given path""" caps = ['universe'] base = [] for segment in path: base.append(str(segment)) caps.append(".".join(base)) return caps |
(loc[0], loc[2], loc[1]) = loc for i in range(len(loc)): loc[i] *= 0.1 loc[0] *= -1 loc[1] *= -1 | (loc[0], loc[2], loc[1]) = (loc[0] * -0.1, loc[1] * 0.1, loc[2] * -0.1) | def importData (reader, object, filename): action = Blender.Armature.NLA.NewAction(filename.split('/')[-1]) action.setActive(object) armature = object.getData() scene = Blender.Scene.getCurrent() context = scene.getRenderingContext() b = {} context.framesPerSec(120) bones = armature.getBones() for bone in bones: b[bo... |
app.server.debug.resetInterpreter(app.key) | def __init__(self, app): self.app = app app.server.debug.resetInterpreter(app.key) code.InteractiveConsole.__init__(self) | |
return "Node(%r)" % self.data | return "Combinatoric.Node(%r)" % self.data | def __repr__ (self): return "Node(%r)" % self.data |
return (type (other) is Node and self.data == other.data) | return (self.data == other.data) | def __eq__ (self, other): return (type (other) is Node and self.data == other.data) |
return (type (other) is not Node or self.data != other.data) | return (self.data != other.data) | def __ne__ (self, other): return (type (other) is not Node or self.data != other.data) |
if edge.u == node[name]: | if edge.v == node[name] and edge.u != edge.v: | def combineU (graphs): name, map = graphs[0] for edge in map.query (node[name]): if edge.u == node[name]: if len (graphs) == 1: yield {name: edge.u} continue |
edges = self.edgeLists[name] | edges = dict (self.data)[name] | def query (self, u, v): """Return the edge from 'u' to 'v'.""" combU = {} combV = {} for name in u.iterkeys (): edges = self.edgeLists[name] edge = edges.query (u[name], v[name]) combU[name] = edge.u combV[name] = edge.v |
print dir(w) | def miss(self, path, mtime): w = NouvelleWriter() core.publish_file(source_path = path, writer = w, destination = NullFile(), settings_overrides = {'output_encoding': 'unicode'} ) w.mtime = mtime print dir(w) del w.document return w | |
print "_load finished" | def _load(self, mainDoc, result): # It's a normal document. Get the document itself and its sidebar, # and store the formatter results that we're interested in. self.mainDoc = mainDoc self.mainColumn = Template.pageBody[self.mainDoc.output] self.mainTitle = self.mainDoc.docTitle if self.mainDoc.docSubtitle: self.subTit... | |
print "in _checkRender" | def _checkRender(self, loaded, result, context): print "in _checkRender" | |
return tag('a', _class='source', href="source/%s/" % source.name)[ info ] | return tag('a', _class='source', href="source/%s/" % source.name)[ tag('div', _class='source')[ info ]] | def renderSource(self, source, context): latest = source.getLatestPacket() info = [] |
return tag('div', _class='navigation')[[ tag('a', _class='navigation', href=" for name, length, anchor in self.intervals]] | return tag('div', _class='navigation')[ tag('a', _class='navigation', href='../../')[ "All Sensors..." ], [tag('a', _class='navigation', href=" for name, length, anchor in self.intervals], ] | def render_navigation(self, context): return tag('div', _class='navigation')[[ tag('a', _class='navigation', href="#%s" % anchor or 'top')[ name ] for name, length, anchor in self.intervals]] |
graphs.append(tag('img', _class='graph', src="graph/temperature:%s" % length)) | graphs.append('temperature') | def renderInterval(self, length): if not length: return self.renderLatest() graphs = [] |
graphs.append(tag('img', _class='graph', src="graph/voltage:%s" % length)) | graphs.append('voltage') | def renderInterval(self, length): if not length: return self.renderLatest() graphs = [] |
graphs.append(tag('img', _class='graph', src="graph/signal:%s" % length)) return tag('div', _class='graphs')[ graphs ] | graphs.append('signal') return tag('div', _class='graphs')[[ tag('img', _class='graph', width=691, height=205, alt="%s graph" % name, src="graph/%s:%s" % (name, length)) for name in graphs ]] | def renderInterval(self, length): if not length: return self.renderLatest() graphs = [] |
info.extend([ tag('div', _class='description')[ self.source.description ], ]) | def renderLatest(self): info = [] | |
def xmlrpc_list(self): | def xmlrpc_list(self, key): | def xmlrpc_list(self): """Return a list of all capabilities that have been assigned keys""" self.caps.faultIfMissing(key, 'universe', 'security.list') return self.caps.list() |
print "init" | def __init__(self, position=(0,0,0), numParticles=250): print "init" self.numParticles = numParticles self.model = ParticleSystem.SpriteFountain(numParticles) SpriteArray.__init__(self, numParticles, allowPointSprite=False) self.model.attachDrawable(self) | |
window.show() | window.show_all() | def close( window, event, user_data ): window.hide() |
print '%s said a URL: %s' % (nick, match.group()) | print '%s said url: %s' % ( nick, match.group() ) store.set( store.append(), 0, nick, 1, match.group() ) | def grabbedURL( nick, match ): print '%s said a URL: %s' % (nick, match.group()) |
self.search = Heuristic (graph, self.f, fixNode (source), fixNode (goal)) | def fixNode (node): """Short helper function that fixes negative angles and insures that all angles are on the interval [0, 360). """ n = {} for bone, pos in node.iteritems (): if bone == "root": pos = pos[3:6] pos = [Numeric.remainder (d, 360.0) for d in pos] pos = tuple (map (fix360, map (fixnegative, pos))) n[bone] ... | |
if node.inside (pos[bone]): | if not node.inside (pos[bone]): | def find_node (self, pos): """Finds the node in ``self.graph`` conataining the position ``pos``. |
cursor.execute("SELECT id, xml FROM stats_messages WHERE target_path = %s ORDER BY id DESC%s" % | cursor.execute("SELECT id, xml FROM stats_messages FORCE INDEX (target_path_2, id) " "WHERE target_path = %s ORDER BY id DESC%s" % | def _getLatest(self, cursor, limit): if limit is None: limitClause = '' else: limitClause = " LIMIT %d" % limit cursor.execute("SELECT id, xml FROM stats_messages WHERE target_path = %s ORDER BY id DESC%s" % (Database.quote(self.target.path, 'varchar'), limitClause)) return cursor.fetchall() |
self.messages = MessageBuffer(os.path.join(self.diskPath, 'messages')) | self.messages = MessageBuffer(os.path.join(self.diskPath, '_msg')) | def __init__(self, path=''): self.setPath(path) self.messages = MessageBuffer(os.path.join(self.diskPath, 'messages')) self.counters = Counters(self) self.metadata = Metadata(self) |
elif segment and segment != '.': | elif segment == '.': pass elif segment[0] in ('.', '_'): raise ValueError("Stats path segment %r begins with a reserved character" % segment) else: | def setPath(self, path): # Remove leading and trailing slashes, remove duplicate # slashes, process '.' and '..' directories. self.pathSegments = [] for segment in path.split('/'): if segment == '..': if self.pathSegments: del self.pathSegments[-1] elif segment and segment != '.': self.pathSegments.append(segment) self... |
self.messages.push(message) | self.messages.push(str(message)) | def deliver(self, message=None): """An event has occurred which should be logged by this stats target""" if message: self.messages.push(message) self.counters.increment() SubscriptionDelivery(self).notify('messages') |
entry.connect("toggled", lambda widget: setFunction(entry.get_active())) | entry.connect("toggled", lambda widget: setFunction(bool(entry.get_active()))) | def addWidget(self, initialValue, setFunction): entry = gtk.CheckButton() self.setWidget(entry, initialValue) entry.connect("toggled", lambda widget: setFunction(entry.get_active())) return entry |
def twistedInstall(interval=5): from twisted.internet import reactor s = Sampler() def sample(): s.run() reactor.callLater(interval, sample) sample() | os.chdir("types") types = [t for t in os.listdir(".") if not t.startswith(".")] | def twistedInstall(interval=5): from twisted.internet import reactor s = Sampler() def sample(): s.run() reactor.callLater(interval, sample) sample() |
class Sampler: def __init__(self, log="pymemprof.log"): self.log = open(log, "a") def run(self): timestamp = time.time() typeMap = {} for obj in gc.get_objects(): if hasattr(obj, '__class__'): t = obj.__class__ else: t = type(obj) t = str(getattr(t, '__name__', t)) typeMap[t] = typeMap.get(t, 0) + 1 tokens = [str(t... | g = Gnuplot.Gnuplot() for t in types: g('set terminal png') g('set output "%s.png"' % t) g('plot "%s"' % t) | def sample(): s.run() reactor.callLater(interval, sample) |
if not self.name: self.name = "Mesh" | def __init__(self, list=None): if list is not None: for property in list: getattr(self, "set_%s" % property[0])(property[1:]) if not self.name: self.name = "Mesh" | |
self.initialNickGenerator = self.botNet.nickAllocator.generate() self.nickname = self.initialNickGenerator.next() | self.nickname = self.findNickQuickly() | def connectionMade(self): """Called by IRCClient when we have a socket connection to the server.""" self.emptyChannels() self.network = self.factory.network self.botNet = self.factory.botNet |
self.register(self.initialNickGenerator.next()) | self.setNick("CIA-temp%03d" % random.randint(0, 999)) | def irc_ERR_NICKNAMEINUSE(self, prefix, params): """An alternate nickname-in-use error handler that picks the next nick from our allocator instead of using those blasted underscores """ self.register(self.initialNickGenerator.next()) |
log.msg("%r got an unsuitable nickname, trying to find a better one..." % self) | log.msg("%r starting nick negotiation" % self) | def nickChanged(self, newname): irc.IRCClient.nickChanged(self, newname) if not self.botNet.nickAllocator.isValid(newname): # We got a bad nick, try to find a better one log.msg("%r got an unsuitable nickname, trying to find a better one..." % self) self.findNick().addCallback(self.foundBetterNick) |
result.setTimeout(30, result.callback, False) self.sendLine("WHOIS %s" % nick) self.currentWhoisDeferred = result | if nick in self.pendingWhoisTests: self.pendingWhoisTests[nick].append(result) else: self.pendingWhoisTests[nick] = [result] self.sendLine("WHOIS %s" % nick) | def isNickUsed(self, nick): """Determine if the given nick is in use, using WHOIS. Returns a Deferred that eventually resolves to a boolean. |
self.currentWhoisDeferred.callback(True) del self.currentWhoisDeferred | nick = params[1] if nick in self.pendingWhoisTests: for result in self.pendingWhoisTests[nick]: result.callback(True) del self.pendingWhoisTests[nick] | def irc_RPL_WHOISUSER(self, prefix, params): """Reply to the WHOIS command we use to evaluate if a nick is used or not. This one would indicate that the nick is indeed used. """ self.currentWhoisDeferred.callback(True) del self.currentWhoisDeferred |
self.currentWhoisDeferred.callback(False) del self.currentWhoisDeferred | nick = params[1] if nick in self.pendingWhoisTests: for result in self.pendingWhoisTests[nick]: result.callback(False) del self.pendingWhoisTests[nick] def irc_RPL_WHOISSERVER(self, prefix, params): pass def irc_RPL_WHOISIDLE(self, prefix, params): pass def irc_RPL_WHOISCHANNELS(self, prefix, params): pass def irc_RP... | def irc_ERR_NOSUCHNICK(self, prefix, params): """Reply to the WHOIS command we use to evaluate if a nick is used or not. This indicates that the nick is available. """ self.currentWhoisDeferred.callback(False) del self.currentWhoisDeferred |
self.padding = padding self.pauseDuration = pauseDuration self.scrollRate = scrollRate | def textChanged(self, lines): Text.textChanged(self, lines) | def __init__(self, text = '', gravity = (0, -1), align = (0,0), priority = 1, background = ' ', padding = ' '*5, pauseDuration = 1, scrollRate = 10, visible = True, ): Text.__init__(self, text, gravity, align, priority, background, visible=visible) self.padding = padding se... |
def textChanged(self, lines): Text.textChanged(self, lines) | def __init__(self, text = '', gravity = (0, -1), align = (0,0), priority = 1, background = ' ', padding = ' '*5, pauseDuration = 1, scrollRate = 10, visible = True, ): Text.__init__(self, text, gravity, align, priority, background, visible=visible) self.padding = padding se... | |
self.text = time.strftime(format, time.localtime(self.getTime())) | self.text = time.strftime(format, self.getTime()) | def update(self, dt): format = self.format if self.blinkTime: if self.blinkState: format = format.replace(":", " ") self.blinkRemaining -= dt if self.blinkRemaining < 0: self.blinkState = not self.blinkState self.blinkRemaining += self.blinkTime self.text = time.strftime(format, time.localtime(self.getTime())) |
return time.time() | return time.localtime(time.time()) | def getTime(self): """Subclasses may override this to provide an alternate time to display""" return time.time() |
self.lifetimes[widget] -= dt if self.lifetimes[widget] <= 0: try: self.widgets.remove(widget) self.layoutRequired = True except ValueError: pass | try: self.lifetimes[widget] -= dt if self.lifetimes[widget] <= 0: try: self.widgets.remove(widget) self.layoutRequired = True except ValueError: pass except KeyError: pass | def update(self, dt=None): """Update all widgets with the given time step. This calculates its own time step if one isn't provided. """ if dt is None: now = time.time() if self.lastTime is None: self.lastTime = now return else: dt = now - self.lastTime self.lastTime = now |
failed widgets. If we have a vertical placement error, returns False. """ unplaceable = [] | widgets we should try to remove. If we have a vertical placement error, returns False. """ | def layoutIteration(self, widgets): """Attempt to lay out all given widgets. Returns True on success. If we have a horizontal placement error this returns a list of failed widgets. If we have a vertical placement error, returns False. """ unplaceable = [] |
unplaceable.append(widget) if unplaceable: return unplaceable | return widgets | def layoutIteration(self, widgets): """Attempt to lay out all given widgets. Returns True on success. If we have a horizontal placement error this returns a list of failed widgets. If we have a vertical placement error, returns False. """ unplaceable = [] |
a_path = self.pathToNode(a) costs[keyA] = self.costf(a_path, self.goal) | a_path = pathToNode(a) costs[keyA] = self.costf(a_path, goal) | def compare(a, b): keyA = toTuple(a) keyB = toTuple(b) |
b_path = self.pathToNode(b) costs[keyB] = self.costf(b_path, self.goal) | b_path = pathToNode(b) costs[keyB] = self.costf(b_path, goal) | def compare(a, b): keyA = toTuple(a) keyB = toTuple(b) |
if latest.get('average'): | if latest and latest.get('average'): | def renderSource(self, source, context): latest = source.getLatestPacket() info = [] |
if latest.get('voltage'): | if latest and latest.get('voltage'): | def renderSource(self, source, context): latest = source.getLatestPacket() info = [] |
if latest.get('time'): | if latest and latest.get('time'): | def renderSource(self, source, context): latest = source.getLatestPacket() info = [] |
if self.latest.get('average'): graphs.append('temperature') if self.latest.get('voltage'): graphs.append('voltage') if self.latest.get('signal_strength'): graphs.append('signal') return tag('div', _class='graphs')[[ | if self.latest: if self.latest.get('average'): graphs.append('temperature') if self.latest.get('voltage'): graphs.append('voltage') if self.latest.get('signal_strength'): graphs.append('signal') return tag('div', _class='graphs')[" ", [ | def renderInterval(self, length): if not length: return self.renderLatest() |
info = [] if self.latest.get('average'): info.append(renderTemperature(self.latest)) if self.latest.get('voltage'): info.append(tag('div', _class='extraInfo')[ renderBatteryBargraph(self.latest), ]) if self.latest.get('time'): info.append(tag('div', _class='extraInfo')[ renderTimestamp(self.latest), ]) | if self.latest: info = [] if self.latest.get('average'): info.append(renderTemperature(self.latest)) if self.latest.get('voltage'): info.append(tag('div', _class='extraInfo')[ renderBatteryBargraph(self.latest), ]) if self.latest.get('time'): info.append(tag('div', _class='extraInfo')[ renderTimestamp(self.latest), ... | def renderLatest(self): info = [] |
domain = context['request'].host[1], | domain = context['request'].getRequestHostname(), | def render_cloud(self, context): """Implements the first step of supporting the RSS 2.0 <cloud> tag. This element describes how the RSS aggregator can subscribe for instant notification of changes to this resource. """ return tag('cloud', domain = context['request'].host[1], port = context['requ... |
A[row, col:col+4] = [1, i+1, (i+1)**2, (i+1)**3] b[row] = data[i] row += 1 | if i <= n: A[row, col:col+4] = [1, i+1, (i+1)**2, (i+1)**3] b[row] = data[i + 1] row += 1 | def __createMatrices (self, data): """Generate the two matrices for the system of linear equations used to create the spline. """ n = len (data) - 1 |
for i in range (n): | for i in range (n-1): | def __createMatrices (self, data): """Generate the two matrices for the system of linear equations used to create the spline. """ n = len (data) - 1 |
t, y = intervals[0][0] | t, y = (0, data[0]) | def __createMatrices (self, data): """Generate the two matrices for the system of linear equations used to create the spline. """ n = len (data) - 1 |
t, y = intervals[-1][1] | t, y = (n, data[-1]) | def __createMatrices (self, data): """Generate the two matrices for the system of linear equations used to create the spline. """ n = len (data) - 1 |
generator = XML.dig(m.xml, "message", "gemerator") | generator = XML.dig(m.xml, "message", "generator") | def _render_rows(self, xml, context, result): # No message? if not xml: result.callback([]) return m = Message.Message(xml) rows = [] |
name = XML.digValue(gen, str, "name").strip() if gen.url: name = tag('a', href=str(gen.url).strip())[ name ] items = ["Generated by ", Template.value[name]] if gen.version: items.extend([" version ", str(gen.version).strip()]) | name = XML.digValue(gen, str, "name") url = XML.digValue(gen, str, "url") version = XML.digValue(gen, str, "version") if url: name = tag('a', href=url)[ name ] items = ["Generated by ", Template.value[ name ]] if version: items.extend([" version ", version]) | def format_generator(self, gen): """Format the information contained in this message's <generator> tag""" name = XML.digValue(gen, str, "name").strip() if gen.url: name = tag('a', href=str(gen.url).strip())[ name ] items = ["Generated by ", Template.value[name]] if gen.version: items.extend([" version ", str(gen.versio... |
def randomCommit(): | def randomCommit(rev=1): | def randomCommit(): """Create a random commit message""" return """ <message> <generator><name>torture_stats.py</name></generator> <source><project>%s</project></source> <body> <commit> <author>%s</author> <log>%s</log> </commit> </body> </message> """ % (generateRandom(randomProject), generateRandom(randomAuthor), gen... |
generateRandom(randomLog)) | generateRandom(randomLog), rev) | def randomCommit(): """Create a random commit message""" return """ <message> <generator><name>torture_stats.py</name></generator> <source><project>%s</project></source> <body> <commit> <author>%s</author> <log>%s</log> </commit> </body> </message> """ % (generateRandom(randomProject), generateRandom(randomAuthor), gen... |
messages = [randomCommit() for i in xrange(10000)] | messages = [randomCommit(i) for i in xrange(10000)] | def main(self): # Load rulesets print "Loading rulesets..." for ruleset in self.rulesets: self.server.ruleset.store(self.key, ruleset) |
def receiveBits(): | def receiveBits(device): """Receive bits from the device, yielding (bit, noise) tuples""" | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... |
port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" | port = open(device, "rb") | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... |
noise += bitCounts[ord(b) ^ 0xC0] bits += "1" | yield ("1", bitCounts[ord(b) ^ 0xC0]) | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... |
noise += bitCounts[ord(b) ^ 0xFC] bits += "0" | yield ("0", bitCounts[ord(b) ^ 0xFC]) def receiveFrames(device, flag="011110"): """Receive sequences of bits bounded by two 'flag' sequences. Yields (bitstring, signalStrength) tuples. """ bits = '' noise = 0 for bit, bitNoise in receiveBits(device): noise += bitNoise bits += bit | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... |
noise = 0 | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... | |
receivedRawPacket(bits[:-len(flag)], signalStrength) | yield (bits[:-len(flag)], signalStrength) | def receiveBits(): bitCounts = createBitCountTable() port = open("/dev/usb/tts/0", "rb") bits = '' noise = 0 flag = "011110" while 1: # Each byte read from the serial port is actually one bit # of data. We can measure noise by checking how closely it # matches the ideal bit patterns. b = port.read(1) if bitCounts[ord(... |
def receivedRawPacket(bits, signalStrength): """We received a bit sequence between two flags. It might be a valid packet""" bits = unstuff(bits) if len(bits) < 8: return | def receivedRawPacket(bits, signalStrength): """We received a bit sequence between two flags. It might be a valid packet""" # Unstuff it. Is it too short? bits = unstuff(bits) if len(bits) < 8: return # Check the CRC content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: return # Yay, it's valid print c... | |
content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: return | def receiveContent(device): """Receive validated packet content. Yields (content, signalStrength) tuples""" for bits, signalStrength in receiveFrames(device): bits = unstuff(bits) if len(bits) < 8: continue | def receivedRawPacket(bits, signalStrength): """We received a bit sequence between two flags. It might be a valid packet""" # Unstuff it. Is it too short? bits = unstuff(bits) if len(bits) < 8: return # Check the CRC content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: return # Yay, it's valid print c... |
print content, signalStrength | content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: continue yield (content, signalStrength) logFile = None def log(*values): """Log a tuple of values in CSV format to stdout and a log file""" global logFile if logFile is None: logFile = open("rx-log.csv", "w") line = ", ".join([str(value) for value... | def receivedRawPacket(bits, signalStrength): """We received a bit sequence between two flags. It might be a valid packet""" # Unstuff it. Is it too short? bits = unstuff(bits) if len(bits) < 8: return # Check the CRC content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: return # Yay, it's valid print c... |
receiveBits() | log("time", "signalStrength", "protocol", "station", "sequence", "voltage", "temperature") for content, signalStrength in receiveContent("/dev/usb/tts/0"): if len(content) != 31: continue try: protocol = unpack(content[:2]) station = unpack(content[2:8]) sequence = unpack(content[8:13]) voltage = unpack(content[13:23... | def receivedRawPacket(bits, signalStrength): """We received a bit sequence between two flags. It might be a valid packet""" # Unstuff it. Is it too short? bits = unstuff(bits) if len(bits) < 8: return # Check the CRC content = bits[:-8] crc = unpack(bits[-8:]) if crc8(content) != crc: return # Yay, it's valid print c... |
step = traj.len () / data.len () length = data.len () * step | step = len (traj) / len (data) length = len (len) * step | def _map (self, traj, data): """ Map the frames from the AMC file to the chaotic attractor. """ result = {} step = traj.len () / data.len () length = data.len () * step |
def __init__ (self): pass | def __init__ (self, index, data): | def __init__ (self): pass |
class TilePlaceholder: | class EmptyTilePlaceholder: | def draw(self, canvas, x, y): canvas.blit(self.image, target=(x,y)) |
haven't downloaded yet. The interface is identical to a real TileImage. | haven't downloaded yet. This just gives us a generic gray block. | def draw(self, canvas, x, y): canvas.blit(self.image, target=(x,y)) |
def get(self, *key): | def get(self, key): | def get(self, *key): try: obj = self.mru[key] except KeyError: # Cache miss. If our MRU list is full, evict something. if len(self.mru) == self.size: self.mru.popOldest() |
obj = self.backing.get(*key) | obj = self.backing.get(key, memCache=self) | def get(self, *key): try: obj = self.mru[key] except KeyError: # Cache miss. If our MRU list is full, evict something. if len(self.mru) == self.size: self.mru.popOldest() |
def get(self, source, tile): | def get(self, (source, tile), memCache=None): | def get(self, source, tile): """Request a tile from the cache. Returns a TileImage if it's available now, otherwise returns a TilePlaceholder and requests the tile from our fetcher. """ path = self.getPath(source, tile) if os.path.isfile(path): try: return TileImage(path) except SymbianError: # An invalid image. Retry ... |
return TilePlaceholder() | if memCache: try: x = tile[0] & 1 y = tile[1] & 1 parent = memCache.mru[(source, (tile[0] >> 1, tile[1] >> 1, tile[2] - 1))] except KeyError: pass else: return ZoomedTilePlaceholder(parent, x, y) return EmptyTilePlaceholder() | def get(self, source, tile): """Request a tile from the cache. Returns a TileImage if it's available now, otherwise returns a TilePlaceholder and requests the tile from our fetcher. """ path = self.getPath(source, tile) if os.path.isfile(path): try: return TileImage(path) except SymbianError: # An invalid image. Retry ... |
self.ui.drawStatus() | def completed(self, url): """A URL has completed. Notify the UI, and remove it from our pending list. """ del self.pendingUrls[url] self.ui.downloadProgress = None self.ui.drawStatus() self.ui.needsRedraw() | |
self.ui.drawStatus() | self.ui.needsStatusUpdate() | def progress(self, p): """Update the UI's progress bar""" self.ui.downloadProgress = p self.ui.drawStatus() |
obj = self.cache.get(self.sources[self.sourceIndex], tile) | obj = self.cache.get((self.sources[self.sourceIndex], tile)) | def drawTile(self, x, y, tile): """Retrieve and draw one tile at the given position""" obj = self.cache.get(self.sources[self.sourceIndex], tile) obj.draw(self.backbuffer, x, y) |
self.drawAll() | if self.redrawFlag: self.redrawFlag = 2 else: self.redrawFlag = 1 while self.redrawFlag: self.drawAll() self.redrawFlag -= 1 def needsStatusUpdate(self): """Update the status if we aren't busy, otherwise wait for drawAll to get there. """ if not self.redrawFlag: self.drawStatus() | def needsRedraw(self): """Calling this function indicates that we need to redraw the map. This is called by UI callbacks, so it can happen any time an active object may be invoked by Symbian- even during a redraw. If we get called during a redraw, this schedules another redraw to happen immediately after this one is fi... |
if not self.__class__.componentTree: self.__class__.componentTree = XML.parseString(self.__class__.defaultComponentTree).documentElement | if self.__class__._defaultTreeOwner is not self.__class__.defaultComponentTree: self.__class__._defaultTreeOwner = self.__class__.defaultComponentTree self.__class__._cachedDefaultTree = XML.parseString(self.__class__.defaultComponentTree).documentElement | def format(self, args): """The formatter entry point. This just finds the current component tree and invokes walkComponents and joinComponents on it. """ # Parse the default component tree only once if not self.__class__.componentTree: self.__class__.componentTree = XML.parseString(self.__class__.defaultComponentTree).... |
tree = self.componentTree | tree = self.componentTree or self.__class__._cachedDefaultTree | def format(self, args): """The formatter entry point. This just finds the current component tree and invokes walkComponents and joinComponents on it. """ # Parse the default component tree only once if not self.__class__.componentTree: self.__class__.componentTree = XML.parseString(self.__class__.defaultComponentTree).... |
self.material.setEmit(float(emission[4])) | if len(emission) == 3: self.material.setEmit(1.0) else: self.material.setEmit(float(emission[3])) | def set_emission(self, emission): # FIXME - need to set emission color self.material.setEmit(float(emission[4])) |
'output_encoding': 'unicode', | def miss(self, path, mtime): w = NouvelleWriter() core.publish_file(source_path = path, writer = w, destination = NullFile(), settings_overrides = { 'output_encoding': 'unicode', | |
spark_material.texture = soya.open_image("blue_spark.png") | spark_material.texture = soya.open_image(os.path.join(datadir, "blue_spark.png")) | def __init__(self,parent): soya.Particles.__init__(self,parent,nb_max_particles=150) self.t = 0 |
r = 1.0 self.set_xyz(math.sin(self.t)*r, math.cos(self.t)*r - r, 0) | self.set_xyz(math.sin(self.t) * 1.0, math.cos(self.t) * 1.0, 0) | def advance_time(self, proportion): soya.Smoke.advance_time(self, proportion) |
def setup(): soya.init() print "argv: %r" % (sys.argv,) soya.path.append(os.path.join(os.path.dirname(sys.argv[0]), "data")) | def setup(self): soya.init(width=self.resolution[0], height=self.resolution[1]) | def setup(): soya.init() print "argv: %r" % (sys.argv,) soya.path.append(os.path.join(os.path.dirname(sys.argv[0]), "data")) |
self.idler = soya.Idler(scene) | self.idler = soya.Idler(self.scene) | def setup(): soya.init() print "argv: %r" % (sys.argv,) soya.path.append(os.path.join(os.path.dirname(sys.argv[0]), "data")) |
def render(): | def render(self): | def render(): self.idler.begin_round() self.idler.advance_time(1.0) self.idler.end_round() self.camera.render() |
print "mtime %r -> %r" % (self.path, self.mtime.seconds) | if self.dirCache is not None: self.nlink = len(self.dirCache) + 1 | def updateStat(self): """Unlike SpreadFile objects, SpreadDirectories may have their stat() info updated dynamically due to FAM events. This is necessary to get clients to update themselves when a directory changes. Most stat info comes from an arbitrary directory, but all timestamps are the newest of all directories. ... |
if code in ('deleted', 'changed', 'created'): self.updateStat() | def onMonitorEvent(self, event): code = event.code2str() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.