rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.console.setFont(QFont("Monospace"))
self.console.document().setDefaultFont(QFont("Monaco"))
def __init__(self, parent=None, signalManager=None): OWWidget.__init__(self, parent, signalManager, 'Python Script') self.inputs = [("inExampleTable", ExampleTable, self.setExampleTable), ("inDistanceMatrix", orange.SymMatrix, self.setDistanceMatrix), ("inNetwork", orngNetwork.Network, self.setNetwork), ("inLearner", ...
print ' <tr><td><a href="%s/%s">%s</a></td><td>%s</td></tr>' % (dir, name, name, lastResult)
if lastResult =="OK": print ' <tr><td><a href="results/%s/%s/%s.txt">%s</a></td><td>%s</td></tr>' % (module, dir, name, name, lastResult) else: print ' <tr><td><a href="results/%s/%s/%s.%s.%s.%s.txt">%s</a></td><td>%s</td></tr>' % (module, dir, name, platform, pyversion, lastResult, name, lastResult)
def test_scripts(complete, just_print, module="orange", root_directory=".", test_files=None, directories=None): """Test the scripts in the given directory.""" global error_status if sys.platform == "win32" and sys.executable[-6:].upper() != "_D.EXE": import win32process, win32api win32process.SetPriorityClass(win32api....
if self.codeFile == "": return f = open(self.codeFile, 'r')
if self.codeFile == "": return self.error(0) try: f = open(self.codeFile, 'r') except (IOError, OSError), ex: self.text.setPlainText("") return
def openScript(self, filename=None): if filename == None: self.codeFile = str(QFileDialog.getOpenFileName(self, 'Open Python Script', self.codeFile, 'Python files (*.py)\nAll files(*.*)')) else: self.codeFile = filename if self.codeFile == "": return f = open(self.codeFile, 'r') self.text.setPlainText(f.read()) f.clo...
else max(enumerate(orange.Distribution(a, data)), key=lambda x:x[1])[0] if a.varType == orange.VarTypes.Discrete
else _modus(orange.Distribution(a, data)) if a.varType == orange.VarTypes.Discrete
def data_center(data): """Return the central - average - point in the data set""" atts = data.domain.attributes astats = orange.DomainBasicAttrStat(data) center = [astats[a].avg if a.varType == orange.VarTypes.Continuous \ else max(enumerate(orange.Distribution(a, data)), key=lambda x:x[1])[0] if a.varType == orange.Va...
(based on Ziv Bar-Joseph et al. (Fast optimal leaf ordering for herarchical clustering')
(based on Ziv Bar-Joseph et al. (Fast optimal leaf ordering for hierarchical clustering')
def orderLeaves(tree, matrix, progressCallback=None): """Order the leaves in the clustering tree. (based on Ziv Bar-Joseph et al. (Fast optimal leaf ordering for herarchical clustering') Arguments: tree --binary hierarchical clustering tree of type orange.HierarchicalCluster matrix --orange.SymMatrix that was used t...
orderedMs = sorted(other(u, Vll, Vlr), key=lambda m: M[tree.left, u, m]) orderedKs = sorted(other(w, Vrl, Vrr), key=lambda k: M[tree.right, w, k])
orderedMs = sorted(other(u, Vll, Vlr), key=lambda m: M[tree_left, u, m]) orderedKs = sorted(other(w, Vrl, Vrr), key=lambda k: M[tree_right, w, k])
def _optOrdering(tree): if len(tree)==1: for leaf in tree: M[tree, leaf, leaf] = 0
if M[tree.left, u, m] + M[tree.right, w, k0] + C >= curMin:
if M[tree_left, u, m] + M[tree_right, w, k0] + C >= curMin:
def _optOrdering(tree): if len(tree)==1: for leaf in tree: M[tree, leaf, leaf] = 0
if M[tree.left, u, m] + M[tree.right, w, k] + C >= curMin:
if M[tree_left, u, m] + M[tree_right, w, k] + C >= curMin:
def _optOrdering(tree): if len(tree)==1: for leaf in tree: M[tree, leaf, leaf] = 0
if curMin > M[tree.left, u, m] + M[tree.right, w, k] + matrix[m, k]: curMin = M[tree.left, u, m] + M[tree.right, w, k] + matrix[m, k]
if curMin > M[tree_left, u, m] + M[tree_right, w, k] + matrix[m, k]: curMin = M[tree_left, u, m] + M[tree_right, w, k] + matrix[m, k]
def _optOrdering(tree): if len(tree)==1: for leaf in tree: M[tree, leaf, leaf] = 0
ordering[tree, u, w] = (tree.left, u, curMK[0], tree.right, w, curMK[1]) ordering[tree, w, u] = (tree.right, w, curMK[1], tree.left, u, curMK[0])
ordering[tree, u, w] = (tree_left, u, curMK[0], tree_right, w, curMK[1]) ordering[tree, w, u] = (tree_right, w, curMK[1], tree_left, u, curMK[0])
def _optOrdering(tree): if len(tree)==1: for leaf in tree: M[tree, leaf, leaf] = 0
return M[tree.left, u, m] + M[tree.right, w, k] + matrix[m, k]
return M[tree_left, u, m] + M[tree_right, w, k] + matrix[m, k]
def MFunc((m, k)): return M[tree.left, u, m] + M[tree.right, w, k] + matrix[m, k]
ordering[tree, u, w] = (tree.left, u, m, tree.right, w, k) ordering[tree, w, u] = (tree.right, w, k, tree.left, u, m)
ordering[tree, u, w] = (tree_left, u, m, tree_right, w, k) ordering[tree, w, u] = (tree_right, w, k, tree_left, u, m)
def MFunc((m, k)): return M[tree.left, u, m] + M[tree.right, w, k] + matrix[m, k]
tmp += range(sel[0].x(), sel[1].x()+1) tmp +=range(sel[0].y(), sel[1].y()+1) else: tmp += range(self.distanceMap.elementIndices[sel[0].x()], self.distanceMap.elementIndices[sel[1].x()+1]) tmp +=range(self.distanceMap.elementIndices[sel[0].y()], self.distanceMap.elementIndices[sel[1].y()+1])
tmp += range(x1, x2) tmp += range(y1, y2) else: tmp += range(self.distanceMap.elementIndices[x1], self.distanceMap.elementIndices[x2]) tmp += range(self.distanceMap.elementIndices[y1], self.distanceMap.elementIndices[y2])
def sendOutput(self): if len(self.matrix.items)<1: return
entireSelection = [] newSel = False for selLine in self.selectionLines: self.scene.removeItem(selLine) self.selectionLines = [] if len(self.selection.getSelection())>0: for sel in self.selection.getSelection(): for i in range(sel[0].x(), sel[1].x()): for j in range(sel[0].y(), sel[1].y()): selTuple = (i, j) if not (se...
selections = self.selection.getSelection() for rect in self.selectionRects: self.scene.removeItem(rect) self.selectionRects = [] color = self.selectionColor pen = QPen(self.qrgbToQColor(color),v_sel_width) pen.setCosmetic(True) for selection in selections: rect = QGraphicsRectItem(QRectF(selection), self.distanceImage...
def updateSelectionRect(self): entireSelection = [] newSel = False for selLine in self.selectionLines: self.scene.removeItem(selLine) self.selectionLines = [] if len(self.selection.getSelection())>0: for sel in self.selection.getSelection(): for i in range(sel[0].x(), sel[1].x()): for j in range(sel[0].y(), sel[1].y()...
self.currSel = QPoint(x,y) self.currSelEnd = QPoint(x,y)
self.currSel = QRect(x, y, 1, 1) self.currSelEnd = QRect(x, y, 1, 1)
def SelStart(self, x, y): if x < 0: x=0 if y < 0: y=0 self.currSel = QPoint(x,y) self.currSelEnd = QPoint(x,y) self.selecting = True
self.currSelEnd = QPoint(x,y)
self.currSelEnd = QRect(x, y, 1, 1)
def UpdateSel(self, x, y): self.currSelEnd = QPoint(x,y)
minx = min(self.currSel.x(), self.currSelEnd.x()) maxx = max(self.currSel.x(), self.currSelEnd.x()) miny = min(self.currSel.y(), self.currSelEnd.y()) maxy = max(self.currSel.y(), self.currSelEnd.y()) if (minx==maxx) and (miny==maxy): maxx+=1 maxy+=1 self.selection += [(QPoint(minx, miny),QPoint(maxx,maxy))]
self.selection += [self.currSel.united(self.currSelEnd).normalized()]
def SelEnd(self): minx = min(self.currSel.x(), self.currSelEnd.x()) maxx = max(self.currSel.x(), self.currSelEnd.x())
res = self.selection + [] if self.selecting==True: minx = min(self.currSel.x(), self.currSelEnd.x()) maxx = max(self.currSel.x(), self.currSelEnd.x()) miny = min(self.currSel.y(), self.currSelEnd.y()) maxy = max(self.currSel.y(), self.currSelEnd.y()) res += [(QPoint(minx, miny),QPoint(maxx,maxy))]
res = list(self.selection) if self.selecting == True: res += [self.currSel.united(self.currSelEnd).normalized()]
def getSelection(self): res = self.selection + [] if self.selecting==True: minx = min(self.currSel.x(), self.currSelEnd.x()) maxx = max(self.currSel.x(), self.currSelEnd.x())
matrix[a1, a2] = orange.PearsonCorrelation(a1, a2, self.data, 0).p
matrix[a1, a2] = (1.0 - orange.PearsonCorrelation(a1, a2, self.data, 0).r) / 2.0
def computeMatrix(self): self.error() if self.data: atts = self.data.domain.attributes matrix = orange.SymMatrix(len(atts)) matrix.setattr('items', atts)
matrix[a1, a2] = statc.spearmanr(f1, filleds[a2])[1]
matrix[a1, a2] = (1.0 - statc.spearmanr(f1, filleds[a2])[0]) / 2.0
def computeMatrix(self): self.error() if self.data: atts = self.data.domain.attributes matrix = orange.SymMatrix(len(atts)) matrix.setattr('items', atts)
filename = str(QFileDialog.getSaveFileName(self, 'Save Orange Data File', startfile, self.dlgFormats ))
filename, selectedFilter = str(QFileDialog.getSaveFileName(self, 'Save Orange Data File', startfile, self.dlgFormats)), self.dlgFormats.split("\n")[0]
def browseFile(self): if self.recentFiles: startfile = self.recentFiles[0] else: startfile = "."
filt_ext = self.re_filterExtension.search(str(dlg.selectedFilter())).group("ext")
filt_ext = self.re_filterExtension.search(str(str(selectedFilter))).group("ext")
def browseFile(self): if self.recentFiles: startfile = self.recentFiles[0] else: startfile = "."
subDir = os.sep+os.path.relpath(self.directory, orngEnviron.widgetDir) if "relpath" in os.path.__dict__ else self.directory.replace(orngEnviron.widgetDir, "") return os.path.join(orngEnviron.orangeDocDir, "catalog%s" % subDir)
dir, widgetDir = os.path.realpath(self.directory), os.path.realpath(orngEnviron.widgetDir) subDir = os.path.relpath(dir, widgetDir) if "relpath" in os.path.__dict__ else dir.replace(widgetDir, "") return os.path.join(orngEnviron.orangeDocDir, "catalog", subDir)
def docDir(self): if not self.addOn: # A built-in widget subDir = os.sep+os.path.relpath(self.directory, orngEnviron.widgetDir) if "relpath" in os.path.__dict__ else self.directory.replace(orngEnviron.widgetDir, "") return os.path.join(orngEnviron.orangeDocDir, "catalog%s" % subDir) else: # An add-on widget addOnDocD...
OWGUI.button(ib, self, "Degree distribution", callback=self.showDegreeDistribution) OWGUI.button(ib, self, "Save network", callback=self.saveNetwork) OWGUI.button(ib, self, "Save image", callback=self.graph.saveToFile)
OWGUI.button(ib, self, "Degree distribution", callback=self.showDegreeDistribution, debuggingEnabled=False) OWGUI.button(ib, self, "Save network", callback=self.saveNetwork, debuggingEnabled=False) OWGUI.button(ib, self, "Save image", callback=self.graph.saveToFile, debuggingEnabled=False)
def __init__(self, parent=None, signalManager=None): OWWidget.__init__(self, parent, signalManager, 'Net Explorer') #self.contextHandlers = {"": DomainContextHandler("", [ContextField("attributes", selected="markerAttributes"), ContextField("attributes", selected="tooltipAttributes"), "color"])} self.inputs = [("Networ...
vars = [x.name for x in self.visualize.getVars()] if not self.comboAttSelection.currentText() in vars: return att = str(self.comboAttSelection.currentText()) vertices = self.graph.networkCurve.getSelectedVertices() if len(vertices) != 1: return attributes = str(self.visualize.graph.items[vertices[0]][att]).split(', '...
if self.visualize: vars = [x.name for x in self.visualize.getVars()] if not self.comboAttSelection.currentText() in vars: return att = str(self.comboAttSelection.currentText()) vertices = self.graph.networkCurve.getSelectedVertices() if len(vertices) != 1: return attributes = str(self.visualize.graph.items[vertices[0...
def sendAttSelectionList(self): vars = [x.name for x in self.visualize.getVars()] if not self.comboAttSelection.currentText() in vars: return att = str(self.comboAttSelection.currentText()) vertices = self.graph.networkCurve.getSelectedVertices() if len(vertices) != 1: return attributes = str(self.visualize.graph.ite...
if self.btnForce.isChecked():
if self.btnForce.isChecked() and self.visualize is not None:
def drawForce(self): if self.btnForce.isChecked(): self.graph.forceVectors = self.visualize.computeForces() else: self.graph.forceVectors = None self.updateCanvas()
if self.visualize.vertexDistance == None:
if self.visualize and self.visualize.vertexDistance == None:
def showDistancesClick(self): if self.visualize.vertexDistance == None: self.warning("Vertex distance signal is not set. Distances are not known.") self.graph.showDistances = self.showDistances
OWGUI.lineEdit(hbox, self, "symbolDC", "Don't care:", labelWidth=80, orientation="horizontal", tooltip="Default values: empty fields (space), '?' or 'NA'") OWGUI.lineEdit(hbox, self, "symbolDK", "Don't know:", labelWidth=80, orientation="horizontal", tooltip="Default values: '~' or '*'")
OWGUI.lineEdit(hbox, self, "symbolDC", "Don't care:", labelWidth=80, orientation="horizontal", tooltip="Default values: '~' or '*'") OWGUI.lineEdit(hbox, self, "symbolDK", "Don't know:", labelWidth=80, orientation="horizontal", tooltip="Default values: empty fields (space), '?' or 'NA'")
def __init__(self, parent=None, signalManager = None): OWWidget.__init__(self, parent, signalManager, "File", wantMainArea = 0, resizingEnabled = 1)
maxNu = max(self.maxNu(newexamples) - 1e-7, 0.0)
if self.svm_type == SVMLearner.Nu_SVC: maxNu = max(self.maxNu(newexamples) - 1e-7, 0.0) else: maxNu = 1.0
def learnClassifier(self, examples): transformer=orange.DomainContinuizer() transformer.multinomialTreatment=orange.DomainContinuizer.NValues transformer.continuousTreatment=orange.DomainContinuizer.NormalizeBySpan transformer.classTreatment=orange.DomainContinuizer.Ignore newdomain=transformer(examples) newexamples=ex...
self.inputAttributes = [ (item, self.data.domain[item].varType) for item in itemsText]
self.inputAttributes = [ (item, self.data.domain[item].varType) for item in itemsText if item in self.data.domain]
def setInputAttributes(self): self.selectedInput = [] if self.data: self.inputAttributes = filter(lambda x:x not in self.usedAttributes, self.allAttributes) else: self.inputAttributes = [] #print "before: ", self.inputAttributes self.filterInputAttrs.setAllListItems() self.filterInputAttrs.updateListBoxItems(callCallba...
data = orange.ExampleTable(r"E:\Development\Orange Datasets\UCI\iris.tab")
data = orange.ExampleTable(r'../../doc/datasets/iris.tab')
def onAttributesButtonDownClick(self): self.moveSelection("chosenAttributes", "selectedChosen", 1)
time.sleep(10)
time.sleep(30)
def test_module(module_name, module_file_list): """ <Purpose> Execute all test files contained within module_file_list matching the module_name in the form of each test file name 'ut_<module_name>_<descriptor>.py' <Arguments> module_name: module name to be tested module_file_list: a list of files to be filtered by mod...
try: advertise_announce(unique_id, myip, DNS_CACHE_TTL) servicelogger.log("[INFO]: Advertised " + str(unique_id) + " which maps to " + myip) except Exception, error: if 'announce error' in str(error): pass else: raise Exception(error)
advertise_success = False while not advertise_success: try: advertise_announce(unique_id, myip, DNS_CACHE_TTL) servicelogger.log("[INFO]: Advertised " + str(unique_id) + " which maps to " + myip) advertise_success = True except Exception, error: if 'announce error' in str(error): advertise_success = True else: ad...
def advertise_to_DNS(unique_id): """ Advertise unique_id to the zenodotus DNS server. We strip away whatever that follows the NAME_SERVER part of the unique_id. For instance, if our unique_id is abc.NAME_SERVER:1234@xyz, then we only advertise abc.NAME_SERVER. """ # IP that maps to the unique_id myip = emulcomm.getmyi...
copy_to_target("production_nat_new/src/nmpatch/nmmain.py") copy_to_target("production_nat_new/src/nmpatch/nmclient.repy") copy_to_target("production_nat_new/src/nmpatch/sockettimeout.repy") copy_to_target("production_nat_new/src/nmpatch/ShimStackInterface.repy")
copy_to_target("production_nat_new/src/nmpatch/nmmain.py", target_dir) copy_to_target("production_nat_new/src/nmpatch/nmclient.repy", target_dir) copy_to_target("production_nat_new/src/nmpatch/sockettimeout.repy", target_dir) copy_to_target("production_nat_new/src/ShimStackInterface.repy", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
acceptor_state['lock'].acquire() result = acceptor_state['started'] acceptor_state['lock'].release()
accepter_state['lock'].acquire() result = accepter_state['started'] accepter_state['lock'].release()
def is_accepter_started(): acceptor_state['lock'].acquire() result = acceptor_state['started'] acceptor_state['lock'].release() return result
if is_accepter_started():
if not node_reset_config['reset_accepter'] and is_accepter_started():
def start_accepter(): shimstack = ShimStackInterface('(NatDeciderShim)') unique_id = rsa_publickey_to_string(configuration['publickey']) unique_id = sha_hexhash(unique_id) + str(configuration['service_vessel']) # do this until we get the accepter started... while True: if is_accepter_started(): # we're done, return...
acceptor_state['lock'].acquire() acceptor_state['started']= True acceptor_state['lock'].release()
accepter_state['lock'].acquire() accepter_state['started']= True accepter_state['lock'].release()
def start_accepter(): shimstack = ShimStackInterface('(NatDeciderShim)') unique_id = rsa_publickey_to_string(configuration['publickey']) unique_id = sha_hexhash(unique_id) + str(configuration['service_vessel']) # do this until we get the accepter started... while True: if is_accepter_started(): # we're done, return...
def start_vessel(vesselhandle, identity, program_file, arg_list=[]):
def start_vessel(vesselhandle, identity, program_file, arg_list=None):
def start_vessel(vesselhandle, identity, program_file, arg_list=[]): """ <Purpose> Start a program running on a vessel. <Arguments> vesselhandle The vesselhandle of the vessel that is to be started. identity The identity of either the owner or a user of the vessel. program_file The name of the file that already exists ...
arg_list.insert(0, program_file) arg_string = " ".join(arg_list)
arg_string = program_file if arg_list is not None: arg_string += " " + " ".join(arg_list)
def start_vessel(vesselhandle, identity, program_file, arg_list=[]): """ <Purpose> Start a program running on a vessel. <Arguments> vesselhandle The vesselhandle of the vessel that is to be started. identity The identity of either the owner or a user of the vessel. program_file The name of the file that already exists ...
msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME_TO_SET_USER_KEYS_ON
msg = "[" + vessel['nodelocation'] + "] Skipping: vesselname is not: " + VESSELNAME_TO_SET_USER_KEYS_ON
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
print("[" + vessel['location'] + "] Setting user keys.")
print("[" + vessel['nodelocation'] + "] Setting user keys.")
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
experimentlib.set_vessel_users(vessel['handle'], identity, USERKEY_LIST)
experimentlib.set_vessel_users(vessel['vesselhandle'], identity, USERKEY_LIST)
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
msg = "[" + vessel['location'] + "] Failure: " + str(e)
msg = "[" + vessel['nodelocation'] + "] Failure: " + str(e)
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
print("[" + vessel['location'] + "] Success.")
print("[" + vessel['nodelocation'] + "] Success.")
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
print("[" + vessel['location'] + "] Already had correct user keys.")
print("[" + vessel['nodelocation'] + "] Already had correct user keys.")
def set_keys(vessel, identity): """ The first argument will be a vesseldict rather than a vesselhandle because we passed the result of get_vessels_on_nodes to run_parallelized. """ if vessel['vesselname'] != VESSELNAME_TO_SET_USER_KEYS_ON: msg = "[" + vessel['location'] + "] Skipping: vesselname is not: " + VESSELNAME...
if not os.path.isdir(os.path.dirname(generatedfilename)):
if os.path.dirname(generatedfilename) != '' and not os.path.isdir(os.path.dirname(generatedfilename)):
def _generate_python_file_from_repy(repyfilename, generatedfilename, shared_mycontext, callfunc, callargs): """ Generate a python module from a repy file so it can be imported The first line is TRANSLATION_TAGLINE, so it's easy to detect that the file was automatically generated """ #Start the generation! Print out t...
copy_to_target("production_nat_new/src/nmpatch/nmmain.py", target_dir) copy_to_target("production_nat_new/src/nmpatch/nmclient.repy", target_dir) copy_to_target("production_nat_new/src/nmpatch/sockettimeout.repy", target_dir) copy_to_target("production_nat_new/src/nmpatch/ShimStackInterface.repy", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
_call_seattlegeni_func(client.renew_vessels, vesselhandle_list)
_call_seattlegeni_func(client.renew_resources, vesselhandle_list)
def seattlegeni_renew_vessels(identity, vesselhandle_list): """ <Purpose> Renew vessels previously acquired from SeattleGENI. <Arguments> identity The identity to use for communicating with SeattleGENI. vesselhandle_list The vessels to be renewed. <Exceptions> The common SeattleGENI exceptions described in the module c...
copy_to_target("repy/tests/*", target_dir) copy_to_target("nodemanager/tests/*", target_dir) copy_to_target("portability/tests/*", target_dir) copy_to_target("seash/tests/*", target_dir)
copy_to_target("repy/tests/run_tests.py", target_dir) copy_to_target("repy/tests/restrictions.*", target_dir) copy_to_target("repy/testsV2/*", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
copy_to_target("keydaemon/tests/*", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
copy_to_target("assignments/webserver/*", target_dir) copy_to_target("softwareupdater/test/*", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
raise TranslationError("File name exists but wasn't automatically generated: " + generatedfile)
if not first_line.startswith(TRANSLATION_TAGLINE): raise TranslationError("File name exists but wasn't automatically generated: " + generatedfile)
def _translation_is_needed(repyfilename, generatedfile): """ Checks if generatedfile needs to be regenerated. Does several checks to decide if generating generatedfilename based on repyfilename is a good idea. --does file already exist? --was it automatically generated? --was it generated from the same source file? --w...
if platform.machine().startswith('armv'): _output('Seattle is being installed on a Nokia N800/900 Internet Tablet.') import pwd if pwd.getpwuid(os.getuid())[0] != 'root': _output('Please run the installer as root. This can be done by ' \ + 'installing/using the rootsh or openssh package.') return continue_install...
def main(): if OS not in SUPPORTED_OSES: raise UnsupportedOSError("This operating system is not supported.") # Begin pre-installation process. # Pre-install: parse the passed-in arguments. try: # Armon: Changed getopt to accept parameters for Repy and NM IP/Iface # restrictions, also a special disable flag opts, arg...
actual_time = after_stop_event[1] - before_stop_event[1] diff_time = actual_time - expected_time
api_start = before_stop_event[1] api_end = after_stop_event[1] actual_time = api_end - api_start all_stops = get_stoptimes_on_interval(api_start, api_end) all_stoptimes = 0 for stop in all_stops: TOS, stop_amount = stop all_stoptimes += stop_amount
def commit_time(thread_dict, TOC): resource = thread_dict["resource"] thread_dict[resource] += TOC - thread_dict["begin"] thread_dict["begin"] = TOC
if diff_time > amount: commit_time(thread_dict, TOC) thread_dict["begin"] = resume_time thread_dict["stopped"] += amount
if all_stoptimes > expected_time: if all_stops[0][0] == TOC: resource_time = max(expected_time, actual_time - all_stoptimes) thread_dict[thread_dict["resource"]] += resource_time thread_dict["begin"] = api_end thread_dict["stopped"] += actual_time - resource_time
def commit_time(thread_dict, TOC): resource = thread_dict["resource"] thread_dict[resource] += TOC - thread_dict["begin"] thread_dict["begin"] = TOC
if thread != ALL_THREADS: for type in TIME_UTIL_KEYS: total_time[type] += thread_dict[type]
if thread_dict is total_time: continue for type in TIME_UTIL_KEYS: total_time[type] += thread_dict[type]
def commit_time(thread_dict, TOC): resource = thread_dict["resource"] thread_dict[resource] += TOC - thread_dict["begin"] thread_dict["begin"] = TOC
guid=PyRSS2Gen.Guid(config.TESTLOG_URL + datestr.replace(' ', '_')),
guid=PyRSS2Gen.Guid(config.TESTLOG_URL + str(runnumber)),
def _create_rss_file(resultslist): failureitems = [] for (runnumber, revision, resulttext) in resultslist: if resulttext[0].strip() != "SUCCESS": datestr = resulttext[1].strip() dateobj = datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S") # The PyRSS2Gen module expects this to be in GMT, and python is a pain # f...
raise UserError("There is an error in autosave: '" + str(error) + "'. You can turn off autosave using the command 'set autosave off'.")
raise seash_exceptions.UserError("There is an error in autosave: '" + str(error) + "'. You can turn off autosave using the command 'set autosave off'.")
def command_loop(): # Things that may be set herein and used in later commands. # Contains the local variables of the original command loop. # Keeps track of the user's state in seash. Referenced # during command executions by the command_parser. environment_dict = { 'host': None, 'port': None, 'expnum': None, 'filena...
twopercent_resourcetemplate = onepercentmanyevents_resource_fd.read()
twopercent_resourcetemplate = twopercent_resource_fd.read()
def main(): """ <Purpose> The main function that calls the process_nodes_and_change_state() function in the node_transition_lib passing in the process and error functions. <Arguments> None <Exceptions> None <Side Effects> None """ # Open and read the resource file that is necessary for twopercent vessels. # This wi...
test_single(file_path)
if not file_path.startswith('ut_') or len(file_path.split('_'))<3: print "Error, cannot determine module name from filename '"+file_path+"'" return else: module_name = file_path.split('_')[1] files_to_use = [file_path] module_file_list = filter_files(valid_files, module = module_name) files_to_use = files_to_use + ...
def main(): """ <Purpose> Executes the main program that is the unit testing framework. Tests different modules, files, capabilities, dependent on command line arguments. <Arguments> None <Exceptions> None. <Side Effects> None <Returns> None """ ### ### Define allowed arguments. ### parser = optparse.OptionParser()...
def test_single(file_path): """ <Purpose> Given the test file path, this function will execute the test using the test framework.
def execute_and_check_program(file_path): """ <Purpose> Given the test file path, this function will execute the program and monitor its behavior
def test_single(file_path): """ <Purpose> Given the test file path, this function will execute the test using the test framework. <Arguments> Test file path. <Exceptions> None. <Side Effects> None <Returns> None """ file_path = os.path.normpath(file_path) testing_monitor(file_path)
test_single(setup_file)
execute_and_check_program(setup_file)
def test_module(module_name, module_file_list): """ <Purpose> Execute all test files contained within module_file_list matching the module_name in the form of each test file name 'ut_<module_name>_<descriptor>.py' <Arguments> module_name: module name to be tested module_file_list: a list of files to be filtered by mod...
test_single(test_file)
execute_and_check_program(test_file)
def test_module(module_name, module_file_list): """ <Purpose> Execute all test files contained within module_file_list matching the module_name in the form of each test file name 'ut_<module_name>_<descriptor>.py' <Arguments> module_name: module name to be tested module_file_list: a list of files to be filtered by mod...
test_single(shutdown_file)
execute_and_check_program(shutdown_file)
def test_module(module_name, module_file_list): """ <Purpose> Execute all test files contained within module_file_list matching the module_name in the form of each test file name 'ut_<module_name>_<descriptor>.py' <Arguments> module_name: module name to be tested module_file_list: a list of files to be filtered by mod...
if not first_line.startswith(TRANSLATION_TAGLINE):
if not first_line.startswith(ENCODING_STRING) or not second_line.startswith(TRANSLATION_TAGLINE):
def _translation_is_needed(repyfilename, generatedfile): """ Checks if generatedfile needs to be regenerated. Does several checks to decide if generating generatedfilename based on repyfilename is a good idea. --does file already exist? --was it automatically generated? --was it generated from the same source file? --w...
f = open('nodeman.cfg') dictobj = eval(f.read()) f.close() except Exception, e: print "addme.py: unable to read public key: '%s'" % e return publickey = dictobj['publickey'] keystr = "%s %s" % (publickey['e'], publickey['n']) print "(%s)" % keystr vesselcount = 0 maxvessels = 2 try: maxvessels = int(sys.argv[1]) excep...
main() except Exception,e: servicelogger.log_last_exception() harshexit.harshexit(15)
def do_example_acquire_renew_release(): client = SeattleGENIClient(username=USERNAME, api_key=API_KEY, allow_ssl_insecure=ALLOW_SSL_INSECURE) try: f = open('nodeman.cfg') dictobj = eval(f.read()) f.close() except Exception, e: print "addme.py: unable to read public key: '%s'" % e return publickey = dictobj['publickey...
tcp_time_updatetime(12345) times.append(time_gettime())
connected_server = tcp_time_updatetime(12345) current_time = time_gettime() times.append(current_time) server_list.append(connected_server) integrationtestlib.log("Calling time_gettime(). Retrieved time: " + str(current_time))
def main(): # initialize the gmail module success,explanation_str = send_gmail.init_gmail() if not success: integrationtestlib.log(explanation_str) sys.exit(0) notify_str = '' #add Eric Kimbrel to the email notify list integrationtestlib.notify_list.append("lekimbrel@gmail.com") integrationtestlib.log("Starting tes...
notify_str += 'failed to get ntp time via tcp at least twice in 5 attempts'
notify_str += "failed to get ntp time via tcp at least twice in 5 attempts\n\n" notify_str += "Appending a list of all the exceptions returned and servers we attempted to connect to:\n\n" notify_str += str(exception_string_list)
def main(): # initialize the gmail module success,explanation_str = send_gmail.init_gmail() if not success: integrationtestlib.log(explanation_str) sys.exit(0) notify_str = '' #add Eric Kimbrel to the email notify list integrationtestlib.notify_list.append("lekimbrel@gmail.com") integrationtestlib.log("Starting tes...
if diff > (test_stop1 - test_start): integrationtestlib.log('WARNING large descrepancy between tcp times: '+str(diff)) notify_str += ' WARNING large descrepancy between tcp times: '+str(diff)
test_diff = test_stop1 - test_start if math.fabs(diff - test_diff) > 10: fail_test_str += ' WARNING large descrepancy between tcp times. \nThe difference between tcp_time diff and the actual test diff is: '+str(diff - test_diff) fail_test_str += "\n\nThe start time of test was: " + str(test_start) + ". The end time o...
def main(): # initialize the gmail module success,explanation_str = send_gmail.init_gmail() if not success: integrationtestlib.log(explanation_str) sys.exit(0) notify_str = '' #add Eric Kimbrel to the email notify list integrationtestlib.notify_list.append("lekimbrel@gmail.com") integrationtestlib.log("Starting tes...
fail_test(str(e))
integrationtestlib.log("Failed to call ntp_time_updatetime(). Returned with exception: " +str(e)) notify_str += "\nFailed to call ntp_time_updatetime(). Returned with exception: " +str(e)
def main(): # initialize the gmail module success,explanation_str = send_gmail.init_gmail() if not success: integrationtestlib.log(explanation_str) sys.exit(0) notify_str = '' #add Eric Kimbrel to the email notify list integrationtestlib.notify_list.append("lekimbrel@gmail.com") integrationtestlib.log("Starting tes...
copy_to_target("production_nat_new/src/nmpatch/nmmain.py", target_dir) copy_to_target("production_nat_new/src/nmpatch/nmclient.repy", target_dir) copy_to_target("production_nat_new/src/nmpatch/sockettimeout.repy", target_dir) copy_to_target("production_nat_new/src/nmpatch/ShimStackInterface.repy", target_dir)
def main(): repytest = False RANDOMPORTS = False target_dir = None for arg in sys.argv[1:]: # -t means we will copy repy tests if arg == '-t': repytest = True # The user wants us to fill in the port numbers randomly. elif arg == '-randomports': RANDOMPORTS = True # Not a flag? Assume it's the target directory else: ...
meta_modules = load_and_realise_network('/complete/path/to/dvnfile.dvn')
meta_modules = interface.load_and_realise_network( '/complete/path/to/dvnfile.dvn')
def main(): print "hello from offline DeVIDE!" meta_modules = load_and_realise_network('/complete/path/to/dvnfile.dvn') # 1. First we are going to configure the reader module to load the file we want. # you can get and change the config of any module that you have named in a previous # DeVIDE session with right click ...
config = get_module_config('named_reader')
config = interface.get_module_config('named_reader')
def main(): print "hello from offline DeVIDE!" meta_modules = load_and_realise_network('/complete/path/to/dvnfile.dvn') # 1. First we are going to configure the reader module to load the file we want. # you can get and change the config of any module that you have named in a previous # DeVIDE session with right click ...
set_module_config('named_reader', config)
interface.set_module_config('named_reader', config)
def main(): print "hello from offline DeVIDE!" meta_modules = load_and_realise_network('/complete/path/to/dvnfile.dvn') # 1. First we are going to configure the reader module to load the file we want. # you can get and change the config of any module that you have named in a previous # DeVIDE session with right click ...
execute_network()
interface.execute_network()
def main(): print "hello from offline DeVIDE!" meta_modules = load_and_realise_network('/complete/path/to/dvnfile.dvn') # 1. First we are going to configure the reader module to load the file we want. # you can get and change the config of any module that you have named in a previous # DeVIDE session with right click ...
'PNG files (*.png)|*.png|All files (*.*)|*.*'}),
'TIFF files (*.tif)|*.tif|All files (*.*)|*.*'}),
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager)
assert os.path.normpath(package_parent_dir) == \ os.path.normpath( os.path.dirname(os.path.dirname(filename)))
assert os.path.normpath( os.path.abspath(package_parent_dir)) == \ os.path.normpath( os.path.dirname(os.path.dirname(filename))), \ "Internal error: %r != %r" % ( os.path.normpath( os.path.abspath(package_parent_dir)), os.path.normpath( os.path.dirname(os.path.dirname(filename))))
def __init__(self, module_name, filename = None, pyke_version = pyke.version, loader = None, sources = None, compiler_version = 0): r'''
('INDENT', 2),
def fc_forall_require(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)...
'POPINDENT',
def fc_forall_require(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)...
forall358_worked = True
forall356_worked = True
def bc_rules(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)): rule.r...
forall358_worked = False
forall356_worked = False
def bc_rules(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)): rule.r...
forall358_worked = True if forall358_worked: break
forall356_worked = True if forall356_worked: break
def bc_rules(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)): rule.r...
if not forall358_worked:
if not forall356_worked:
def bc_rules(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)): rule.r...
if forall358_worked:
if forall356_worked:
def bc_rules(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) try: if all(itertools.imap(lambda pat, arg: pat.match_pattern(context, context, arg, arg_context), patterns, arg_patterns)): rule.r...
((721, 731), (270, 280)), ((735, 735), (281, 281)), ((761, 765), (284, 288)), ((769, 769), (290, 290)), ((773, 773), (291, 291)), ((776, 794), (292, 296)), ((797, 802), (297, 302)), ((824, 828), (305, 308)), ((832, 832), (310, 310)), ((834, 845), (311, 313)), ((860, 864), (316, 316)), ((878, 882), (319, 320)), ((885, 8...
((721, 729), (270, 278)), ((733, 733), (279, 279)), ((759, 763), (282, 286)), ((767, 767), (288, 288)), ((771, 771), (289, 289)), ((774, 792), (290, 294)), ((795, 800), (295, 300)), ((822, 826), (303, 306)), ((830, 830), (308, 308)), ((832, 843), (309, 311)), ((858, 862), (314, 314)), ((876, 880), (317, 318)), ((883, 8...
def populate(engine): This_rule_base = engine.get_create('compiler') bc_rule.bc_rule('file', This_rule_base, 'compile', file, None, (contexts.variable('generated_root_pkg'), contexts.variable('rb_name'), pattern.pattern_tuple((pattern.pattern_literal('file'), contexts.variable('parent'), pattern.pattern_tuple((context...
except Exception, e:
except StandardError, e:
def importname(modulename, name): """ Safely imports modules for runtime importing. Returns the module object or ``None`` if there were problems importing. :param modulename: the package name of the module to import from :param name: the name of the module to import """ logger = getLogger() if not modulename: m = nam...
"""Takes in a string and converts ``'`` to ``&apos;`` and ``"`` to ``&quot;``.
"""Takes in a string and converts: * ``&`` to ``&amp;`` * ``>`` to ``&gt;`` * ``<`` to ``&lt;`` * ``\"`` to ``&quot;`` * ``'`` to ``& * ``/`` to ``&
def escape_text(s): """Takes in a string and converts ``'`` to ``&apos;`` and ``"`` to ``&quot;``. Note: if ``s`` is ``None``, then we return ``None``. >>> escape_text(None) None >>> escape_text("") "" >>> escape_text("a'b") "a&apos;b" >>> escape_text('a"b') "a&quot;b" """ if not s: return s for mem in (("&", "&amp...
"a&apos;b"
"a&
def escape_text(s): """Takes in a string and converts ``'`` to ``&apos;`` and ``"`` to ``&quot;``. Note: if ``s`` is ``None``, then we return ``None``. >>> escape_text(None) None >>> escape_text("") "" >>> escape_text("a'b") "a&apos;b" >>> escape_text('a"b') "a&quot;b" """ if not s: return s for mem in (("&", "&amp...
staticdir = cdict.get("static_dir", "") if not staticdir: raise Exception("You must set static_dir in your config file.")
def render_url(cdict, pathinfo, querystring=""): """ Takes a url and a querystring and renders the page that corresponds with that by creating a Request and a PyBlosxom object and passing it through. It then returns the resulting Response. This returns a PyBlosxom ``Response`` object. :param cdict: the config.py dic...
return p.getResponse()
return p.get_response()
def render_url(cdict, pathinfo, querystring=""): """ Takes a url and a querystring and renders the page that corresponds with that by creating a Request and a PyBlosxom object and passing it through. It then returns the resulting Response. This returns a PyBlosxom ``Response`` object. :param cdict: the config.py dic...
data = self._request.getData() pyhttp = self._request.getHttp() config = self._request.getConfiguration()
data = self._request.get_data() pyhttp = self._request.get_http() config = self._request.get_configuration()
def initialize(self): """The initialize step further initializes the Request by setting additional information in the ``data`` dict, registering plugins, and entryparsers. """ data = self._request.getData() pyhttp = self._request.getHttp() config = self._request.getConfiguration()
config = self._request.getConfiguration()
config = self._request.get_configuration()
def run_render_one(self, url, headers): """Renders a single page from the blog.
config = self._request.getConfiguration() data = self._request.getData()
config = self._request.get_configuration() data = self._request.get_data()
def run_static_renderer(self, incremental=False): """This will go through all possible things in the blog and statically render everything to the ``static_dir`` specified in the config file.
pyhttp = self.getHttp()
pyhttp = self.get_http()
def buffer_input_stream(self): """ Buffer the input stream in a StringIO instance. This is done to have a known/consistent way of accessing incomming data. For example the input stream passed by mod_python does not offer the same functionallity as ``sys.stdin``. """ # TODO: tests on memory consumption when uploading h...
self.getConfiguration()['stdoutput'] = response
self.get_configuration()['stdoutput'] = response
def set_response(self, response): """Sets the Response object. """ self._response = response # for backwards compatibility self.getConfiguration()['stdoutput'] = response
config = request.getConfiguration() data = request.getData()
config = request.get_configuration() data = request.get_data()
def blosxom_handler(request): """This is the default blosxom handler. It calls the renderer callback to get a renderer. If there is no renderer, it uses the blosxom renderer. It calls the pathinfo callback to process the path_info http variable. It calls the filelist callback to build a list of entries to display. ...
data = request.getData() config = request.getConfiguration()
data = request.get_data() config = request.get_configuration()
def blosxom_file_list_handler(args): """This is the default handler for getting entries. It takes the request object in and figures out which entries based on the default behavior that we want to show and generates a list of EntryBase subclass objects which it returns. :param args: dict containing the incoming Reques...
config = request.getConfiguration() data = request.getData() pyhttp = request.getHttp()
config = request.get_configuration() data = request.get_data() pyhttp = request.get_http()
def blosxom_process_path_info(args): """Process HTTP ``PATH_INFO`` for URI according to path specifications, fill in data dict accordingly. The paths specification looks like this: - ``/foo.html`` and ``/cat/foo.html`` - file foo.* in / and /cat - ``/cat`` - category - ``/2002`` - category - ``/2002`` - year - ``/200...
"""Takes a string and if it begins with " or ' and ends with " or ', then it returns the string. If it's an int, returns
""" Takes a string and if it begins with \" or \' and ends with \" or \', then it returns the string. If it's an int, returns
def s_or_i(text): """Takes a string and if it begins with " or ' and ends with " or ', then it returns the string. If it's an int, returns the int. Otherwise it returns the text. """ if text.startswith('"'): if text.endswith('"'): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s'...
if text.startswith('"'): if text.endswith('"'): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s' missing end \"" % text) elif text.startswith("'"): if text.endswith("'"): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s' missing end '" % text)
text = text.strip() if (((text.startswith('"') and not text.endswith('"')) or (not text.startswith('"') and text.endswith('"')))): raise ConfigSyntaxErrorException( "config syntax error: string '%s' missing start or end \"" % text) elif (((text.startswith("'") and not text.endswith("'")) or (not text.startswith("'") an...
def s_or_i(text): """Takes a string and if it begins with " or ' and ends with " or ', then it returns the string. If it's an int, returns the int. Otherwise it returns the text. """ if text.startswith('"'): if text.endswith('"'): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s'...