def _read_bond(self, bo): b = bond(self.paper) b.order = gtml_to_bkchem_bond_order_remap.index( dom_ext.getAllTextFromElement(xpath.Evaluate("bond", bo)[0])) ids = [i.nodeValue for i in xpath.Evaluate("end/@idref", bo)] b.atoms = [self._atom_id_remap[i] for i in ids] return b
def show(id, contestants, swiss_rounds, finalists): game = 0 player_score = {} player_won = {} player_lost = {} for filename in sorted(os.listdir('.'), cmp_filenames): if not filename.startswith('%d-' % id): continue game += 1 if game <= swiss_rounds * contestants: continue doc = minidom.parse(filename) name1 = xpath.Evaluate('/game/player1/name/text()', doc)[0].data name2 = xpath.Evaluate('/game/player2/name/text()', doc)[0].data result = xpath.Evaluate('/game/result', doc)[0] score1 = int(result.attributes['score1'].value) score2 = int(result.attributes['score2'].value) for name, score in [(name1, score1), (name2, score2)]: if name not in player_score: player_score[name] = player_won[name] = player_lost[name] = 0 if score == max(score1, score2): player_won[name] += 1 if score == min(score1, score2): player_lost[name] += 1 player_score[name] += score ranking = [(score, name) for name, score in player_score.iteritems()] ranking.sort(reverse=True) for score, name in ranking: print score, name, player_won[name], player_lost[name]
def ParseXML(self): print "\nObtaining XML info from SSB 'Site Readiness' view\n" prog = ProgressBar(0, 100, 77) xmlCacheDir = self.options.path_out + "/INPUTxmls" if not os.path.exists(xmlCacheDir): os.makedirs(xmlCacheDir) ColumnItems = self.cinfo.urls.keys() ColumnItems.sort() for col in ColumnItems: prog.increment(100./len(ColumnItems)) url = self.cinfo.urls[col] xmlFile = xmlCacheDir + "/" + col + ".xml" if self.options.xml == 'false' and not os.path.exists(xmlCacheDir): print "\nWARNING: you cannot re-use the XML files as the files were not obtained before. Obtaining them...\n" self.options.xml = 'true' if self.options.xml == 'true': # download xml file if requested print "Column %s - Getting the url %s" % (col, url) os.system("curl -s -H 'Accept: text/xml' '%s' > %s" % (url,xmlFile)) f = file(xmlFile,'r') # read xml file that was either just written, or was written in the previous run t = xml.dom.minidom.parse(f) f.close() #print t.toprettyxml() for subUrl in xpath.Evaluate("/getplotdata/csvdata/item", t): #print subUrl.toprettyxml() info = {} # basic info about the site for this column for option in ('Status', "COLOR", 'Time', 'EndTime','VOName','URL'): for target in xpath.Evaluate(option, subUrl): if target.hasChildNodes(): s = target.firstChild.nodeValue.encode('ascii') else: s = "" info[option] = s voname = info['VOName'] time = info['Time'] xmlMatrix = self.matrices.xmlInfo if self.options.oneSite != "" and voname.find(self.options.oneSite) != 0: continue if not xmlMatrix.has_key(voname): # if site not already in dict, add an empty dict for it xmlMatrix[voname] = {} if not xmlMatrix[voname].has_key(col): # if site entry doesn't already have this column, add an empty dict for this column xmlMatrix[voname][col] = {} xmlMatrix[voname][col][time] = info # set the actual values # Correct some of the strings value = xmlMatrix[voname][col][time]['Status'] if col=="HammerCloud" and value != "n/a": value = str(int(float(value))) if value.find("%") != 0: value += "%" elif col=="SUMAvailability": value = str(int(round(float(value)))) if value.find("%") != 0: value += "%" xmlMatrix[voname][col][time]['Status'] = value prog.finish()
def PresentAttributes(self): ids = [] path = '//ScopePool/@name' for scopeNode in \ xpath.Evaluate(path, self.doc.documentElement): path = '//ScopePool[@name="%s"]/AttributePool/@name' % scopeNode.value for attributeNode in \ xpath.Evaluate(path, self.doc.documentElement): ids.append(str(scopeNode.value + "::" + attributeNode.value)) return ids
def getLdapCredentials(gosaconffile): gosaxml = xml.dom.minidom.parse(gosaconffile) ldapwriteuser = xpath.Evaluate( '/conf/main/location[@name="default"]/referral/@admin', gosaxml) ldapwriteuser = ldapwriteuser[0].value ldapwritepwd = xpath.Evaluate( '/conf/main/location[@name="default"]/referral/@password', gosaxml) ldapwritepwd = ldapwritepwd[0].value return ldapwriteuser, ldapwritepwd
def process_reactions(self, doc): for react in xpath.Evaluate("//graph[@type='reaction']", doc): reactants = [] products = [] for e in xpath.Evaluate("edge/end[@type='initial']", react): id = e.getAttribute('idref') if id not in reactants: reactants.append(id) for e in xpath.Evaluate("edge/end[@type='terminal']", react): id = e.getAttribute('idref') if id not in products: products.append(id) self._reactions.append((reactants, products))
def _read_molecule(self, el): m = molecule(self.paper) for v in xpath.Evaluate("vertex", el): a2 = self._read_atom(v, m) m.insert_atom(a2) # bonds bond_lengths = [] for b in xpath.Evaluate("edge", el): b2 = self._read_bond(b) b2.molecule = m m.add_edge(b2.atom1, b2.atom2, b2) self._mol_ids[el.getAttribute('id')] = m return m
def xpath(input, expr): """ Evaluate the xpath expression against the input XML. """ if isinstance(input, (str, )) or hasattr(input, 'read'): # If input is a filename or an open file, then parse the XML. input = xml(input) return list(map(HandyXmlWrapper, xml_xpath.Evaluate(expr, input)))
def getParadigms(dixFile, wordType): from xml.dom import minidom from xml import xpath doc = minidom.parse("apertium-en-de.de.dix").documentElement xpath = '/dictionary/pardefs/pardef[substring-after(@n,"__")="%s"]' % (wordType) return xpath.Evaluate(xpath, doc)
def _createInfoDict(self, scan): from ComAssistantInfo import AttrAssistantInfo from ComAssistantHelper import createAssistantHelper self.infodict=InfoDict() # get the root element _info=self.value_def_doc.getElementsByTagName("info")[0] # For all <entry> elements for _elem in _info.getElementsByTagName("entry"): _elem = InfoElement(_elem) _node=None # OK, now get the list of <xpath> elements for _xpath in _elem.getXpathList(): _xpathname=_xpath.getAttribute("name") ComLog.getLogger(__logStrLevel__).debug("xpath %s" %_xpathname) try: _node=xpath.Evaluate(_xpathname, self.doc)[0] ComLog.getLogger(__logStrLevel__).debug("xpath %s does match" %_xpathname) break except Exception, e: ComLog.getLogger(__logStrLevel__).debug("xpath %s does not match" %_xpathname) pass if _node == None: ComLog.getLogger(__logStrLevel__).warning("element %s not found" %_elem.getName()) break _ainfo=AttrAssistantInfo(_node, _elem.getName(), \ _elem.getAttribute("type"),\ _elem.getComment(),\ None,\ createAssistantHelper(_elem.getHelperClassName(), _elem.getHelperQuery())) if scan: _ainfo.scan() self.infodict.addValue(_elem.getName(),_ainfo)
def get_molecules(self, file_name): self.molecules = [] # prepare the file to resolve entities f = StringIO.StringIO() f.write("<!DOCTYPE item [") entities = file('mathmlentities.ent') f.write(entities.read()) entities.close() f.write("<!ENTITY epsilon 'ε'><!ENTITY nevim '&nevim;'>]>") the_file = file(file_name) f.write(the_file.read()) the_file.close() f.seek(0) doc = dom.parse(f) f.close() for ch in xpath.Evaluate("//graph[@type='molecule']", doc): m = self._read_molecule(ch) self.molecules.append(m) # reactions self.process_reactions(doc) # placing the molecules self.place_molecules() # things that have to be done after the whole molecule is read and placed for m in self.molecules: if isinstance(m, molecule): [a.generate_marks_from_cheminfo() for a in m.atoms] return self.molecules
def fileChanged(self, filechooser=None): filename = self.file.get_filename() self.lessonStore.clear() if filename != None: self.examTree = parse(filename) title = xpath.Evaluate('//exam/@title', self.examTree) if len(title) > 0: self.window.setExamTitle(title[0].nodeValue) else: self.window.setExamTitle('') lessons = xpath.Evaluate('//lesson/@title', self.examTree) for lesson in lessons: self.lessonStore.append((lesson.nodeValue, )) else: self.window.setExamTitle('') self.lessonSelectionChanged()
def get_vm_meminfos(doc, domid): r = xpath.Evaluate('/domain/memory/text()', doc) if len(r) > 0: val = r[0].nodeValue else: val = '0' ret = 'memory:' + val + ',' r = xpath.Evaluate('/domain/currentMemory/text()', doc) if len(r) > 0: val = r[0].nodeValue else: val = '0' ret += 'currMem:' + val return ret
def processSurvey(self): # if not self.form.has_key("survey_data"): # return # process all fields ## self.doc.documentElement is the xml document describing the survey ## for dataField in xpath.Evaluate("//dataField", self.doc.documentElement): df = WebSurveyDataField(dataField) df.obtainValue(self.form) # if user pressed back button, we shouldn't validate what he/she # had entered. We can pass entered values, but we can validate # them later. if form.has_key("backbutton"): self.sentscreen -= 1 if form.has_key("survey_data"): for dataField in xpath.Evaluate("//dataField[count(parent::dataFields/parent::wizardScreen/preceding::wizardScreen) <= %s]" % self.sentscreen, self.doc.documentElement): df = WebSurveyDataField(dataField) df.validateValue() # if all the filled fields are ok, advance to the next screen of the # wizard if self.sentscreen is None: self.nextscreen = 0 elif self.form.has_key("backbutton"): self.nextscreen = self.sentscreen else: if len(xpath.Evaluate("//dataField[@valid = 'no']", self.doc.documentElement)) == 0: self.nextscreen = self.sentscreen + 1 else: self.nextscreen = self.sentscreen # if the response is valid, act if len(xpath.Evaluate("//dataField", self.doc.documentElement)) \ == len(xpath.Evaluate("//dataField[@valid = 'yes']", self.doc.documentElement)): oo = os.popen( '/usr/sbin/sendmail -t', 'w' ) oo.write( "To: [email protected]\n" ) oo.write( "From: %s <%s>\n" % (self.form['name'].value, self.form['email'].value) ) oo.write("Subject: [ddc_query] %s\n" % self.form['title'].value) oo.write("\n") # blank line separating headers from body oo.write("%s\n\nFrom: %s\nEmail: %s\n" % (self.form['user_comment'].value, self.form['name'].value, self.form['email'].value) ) oo.write("Category:%s\n" % self.form['suggtype'].value ) sts = oo.close() if sts: oo = open( '/tmp/mnj_oo.txt', 'w' ) oo.write( sts ) oo.close() return
def GetMethodElements(self, classElement): '''Returns the method elements from a class element. classElement - The class element.''' methodElements = xpath.Evaluate( 'compounddef/sectiondef[@kind = "public-func"]/memberdef[@kind = "function"]', classElement) return methodElements
def get_handler_class(my, process_name): nodes = xpath.Evaluate("/pipeline/process[@name='%s']/action" % process_name, my.doc) if not nodes: return "" action = nodes[0] action_class = action.getAttribute("class") return action_class
def get_process_info(my, process_name): processes = xpath.Evaluate("/pipeline/process[@name='%s']" % process_name, my.doc) if not processes: return {} process = processes[0] #print "get_process_info: ", process_name return process_name
def xpath(self, expression, other_namespaces=None): if other_namespaces: other_namespaces = other_namespaces.copy() other_namespaces.update(_MATH_NS_DICT) else: other_namespaces = _MATH_NS_DICT context = Context(self, processorNss=other_namespaces) return xpath.Evaluate(expression, context=context)
def load(self, examTree, lessons): self.questions = [] allLessons = xpath.Evaluate('//lesson', examTree) for lesson in allLessons: if lesson.getAttribute('title') not in lessons: continue tasks = xpath.Evaluate('./task', lesson) for task in tasks: questions = xpath.Evaluate('./question/text()', task) if len(questions) == 0: continue question = questions[0].data answers = [ a.data for a in xpath.Evaluate('./answer/text()', task) ] self.questions.append(Question(question, answers)) self.reset()
def getID(fname): print fname # create Reader object reader = Sax2.Reader() # parse the document doc = reader.fromStream(fname) nodes = xpath.Evaluate('//*[local-name()="id"]', doc.documentElement) return nodes[0].firstChild.nodeValue
def get_group_id(group): data = { "method": "flickr.groups.search", "api_key": api_key, "text": group, } url = "%s?%s" % (api_url, urllib.urlencode(data)) xml = urllib.urlopen(url).read() doc = minidom.parseString(xml) return xpath.Evaluate("//group[0]/@nsid")[0]
def xpath(self, expr=''): """ Return the snippets corresponding to the given xpath query. """ from xml.dom.ext import GetAllNs from xml import xpath dom = self.get_dom(self(method='xml')) context = xpath.Context.Context(dom, processorNss=GetAllNs(dom.documentElement)) return xpath.Evaluate(expr, context=context)
def _InsertNode(self, nodesToMove, scope, name=None): path = '//ScopePool[@name="%s"]' % (scope) scopeNodes = xpath.Evaluate(path, self.doc.documentElement) for scopeNode in scopeNodes: for node in nodesToMove: cloned = self.doc.importNode(node, True) if name != None: cloned.setAttribute("name", name) scopeNode.appendChild(cloned) return assert None, "Target scope not found"
def __getitem__(self, key): from xml import xpath # pyxml's xpath does not support /element1[...]/element2... nodes = xpath.Evaluate('//dict[key=%r]' % key, self.document) results = [] for node in nodes: v = self._convert_value_node(node)[key] if isinstance(v, dict) and '_order' in v: # this is just information for display pass else: results.append(v) return results
def builtin(): '''Run the builtin tests from the C14N spec.''' for i in range(len(examples)): num = i + 1 eg = examples[i] filename = 'out%d.xml' % num try: os.unlink(filename) except: pass print 'Doing %d, %s...' % (num, string.replace(eg[0:30], '\n', '\\n')), r = ReaderforC14NExamples() try: dom = r.fromString(eg) except Exception, e: print '\nException', repr(e) traceback.print_exc() continue # Get the nodeset; the tests have some special cases. pattern = '(//. | //@* | //namespace::*)' con = Context(dom) if eg == eg5: pattern = '(//. | //@* | //namespace::*)[not (self::comment())]' elif eg == eg7: con = Context(dom, processorNss={'ietf': 'http://www.ietf.org'}) nodelist = xpath.Evaluate(pattern, context=con) s = StringIO.StringIO() outf = utf8_writer(s) #Get the unsuppressedPrefixes for exc-c14n; the tests have special casese pfxlist = [] # Canonicalize a DOM with a document subset list according to XML-C14N if eg == eg1: Canonicalize(dom, outf, subset=nodelist, comments=1) else: Canonicalize(dom, outf, subset=nodelist) expected = base64.decodestring(test_results[eg]) if s.getvalue() == expected: print 'Ok' else: print 'Error!' print 'Got:\n', s.getvalue() print 'Expected:\n', expected
def xpath(self, expression, other_namespaces=None): """Evaluate an XPath expression against the MathDOM. The 'math' prefix will automatically be available for the MathML namespace. If other namespaces are needed, the can be specified as a {prefix : namespaceURI} dictionary. """ if other_namespaces: other_namespaces = other_namespaces.copy() other_namespaces.update(_MATH_NS_DICT) else: other_namespaces = _MATH_NS_DICT context = Context(self._document.documentElement, processorNss=other_namespaces) return xpath.Evaluate(expression, context=context)
def GetDetailedParameterInformation(self, methodElement): '''Returns a string representing the information about the parameters which can be passed to a method.''' parameterNames = xpath.Evaluate( 'detaileddescription/para/parameterlist/parametername', methodElement) parameterDescriptions = xpath.Evaluate( 'detaileddescription/para/parameterlist/parameterdescription/para', methodElement) paramInformation = '' nParams = len(parameterNames) for i in range(nParams): paramInformation += textwrap.fill( self.GetTextFromElement(parameterNames[i]) + ' ' + self.GetTextFromElement(parameterDescriptions[i]), 65, subsequent_indent=' ') if i < nParams - 1: paramInformation += '\n' if paramInformation != '': paramInformation = '\n' + paramInformation return paramInformation
def GetTextFromElement(self, element, xpathStr='text()'): '''Returns the text in an element. element - The element. xpaths - Optional xpath string to match against. The default xpath string is "text()". ''' textNodes = xpath.Evaluate(xpathStr, element) text = '' for textNode in textNodes: if textNode.nodeValue != None: text += normalizeWhiteSpace(textNode.nodeValue) return text
def _getParams(self, xml, template): ''' param xml: xml file containing params with values returns: python dict containing values (uncasted) ''' td = minidom.parseString(template) d = minidom.parseString(xml) param = xpath.Evaluate('//params', td)[0] params = {} for paramNode in param.childNodes: try: if paramNode.nodeType == 3: # we ignore the text nodes continue name = paramNode.nodeName defaultValue = paramNode.childNodes[0].data except (IndexError, AttributeError), e: defaultValue = "" try: valueParam = xpath.Evaluate('//%s' % name, d)[0] value = valueParam.childNodes[0].data except (IndexError, AttributeError), e: value = defaultValue
def get_vm_cpuinfos(doc, domid): val = 0 r = xpath.Evaluate('/domain/vcpu/text()', doc) if len(r) > 0: val = r[0].nodeValue ret = 'vcpu:' + val + ',' cmd = 'virsh vcpuinfo ' + domid (stat, output) = commands.getstatusoutput(cmd) l = output.find('\nCPU Affinity') output = output[0:l] output = output.replace(' ', '') ret += output.replace('\n', ',') return ret