rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
CONFIG_DESCRIPTIONS[option] = (argument, description.rstrip())
CONFIG_DESCRIPTIONS[option.lower()] = (argument, description.rstrip())
def loadOptionDescriptions(loadPath = None): """ Fetches and parses descriptions for tor's configuration options from its man page. This can be a somewhat lengthy call, and raises an IOError if issues occure. If available, this can load the configuration descriptions from a file where they were previously persisted to...
CONFIG_DESCRIPTIONS[lastOption] = (lastArg, strippedDescription)
CONFIG_DESCRIPTIONS[lastOption.lower()] = (lastArg, strippedDescription)
def loadOptionDescriptions(loadPath = None): """ Fetches and parses descriptions for tor's configuration options from its man page. This can be a somewhat lengthy call, and raises an IOError if issues occure. If available, this can load the configuration descriptions from a file where they were previously persisted to...
if option in CONFIG_DESCRIPTIONS: returnVal = CONFIG_DESCRIPTIONS[option]
if option.lower() in CONFIG_DESCRIPTIONS: returnVal = CONFIG_DESCRIPTIONS[option.lower()]
def getConfigDescription(option): """ Provides a tuple with arguments and description for the given tor configuration option, fetched from its man page. This provides None if no such option has been loaded. If the man page is in the process of being loaded then this call blocks until it finishes. Arguments: option - t...
if logErrors: log.log(log.WARN, "Unable to validate torrc")
if logErrors: log.log(log.WARN, "Unable to validate line %i of the torrc: %s" % (lineNumber + 1, lineText))
def reset(self, logErrors=True): """ Reloads torrc contents and resets scroll height. Returns True if successful, else false. """ try: resetSuccessful = True confFile = open(self.confLocation, "r") self.confContents = confFile.readlines() confFile.close() # checks if torrc differs from get_option data self.irrelevan...
colCount = param.primaryCounts[self.updateInterval][col + 1] - primaryMinBound
colCount = int(param.primaryCounts[self.updateInterval][col + 1]) - primaryMinBound
def draw(self, subwindow, width, height): """ Redraws graph panel """ if self.currentDisplay: param = self.stats[self.currentDisplay] graphCol = min((width - 10) / 2, param.maxCol) primaryColor = uiTools.getColor(param.getColor(True)) secondaryColor = uiTools.getColor(param.getColor(False)) if self.showLabel: self.a...
colCount = param.secondaryCounts[self.updateInterval][col + 1] - secondaryMinBound
colCount = int(param.secondaryCounts[self.updateInterval][col + 1]) - secondaryMinBound
def draw(self, subwindow, width, height): """ Redraws graph panel """ if self.currentDisplay: param = self.stats[self.currentDisplay] graphCol = min((width - 10) / 2, param.maxCol) primaryColor = uiTools.getColor(param.getColor(True)) secondaryColor = uiTools.getColor(param.getColor(False)) if self.showLabel: self.a...
totalBandwidth += descInfo[nsEntry.idhex][0]
if nsEntry.idhex in descInfo: totalBandwidth += descInfo[nsEntry.idhex][0] elif nsEntry.bandwidth: totalBandwidth += nsEntry.bandwidth
def getBandwidth(self, descInfo, relayType, newOnly=True): totalBandwidth = 0 relaySet = self.newRelays[relayType] if newOnly else self.allRelays[relayType] for nsEntry in relaySet: totalBandwidth += descInfo[nsEntry.idhex][0] #if nsEntry.bandwidth: totalBandwidth += nsEntry.bandwidth return totalBandwidth
descInfo[nsEntry.idhex] = (0, "")
pass
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
if len(samplings) > 168:
if len(samplings) > 192:
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
earlierDate = samplings[-25].getValidAfter().split(" ")[0] if lastDate == earlierDate: samplings = samplings[:-25]
cropStart = -25 while samplings[cropStart].getValidAfter().split(" ")[0] != lastDate: cropStart += 1 samplings = samplings[:cropStart]
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
exitPolicy = [str(policyLine) for policyLine in descInfo[nsEntry.idhex][1]]
if nsEntry.idhex in descInfo: bwLabel = getSizeLabel(descInfo[nsEntry.idhex][0], 2) exitPolicyLabel = ", ".join([str(policyLine) for policyLine in descInfo[nsEntry.idhex][1]]) else: bwLabel = getSizeLabel(nsEntry.bandwidth, 2) exitPolicyLabel = "Unknown"
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
nsContents += " bandwidth: %s\n" % getSizeLabel(descInfo[nsEntry.idhex][0], 2)
nsContents += " bandwidth: %s\n" % bwLabel
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
nsContents += " exit policy: %s\n\n" % ", ".join(exitPolicy)
nsContents += " exit policy: %s\n\n" % exitPolicyLabel
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
if countAlert or bwAlert or (tick % 24 == 0):
isMidnightEntry = newSampling.getValidAfter().split(" ")[1] == "23:00:00" if countAlert or bwAlert or isMidnightEntry:
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
samplingTotalBw += descInfo[nsEntry.idhex][0]
if nsEntry.idhex in descInfo: samplingTotalBw += descInfo[nsEntry.idhex][0] else: samplingTotalBw += nsEntry.bandwidth
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
timezoneOffset = time.altzone if time.localtime()[8] else time.timezone currentDay = int((time.time() - timezoneOffset) / 86400)
currentDay = daysSince()
def getDaybreaks(events, ignoreTimeForCache = False): """ Provides the input events back with special 'DAYBREAK_EVENT' markers inserted whenever the date changed between log entries (or since the most recent event). The timestamp matches the beginning of the day for the following entry. Arguments: events -...
eventDay = int((entry.timestamp - timezoneOffset) / 86400)
eventDay = daysSince(entry.timestamp)
def getDaybreaks(events, ignoreTimeForCache = False): """ Provides the input events back with special 'DAYBREAK_EVENT' markers inserted whenever the date changed between log entries (or since the most recent event). The timestamp matches the beginning of the day for the following entry. Arguments: events -...
markerTimestamp = (eventDay * 86400) + timezoneOffset
markerTimestamp = (eventDay * 86400) + TIMEZONE_OFFSET
def getDaybreaks(events, ignoreTimeForCache = False): """ Provides the input events back with special 'DAYBREAK_EVENT' markers inserted whenever the date changed between log entries (or since the most recent event). The timestamp matches the beginning of the day for the following entry. Arguments: events -...
if len(self._pauseBuffer) > cacheSize: del self._pauseBuffer[cacheSize:]
self._trimEvents(self._pauseBuffer) self.valsLock.release()
def registerEvent(self, event): """ Notes event and redraws log. If paused it's held in a temporary buffer. Arguments: event - LogEntry for the event that occurred """ if not event.type in self.loggedEvents: return # strips control characters to avoid screwing up the terminal event.msg = "".join([char for char in ev...
if len(self.msgLog) > cacheSize: del self.msgLog[cacheSize:]
self._trimEvents(self.msgLog)
def registerEvent(self, event): """ Notes event and redraws log. If paused it's held in a temporary buffer. Arguments: event - LogEntry for the event that occurred """ if not event.type in self.loggedEvents: return # strips control characters to avoid screwing up the terminal event.msg = "".join([char for char in ev...
timezoneOffset = time.altzone if time.localtime()[8] else time.timezone currentTime = time.time()
def run(self): """ Redraws the display, coalescing updates if events are rapidly logged (for instance running at the DEBUG runlevel) while also being immediately responsive if additions are less frequent. """ timezoneOffset = time.altzone if time.localtime()[8] else time.timezone currentTime = time.time() # unix time...
dayStartTime = currentTime - (currentTime - timezoneOffset) % 86400
currentTime = time.time() dayStartTime = currentTime - (currentTime - TIMEZONE_OFFSET) % 86400
def run(self): """ Redraws the display, coalescing updates if events are rapidly logged (for instance running at the DEBUG runlevel) while also being immediately responsive if additions are less frequent. """ timezoneOffset = time.altzone if time.localtime()[8] else time.timezone currentTime = time.time() # unix time...
dayStartTime = currentTime - (currentTime - timezoneOffset) % 86400
dayStartTime = currentTime - (currentTime - TIMEZONE_OFFSET) % 86400
def run(self): """ Redraws the display, coalescing updates if events are rapidly logged (for instance running at the DEBUG runlevel) while also being immediately responsive if additions are less frequent. """ timezoneOffset = time.altzone if time.localtime()[8] else time.timezone currentTime = time.time() # unix time...
if nsCall: familyAddress, familyPort = nsCall[0][6], nsCall[0][7]
if nsCall: familyAddress, familyPort = nsCall[0].ip, nsCall[0].orport
def reset(self): """ Reloads netstat results. """ # inaccessable during startup so might need to be refetched try: if not self.address: self.address = self.conn.get_info("address")["address"] except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed): pass self.connectionsLock.acquire() self.clientConnectionLock.a...
if currentTime - lastPerformanceLog >= CONFIG["features.logRefreshRate"]:
if currentTime - lastPerformanceLog >= CONFIG["logging.rate.refreshRate"]:
def drawTorMonitor(stdscr, loggedEvents, isBlindMode): """ Starts arm interface reflecting information on provided control port. stdscr - curses window conn - active Tor control port connection loggedEvents - types of events to be logged (plus an optional "UNKNOWN" for otherwise unrecognized events) """ # loads confi...
if line.startswith("CLIENT"): lastCategory = CLIENT
if line.startswith("OPTIONS"): lastCategory = GENERAL elif line.startswith("CLIENT"): lastCategory = CLIENT
def loadOptionDescriptions(loadPath = None): """ Fetches and parses descriptions for tor's configuration options from its man page. This can be a somewhat lengthy call, and raises an IOError if issues occure. If available, this can load the configuration descriptions from a file where they were previously persisted to...
primaryMinBound = min(param.primaryCounts[self.updateInterval][1:graphCol + 1]) secondaryMinBound = min(param.secondaryCounts[self.updateInterval][1:graphCol + 1])
primaryMinBound = int(min(param.primaryCounts[self.updateInterval][1:graphCol + 1])) secondaryMinBound = int(min(param.secondaryCounts[self.updateInterval][1:graphCol + 1]))
def draw(self, subwindow, width, height): """ Redraws graph panel """ if self.currentDisplay: param = self.stats[self.currentDisplay] graphCol = min((width - 10) / 2, param.maxCol) primaryColor = uiTools.getColor(param.getColor(True)) secondaryColor = uiTools.getColor(param.getColor(False)) if self.showLabel: self.a...
self.allowDNS = True
self.allowDNS = False
def __init__(self, stdscr, conn, isDisabled): TorCtl.PostEventListener.__init__(self) panel.Panel.__init__(self, stdscr, "conn", 0) self.scroll = 0 self.conn = conn # tor connection for querrying country codes self.listingType = LIST_IP # information used in listing entries self.allowDNS = True ...
msgHtml += dailyCellEntry % (date + " ", max(gCounts), sum(gNew), getSizeLabel(sum(gBw)), max(mCounts), sum(mNew), getSizeLabel(sum(mBw)), max(eCounts), sum(eNew), getSizeLabel(sum(eBw)), bwAvgLabel)
msgHtml += dailyCellEntry % (date + " ", gCountAvg, sum(gNew), getSizeLabel(sum(gBw)), mCountAvg, sum(mNew), getSizeLabel(sum(mBw)), eCountAvg, sum(eNew), getSizeLabel(sum(eBw)), bwAvgLabel)
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
if not nsEntry.idhex in seenFingerprints: newEntries.append(nsEntry) seenFingerprints.add(nsEntry.idhex)
if not nsEntry.idhex in descInfo:
def monitorConsensus(): gmailAccount, gmailPassword = DEFAULT_GMAIL_ACCOUNT, "" toAddress = DEFAULT_TO_ADDRESS seenFingerprintsPath = DEFAULT_FINGERPRINTS nsOutputPath = DEFAULT_NS_OUTPUT isQuiet = False # parses user input, noting any issues try: opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED) except geto...
if missingSec: msg += " (last %s is missing)" % uiTools.getTimeLabel(missingSec)
if missingSec: msg += " (last %s is missing)" % uiTools.getTimeLabel(missingSec, 0, True)
def prepopulateFromState(self): """ Attempts to use tor's state file to prepopulate values for the 15 minute interval via the BWHistoryReadValues/BWHistoryWriteValues values. This returns True if successful and False otherwise. """ # gets the uptime (using the same parameters as the header panel to take # advantage of...
self.addstr(row + 2, 0, "%4i" % primaryVal, primaryColor)
if not primaryVal in (primaryMinBound, primaryMaxBound): self.addstr(row + 2, 0, "%4i" % primaryVal, primaryColor)
def draw(self, subwindow, width, height): """ Redraws graph panel """ if self.currentDisplay: param = self.stats[self.currentDisplay] graphCol = min((width - 10) / 2, param.maxCol) primaryColor = uiTools.getColor(param.getColor(True)) secondaryColor = uiTools.getColor(param.getColor(False)) if self.showLabel: self.a...
self.addstr(row + 2, graphCol + 5, "%4i" % secondaryVal, secondaryColor)
if not secondaryVal in (secondaryMinBound, secondaryMaxBound): self.addstr(row + 2, graphCol + 5, "%4i" % secondaryVal, secondaryColor)
def draw(self, subwindow, width, height): """ Redraws graph panel """ if self.currentDisplay: param = self.stats[self.currentDisplay] graphCol = min((width - 10) / 2, param.maxCol) primaryColor = uiTools.getColor(param.getColor(True)) secondaryColor = uiTools.getColor(param.getColor(False)) if self.showLabel: self.a...
missingSec = 900 * max(missingReadEntries, missingWriteEntries) if missingSec: msg += "(last %s is missing)" % uiTools.getTimeLabel(missingSec)
missingSec = time.time() - min(lastReadTime, lastWriteTime) if missingSec: msg += " (last %s is missing)" % uiTools.getTimeLabel(missingSec)
def prepopulateFromState(self): """ Attempts to use tor's state file to prepopulate values for the 15 minute interval via the BWHistoryReadValues/BWHistoryWriteValues values. This returns True if successful and False otherwise. """ # gets the uptime (using the same parameters as the header panel to take # advantage of...
if familyEntry: self.family = [entry[1:] for entry in familyEntry.split(",")]
if familyEntry: self.family = familyEntry.split(",")
def resetOptions(self): self.familyResolutions = {} try: self.address = "" # fetched when needed if unset self.nickname = self.conn.get_option("Nickname")[0][1] self.orPort = self.conn.get_option("ORPort")[0][1] self.dirPort = self.conn.get_option("DirPort")[0][1] self.controlPort = self.conn.get_option("ControlPort"...
for fingerprint in self.family:
for familyEntry in self.family: fingerprint = None if familyEntry in self.familyFingerprints: fingerprint = self.familyFingerprints[familyEntry]
def reset(self): """ Reloads connection results. """ if self.isDisabled: return # inaccessable during startup so might need to be refetched try: if not self.address: self.address = self.conn.get_info("address")["address"] except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed): pass self.connectionsLock.acquir...
nsCall = self.conn.get_network_status("id/%s" % fingerprint)
if fingerprint: nsCall = self.conn.get_network_status("id/%s" % fingerprint) else: nsCall = self.conn.get_network_status("name/%s" % familyEntry)
def reset(self): """ Reloads connection results. """ if self.isDisabled: return # inaccessable during startup so might need to be refetched try: if not self.address: self.address = self.conn.get_info("address")["address"] except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed): pass self.connectionsLock.acquir...
familyResolutionsTmp[(familyAddress, familyPort)] = fingerprint
if fingerprint: familyResolutionsTmp[(familyAddress, familyPort)] = fingerprint
def reset(self): """ Reloads connection results. """ if self.isDisabled: return # inaccessable during startup so might need to be refetched try: if not self.address: self.address = self.conn.get_info("address")["address"] except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed): pass self.connectionsLock.acquir...
familyResolutionsTmp[("256.255.255.255", portIdentifier)] = fingerprint
if fingerprint: familyResolutionsTmp[("256.255.255.255", portIdentifier)] = fingerprint
def reset(self): """ Reloads connection results. """ if self.isDisabled: return # inaccessable during startup so might need to be refetched try: if not self.address: self.address = self.conn.get_info("address")["address"] except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed): pass self.connectionsLock.acquir...
elif armEventBacklog[0].timestamp > torEventBacklog[0].timestamp:
elif armEventBacklog[0].timestamp < torEventBacklog[0].timestamp:
def __init__(self, stdscr, loggedEvents, config=None): panel.Panel.__init__(self, stdscr, "log", 0) threading.Thread.__init__(self) self._config = dict(DEFAULT_CONFIG) if config: config.update(self._config) # ensures prepopulation and cache sizes are sane self._config["features.log.prepopulateReadLimit"] = max(self....
local, foreign = comp[7].split("->")
local, foreign = comp[8].split("->")
def getConnections(resolutionCmd, processName, processPid = ""): """ Retrieves a list of the current connections for a given process, providing a tuple list of the form: [(local_ipAddr1, local_port1, foreign_ipAddr1, foreign_port1), ...] this raises an IOError if no connections are available or resolution fails (in mos...
if isPrivate: if type == "inbound": src = "<scrubbed>" elif type == "outbound": dst = "<scrubbed>"
if isPrivate: dst = "<scrubbed>"
def draw(self): self.connectionsLock.acquire() try: # hostnames frequently get updated so frequent sorting needed if self.listingType == LIST_HOSTNAME: self.sortConnections() if self.showLabel: # notes the number of connections for each type if above zero countLabel = "" for i in range(len(self.connectionCount)): if s...
authPassword = config.get(DEFAULTS["startup.controlPassword"], None)
authPassword = config.get("startup.controlPassword", DEFAULTS["startup.controlPassword"])
def isValidIpAddr(ipStr): """ Returns true if input is a valid IPv4 address, false otherwise. """ for i in range(4): if i < 3: divIndex = ipStr.find(".") if divIndex == -1: return False # expected a period to be valid octetStr = ipStr[:divIndex] ipStr = ipStr[divIndex + 1:] else: octetStr = ipStr try: octet = int(oct...
if self._config["features.graph.bw.accounting.show"]:
if eventType == torTools.TOR_INIT and self._config["features.graph.bw.accounting.show"]:
def resetListener(self, conn, eventType): # updates title parameters and accounting status if they changed self._titleStats = [] # force reset of title self.new_desc_event(None) # updates title params if self._config["features.graph.bw.accounting.show"]: self.isAccounting = conn.getInfo('accounting/enabled') == '1...
labelingLine = graphPanel.GraphStats.getContentHeight(self) + panel.graphHeight - 2
def draw(self, panel, width, height): # if display is narrow, overwrites x-axis labels with avg / total stats if width <= COLLAPSE_WIDTH: # line of the graph's x-axis labeling labelingLine = graphPanel.GraphStats.getContentHeight(self) + panel.graphHeight - 2 # clears line panel.addstr(labelingLine, 0, " " * width) gr...
self.win.addstr(y, x, msg[:self.maxX - x - 1], attr)
try: self.win.addstr(y, x, msg[:self.maxX - x - 1], attr) except: pass
def addstr(self, y, x, msg, attr=curses.A_NORMAL): """ Writes string to subwindow if able. This takes into account screen bounds to avoid making curses upset. This should only be called from the context of a panel's draw method. Arguments: y - vertical location x - horizontal location msg - text to be added att...
self.win.vline(drawBottom, 1, curses.ACS_LRCORNER, 1) self.win.hline(drawBottom, 0, curses.ACS_HLINE, 1)
self.win.addch(drawBottom, 1, curses.ACS_LRCORNER) self.win.addch(drawBottom, 0, curses.ACS_HLINE)
def addScrollBar(self, top, bottom, size, drawTop = 0, drawBottom = -1): """ Draws a left justified scroll bar reflecting position within a vertical listing. This is shorted if necessary, and left undrawn if no space is available. The bottom is squared off, having a layout like: | *| *| *| | -+ This should only be cal...
labelingLine = self.getContentHeight() + panel.graphHeight - 5
labelingLine = graphPanel.GraphStats.getContentHeight(self) + panel.graphHeight - 2
def draw(self, panel, width, height): # if display is narrow, overwrites x-axis labels with avg / total stats if width <= COLLAPSE_WIDTH: # line of the graph's x-axis labeling labelingLine = self.getContentHeight() + panel.graphHeight - 5 # clears line panel.addstr(labelingLine, 0, " " * width) graphCol = min((width -...
return self._getRelayAttr("fingerprint", default)
return self._getRelayAttr("fingerprint", default, False)
def getMyFingerprint(self, default = None): """ Provides the fingerprint for this relay. Arguments: default - result if the query fails """ return self._getRelayAttr("fingerprint", default)
def _getRelayAttr(self, key, default):
def _getRelayAttr(self, key, default, cacheUndefined = True):
def _getRelayAttr(self, key, default): """ Provides information associated with this relay, using the cached value if available and otherwise looking it up. Arguments: key - parameter being queried (from CACHE_ARGS) default - value to be returned if undefined """ currentVal = self._cachedParam[key] if currentVal:...
key - parameter being queried (from CACHE_ARGS) default - value to be returned if undefined
key - parameter being queried (from CACHE_ARGS) default - value to be returned if undefined cacheUndefined - caches when values are undefined, avoiding further lookups if true
def _getRelayAttr(self, key, default): """ Provides information associated with this relay, using the cached value if available and otherwise looking it up. Arguments: key - parameter being queried (from CACHE_ARGS) default - value to be returned if undefined """ currentVal = self._cachedParam[key] if currentVal:...
else: self._cachedParam[key] = UNKNOWN
elif cacheUndefined: self._cachedParam[key] = UNKNOWN
def _getRelayAttr(self, key, default): """ Provides information associated with this relay, using the cached value if available and otherwise looking it up. Arguments: key - parameter being queried (from CACHE_ARGS) default - value to be returned if undefined """ currentVal = self._cachedParam[key] if currentVal:...
author = models.ForeignKey(_('author'), User)
author = models.ForeignKey(User, verbose_name=_('author'))
def get_query_set(self): return super(EntryLiveManager, self).get_query_set().filter( status=self.model.LIVE_STATUS )
status = models.IntegerField(_('slug'),
status = models.IntegerField(_('status'),
def get_query_set(self): return super(EntryLiveManager, self).get_query_set().filter( status=self.model.LIVE_STATUS )
dispatch_server = ('messenger.hotmail.com', 1863)
def main(password): global counter sys.stdout.write ("[-] Trying : %s \n" % (password)) sys.stdout.flush() file.write("[-] Trying : %s \n" % (str(password))) try: dispatch_server = ('messenger.hotmail.com', 1863) msntmp = msnp.Session(msnparse()) msntmp.login(email, password) print "[+] W00t w00t !!!\n[+] Username : [%...
if(not os.path.isdir(ICON_SVG_PATH)): create_pngs() smiley_icon_image=gtk.image_new_from_file(os.path.join(ICON_SVG_PATH,'smiley-icon')+".png") self.smiley = RadioMenuButton(icon_widget=smiley_icon_image) self.smiley.set_tooltip(_('Insert Smiley')) toolbar_box.toolbar.insert(self.smiley, -1) self.smiley.show()...
def __init__(self, handle): super(Chat, self).__init__(handle)
message = hippo.CanvasText( text=text,
text=process_text_for_continuous_smileys(text) line=text words=line.split(' ') for word in words: if is_smiley(word): image=get_smiley(word) msg_hbox.append(image) else: message = hippo.CanvasText(text=word+" ",
def add_text(self, buddy, text, status_message=False): """Display text on screen, with name and colors.
if choice != 'q':
choose_from = range(len(categories)+1) del choose_from[0] for i in range(len(choose_from)): choose_from[i] = str(choose_from[i]) print choose_from if choice in choose_from:
def chooseCategory(categories): """ Asks the user to choose a category. May exit the program. Type: Category list -> Category or None """ print " Choose a category (or quit)" print i = 0 for x in categories: i = i + 1 print " (%i) %s" % (i, x.name) print print " (q) Quit" choice = getChoice("") if choice != 'q...
bye()
starting()
def chooseCategory(categories): """ Asks the user to choose a category. May exit the program. Type: Category list -> Category or None """ print " Choose a category (or quit)" print i = 0 for x in categories: i = i + 1 print " (%i) %s" % (i, x.name) print print " (q) Quit" choice = getChoice("") if choice != 'q...
print "Some spec-file: %s" % spec
def get_sources(self): sources_list = {} for spec in os.listdir(self.current_dir): if 'spec' not in spec: # == '.' or spec == '..': continue #print "Some spec-file: %s" % spec params = {} spec_f = open(os.path.join(self.current_dir, spec), 'r') for line in spec_f: if ':' not in line: continue try: key, value = line.spl...
name = params['name'] version = params['version']
def get_sources(self): sources_list = {} for spec in os.listdir(self.current_dir): if 'spec' not in spec: # == '.' or spec == '..': continue #print "Some spec-file: %s" % spec params = {} spec_f = open(os.path.join(self.current_dir, spec), 'r') for line in spec_f: if ':' not in line: continue try: key, value = line.spl...
if '://' in params[p] and ('source' in params[p] or 'patch' in params[p]) and p.lower() != 'url':
if '://' in params[p] and ('source' in p.lower() or 'patch' in p.lower()) and p.lower() != 'url':
def get_sources(self): sources_list = {} for spec in os.listdir(self.current_dir): if 'spec' not in spec: # == '.' or spec == '..': continue #print "Some spec-file: %s" % spec params = {} spec_f = open(os.path.join(self.current_dir, spec), 'r') for line in spec_f: if ':' not in line: continue try: key, value = line.spl...
filename = self._filename_from_url(url_raw)
filename = self._filename_from_url(u.url)
def get_sources(self): sources_list = {} for spec in os.listdir(self.current_dir): if 'spec' not in spec: # == '.' or spec == '..': continue #print "Some spec-file: %s" % spec params = {} spec_f = open(os.path.join(self.current_dir, spec), 'r') for line in spec_f: if ':' not in line: continue try: key, value = line.spl...
storages = [s.name for s in zeo_conf.sections
storages = [s.name or '1' for s in zeo_conf.sections
def install(self): options = self.options
driver = os.environ.get('SELENIUM_DRIVER', 'firefox')
driver = os.environ.get('SELENIUM_DRIVER', '') or 'firefox'
def setUpPloneSite(self, portal): # Start up Selenium driver = os.environ.get('SELENIUM_DRIVER', 'firefox') webdriver = __import__( 'selenium.%s.webdriver' % driver, fromlist=['WebDriver']) self['selenium'] = webdriver.WebDriver()
self['selenium'] = webdriver.WebDriver()
args = [arg.strip() for arg in os.environ.get('SELENIUM_ARGS', '').split() if arg.strip()] self['selenium'] = webdriver.WebDriver(*args)
def setUpPloneSite(self, portal): # Start up Selenium driver = os.environ.get('SELENIUM_DRIVER', 'firefox') webdriver = __import__( 'selenium.%s.webdriver' % driver, fromlist=['WebDriver']) self['selenium'] = webdriver.WebDriver()
def addProfile(self, profileName): return applyProfile(self['portal'], profileName)
def applyProfile(self, portal, profileName): return applyProfile(portal, profileName)
def addProfile(self, profileName): return applyProfile(self['portal'], profileName)
a a base. If you use this, you *must* call ``popGlobalRegistry()`` to
a base. If you use this, you *must* call ``popGlobalRegistry()`` to
def pushGlobalRegistry(portal, new=None, name=None): """Set a new global component registry that uses the current registry as a a base. If you use this, you *must* call ``popGlobalRegistry()`` to restore the original state. If ``new`` is not given, a new registry is created. If given, you must provide a ``zope.compone...
for go_type in options.go_category:
for go_type in options.ontology:
def DumpGOFromDatabase( outfile, dbhandle, options ): """read go assignments from database. and dump them into a flatfile. (one to many mapping of genes to GO categories) and a dictionary of go-term to go information """ if options.loglevel >= 1: options.stdlog.write("# category\ttotal\tgenes\tcategories\n" ) all_g...
parser.add_option( "--ontology", dest="ontology", type="choice",
parser.add_option( "--ontology", dest="ontology", type="choice", action="append",
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
filename_categories = None,
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
if options.ontology == []:
if not options.ontology:
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
if e.mAlignment and e.mAlignment[0][0] == "S":
if e.mAlignment and last_e.mAlignment and e.mAlignment[0][0] == "S":
def findCodonReverse( sequence, start, found_codons, abort_codons = None ): """find codon by tracking along sequence from start. This procedure will stop at completely masked codons and abort_codons """ found = False if abort_codons: acodons = abort_codons + ("NNN", "XXX") else: acodons = ("NNN", "XXX") while star...
get_genes = None )
get_genes = None, strict = False )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
missing = set(genes).difference( set(background)) assert len(missing) == 0, "%i genes in foreground but not in background: %s" % (len(missing), str(missing))
E.info( "read %i genes for background" % len(input_background) )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
background = tuple(gene2go.keys())
background = list(gene2go.keys())
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
if options.qvalue_method == "empirical":
elif options.qvalue_method == "empirical":
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
mem_seq = pepides[mem_id]
mem_seq = peptides[mem_id]
def EliminateRedundantEntries( rep, data, eliminated_predictions, options, peptides, extended_peptides, filter_quality = None, this_quality = None ): """eliminate redundant entries in a set.""" eliminated = [] rep_id = rep.transcript_id rep_coverage, rep_pid = rep.mQueryCoverage, rep.mPid alignator = alignlib.makeAl...
seq1 = alignlib.makeSequence( rep_seq ) seq2 = alignlib.makeSequence( mem_seq )
seq1 = alignlib.makeSequence( str(rep_seq) ) seq2 = alignlib.makeSequence( str(mem_seq) )
def EliminateRedundantEntries( rep, data, eliminated_predictions, options, peptides, extended_peptides, filter_quality = None, this_quality = None ): """eliminate redundant entries in a set.""" eliminated = [] rep_id = rep.transcript_id rep_coverage, rep_pid = rep.mQueryCoverage, rep.mPid alignator = alignlib.makeAl...
parser = optparse.OptionParser( version = "%prog version: $Id: select_transcripts.py 2263 2008-11-17 16:36:29Z andreas $", usage = USAGE )
parser = optparse.OptionParser( version = "%prog version: $Id: select_transcripts.py 2263 2008-11-17 16:36:29Z andreas $", usage = globals()["__doc__"] )
def PrintMembers( rep_id, outfile, eliminated, eliminated_by_method ): """write members to outfile and keep counts. """ nmembers = 0 for mem_id, method in eliminated: nmembers += 1 if method not in eliminated_by_method: eliminated_by_method[method] = 0 eliminated_by_method[method] += 1 outfile.write( "%s\t%s\t%s\n" % ...
assert( x <= y )
if x < len(input[e.mQueryToken]): assert x <= y, "sanity check x <= y failed: x=%i, y=%i, l=%i" % (x, y, len(input[e.mQueryToken]) )
def buildFragments( exons, input, pseudogenes, options, coordinate_factor=3, map_peptide2cds = {}, cds_sequences = {}, ): """build fragments out of a sorted list of overlapping exons. The exon list has to be sorted by genome_from, length. The algorithm works in the following way:: start ...
outfile = open(filename, "w")
outfile = IOTools.openFile( filename, "w", create_dir = True )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
outfile = open(options.filename_dump, "w")
outfile = IOTools.openFile( options.filename_dump, "w", create_dir = True )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
background = ReadGeneList( options.filename_background, options )
input_background = ReadGeneList( options.filename_background, options )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
background = ()
input_background = None
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
outfile=open(options.filename_map_slims, "w")
outfile=IOTools.openFile(options.filename_map_slims, "w" )
def getSamples( gene2go, genes, background, options ): sample_size = options.sample # List of all minimum probabilities in simulation simulation_min_pvalues = [] E.info( "sampling: calculating %i samples: " % (sample_size)) counts = {} prob_overs = {} prob_unders = {} samples = {} options.stdlog.write("# ") options...
progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': ''}
progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': '', 'sfdp': ''}
def __find_executables(path): """Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None """ success = False progs = {'dot': '', 'twopi': '', 'neato': '', 'circo'...
deps = set(rosconsole_rosdeps + roslib_rosdeps)
deps = set(roslib_rosdeps)
def test_ROSPackages(self): from roslib.packages import ROSPackages rp = ROSPackages()
t = 'roslib/Log'
t = 'rosgraph_msgs/Log'
def test_cmd_type(self): from ros import rostopic cmd = 'rostopic' s = '/rosout_agg' t = 'roslib/Log'
self.assertEquals('roslib/Log', t)
self.assertEquals('rosgraph_msgs/Log', t)
def test_get_topic_type(self): from ros import rostopic self.assertEquals((None, None, None), rostopic.get_topic_type('/fake', blocking=False)) t, n, f = rostopic.get_topic_type('/rosout', blocking=False) self.assertEquals('roslib/Log', t) self.assertEquals('/rosout', n) self.assert_(f is None)
from roslib.msg import Log
from rosgraph_msgs.msg import Log
def test_get_topic_class(self): from ros import rostopic self.assertEquals((None, None, None), rostopic.get_topic_class('/fake'))
for s in ["Publishers:", "Subscribers", "Type: roslib/Log", " * /rosout"]:
for s in ["Publishers:", "Subscribers", "Type: rosgraph_msgs/Log", " * /rosout"]:
def test_cmd_info(self): from ros import rostopic cmd = 'rostopic'
write_serialize_bits(s, v, NUM_BYTES[f.base_type])
write_serialize_bits_signed(s, v, NUM_BYTES[f.base_type])
def write_serialize_builtin(s, f, var='msg', lookup_slot=True): v = '(cl:slot-value %s \'%s)'%(var, f.name) if lookup_slot else var if f.base_type == 'string': write_serialize_length(s, v) s.write('(cl:map cl:nil #\'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) %s)'%v) elif f.base_type == 'float32': s.write(...
def write_deserialize_bits_signed(s, v, num_bytes): s.write('(cl:let ((unsigned 0))') num_bits = 8*num_bytes with Indent(s): write_deserialize_bits(s, 'unsigned', num_bytes) s.write('(cl:setf %s (cl:if (cl:< unsigned %s) unsigned (cl:- unsigned %s))))'%(v, 2**(num_bits-1), 2**num_bits))
def write_deserialize_bits(s, v, num_bytes): for x in range(0, num_bytes*8, 8): s.write('(cl:setf (cl:ldb (cl:byte 8 %s) %s) (cl:read-byte istream))'%(x, v))
write_deserialize_bits(s, v, NUM_BYTES[f.base_type])
write_deserialize_bits_signed(s, v, NUM_BYTES[f.base_type])
def write_deserialize_builtin(s, f, v): if f.base_type == 'string': write_deserialize_length(s) with Indent(s): s.write('(cl:setf %s (cl:make-string __ros_str_len))'%v) s.write('(cl:dotimes (__ros_str_idx __ros_str_len msg)') with Indent(s): s.write('(cl:setf (cl:char %s __ros_str_idx) (cl:code-char (cl:read-byte istre...
if os.uname()[0] == 'Darwin':
if os.uname()[0] in ['Darwin', 'FreeBSD']:
def make_find_command(path): if os.uname()[0] == 'Darwin': return ["find", "-E", path] else: return ["find", path, "-regextype", "posix-egrep"]
self.assertEquals(set(['rospack', 'roslib', 'std_msgs', 'rosgraph_msgs', 'roslang']), set(rospack_depends('rospy')))
self.assertEquals(set(['rospack', 'roslib', 'std_msgs', 'rosgraph_msgs', 'roslang', 'rosbuild']), set(rospack_depends('rospy')))
def test_rospack(self): from roslib.rospack import rospackexec, rospack_depends, rospack_depends_1,\ rospack_depends_on, rospack_depends_on_1 val = rospackexec(['list']) self.assertEquals(set(['rospack']), set(rospack_depends('roslib'))) self.assertEquals(set(['rospack']), set(rospack_depends_1('roslib'))) self.assert...
pkgs = packages_of('ros') for p in ['test_roslib', 'roslib', 'rospy', 'roscpp']:
pkgs = packages_of('ros_comm') for p in ['test_roslib', 'rospy', 'roscpp']:
def test_packages_of(self): from roslib.stacks import packages_of pkgs = packages_of('ros') for p in ['test_roslib', 'roslib', 'rospy', 'roscpp']: self.assert_(p in pkgs) # due to caching behavior, test twice pkgs = packages_of('ros') for p in ['test_roslib', 'roslib', 'rospy', 'roscpp']: self.assert_(p in pkgs)
self.assertEquals('ros', stack_of('test_roslib'))
self.assertEquals('ros_comm', stack_of('test_roslib'))
def test_stack_of(self): import roslib.packages from roslib.stacks import stack_of self.assertEquals('ros', stack_of('test_roslib')) # due to caching, test twice self.assertEquals('ros', stack_of('test_roslib')) try: stack_of('fake_test_roslib') self.fail("should have failed") except roslib.packages.InvalidROSPkgExcept...
self.assert_('ros' in l)
self.assert_('ros_comm' in l)
def test_list_stacks(self): from roslib.stacks import list_stacks l = list_stacks() self.assert_('ros' in l)