Beispiel #1
0
	def __init__(self, filename, shortXMLfilename):
		self.filename = filename
		self.shortXMLfilename = shortXMLfilename
		
		try:
			self.tableFile = parse(filename)
		except:
			impl = getDOMImplementation()
			self.tableFile = impl.createDocument(None, "table", None)
			self.tableFile.getElementsByTagName("table")[0].setAttribute("class", "sortable")
			self.tableFile.getElementsByTagName("table")[0].setAttribute("id", "xeplist")
			self.tableFile.getElementsByTagName("table")[0].setAttribute("cellspacing", "0")
			self.tableFile.getElementsByTagName("table")[0].setAttribute("cellpadding", "3")
			self.tableFile.getElementsByTagName("table")[0].setAttribute("border", "1")
			
			header = parseString(
'''<tr class='xepheader'>
	<th align='left'>Number</th>
	<th align='left'>Name</th>
	<th align='left'>Type</th>
	<th align='left'>Status</th>
	<th align='left'>Date</th>
</tr>''')
			self.tableFile.getElementsByTagName("table")[0].appendChild(header.getElementsByTagName("tr")[0])
		
		try:
			self.botsFile = parse(shortXMLfilename)
		except:
			impl = getDOMImplementation()
			self.botsFile = impl.createDocument(None, "xeps", None)
Beispiel #2
0
def test_create_sliver(server, slice_urn, slice_credential, dom, api_version=2):
    if api_version < 3:
        print "Testing CreateSliver...",
    else:
        print "Testing Allocate...",
    options = None
    if api_version >= 2:
        options = dict()
        # FIXME: Build up a request_rspec for real
        nodes = dom.getElementsByTagName("node")
        dom_impl = minidom.getDOMImplementation()
        request_rspec = dom_impl.createDocument("http://www.geni.net/resources/rspec/3", "rspec", None)
        top = request_rspec.documentElement
        top.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        top.setAttribute(
            "xsi:schemaLocation",
            "http://www.geni.net/resources/rspec/3 http://www.geni.net/resources/rspec/3/request.xsd",
        )
        top.setAttribute("xmlns", "http://www.geni.net/resources/rspec/3")
        top.setAttribute("type", "request")
        if nodes.length == 0:
            print "failed: no nodes available"
            return
        elif nodes.length == 1:
            top.appendChild(nodes.item(0).cloneNode(True))
        else:
            # pick two at random
            indices = range(nodes.length)
            for _ in range(2):
                index = random.choice(indices)
                indices.remove(index)
                top.appendChild(nodes.item(index).cloneNode(True))
    else:
        resources = dom.getElementsByTagName("resource")
        dom_impl = minidom.getDOMImplementation()
        request_rspec = dom_impl.createDocument(None, "rspec", None)
        top = request_rspec.documentElement
        if resources.length == 0:
            print "failed: no resources available"
            return
        elif resources.length == 1:
            top.appendChild(resources.item(0).cloneNode(True))
        else:
            # pick two at random
            indices = range(resources.length)
            for _ in range(2):
                index = random.choice(indices)
                indices.remove(index)
                top.appendChild(resources.item(index).cloneNode(True))
    users = [{"key": ""}]
    if options is not None:
        try:
            if api_version < 3:
                result = server.CreateSliver(slice_urn, slice_credential, request_rspec.toxml(), users, options)
            else:
                result = server.Allocate(slice_urn, slice_credential, request_rspec.toxml(), options)
        except Exception, e:
            print "failed: %s" % e
            return
Beispiel #3
0
 def __init__(self, document=None, node=None, root=None):
     self.document = document
     if self.document is None and node is not None:
         impl = minidom.getDOMImplementation()
         self.resource = impl.createDocument(None, None, None)
         self.resource.appendChild(node)
     elif self.document is None:
         impl = minidom.getDOMImplementation()
         self.resource = impl.createDocument(None, root, None)
Beispiel #4
0
 def Load(self,file,type):
     if os.path.exists(file):
         source=open(file)
         try:
             dom1=minidom.parse(source)
         except:
             impl=minidom.getDOMImplementation()
             dom1=impl.createDocument(None,type,None)
         return dom1
     else:
         impl=minidom.getDOMImplementation()
         doc=impl.createDocument(None, type,None)
         return doc
Beispiel #5
0
 def makeLibrary(self, monomers, curatedonly=True):
     self.child.all().delete()
     if not self.construct.processed:
         for j in self.construct.process():
             pass
     impl = getDOMImplementation()
     xml = impl.createDocument(None, 'nrp', None)
     root = xml.documentElement
     monomersnode = xml.createElement('monomers')
     varpos = -1
     i = 0
     for monomer in monomers:
         monomernode = xml.createElement('monomer')
         if len(monomer) > 1:
             varpos = i
         i += 1
         for aa in monomer:
             idnode = xml.createElement("id")
             aanode = xml.createTextNode(str(aa))
             idnode.appendChild(aanode)
             monomernode.appendChild(idnode)
         monomersnode.appendChild(monomernode)
     root.appendChild(monomersnode)
     nrpsnode = xml.createElement('nrps')
     domains = self.getDomainSequence()
     for domain in domains:
         domainnode = xml.createElement('domain')
         idnode = xml.createElement('id')
         idtext = xml.createTextNode(str(domain))
         idnode.appendChild(idtext)
         domainnode.appendChild(idnode)
         nrpsnode.appendChild(domainnode)
     root.appendChild(nrpsnode)
     xmlstr = xml.toxml("utf-8")
     args = ['-n', '-', '-s', '-']
     if curatedonly:
         args.extend(["--curated-only", "--curation-group", settings.CURATION_GROUP])
     xmlout = self._runNrpsDesigner(args, xmlstr)
     designerDom = parseString(xmlout)
     nrpsList = designerDom.getElementsByTagName('s:component')
     i = 1
     for nrps in nrpsList:
         description = self.description
         if description is not None and len(description) > 0:
             description += "\n"
         varname = Substrate.objects.get(pk=monomers[varpos][i]).name
         nrp = NRP.objects.create(owner = self.owner, name="%s %s" % (self.name, varname), description=description + "library variant %d: %s" % (i, varname), indigoidineTagged=self.indigoidineTagged, parent=self)
         for j, monomerId in enumerate(monomers):
             index = 0
             if j == varpos:
                 index = i
             monomer = Substrate.objects.get(pk=monomerId[index])
             SubstrateOrder.objects.create(nrp=nrp, substrate=monomer, order=j)
         nrp._design(self._parseNrps(nrps))
         for j,cf in enumerate(self.construct.cf.order_by('order')):
             if cf.fragment.origin != 'ND':
                 nrp.construct.add_fragment(cf.fragment, j, cf.direction)
         for j in nrp.construct.process():
             pass
         i += 1
Beispiel #6
0
    def build_xml(self):
        impl = minidom.getDOMImplementation()
        self.doc = impl.createDocument(None, "updates", None)

        updates = self.doc.documentElement
        update = self.doc.createElement("update")
        updates.appendChild(update)

        update.setAttribute("type", self.update_type)
        update.setAttribute("appVersion", self.app_version)
        update.setAttribute("version", self.platform_version)
        update.setAttribute("buildID", self.build_id)
        update.setAttribute("licenseURL", self.license_url)
        update.setAttribute("detailsURL", self.details_url)

        if self.is_fota_update:
            update.setAttribute("isOSUpdate", "true")

        if self.complete_mar:
            complete_patch = self.build_patch("complete", self.complete_mar)
            update.appendChild(complete_patch)

        if self.partial_mar:
            partial_patch = self.build_patch("partial", self.partial_mar)
            update.appendChild(partial_patch)

        return self.doc.toprettyxml()
def generate_cobertura_xml(coverage_data, options):
	'''Given a list of lines of lcov input, return a String cobertura XML
	representation'''
	
	dom_impl = minidom.getDOMImplementation()
	doctype = dom_impl.createDocumentType("coverage", None, "http://cobertura.sourceforge.net/xml/coverage-03.dtd")
	document = dom_impl.createDocument(None, "coverage", doctype)
	root = document.documentElement
	
	summary = coverage_data['summary']
	
	root.setAttribute('branch-rate', '0')
	root.setAttribute('branches-covered', '0')
	root.setAttribute('branches-valid', '0')
	root.setAttribute('complexity', '0')
	root.setAttribute('line-rate', compute_line_rate(summary['lines-total'], summary['lines-covered']))
	root.setAttribute('lines-valid', str(summary['lines-total']))
	root.setAttribute('timestamp', str(int(time.time())))
	root.setAttribute('version', '1.9')
	
	sources = document.createElement('sources')
	root.appendChild(sources)
	
	packages_element = document.createElement('packages')
	
	packages = coverage_data['packages']
	for package_name, package_data in packages.items():
		# TODO: make more robust
		if package_name in options.excludes:
			continue
		package_element = document.createElement('package')
		package_element.setAttribute('line-rate', package_data['line-rate'])
		package_element.setAttribute('name', package_name)
		classes_element = document.createElement('classes')
		for class_name, class_data in package_data['classes'].items():
			class_element = document.createElement('class')
			class_element.setAttribute('branch-rate', '0')
			class_element.setAttribute('complexity', '0')
			class_element.setAttribute('filename', class_name)
			class_element.setAttribute('line-rate', compute_line_rate(class_data['lines-total'], class_data['lines-covered']))
			class_element.setAttribute('name', class_data['name'])
			lines_element = document.createElement('lines')
			
			lines = class_data['lines'].keys()
			lines.sort()
			for line_number in lines:
				line_element = document.createElement('line')
				line_element.setAttribute('branch', '0')
				line_element.setAttribute('hits', str(class_data['lines'][line_number]))
				line_element.setAttribute('number', str(line_number))
				lines_element.appendChild(line_element)
				
			class_element.appendChild(lines_element)
			classes_element.appendChild(class_element)
			
		package_element.appendChild(classes_element)
		packages_element.appendChild(package_element)
	root.appendChild(packages_element)
	
	return document.toprettyxml()
Beispiel #8
0
    def models_to_xml(self, request, model_name, model_handler, models,
                      list_props=None):
        """Returns a string of xml of the given models (may be list or
        single instance)."""
        impl = minidom.getDOMImplementation()
        doc = None
        try:
            if isinstance(models, (types.ListType, types.TupleType)):
                doc = impl.createDocument(None, LIST_EL_NAME, None)
                list_el = doc.documentElement
                if ((list_props is not None) and \
                      (list_props.has_key(QUERY_OFFSET_PARAM))):
                    list_el.attributes[QUERY_OFFSET_PARAM] = \
                        list_props[QUERY_OFFSET_PARAM]
                for model in models:
                    model_el = append_child(list_el, model_name)
                    model_handler.write_xml_value(model_el, model)
            else:
                doc = impl.createDocument(None, model_name, None)
                model_handler.write_xml_value(doc.documentElement, models)

            return self.doc_to_output(request, doc)
        finally:
            if doc:
                doc.unlink()
	def generate(self, fileName):
		# Once all records have been calculated, create the XML structure itself
		self.document = getDOMImplementation().createDocument(None, 'data', None)
		topNode = self.document.documentElement
		for record in self.data['records']:
			recordNode = self.document.createElement('record')
			topNode.appendChild( recordNode )
			for field, value in record.iteritems():
				fieldNode = self.document.createElement( field )
				recordNode.appendChild( fieldNode )
				# The rest of field types must be converted into str
				if value == False:
					value = ''
				elif isinstance(value, str):
					value = unicode(value, 'utf-8')
				elif not isinstance(value, unicode):
					value = unicode(value)
				valueNode = self.document.createTextNode( value )
				fieldNode.appendChild( valueNode )
		# Once created, the only missing step is to store the XML into a file
		f = codecs.open( fileName, 'wb+', 'utf-8' )
		try:
			topNode.writexml( f )
		finally:
			f.close()
Beispiel #10
0
 def metadata(self, request, model_name=None):
     impl = minidom.getDOMImplementation()
     doc = None
     try:
         if model_name:
             model_handler = self.get_model_handler(model_name)
             if(not model_handler):
                 return None
             self.check_authority(request, OP_LIST, obj=None,
                                  model_name=model_name, prop_name=None)
             doc = impl.createDocument(XSD_NS, XSD_SCHEMA_NAME, None)
             doc.documentElement.attributes[XSD_ATTR_XMLNS] = XSD_NS
             model_handler.write_xsd_metadata(doc.documentElement,
                                              model_name)
         else:
             self.check_authority(request, OP_LIST, obj=None,
                                  model_name=None, prop_name=None)
             doc = impl.createDocument(None, TYPES_EL_NAME, None)
             types_el = doc.documentElement
             for model_name in self.model_handlers.iterkeys():
                 append_child(types_el, TYPE_EL_NAME, model_name)
         output = self.doc_to_output(request, doc)
     finally:
         if doc:
             doc.unlink()
     return self.out_to_response(output)
Beispiel #11
0
    def save(self):
        """Writes the current contact list, group, and contact state out to a
        new contacts file.
        """

	print "Connection - save"

        dom_impl = minidom.getDOMImplementation()
        xml_doc = dom_impl.createDocument(None, 'roster', None)
        roster_xml = xml_doc.documentElement

        # add newline for human-readability
        newline_value = xml_doc.createTextNode('\n')
        roster_xml.appendChild(newline_value)

        contact_channels_map = self.get_contact_channel_membership_info()
        for handle_obj, lists_groups in contact_channels_map.items():
            contact_lists, groups = lists_groups

            contact_xml = handle_obj.get_xml(contact_lists, groups)
            roster_xml.appendChild(contact_xml)

            # add newline for human-readability
            newline_value = xml_doc.createTextNode('\n\n')
            roster_xml.appendChild(newline_value)

        
        account_id = self.get_account_id()
        pin.common.save_roster(xml_doc, account_id)
Beispiel #12
0
    def __init__(self):
        impl = getDOMImplementation()
        self.doc = impl.createDocument(None, 'urlset', None)

        self.urlset = self.doc.documentElement
        self.urlset.setAttribute('xmlns',
                                 'http://www.sitemaps.org/schemas/sitemap/0.9')
Beispiel #13
0
 def toDom(self):
     doc = getDOMImplementation().createDocument("http://info.teragrid.org/glue/2009/02/spec_2.0_r02",
                                                 "Entities",None)
     for share in self.data.shares:
         sdoc = ComputingShareTeraGridXml(share).toDom()
         doc.documentElement.appendChild(sdoc.documentElement.firstChild)
     return doc
Beispiel #14
0
    def __init__(self, filename=""):
        super(DMPlaylist, self).__init__()
        self.document = parse(filename) if filename \
                        else getDOMImplementation().createDocument(None,
                                                            "DMPlaylist", None)
        self._categories = []
        self._items = []

        for node in self.document.documentElement.childNodes:
            if hasattr(node, "tagName"):
                if node.tagName == TAG_CATEGORY:
                    category = DMPlaylistCategory(self.document,
                                                node.getAttribute("name"))
                    for child in node.childNodes:
                        if hasattr(child, "tagName"):
                            childName = "".join(map(lambda x: x.data.strip(),
                                child.childNodes))
                            item = DMPlaylistItem(self.document,
                                childName,
                                child.getAttribute("source"),
                                child.getAttribute("played"))
                            category._items.append(item)
                    self._categories.append(category)
                elif node.tagName == TAG_ITEM:
                    childName = "".join(map(lambda x: x.data.strip(),
                        node.childNodes))
                    item = DMPlaylistItem(self.document,
                        childName,
                        node.getAttribute("source"),
                        node.getAttribute("played"))
                    self._items.append(item)
  def BeginTemplate(self):
    '''Generates the skeleton of the ADMX template. An ADMX template contains
    an ADMX "PolicyDefinitions" element with four child nodes: "policies"
    "policyNamspaces", "resources", "supportedOn" and "categories"
    '''
    dom_impl = minidom.getDOMImplementation('')
    self._doc = dom_impl.createDocument(None, 'policyDefinitions', None)
    policy_definitions_elem = self._doc.documentElement

    policy_definitions_elem.attributes['revision'] = '1.0'
    policy_definitions_elem.attributes['schemaVersion'] = '1.0'

    self._AddPolicyNamespaces(policy_definitions_elem,
                              self.config['admx_prefix'],
                              self.config['admx_namespace'])
    self.AddElement(policy_definitions_elem, 'resources',
                    {'minRequiredRevision' : '1.0'})
    self._AddSupportedOn(policy_definitions_elem,
                         self.config['win_supported_os'])
    self._categories_elem = self.AddElement(policy_definitions_elem,
                                            'categories')
    self._AddCategories(self.config['win_mandatory_category_path'])
    self._AddCategories(self.config['win_recommended_category_path'])
    self._active_policies_elem = self.AddElement(policy_definitions_elem,
                                                 'policies')
    self._active_mandatory_policy_group_name = \
        self.config['win_mandatory_category_path'][-1]
    self._active_recommended_policy_group_name = \
        self.config['win_recommended_category_path'][-1]
Beispiel #16
0
    def makeRequest(self, params):
        """Create and serialise SOAP envelope from a DOM document"""
        global NS
        impl = minidom.getDOMImplementation()
        self.requestDoc = impl.createDocument(self.targetNs, "soap:Envelope", None)
        setDocAttr = self.requestDoc.documentElement.setAttribute
        
        setDocAttr("xmlns:soap", NS["soap"])

        for name, value in self.requestNamespaces.iteritems():
            setDocAttr("xmlns:" + name, value)

        setDocAttr("xmlns", self.targetNs)

        # create header
        if len(self._headers):
            header = self.requestDoc.createElementNS(NS["soap"], "soap:Header")
            self.addLiteral(self.requestDoc, header, self._headers)
            self.requestDoc.documentElement.appendChild(header)

        # and body
        body = self.requestDoc.createElementNS(NS["soap"], "soap:Body")
        self.requestDoc.documentElement.appendChild(body)
        
        operation = self.requestDoc.createElement(self.name)
        if type(params) == dict:
            self.addLiteral(self.requestDoc, operation, params)
        body.appendChild(operation)
    
        return self.requestDoc.toxml()
  def Generate(self):
    """Creates font a DOM with data for every table.

    Uses |table_data_generators| to plug in XML generators.

    Returns:
      A DOM ready for serialization.
    """
    doc = minidom.getDOMImplementation().createDocument(None,
                                                        'font_test_data', None)
    root_element = doc.documentElement
    # We need to set the path of the font as if in the root source directory
    # The assumption is that we have a '../' prefix
    root_element.setAttribute('path', self.font_path[3:])
    h = hashlib.new('sha1')
    h.update(open(self.font_path, 'r').read())
    root_element.setAttribute('sha1', h.hexdigest())
    font = ttLib.TTFont(self.font_path)
    # There is always a postscript name for Windows_BMP
    name_record = font['name'].getName(6, 3, 1)
    root_element.setAttribute('post_name',
                              self.Unpack(name_record.string))
    for (name, table_data_generator) in self.table_data_generators:
      name += '_table'
      table_element = doc.createElement(name)
      root_element.appendChild(table_element)
      table_data_generator.Generate(font, doc, table_element)
    return doc
Beispiel #18
0
    def set_event_command(self, event, command, config=None, create_new=True):
        cfg_nodes = self.root_node.getElementsByTagName("ItemDefinitionGroup")
        for cfg_node in cfg_nodes:
            if config is not None:
                if 'Condition' not in cfg_node.attributes.keys():
                    continue

                cond_attr = cfg_node.attributes["Condition"].value
                if cond_attr.lower().find("debug") >= 0:
                    cur_mode = "Debug"
                else:
                    cur_mode = "Release"

                if cur_mode.lower() != config.lower():
                    continue

            event_node = self.get_or_create_node(cfg_node, event, create_new)
            if event_node is None:
                continue

            cmd_node = self.get_or_create_node(event_node, "Command")
            if cmd_node.firstChild is None:
                impl = minidom.getDOMImplementation()
                dom = impl.createDocument(None, 'catalog', None)
                nodeValue = dom.createTextNode(command)
                cmd_node.appendChild(nodeValue)
            else:
                cmd_node.firstChild.nodeValue = command
 def run(self, test):
     std_out = sys.stdout
     std_err = sys.stderr
     sys.stdout = StringIO()
     sys.stderr = StringIO()
     "Run the given test case or test suite."
     result_xml = getDOMImplementation().createDocument(None, 'testsuites', None)
     result = _OpusXMLTestResult(result_xml, self.descriptions, self.verbosity)
     startTime = time.time()
     test(result)
     stopTime = time.time()
     timeTaken = stopTime - startTime
     result.printErrors()
     
     run = result.testsRun
     
     failed, errored = map(len, (result.failures, result.errors))
     top_element = result_xml.documentElement
     top_element.setAttribute('errors', '%d' % errored)
     top_element.setAttribute('failures', '%d' % failed)
     top_element.setAttribute('tests', '%d' % run)
     top_element.setAttribute('time', '%.3f' % timeTaken)
     stream_xml = result_xml.createElement('system-out')
     stream_text_xml = result_xml.createTextNode('%s' % sys.stdout.getvalue())
     stream_xml.appendChild(stream_text_xml)
     top_element.appendChild(stream_xml)
     stream_xml = result_xml.createElement('system-err')
     stream_text_xml = result_xml.createTextNode('%s' % sys.stderr.getvalue())
     stream_xml.appendChild(stream_text_xml)
     top_element.appendChild(stream_xml)
     self.stream.write(result_xml.toprettyxml())
     sys.stdout = std_out
     sys.stderr = std_err
     return result
Beispiel #20
0
def save(config={}, filename=DEFAULT_CONFIG_FILE):
    impl = getDOMImplementation()
    dom = impl.createDocument(None, "server", impl.createDocumentType('server', None, "../xml/server.dtd"))

    dserver = dom.documentElement

    dconfig = dom.createElement('config')
    
    for sec,key in CONFIG_ITEMS:
        if config[sec]:
            ditem = dom.createElement(sec)
            ditem.setAttribute(key, config[sec])
            dconfig.appendChild(ditem)
    
    dserver.appendChild(dconfig)

    dauth = dom.createElement('auth')
    users = config['users']
    if users:
        for user in users:
            if not users.get(user):
                print "[WARNING] User %s has no password" % user
            duser = dom.createElement('user')
            duser.setAttribute('name', user)
            duser.setAttribute('password', users.get(user))
            dauth.appendChild(duser)
    dserver.appendChild(dauth)

    configFile = file(DEFAULT_CONFIG_FILE, 'w')
    dom.writexml(configFile, addindent='    ', newl='\n', encoding='UTF-8')
    configFile.close()
def citiesCode():
	impl = minidom.getDOMImplementation()
	dom = impl.createDocument(None, 'CitiesCode', None)
	rootNode = dom.documentElement

	provinces = getCitiesCode.getProCode()	#获取省编号
	for pro in provinces:
		province = dom.createElement('province')
		province.setAttribute('id', pro.split('|')[0])
		province.setAttribute('name', pro.split('|')[1])
		cities = getCitiesCode.getCityCode(pro.split('|')[0])	#获取市编号
		for ci in cities:
			city = dom.createElement('city')
			city.setAttribute('id', ci.split('|')[0])
			city.setAttribute('name', ci.split('|')[1])
			areas = getCitiesCode.getAreaCode(ci.split('|')[0])
			for ar in areas:
				area = dom.createElement('area')
				area.setAttribute('id', ar.split('|')[0])
				area.setAttribute('name', ar.split('|')[1])
				city.appendChild(area)
			province.appendChild(city)
		rootNode.appendChild(province)

	writeXML(dom, '../xml/CitiesCode.xml')
Beispiel #22
0
 def request_frame_document(self, message):
     frame = self.message_frame_dict[message]  
     doc = getDOMImplementation().createDocument(None, "stack", None)
     top_element = doc.documentElement
     if frame:
         self.addFrame(frame, top_element, doc, includeContent=True)
     return xmlrpclib.Binary(bz2.compress(doc.toxml()))
Beispiel #23
0
def DoTrackX(rgm, args):
  if len(args) != 1:
    return DoHelp(rgm, args)

  info = rgm.GetInfo()
  _, _, _, _, _, _, _, tracks, _ = info

  range_iter = ParseRange(args[0], 0, tracks-1)
  if not range_iter:
    return DoHelp(rgm, args)

  gpxdoc = minidom.getDOMImplementation().createDocument(
      'http://www.topografix.com/GPX/1/1', 'gpx', None)
  e_gpx = gpxdoc.documentElement
  e_gpx.setAttribute('version', '1.1')
  e_gpx.setAttribute('creator', 'rgm3800py')

  e_trk = gpxdoc.createElement('trk')
  e_gpx.appendChild(e_trk)

  for i in range_iter:
    e_trkseg = gpxdoc.createElement('trkseg')
    e_trk.appendChild(e_trkseg)

    waypoints = rgm.GetWaypoints(i)
    for wp in waypoints:
      e_trkseg.appendChild(wp.GetGPXTrackPT(gpxdoc))

  print gpxdoc.toxml()
  return 0
Beispiel #24
0
def xml_document(top):
    # First, make the header
    impl = getDOMImplementation()
    xml = impl.createDocument(None, top, None)
    top = xml.documentElement

    return xml, top
    def __init__(self, samplerate, nframes, wavpath):
        """Init a sonic visualiser environment structure based on
        the attributes of the main audio file
        
        Args:
          samplerate(int): media sample rate (Hz)
          nframes(int): number of samples
          wavpath(str): Full path to the wav file used in the current environment

        """
        imp = minidom.getDOMImplementation()
        dt = imp.createDocumentType('sonic-visualiser', None, None)
        self.doc = doc = imp.createDocument(None,'sv', dt)
        root = doc.documentElement
        self.__dname = dict()

        self.data = root.appendChild(doc.createElement('data'))
        self.display = root.appendChild(doc.createElement('display'))
        window = self.display.appendChild(doc.createElement('window'))
        self.defwidth = 900
        window.setAttribute('width', str(self.defwidth))
        window.setAttribute('height', str(856))
        self.selections = root.appendChild(doc.createElement('selections'))


        self.nbdata = 0

        #self.nchannels = nchannels
        self.samplerate =  samplerate
        self.nframes = nframes

        self.__setMainWaveModel(wavpath)
Beispiel #26
0
	def to_xml(self):
		"""
		Turn this into an XML
		document
		"""
		impl = getDOMImplementation()
		doc = impl.createDocument(None, 'Exception', None)

		rootNode = doc.documentElement

		type_node = doc.createElement("type")
		text_node = doc.createTextNode(self.__class__.__name__)
		type_node.appendChild(text_node)
		rootNode.appendChild(type_node)

		type_node = doc.createElement("code")
		text_node = doc.createTextNode(str(self.code))
		type_node.appendChild(text_node)
		rootNode.appendChild(type_node)

		type_node = doc.createElement("message")
		text_node = doc.createTextNode(self.message)
		type_node.appendChild(text_node)
		rootNode.appendChild(type_node)

		type_node = doc.createElement("description")
		text_node = doc.createTextNode(self.description)
		type_node.appendChild(text_node)
		rootNode.appendChild(type_node)

		return doc
Beispiel #27
0
	def generate(self, fileName):
		self.allRecords = []
		relations = self.report.relations()
		# The following loop generates one entry to allRecords list for each record
		# that will be created. If there are any relations it acts like a
		# LEFT JOIN against the main model/table.
		for record in self.pool.get(self.model).browse(self.cr, self.uid, self.ids, self.context):
			newRecords = self.generateIds( record, relations, '', [ { 'root': record } ] )
			copies = 1
			if self.report.copiesField() and record.__hasattr__(self.report.copiesField()):
				copies = int( record.__getattr__(self.report.copiesField()) )
			for new in newRecords:
				for x in xrange(copies):
					self.allRecords.append( new )

		# Once all records have been calculated, create the XML structure itself
		self.document = getDOMImplementation().createDocument(None, 'data', None)
		topNode = self.document.documentElement
		for records in self.allRecords:
			recordNode = self.document.createElement('record')
			topNode.appendChild( recordNode )
			self.generateXmlRecord( records['root'], records, recordNode, '', self.report.fields() )

		# Once created, the only missing step is to store the XML into a file
		f = codecs.open( fileName, 'wb+', 'utf-8' )
		try:
			topNode.writexml( f )
		finally:
			f.close()
Beispiel #28
0
    def __init__(self, cls, db_name, db_user, db_passwd,
                 db_host, db_port, db_table, ddl_dir, enable_ssl):
        self.cls = cls
        if not db_name:
            db_name = cls.__name__.lower()
        self.db_name = db_name
        self.db_user = db_user
        self.db_passwd = db_passwd
        self.db_host = db_host
        self.db_port = db_port
        self.db_table = db_table
        self.ddl_dir = ddl_dir
        self.s3 = None
        self.converter = XMLConverter(self)
        self.impl = getDOMImplementation()
        self.doc = self.impl.createDocument(None, 'objects', None)

        self.connection = None
        self.enable_ssl = enable_ssl
        self.auth_header = None
        if self.db_user:
            import base64
            base64string = base64.encodestring('%s:%s' % (self.db_user, self.db_passwd))[:-1]
            authheader =  "Basic %s" % base64string
            self.auth_header = authheader
Beispiel #29
0
    def save(self):
        """
        _save_

        Serialise this to XML compatible with PhEDEx injection

        """
        impl = getDOMImplementation()

        doc = impl.createDocument(None, "block", None)
        result = doc.createElement("block")
        result.setAttribute('name', self.fileblockName)
        result.setAttribute('is-open', self.isOpen)
        for lfn, checksums, size in self:
            # checksums is a comma separated list of key:value pair
            formattedChecksums = ",".join(["%s:%s" % (x.lower(), y) for x, y \
                                           in checksums.items() \
                                           if y not in (None, '')])
            ifile = doc.createElement("file")
            ifile.setAttribute('name', lfn)
            ifile.setAttribute('checksum', formattedChecksums)
            ifile.setAttribute('bytes', str(size))
            result.appendChild(ifile)

        return result
 def _initEmptyManifest(self):
     self.doc = xml.getDOMImplementation().createDocument(None, 'manifest', None)
     root = self.doc.documentElement
     root.setAttribute('xmlns:android', 'http://schemas.android.com/apk/res/android')
     root.setAttribute('package', 'prj.chameleon.entry')
     applicationDoc = self.doc.createElement('application')
     root.appendChild(applicationDoc)
    def createXML(self, frame_count):
        implementation = getDOMImplementation()
        document = implementation.createDocument(None, None, None)

        annotation = document.createElement("annotation")
        document.appendChild(annotation)
        folder = document.createElement("folder")
        folder.appendChild(document.createTextNode("JPEGImages"))
        annotation.appendChild(folder)
        filename = document.createElement("filename")
        filename.appendChild(
            document.createTextNode(fileName + "_" + str(frame_count)))
        annotation.appendChild(filename)
        path = document.createElement("path")
        path.appendChild(
            document.createTextNode(
                "C:/AIoT/Projects/keras-yolo3-master/VOCdevkit/VOC2007/JPEGImages/"
                + fileName + "_%d.jpg" % frame_count))
        annotation.appendChild(path)
        source = document.createElement("source")
        annotation.appendChild(source)
        database = document.createElement("database")
        database.appendChild(document.createTextNode("Unknown"))
        source.appendChild(database)
        size = document.createElement("size")
        annotation.appendChild(size)
        width = document.createElement("width")
        width.appendChild(document.createTextNode("1920"))
        size.appendChild(width)
        height = document.createElement("height")
        height.appendChild(document.createTextNode("1080"))
        size.appendChild(height)
        depth = document.createElement("depth")
        depth.appendChild(document.createTextNode("3"))
        size.appendChild(depth)
        segmented = document.createElement("segmented")
        segmented.appendChild(document.createTextNode("0"))
        annotation.appendChild(segmented)

        tup_list = self.dict.get(frame_count)
        for tup in tup_list:
            object = document.createElement("object")
            annotation.appendChild(object)
            name = document.createElement("name")
            name.appendChild(document.createTextNode("person"))
            object.appendChild(name)
            pose = document.createElement("pose")
            pose.appendChild(document.createTextNode("Unspecified"))
            object.appendChild(pose)
            truncated = document.createElement("truncated")
            truncated.appendChild(document.createTextNode("0"))
            object.appendChild(truncated)
            difficult = document.createElement("difficult")
            difficult.appendChild(document.createTextNode("0"))
            object.appendChild(difficult)
            bndbox = document.createElement("bndbox")
            object.appendChild(bndbox)
            xmin = document.createElement("xmin")
            xmin.appendChild(document.createTextNode(tup[3]))
            bndbox.appendChild(xmin)
            ymin = document.createElement("ymin")
            ymin.appendChild(document.createTextNode(tup[2]))
            bndbox.appendChild(ymin)
            xmax = document.createElement("xmax")
            xmax.appendChild(document.createTextNode(tup[1]))
            bndbox.appendChild(xmax)
            ymax = document.createElement("ymax")
            ymax.appendChild(document.createTextNode(tup[0]))
            bndbox.appendChild(ymax)

        out = open(xml_save_path + "/" + fileName + "_%d.xml" % frame_count,
                   "w")
        document.writexml(out, '', '\t', '\n')
        print("Save xml: " + fileName + "_%d.xml" % frame_count)
Beispiel #32
0
    def export_to_xml(self, path, names_to_labels, imagecontainer):
        impl = minidom.getDOMImplementation()
        ann = self._annotations
        for plateid in ann:

            # load plate specific meta data
            imagecontainer.set_plate(plateid)
            meta_data = imagecontainer.get_meta_data()
            time_points = meta_data.times
            # the reference time on which this file is based on
            min_time = time_points[0]

            for position in ann[plateid]:
                ann2 = ann[plateid][position]
                bycn = OrderedDict()
                for time in ann2:
                    for cn in ann2[time]:
                        if not cn in bycn:
                            bycn[cn] = OrderedDict()
                        bycn[cn][time] = ann2[time][cn]

                doc = impl.createDocument(None, 'CellCounter_Marker_File', None)
                top = doc.documentElement
                element = doc.createElement('Marker_Data')
                top.appendChild(element)

                idx_base = time_points.index(min_time)

                for cn in bycn:
                    element2 = doc.createElement('Marker_Type')
                    element.appendChild(element2)
                    element3 = doc.createElement('Type')
                    class_label = names_to_labels[cn]
                    text = doc.createTextNode(str(class_label))
                    element3.appendChild(text)
                    element2.appendChild(element3)
                    for time in bycn[cn]:
                        idx = time_points.index(time) + 1 - idx_base

                        for item in bycn[cn][time]:
                            element3 = doc.createElement('Marker')

                            element4 = doc.createElement('MarkerX')
                            text = doc.createTextNode(str(item[0]))
                            element4.appendChild(text)
                            element3.appendChild(element4)
                            element4 = doc.createElement('MarkerY')
                            text = doc.createTextNode(str(item[1]))
                            element4.appendChild(text)
                            element3.appendChild(element4)
                            element4 = doc.createElement('MarkerZ')
                            text = doc.createTextNode(str(idx))
                            element4.appendChild(text)
                            element3.appendChild(element4)

                            element2.appendChild(element3)

                filename = 'PL%s___P%s___T%05d.xml' % \
                           (plateid, position, min_time)
                f = file(os.path.join(path, filename), 'w')
                doc.writexml(f, indent='  ', addindent='  ', encoding='utf8',
                             newl='\n')
                f.close()
Beispiel #33
0
def convert(stats, epg, epgfile):
    impl = miniDom.getDOMImplementation()
    dcmnt = impl.createDocument(None, u'tv', None)
    root = dcmnt.documentElement
    # create channels
    for stat in stats:
        if stats[0] == "webik":
            continue
        channNode = dcmnt.createElement(u'channel')
        displNode = dcmnt.createElement(u'display-name')
        displText = dcmnt.createTextNode(stat[1])
        displNode.appendChild(displText)
        displNode.setAttribute('lang', 'cs')
        channNode.appendChild(displNode)
        channNode.setAttribute('id', stat[0])
        root.appendChild(channNode)
    # create programms
    for stat in stats:
        if stat[0] == "webik":
            continue
        # load data of one channel to temporary list
        tmpday = []
        for day in epg:
            for item in day[stat[0]]:
                tmpprog = {}
                tmpprog['title'] = item['title']
                tmpprog['description'] = item['description']
                if 'edition' in item and 'asset' in item['edition']:
                    tmpprog['icon'] = item['edition']['asset']
                tmpprog['start'] = item['since']
                tmpprog['stop'] = item['till']
                tmpday.append(tmpprog)
        # check and repair time continuity
        tmpday2 = []
        flag = False
        for i in range(len(tmpday)):
            if flag:
                flag = False
                continue
            if i < len(tmpday) - 2:

#                if tmpday[i]['start'] == tmpday[i + 1]['start']:
#                    flag = True
#                    if tmpday[i]['stop'] > tmpday[i + 1]['stop']:
#                        tmpday2.append(tmpday[i])
#                        continue
#                    elif tmpday[i]['stop'] < tmpday[i + 1]['stop']:
#                        tmpday2.append(tmpday[i + 1])
#                        continue

                if tmpday[i]['start'] <= tmpday[i + 1]['start']:
                    if tmpday[i]['stop'] > tmpday[i + 1]['stop']:
                        flag = True
                        tmpday2.append(tmpday[i])
                        continue
                    if tmpday[i]['stop'] > tmpday[i + 1]['start']:
                        flag = True
                        tmpday2.append(tmpday[i])
                        continue
                elif tmpday[i]['start'] >= tmpday[i + 1]['start']:
                    if tmpday[i]['stop'] < tmpday[i + 1]['stop']:
                        flag = True
                        tmpday2.append(tmpday[i+1])
                        continue
                    if tmpday[i]['start'] < tmpday[i + 1]['stop']:
                        flag = True
                        tmpday2.append(tmpday[i + 1])
                        continue

                if tmpday2 and tmpday[i]['start']>=tmpday2[-1]['start'] and tmpday[i]['stop']<=tmpday2[-1]['stop']:
                    continue
            tmpday2.append(tmpday[i])
        for item in tmpday2:
            prgNode = dcmnt.createElement(u'programme')
            titleNode = dcmnt.createElement(u'title')
            titleText = dcmnt.createTextNode(item['title'])
            titleNode.appendChild(titleText)
            titleNode.setAttribute('lang', 'cs')
            prgNode.appendChild(titleNode)
            descNode = dcmnt.createElement(u'desc')
            descText = dcmnt.createTextNode(item['description'])
            descNode.appendChild(descText)
            descNode.setAttribute('lang', 'cs')
            prgNode.appendChild(descNode)
            if 'icon' in item:
                iconNode = dcmnt.createElement(u'icon')
                iconNode.setAttribute('src', item['icon'])
                prgNode.appendChild(iconNode)
            prgNode.setAttribute('start', convertTime(item['start']))
            prgNode.setAttribute('stop', convertTime(item['stop']))
            prgNode.setAttribute('channel', stat[0])
            root.appendChild(prgNode)
    with codecs_open(epgfile, "w", "utf-8") as out:
        dcmnt.writexml(out, addindent = '    ', newl = '\n', encoding = "utf-8")
        out.close()
    def exportDesignAsXML(self,
                          elementids=None,
                          REQUEST=None,
                          dbsettings=True):
        """
        """
        impl = getDOMImplementation()
        doc = impl.createDocument(None, "plominodatabase", None)
        root = doc.documentElement
        root.setAttribute("id", self.id)

        if REQUEST:
            str_elementids = REQUEST.get("elementids")
            if str_elementids is not None:
                elementids = str_elementids.split("@")

        if elementids is None:
            elements = self.getForms() + self.getViews() + self.getAgents() + [
                o for o in self.resources.getChildNodes()
            ]
        else:
            elements = []
            for id in elementids:
                if id.startswith('resources/'):
                    e = getattr(self.resources, id.split('/')[1])
                else:
                    e = getattr(self, id)
                elements.append(e)

        # Sort elements by type (to store forms before views), then by id
        elements.sort(key=lambda elt: elt.getId())
        elements.sort(key=lambda elt: elt.Type())

        designNode = doc.createElement('design')

        # export database settings
        if dbsettings:
            node = self.exportElementAsXML(doc, self, isDatabase=True)
            designNode.appendChild(node)

        # export database design elements
        for e in elements:
            if e.meta_type in plomino_schemas.keys():
                node = self.exportElementAsXML(doc, e)
            else:
                node = self.exportResourceAsXML(doc, e)

            designNode.appendChild(node)

        root.appendChild(designNode)
        s = doc.toxml()

        if REQUEST:
            REQUEST.RESPONSE.setHeader('content-type',
                                       "text/xml;charset=utf-8")

        # Usage of lxml to make a pretty output
        try:
            from lxml import etree
            parser = etree.XMLParser(strip_cdata=False, encoding="utf-8")
            return etree.tostring(etree.XML(s, parser),
                                  encoding="utf-8",
                                  pretty_print=True)
        except ImportError:
            return s.encode('utf-8').replace("><", ">\n<")
Beispiel #35
0
            idref = bookid+itemref.getAttribute("idref")
            if idref in itemhrefs:
                firstitemhrefs.append(itemhrefs[idref])
                break

        for itemref in itemreflist:
            itemrefs.append(bookid+itemref.getAttribute("idref"))

        booknum=booknum+1;

    printt("after file loop:%s"%(time()-t))
    t = time()

    ## create content.opf file.
    uniqueid="epubmerge-uid-%d" % time() # real sophisticated uid scheme.
    contentdom = getDOMImplementation().createDocument(None, "package", None)
    package = contentdom.documentElement

    package.setAttribute("version","2.0")
    package.setAttribute("xmlns","http://www.idpf.org/2007/opf")
    package.setAttribute("unique-identifier","epubmerge-id")
    metadata=newTag(contentdom,"metadata",
                    attrs={"xmlns:dc":"http://purl.org/dc/elements/1.1/",
                           "xmlns:opf":"http://www.idpf.org/2007/opf"})
    metadata.appendChild(newTag(contentdom,"dc:identifier",text=uniqueid,attrs={"id":"epubmerge-id"}))
    if( titleopt is None ):
        titleopt = booktitles[0]+" Anthology"
    metadata.appendChild(newTag(contentdom,"dc:title",text=titleopt))

    # If cmdline authors, use those instead of those collected from the epubs
    # (allauthors kept for TOC & description gen below.
Beispiel #36
0
    def __init__(self, wixDir, manufacturer, suiteName, appName, architecture,
                 versionType, versionMajor, versionMinor, upgradePolicy,
                 commitBranch, commitDate, commitIndex):

        self.wixDir = wixDir
        self.manufacturer = manufacturer
        self.suiteName = suiteName
        self.appName = appName
        self.architecture = architecture
        self.versionType = versionType
        self.versionMajor = versionMajor
        self.versionMinor = versionMinor
        self.upgradePolicy = upgradePolicy
        self.commitBranch = commitBranch
        self.commitDate = commitDate
        self.commitIndex = commitIndex

        # Check versionType
        allowedVersionTypes = ["stable", "beta", "alpha"]
        if not self.versionType in allowedVersionTypes:
            raise ValueError('Unknown versionType: "' + self.versionType +
                             '".' + ' Allowed values are: "' +
                             '", "'.join(allowedVersionTypes) + '".')

        # Check commit information
        if versionType in ["beta", "alpha"]:
            hasCommitInfo = (self.commitBranch and self.commitDate
                             and self.commitIndex)
            if not hasCommitInfo:
                raise ValueError(
                    'Commit info not found while required to deploy when' +
                    ' versionType = "' + versionType + '.' +
                    ' Please compile from a git repository.')

        # Check upgradePolicy
        allowedUpgradePolicies = {
            "stable": ["all", "minor", "none"],
            "beta": ["minor", "none"],
            "alpha": ["minor", "none"]
        }
        if not self.upgradePolicy in allowedUpgradePolicies[self.versionType]:
            raise ValueError(
                'Unknown upgradePolicy: "' + self.upgradePolicy + '".' +
                ' Allowed values when versionType = "' + self.versionType + '"'
                ' are: ' +
                '", "'.join(allowedUpgradePolicies[self.versionType]) + '".')

        # Check architecture
        allowedArchitectures = ["x86", "x64"]
        if not self.architecture in allowedArchitectures:
            raise ValueError('Unknown architecture: "' + self.versionType +
                             '".' + ' Allowed values are: "' +
                             '", "'.join(allowedArchitectures) + '".')

        # Set appOrSuiteName. Examples:
        # - for suite installers: "VGC"
        # - for app installers: "VGC Illustration", "VGC Animation", etc.
        self.appOrSuiteName = self.suiteName
        if self.appName:
            self.appOrSuiteName += " " + self.appName

        # Set commitDateAndIndex
        # Example: "2019-07-08.1"
        if self.versionType in ["beta", "alpha"]:
            commitDateAndIndex = self.commitDate + "." + self.commitIndex

        # Set branchSuffix
        # Example: "-gh62"
        branchSuffix = ""
        if ((self.versionType == "beta"
             and self.commitBranch != self.versionMajor) or
            (self.versionType == "alpha" and self.commitBranch != "master")):
            branchSuffix = "-" + self.commitBranch

        # Set installVersion and installHumanVersion
        # Example: "19.7.08001" / "2019-07-08.1"
        if self.versionType == "stable":
            major = int(self.versionMajor[2:4])
            minor = int(self.versionMinor)
            self.installVersion = "{}.{}".format(major, minor)
            self.installHumanVersion = "{}.{}".format(self.versionMajor, minor)
        elif self.versionType in ["beta", "alpha"]:
            major = int(self.commitDate[2:4])
            minor = int(self.commitDate[5:7])
            build = int(self.commitDate[8:10]) * 1000 + int(self.commitIndex)
            self.installVersion = "{}.{}.{}".format(major, minor, build)
            self.installHumanVersion = commitDateAndIndex

        # Set installFamilySuffix and fullVersion (except the architecture suffix)
        # Example:
        #   installFamilySuffix = " 2020 Beta"
        #   fullVersion     = "2020 Beta 2019-07-08.1"
        if self.versionType == "stable":
            if self.upgradePolicy == "all": p = ""
            elif self.upgradePolicy == "minor": p = " {}"
            elif self.upgradePolicy == "none": p = " {}.{}"
            self.installFamilySuffix = p.format(self.versionMajor,
                                                self.versionMinor)
            self.fullVersion = self.versionMajor
            if minor > 0:
                self.fullVersion += "." + self.versionMinor
        elif self.versionType == "beta":
            if self.upgradePolicy == "minor": p = " {} Beta{}"
            elif self.upgradePolicy == "none": p = " {} Beta{} {}"
            q = "{} Beta{} {}"
            self.installFamilySuffix = p.format(self.versionMajor,
                                                branchSuffix,
                                                commitDateAndIndex)
            self.fullVersion = q.format(self.versionMajor, branchSuffix,
                                        commitDateAndIndex)
        elif self.versionType == "alpha":
            if self.upgradePolicy == "minor": p = " Alpha{}"
            elif self.upgradePolicy == "none": p = " Alpha{} {}"
            q = "Alpha{} {}"
            self.installFamilySuffix = p.format(branchSuffix,
                                                commitDateAndIndex)
            self.fullVersion = q.format(branchSuffix, commitDateAndIndex)

        # Set architecture and add it as suffix to installFamily and fullVersion
        # Example:
        #   installFamilySuffix = " 2020 Beta 32-bit"
        #   fullVersion     = "2020 Beta 2019-07-08.1 32-bit"
        if self.architecture == "x64":
            self.win64yesno = "yes"
            self.programFilesFolder = "ProgramFiles64Folder"
        elif self.architecture == "x86":
            self.win64yesno = "no"
            self.programFilesFolder = "ProgramFilesFolder"
            self.installFamilySuffix += " 32-bit"
            self.fullVersion += " 32-bit"

        # Set installFamily
        # Example: "VGC 2020 Beta 32-bit"
        self.installFamily = self.suiteName + self.installFamilySuffix

        # Set installerName and msiName
        if self.versionType == "stable" and self.upgradePolicy == "minor":
            installerTypeSuffix = " - Minor Updates Only"
        elif self.upgradePolicy == "none":
            installerTypeSuffix = " - No Updates"
        else:
            installerTypeSuffix = ""
        self.msiName = self.appOrSuiteName + " " + self.fullVersion + installerTypeSuffix
        self.installerName = self.appOrSuiteName + " " + self.fullVersion + " Installer" + installerTypeSuffix

        # Create XML document.
        #
        domImplementation = getDOMImplementation()
        self.domDocument = domImplementation.createDocument(None, "Wix", None)

        # Get Wix root element and set its xmlns attribute.
        #
        self.root = WixElement(self.domDocument.documentElement, self, "")
        self.root.setAttribute("xmlns",
                               "http://schemas.microsoft.com/wix/2006/wi")

        # Add product. Note that we regenerate its ProductCode GUID
        # (= 'Id' attribute) when the version change since we consider all
        # changes of version to be "Major Upgrades" in MSI terminology. We need
        # this since components may be added, moved or removed even when going
        # from VGC 2020.0 to VGC 2020.1. Also, we desire that the name of our
        # MSI file changes in this case, and it is a Microsoft requirement to
        # keep the same MSI filename during a "Minor Upgrade" or "Small Upgrade".
        #
        self.product = self.root.createChild(
            "Product",
            [("Name", self.appOrSuiteName + self.installFamilySuffix),
             ("Id",
              self.dynamicGuid("Product/ProductCode/" + self.appOrSuiteName)),
             ("UpgradeCode",
              self.staticGuid("Product/UpgradeCode/" + self.appOrSuiteName)),
             ("Language", "1033"), ("Codepage", "1252"),
             ("Version", self.installVersion),
             ("Manufacturer", self.manufacturer)])

        # Add package
        #
        # Note: manual specification of "Platform" is discouraged in favour
        # of using the candle.exe -arch x64/x86 switch, but we use both anyway.
        #
        self.package = self.product.createChild(
            "Package",
            [("Id", self.dynamicGuid("Package/Id/" + self.appOrSuiteName)),
             ("Keywords", "Installer"),
             ("Description", "Installer of " + self.msiName),
             ("Manufacturer", self.manufacturer), ("InstallerVersion", "500"),
             ("InstallPrivileges", "elevated"), ("InstallScope", "perMachine"),
             ("Languages", "1033"), ("Compressed", "yes"),
             ("SummaryCodepage", "1252"), ("Platform", self.architecture)])

        # Add media
        self.media = self.product.createChild("Media",
                                              [("Id", "1"),
                                               ("Cabinet", "Cabinet.cab"),
                                               ("EmbedCab", "yes")])

        # See: https://stackoverflow.com/questions/2058230/wix-create-non-advertised-shortcut-for-all-users-per-machine
        self.product.createChild("Property", [("Id", "DISABLEADVTSHORTCUTS"),
                                              ("Value", "1")])

        # Allow major upgrades and prevent downgrades.
        #
        # We use the afterInstallExecute schedule in order not to break user
        # shortcuts in the Desktop or Task Bar, see:
        #     http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Keep-Desktop-Shortcuts-and-Pinned-Task-Bar-Icons-with-Upgrades-td7599707.html
        #     https://stackoverflow.com/questions/32318662/user-pinned-taskbar-shortcuts-and-major-upgrades
        #
        self.majorUpgrades = self.product.createChild(
            "MajorUpgrade",
            [("Schedule", "afterInstallExecute"),
             ("DowngradeErrorMessage",
              "A newer version of [ProductName] is already installed.")])

        # Add basic directory structure.
        self.targetDirectory = self.product.createDirectory(
            "SourceDir", "TARGETDIR")
        self.programFilesDirectory = self.targetDirectory.createDirectory(
            "PFiles", self.programFilesFolder)
        self.installDirectory = self.programFilesDirectory.createDirectory(
            self.installFamily, "INSTALLFOLDER")
        self.startMenuDirectory = self.targetDirectory.createDirectory(
            "Programs", "ProgramMenuFolder")
        self.desktopDirectory = self.targetDirectory.createDirectory(
            "Desktop", "DesktopFolder")
 def _CreateDocumentElement(self):
     dom_impl = minidom.getDOMImplementation('')
     doc = dom_impl.createDocument(None, 'root', None)
     return doc.documentElement
Beispiel #38
0
from xml.parsers import expat
from xml.dom.minidom import _append_child, _set_attribute_node
from xml.dom.NodeFilter import NodeFilter

from xml.dom.minicompat import *

TEXT_NODE = Node.TEXT_NODE
CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE
DOCUMENT_NODE = Node.DOCUMENT_NODE

FILTER_ACCEPT = xmlbuilder.DOMBuilderFilter.FILTER_ACCEPT
FILTER_REJECT = xmlbuilder.DOMBuilderFilter.FILTER_REJECT
FILTER_SKIP = xmlbuilder.DOMBuilderFilter.FILTER_SKIP
FILTER_INTERRUPT = xmlbuilder.DOMBuilderFilter.FILTER_INTERRUPT

theDOMImplementation = minidom.getDOMImplementation()

# Expat typename -> TypeInfo
_typeinfo_map = {
    "CDATA": minidom.TypeInfo(None, "cdata"),
    "ENUM": minidom.TypeInfo(None, "enumeration"),
    "ENTITY": minidom.TypeInfo(None, "entity"),
    "ENTITIES": minidom.TypeInfo(None, "entities"),
    "ID": minidom.TypeInfo(None, "id"),
    "IDREF": minidom.TypeInfo(None, "idref"),
    "IDREFS": minidom.TypeInfo(None, "idrefs"),
    "NMTOKEN": minidom.TypeInfo(None, "nmtoken"),
    "NMTOKENS": minidom.TypeInfo(None, "nmtokens"),
}

Beispiel #39
0
def make_xml():
    impl = getDOMImplementation()
    impl2 = getDOMImplementation()
    #creation du document reponse correction qui sera envoyé a gestionnaire_Correction
    documentCopieReponse = impl2.createDocument(None, "Reponse", None)
    rootNodeReponse = documentCopieReponse.documentElement
    rootNodeReponse.setAttribute("type", "correction")
    idNodeReponse = documentCopieReponse.createElement('Identifiant')
    idQuestionnaire = raw_input('Quelle ID voulez vous mettre a ce questionnaire? ')

    idQuestionnaireText = documentCopieReponse.createTextNode(idQuestionnaire)
    idNodeReponse.appendChild(idQuestionnaireText)
    rootNodeReponse.appendChild(idNodeReponse)

    # creation du document Questionnaire qui sera envoyé a gestionnaire_QCM
    documentQuestionnaire = impl.createDocument(None, "QCM", None)
    rootNodeQuestionnaire = documentQuestionnaire.documentElement
    NodeQuestionnaire = documentQuestionnaire.createElement('Questionnaire')
    NodeQuestionnaire.setAttribute("id", idQuestionnaire)
    NodeQuestionnaire.setAttribute("id_formation",  raw_input('Quelle ID de formation voulez vous mettre pour ce questionnaire? '))
    NodeQuestionnaire.setAttribute("id_matiere", raw_input('Quelle ID de matiere voulez vous mettre pour ce questionnaire? ') )
    rootNodeQuestionnaire.appendChild(NodeQuestionnaire)

    try:
        nbquestion = int(raw_input('Combien de question voulez vous?'))
        while True:
            if nbquestion > 0:
                break
            else:
                nbquestion = int(raw_input('Réponse non approprié, combien de question voulez vous? '))
    except ValueError:
       print "Veuillez choisir un nombre pour le prochain test"
       exit(-1)


    contenuNodeReponse = documentQuestionnaire.createElement("contenu")

    # creation des différentes questions

    # debut de la boucle while de question
    cpt = 0;
    while nbquestion > cpt:
        # creation question pour reponse
        questionNodeReponse = documentQuestionnaire.createElement("Question")
        questionNodeReponse.setAttribute("id", str(cpt))
        # creation question pour questionnaire
        questionNodeQuestionnaire = documentQuestionnaire.createElement("Question")
        questionNodeQuestionnaire.setAttribute("id", str(cpt))
        # enonce pour questionnaire
        newnode3 = documentQuestionnaire.createElement("Enonce")
        text = documentQuestionnaire.createTextNode(raw_input('Entrez une question : '))
        newnode3.appendChild(text)
        questionNodeQuestionnaire.appendChild(newnode3)

        cpt = cpt + 1


        try:
            nbReponse = int(raw_input('Combien de réponse voulez vous ? '))
            while True:
                if nbReponse > 0:
                    break
                else:
                    nbReponse = int(raw_input('Réponse non approprié, combien de réponse voulez vous ? '))
        except ValueError:
            print "Veuillez choisir un nombre pour le prochain test"
            exit(-1)

        cptReponse = 0

        while nbReponse > cptReponse:
            # choix pour les differente reponse
            choixNode = documentQuestionnaire.createElement("choix")
            choixNode.setAttribute("id", str(cptReponse))
            textChoix = documentQuestionnaire.createTextNode(raw_input('Entrez une reponse: '))
            choixNode.appendChild(textChoix)

            cptReponse = cptReponse + 1
            questionNodeQuestionnaire.appendChild(choixNode)

        # demande de bonne reponse et mise en place de la reponse dans le bon endroit
        questionNodeReponse.setAttribute("rep", raw_input('Quelle était l\'ID de la bonne reponse? (La première réponse -> ID = 0, la deuxième réponse -> ID = 1) '))
        contenuNodeReponse.appendChild(questionNodeReponse)
        NodeQuestionnaire.appendChild(questionNodeQuestionnaire)
    rootNodeReponse.appendChild(contenuNodeReponse)
    return documentQuestionnaire.toprettyxml(), documentCopieReponse.toprettyxml()
Beispiel #40
0
    def Init(self):
        dom_impl = minidom.getDOMImplementation('')
        self._doc = dom_impl.createDocument(None, 'html', None)
        body = self.AddElement(self._doc.documentElement, 'body')
        self._main_div = self.AddElement(body, 'div')
        self._indent_level = 0

        # Human-readable names of supported platforms.
        self._PLATFORM_MAP = {
            'win': 'Windows',
            'mac': 'Mac',
            'linux': 'Linux',
            'chrome_os': self.config['os_name'],
            'android': 'Android',
            'ios': 'iOS',
        }
        # Human-readable names of supported products.
        self._PRODUCT_MAP = {
            'chrome': self.config['app_name'],
            'chrome_frame': self.config['frame_name'],
            'chrome_os': self.config['os_name'],
            'webview': self.config['webview_name'],
        }
        # Human-readable names of supported features. Each supported feature has
        # a 'doc_feature_X' entry in |self.messages|.
        self._FEATURE_MAP = {}
        for message in self.messages:
            if message.startswith('doc_feature_'):
                self._FEATURE_MAP[
                    message[12:]] = self.messages[message]['text']
        # Human-readable names of types.
        self._TYPE_MAP = {
            'string': 'String',
            'int': 'Integer',
            'main': 'Boolean',
            'int-enum': 'Integer',
            'string-enum': 'String',
            'list': 'List of strings',
            'string-enum-list': 'List of strings',
            'dict': 'Dictionary',
            'external': 'External data reference',
        }
        self._REG_TYPE_MAP = {
            'string': 'REG_SZ',
            'int': 'REG_DWORD',
            'main': 'REG_DWORD',
            'int-enum': 'REG_DWORD',
            'string-enum': 'REG_SZ',
            'dict': 'REG_SZ',
        }
        self._RESTRICTION_TYPE_MAP = {
            'int-enum': 'choice',
            'string-enum': 'choice',
            'list': 'string',
            'string-enum-list': 'multi-select',
            'dict': 'string',
        }
        # The CSS style-sheet used for the document. It will be used in Google
        # Sites, which strips class attributes from HTML tags. To work around this,
        # the style-sheet is a dictionary and the style attributes will be added
        # "by hand" for each element.
        self._STYLE = {
            'table': 'border-style: none; border-collapse: collapse;',
            'tr': 'height: 0px;',
            'td': 'border: 1px dotted rgb(170, 170, 170); padding: 7px; '
            'vertical-align: top; width: 236px; height: 15px;',
            'thead td': 'font-weight: bold;',
            'td.left': 'width: 200px;',
            'td.right': 'width: 100%;',
            'dt': 'font-weight: bold;',
            'dd dl': 'margin-top: 0px; margin-bottom: 0px;',
            '.monospace': 'font-family: monospace;',
            '.pre': 'white-space: pre;',
            'div.note': 'border: 2px solid black; padding: 5px; margin: 5px;',
            'div.group_desc': 'margin-top: 20px; margin-bottom: 20px;',
            'ul': 'padding-left: 0px; margin-left: 0px;'
        }
Beispiel #41
0
 def newDocument(self):
     """clear DOM"""
     impl = mdom.getDOMImplementation()
     self.doc = impl.createDocument(None, self.rootTag, None)
Beispiel #42
0
import time
import ic_testcase
import datetime
import re
import os
import fileinput
import random
import base64
import tempfile
import shutil

from base64 import b64encode, b64decode, encodestring

import xml.dom.minidom
from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()

from ..utils import getText

my_test_file = "my_test_file.txt"
fw_target_num = 0

RCI_QUERY_SETTING = \
"""<sci_request version="1.0"> 
  <send_message cache="false"> 
    <targets> 
      <device id="%s"/> 
    </targets> 
    <rci_request version="1.1"> 
      <query_setting><system><description/></system></query_setting>
    </rci_request>
Beispiel #43
0
#License as published by the Free Software Foundation; either
#version 2 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Library General Public License for more details.
#
#You should have received a copy of the GNU Library General Public
#License along with this library; if not, write to the Free
#Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
#MA 02111-1307, USA

from propfind import PROPFIND
from xml.dom import minidom
domimpl = minidom.getDOMImplementation()
from utils import get_parenturi


class REPORT(PROPFIND):
    def __init__(self, uri, dataclass, depth, body):
        PROPFIND.__init__(self, uri, dataclass, depth, body)

        doc = minidom.parseString(body)

        self.filter = doc.documentElement

    def create_propname(self):
        """ create a multistatus response for the prop names """

        dc = self._dataclass
    def generate(self):
        if not self.host:
            conn = cups.Connection()
        else:
            if not self.port:
                self.port = 631
            conn = cups.Connection(self.host, self.port)
            
        printers = conn.getPrinters()
        
        for p, v in printers.items():
            if v['printer-is-shared']:
                attrs = conn.getPrinterAttributes(p)
                uri = urlparse.urlparse(v['printer-uri-supported'])

                tree = ElementTree()
                tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', '')))

                name = tree.find('name')
                name.text = 'AirPrint %s @ %%h' % (p)

                service = tree.find('service')

                port = service.find('port')
                port_no = None
                if hasattr(uri, 'port'):
                  port_no = uri.port
                if not port_no:
                    port_no = self.port
                if not port_no:
                    port_no = cups.getPort()
                port.text = '%d' % port_no

                if hasattr(uri, 'path'):
                  rp = uri.path
                else:
                  rp = uri[2]
                
                re_match = re.match(r'^//(.*):(\d+)(/.*)', rp)
                if re_match:
                  rp = re_match.group(3)
                
                #Remove leading slashes from path
                #TODO XXX FIXME I'm worried this will match broken urlparse
                #results as well (for instance if they don't include a port)
                #the xml would be malform'd either way
                rp = re.sub(r'^/+', '', rp)
                
                path = Element('txt-record')
                path.text = 'rp=%s' % (rp)
                service.append(path)

                desc = Element('txt-record')
                desc.text = 'note=%s' % (v['printer-info'])
                service.append(desc)

                product = Element('txt-record')
                product.text = 'product=(GPL Ghostscript)'
                service.append(product)

                state = Element('txt-record')
                state.text = 'printer-state=%s' % (v['printer-state'])
                service.append(state)

                ptype = Element('txt-record')
                ptype.text = 'printer-type=%s' % (hex(v['printer-type']))
                service.append(ptype)

                pdl = Element('txt-record')
                fmts = []
                defer = []

                for a in attrs['document-format-supported']:
                    if a in DOCUMENT_TYPES:
                        if DOCUMENT_TYPES[a]:
                            fmts.append(a)
                    else:
                        defer.append(a)

                fmts = ','.join(fmts+defer)

                dropped = []

                # TODO XXX FIXME all fields should be checked for 255 limit
                while len('pdl=%s' % (fmts)) >= 255:
                    (fmts, drop) = fmts.rsplit(',', 1)
                    dropped.append(drop)

                if len(dropped) and self.verbose:
                    sys.stderr.write('%s Losing support for: %s%s' % (p, ','.join(dropped), os.linesep))

                pdl.text = 'pdl=%s' % (fmts)
                service.append(pdl)

                if self.adminurl:
                    admin = Element('txt-record')
                    admin.text = 'adminurl=%s' % (v['printer-uri-supported'])
                    service.append(admin)
                
                fname = '%s%s.service' % (self.prefix, p)
                
                if self.directory:
                    fname = os.path.join(self.directory, fname)
                
                f = open(fname, 'w')

                if etree:
                    tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8")
                else:
                    xmlstr = tostring(tree.getroot())
                    doc = parseString(xmlstr)
                    dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd')
                    doc.insertBefore(dt, doc.documentElement)
                    doc.writexml(f)
                f.close()
                
                if self.verbose:
                    sys.stderr.write('Created: %s%s' % (fname, os.linesep))
Beispiel #45
0
def doMerge(outputio,
            files,
            authoropts=[],
            titleopt=None,
            descopt=None,
            tags=[],
            languages=['en'],
            titlenavpoints=True,
            flattentoc=False,
            printtimes=False,
            coverjpgpath=None,
            keepmetadatafiles=False,
            source=None):
    '''
    outputio = output file name or StringIO.
    files = list of input file names or StringIOs.
    authoropts = list of authors to use, otherwise add from all input
    titleopt = title, otherwise '<first title> Anthology'
    descopt = description, otherwise '<title> by <author>' list for all input
    tags = dc:subject tags to include, otherwise none.
    languages = dc:language tags to include
    titlenavpoints if true, put in a new TOC entry for each epub, nesting each epub's chapters under it
    flattentoc if true, flatten TOC down to one level only.
    coverjpgpath, Path to a jpg to use as cover image.
    '''

    printt = partial(cond_print,printtimes)

    ## Python 2.5 ZipFile is rather more primative than later
    ## versions.  It can operate on a file, or on a StringIO, but
    ## not on an open stream.  OTOH, I suspect we would have had
    ## problems with closing and opening again to change the
    ## compression type anyway.

    filecount=0
    t = time()

    ## Write mimetype file, must be first and uncompressed.
    ## Older versions of python(2.4/5) don't allow you to specify
    ## compression by individual file.
    ## Overwrite if existing output file.
    outputepub = ZipFile(outputio, "w", compression=ZIP_STORED)
    outputepub.debug = 3
    outputepub.writestr("mimetype", "application/epub+zip")
    outputepub.close()

    ## Re-open file for content.
    outputepub = ZipFile(outputio, "a", compression=ZIP_DEFLATED)
    outputepub.debug = 3

    ## Create META-INF/container.xml file.  The only thing it does is
    ## point to content.opf
    containerdom = getDOMImplementation().createDocument(None, "container", None)
    containertop = containerdom.documentElement
    containertop.setAttribute("version","1.0")
    containertop.setAttribute("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")
    rootfiles = containerdom.createElement("rootfiles")
    containertop.appendChild(rootfiles)
    rootfiles.appendChild(newTag(containerdom,"rootfile",{"full-path":"content.opf",
                                                          "media-type":"application/oebps-package+xml"}))
    outputepub.writestr("META-INF/container.xml",containerdom.toprettyxml(indent='   ',encoding='utf-8'))

    ## Process input epubs.

    items = [] # list of (id, href, type) tuples(all strings) -- From .opfs' manifests
    items.append(("ncx","toc.ncx","application/x-dtbncx+xml")) ## we'll generate the toc.ncx file,
                                                               ## but it needs to be in the items manifest.
    itemrefs = [] # list of strings -- idrefs from .opfs' spines
    navmaps = [] # list of navMap DOM elements -- TOC data for each from toc.ncx files
    is_ffdl_epub = [] # list of t/f

    itemhrefs = {} # hash of item[id]s to itemref[href]s -- to find true start of book(s).
    firstitemhrefs = []

    booktitles = [] # list of strings -- Each book's title
    allauthors = [] # list of lists of strings -- Each book's list of authors.

    filelist = []

    printt("prep output:%s"%(time()-t))
    t = time()

    booknum=1
    firstmetadom = None
    for file in files:
        if file == None : continue

        book = "%d" % booknum
        bookdir = "%d/" % booknum
        bookid = "a%d" % booknum

        epub = ZipFile(file, 'r')

        ## Find the .opf file.
        container = epub.read("META-INF/container.xml")
        containerdom = parseString(container)
        rootfilenodelist = containerdom.getElementsByTagNameNS("*","rootfile")
        rootfilename = rootfilenodelist[0].getAttribute("full-path")

        ## Save the path to the .opf file--hrefs inside it are relative to it.
        relpath = get_path_part(rootfilename)

        metadom = parseString(epub.read(rootfilename))
        #logger.debug("metadom:%s"%epub.read(rootfilename))
        if booknum==1 and not source:
            try:
                firstmetadom = metadom.getElementsByTagNameNS("*","metadata")[0]
                source=firstmetadom.getElementsByTagName("dc:source")[0].firstChild.data.encode("utf-8")
            except:
                source=""

        # if the epub was ever edited with Sigil, it changed the unique-identifier,
        # but dc:contributor was left.
        #is_ffdl_epub.append(metadom.documentElement.getAttribute('unique-identifier') == "fanficdownloader-uid")
        is_ffdl_epub.append(False)

        for c in metadom.getElementsByTagName("dc:contributor"):
            # logger.debug("dc:contributor:%s"%getText(c.childNodes))
            if c.getAttribute("opf:role") == "bkp" and \
                    getText(c.childNodes) in ["fanficdownloader [http://fanficdownloader.googlecode.com]",
                                              "FanFicFare [https://github.com/JimmXinu/FanFicFare]"]:
                is_ffdl_epub[-1] = True # set last.
                break;

        ## Save indiv book title
        try:
            booktitles.append(metadom.getElementsByTagName("dc:title")[0].firstChild.data)
        except:
            booktitles.append("(Title Missing)")

        ## Save authors.
        authors=[]
        for creator in metadom.getElementsByTagName("dc:creator"):
            try:
                if( creator.getAttribute("opf:role") == "aut" or not creator.hasAttribute("opf:role") and creator.firstChild != None):
                    authors.append(creator.firstChild.data)
            except:
                pass
        if len(authors) == 0:
            authors.append("(Author Missing)")
        allauthors.append(authors)

        if keepmetadatafiles:
            itemid=bookid+"rootfile"
            itemhref = rootfilename
            href=bookdir+itemhref
            #logger.debug("write rootfile %s to %s"%(itemhref,href))
            outputepub.writestr(href,
                                epub.read(itemhref))
            items.append((itemid,href,"origrootfile/xml"))

        # spin through the manifest--only place there are item tags.
        # Correction--only place there *should* be item tags.  But
        # somebody found one that did.
        manifesttag=metadom.getElementsByTagNameNS("*","manifest")[0]
        for item in manifesttag.getElementsByTagNameNS("*","item"):
            itemid=bookid+item.getAttribute("id")
            itemhref = unquote(item.getAttribute("href")) # remove %20, etc.
            href=bookdir+relpath+itemhref
            if( item.getAttribute("media-type") == "application/x-dtbncx+xml" ):
                # TOC file is only one with this type--as far as I know.
                # grab the whole navmap, deal with it later.
                tocdom = parseString(epub.read(relpath+item.getAttribute("href")))

                # update all navpoint ids with bookid for uniqueness.
                for navpoint in tocdom.getElementsByTagNameNS("*","navPoint"):
                    navpoint.setAttribute("id",bookid+navpoint.getAttribute("id"))

                # update all content paths with bookdir for uniqueness.
                for content in tocdom.getElementsByTagNameNS("*","content"):
                    content.setAttribute("src",bookdir+relpath+content.getAttribute("src"))

                navmaps.append(tocdom.getElementsByTagNameNS("*","navMap")[0])

                if keepmetadatafiles:
                    #logger.debug("write toc.ncx %s to %s"%(relpath+itemhref,href))
                    outputepub.writestr(href,
                                        epub.read(relpath+itemhref))
                    items.append((itemid,href,"origtocncx/xml"))
            else:
                href=href.encode('utf8')
                #logger.debug("item id: %s -> %s:"%(itemid,href))
                itemhrefs[itemid] = href
                if href not in filelist:
                    try:
                        outputepub.writestr(href,
                                            epub.read(relpath+itemhref))
                        if re.match(r'.*/(file|chapter)\d+\.x?html',href):
                            filecount+=1
                        items.append((itemid,href,item.getAttribute("media-type")))
                        filelist.append(href)
                    except KeyError, ke: # Skip missing files.
                        logger.info("Skipping missing file %s (%s)"%(href,relpath+itemhref))
                        del itemhrefs[itemid]

        itemreflist = metadom.getElementsByTagNameNS("*","itemref")
        # logger.debug("itemreflist:%s"%itemreflist)
        # logger.debug("itemhrefs:%s"%itemhrefs)
        # logger.debug("bookid:%s"%bookid)
        # logger.debug("itemreflist[0].getAttribute(idref):%s"%itemreflist[0].getAttribute("idref"))

        # Looking for the first item in itemreflist that wasn't
        # discarded due to missing files.
        for itemref in itemreflist:
            idref = bookid+itemref.getAttribute("idref")
            if idref in itemhrefs:
                firstitemhrefs.append(itemhrefs[idref])
                break

        for itemref in itemreflist:
            itemrefs.append(bookid+itemref.getAttribute("idref"))

        booknum=booknum+1;
Beispiel #46
0
 def Init(self):
     impl = minidom.getDOMImplementation()
     self._doc = impl.createDocument(None, 'resources', None)
     self._resources = self._doc.documentElement
Beispiel #47
0
 def __init__(self):
     HTMLParser.__init__(self)
     self.__impl = getDOMImplementation()
     self.__document = self.__impl.createDocument(None, None, None)
     self.__elements = []
Beispiel #48
0
def newDocument(tag):
    impl = minidom.getDOMImplementation()
    dom = impl.createDocument(None, tag, None)
    return dom.documentElement
Beispiel #49
0
 def __init__(self, showSkipped=True):
     self._doc = getDOMImplementation().createDocument(
         None, 'testsuite', None)
     self._show_skipped = showSkipped
Beispiel #50
0
def write_sample_feed(buildenv, master_feed, src_impl):
	path = buildenv.local_iface_file

	old_path = os.path.join(buildenv.metadir, buildenv.iface_name + '.xml')
	if os.path.exists(old_path):
		warn("Removing old %s file: use %s instead now", old_path, path)
		os.unlink(old_path)

	impl = minidom.getDOMImplementation()

	XMLNS_IFACE = namespaces.XMLNS_IFACE

	doc = impl.createDocument(XMLNS_IFACE, "interface", None)

	root = doc.documentElement
	root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', XMLNS_IFACE)
	prefixes = Prefixes(XMLNS_IFACE)

	def addSimple(parent, name, text = None):
		elem = doc.createElementNS(XMLNS_IFACE, name)

		parent.appendChild(doc.createTextNode('\n' + '  ' * (1 + depth(parent))))
		parent.appendChild(elem)
		if text:
			elem.appendChild(doc.createTextNode(text))
		return elem

	def close(element):
		element.appendChild(doc.createTextNode('\n' + '  ' * depth(element)))

	addSimple(root, 'name', master_feed.name)
	addSimple(root, 'summary', master_feed.summary)
	addSimple(root, 'description', master_feed.description)
	feed_for = addSimple(root, 'feed-for')

	feed_for.setAttributeNS(None, 'interface', find_feed_for(master_feed))

	group = addSimple(root, 'group')
	main = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-main', None)
	if main:
		group.setAttributeNS(None, 'main', main)

	lib_mappings = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-lib-mappings', None)
	if lib_mappings:
		prefixes.setAttributeNS(group, XMLNS_0COMPILE, 'lib-mappings', lib_mappings)
	
	for d in src_impl.dependencies:
		if parse_bool(d.metadata.get(XMLNS_0COMPILE + ' include-binary', 'false')):
			requires = d.qdom.toDOM(doc, prefixes)
			requires.removeAttributeNS(XMLNS_0COMPILE, 'include-binary')
			group.appendChild(requires)
	set_arch = True

	impl_elem = addSimple(group, 'implementation')
	impl_template = buildenv.get_binary_template()
	if impl_template:
		arm_if_0install_attrs(impl_template)

		# Copy attributes from template
		for fullname, value in impl_template.attrs.items():
			if fullname == 'arch':
				set_arch = False
				if value == '*-*':
					continue
			if ' ' in fullname:
				ns, localName = fullname.split(' ', 1)
			else:
				ns, localName = None, fullname
			prefixes.setAttributeNS(impl_elem, ns, localName, value)
		# Copy child nodes
		for child in impl_template.childNodes:
			impl_elem.appendChild(child.toDOM(doc, prefixes))
		if impl_template.content:
			impl_elem.appendChild(doc.createTextNode(impl_template.content))

		for version_elem in itertools.chain(
			impl_elem.getElementsByTagName('version'),
		):
			pin_components = version_elem.getAttributeNS(XMLNS_0COMPILE, "pin-components")
			if pin_components:
				pin_components = int(pin_components)
				iface = version_elem.parentNode.getAttribute("interface")
				assert iface
				dep_impl = buildenv.chosen_impl(iface)
				impl_version = model.parse_version(dep_impl.attrs.get('version'))

				pinned_components = [impl_version[0][:pin_components]]
                                # (for -pre versions)
				min_version = min(pinned_components, impl_version)

				# clone and increment
				max_version = [pinned_components[0][:]]
				max_version[0][-1] += 1

				version_elem.setAttribute("not-before", model.format_version(min_version))
				version_elem.setAttribute("before", model.format_version(max_version))

	if set_arch:
		group.setAttributeNS(None, 'arch', buildenv.target_arch)

	impl_elem.setAttributeNS(None, 'version', src_impl.version)

	if not impl_elem.hasAttribute('license'):
		license = src_impl.attrs.get('license')
		if license:
			impl_elem.setAttributeNS(None, 'license', license)

	version_modifier = buildenv.version_modifier
	if version_modifier:
		impl_elem.setAttributeNS(None, 'version-modifier', version_modifier)

	impl_elem.setAttributeNS(None, 'id', '..')
	impl_elem.setAttributeNS(None, 'released', time.strftime('%Y-%m-%d'))
	close(group)
	close(root)

	for ns, prefix in list(prefixes.prefixes.items()):
		root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:' + prefix, ns)

	stream = codecs.open(path, 'w', encoding = 'utf-8')
	try:
		doc.writexml(stream)
	finally:
		stream.close()
Beispiel #51
0
 def make_classpath():
     impl = minidom.getDOMImplementation()
     return impl.createDocument(None, 'classpath', None)
Beispiel #52
0
def create_doc_without_doctype(doctype=None):
    return getDOMImplementation().createDocument(None, "doc", doctype)
Beispiel #53
0
 def CreatePlistDocument(self):
     dom_impl = minidom.getDOMImplementation('')
     doctype = dom_impl.createDocumentType(
         'plist', '-//Apple//DTD PLIST 1.0//EN',
         'http://www.apple.com/DTDs/PropertyList-1.0.dtd')
     return dom_impl.createDocument(None, 'plist', doctype)
Beispiel #54
0
 def to_dom(self, serializer=Serializer()):
     dom = minidom.getDOMImplementation()
     document = dom.createDocument(None, self.__tag, None)
     self._append_to_dom_element(document.documentElement, dom, document,
                                 serializer)
     return document
Beispiel #55
0
from requests import post
import xpath
from random import randrange
from time import sleep
from string import Template
from nose.tools import *
from xml.dom.minidom import parseString, getDOMImplementation
import ic_testcase
import logging

dom = getDOMImplementation()

from ic_plugin import ICPlugin

log = logging.getLogger('ic_testcase')
log.setLevel(logging.INFO)
if len(log.handlers) == 0:
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)

logging.getLogger('requests').setLevel(logging.WARNING)

##################################################################
# Elements and Groups to ignore (to not ruin device config)
##################################################################
EXCLUDE_GROUP = []
EXCLUDE_ELEMENT = []
Beispiel #56
0
    def to_xml(self, package):
        """
        create XML document for the package
        """

        imp = minidom.getDOMImplementation('')
        # Create document type
        dt = imp.createDocumentType('package', '', '')
        dt.internalSubset = self.doctype()

        # Create XML document with this document type
        doc = imp.createDocument('', 'package', dt)

        docr = doc.documentElement
        pid = doc.createAttribute('id')
        pid.value = package.id
        docr.setAttributeNode(pid)

        name = doc.createElement('name')
        name.appendChild(doc.createTextNode(package.label))
        docr.appendChild(name)

        version = doc.createElement('version')
        numeric = doc.createElement('numeric')
        numeric.appendChild(doc.createTextNode(str(package.version)))
        label = doc.createElement('label')
        label.appendChild(doc.createTextNode(str(package.version)))
        version.appendChild(numeric)
        version.appendChild(label)
        docr.appendChild(version)

        description = doc.createElement('description')
        description.appendChild(doc.createTextNode(package.description))
        docr.appendChild(description)

        licenses = doc.createElement('licenses')
        licenses.appendChild(doc.createTextNode(package.licenses))
        docr.appendChild(licenses)

        commands = doc.createElement('commands')
        reboot = doc.createAttribute('reboot')
        reboot.value = str(package.reboot)
        commands.setAttributeNode(reboot)

        precommand = doc.createElement('preCommand')
        precommandname = doc.createAttribute('name')
        precommandname.value = package.precmd.name
        precommand.setAttributeNode(precommandname)
        precommand.appendChild(doc.createTextNode(package.precmd.command))

        installinit = doc.createElement('installInit')
        installinitname = doc.createAttribute('name')
        installinitname.value = package.initcmd.name
        installinit.setAttributeNode(installinitname)
        installinit.appendChild(doc.createTextNode(package.initcmd.command))

        command = doc.createElement('command')
        commandname = doc.createAttribute('name')
        commandname.value = package.cmd.name
        command.setAttributeNode(commandname)
        command.appendChild(doc.createTextNode(package.cmd.command))

        postsuccess = doc.createElement('postCommandSuccess')
        postsuccessname = doc.createAttribute('name')
        postsuccessname.value = package.postcmd_ok.name
        postsuccess.setAttributeNode(postsuccessname)
        postsuccess.appendChild(doc.createTextNode(package.postcmd_ok.command))

        postfailure = doc.createElement('postCommandFailure')
        postfailurename = doc.createAttribute('name')
        postfailurename.value = package.postcmd_ko.name
        postfailure.setAttributeNode(postfailurename)
        postfailure.appendChild(doc.createTextNode(package.postcmd_ko.command))

        commands.appendChild(precommand)
        commands.appendChild(installinit)
        commands.appendChild(command)
        commands.appendChild(postsuccess)
        commands.appendChild(postfailure)

        docr.appendChild(commands)

        associateinventory = doc.createElement('associateinventory')
        appenchild = doc.createTextNode(str(package.associateinventory))
        associateinventory.appendChild(appenchild)
        docr.appendChild(associateinventory)

        query = doc.createElement('query')
        Qvendor = doc.createElement('Qvendor')
        Qvendor.appendChild(doc.createTextNode(package.Qvendor))
        query.appendChild(Qvendor)
        Qsoftware = doc.createElement('Qsoftware')
        Qsoftware.appendChild(doc.createTextNode(package.Qsoftware))
        query.appendChild(Qsoftware)
        Qversion = doc.createElement('Qversion')
        Qversion.appendChild(doc.createTextNode(package.Qversion))
        query.appendChild(Qversion)
        boolcnd = doc.createElement('boolcnd')
        boolcnd.appendChild(doc.createTextNode(package.boolcnd))
        query.appendChild(boolcnd)

        docr.appendChild(query)

        return doc.toprettyxml(encoding='utf-8')
Beispiel #57
0
  def test_upgradeSite(self):
    templates_tool = self.dummy_template_tool
    repository = "dummy_repository"

    # setup dummy repository to make unit test independant from any real
    # repository. This function creates the bt5list XML of the repository and
    # the minimum BT files.
    def createBtAndAddToRepository(repository, xml, **kw):
      bt_dir = "%s/%s/bt" % (repository, kw['title'])
      if not os.path.exists(bt_dir):
        os.makedirs(bt_dir)
      with open("%s/title" % bt_dir, "wb") as f:
        f.write(kw['title'])
      template = xml.createElement('template')
      template.setAttribute('id', kw['title'])
      defaults = {
        'copyright': "Copyright Test Template Tool",
        'license': "GPL",
        'title': kw['title'], # title is mandatory
        'version': "1.0",
        'revision': "1"
      }
      for el in ['copyright', 'version', 'revision', 'license', 'title']:
        node = xml.createElement(el)
        node.appendChild(xml.createTextNode(kw.get(el, defaults[el])))
        template.appendChild(node)
      for dep in kw.get('dependency_list', []):
        node = xml.createElement('dependency')
        node.appendChild(xml.createTextNode(dep))
        template.appendChild(node)
      xml.documentElement.appendChild(template)

    def copyTestCoreBt(bt_name):
      bt_path = "%s/%s" % (repository, bt_name)
      available_bt, = self.portal.portal_templates.getRepositoryBusinessTemplateList(
                        template_list=('test_core',)
                      )
      test_core_path = available_bt.repository + "/test_core"
      if os.path.exists(bt_path):
        shutil.rmtree(bt_path)
      shutil.copytree(test_core_path, bt_path)

    # bt4 and bt5 are copies of test_core
    copyTestCoreBt("bt4")
    copyTestCoreBt("bt5")
    # create bt1..5 BT inside dummy_repository
    repo_xml = getDOMImplementation().createDocument(None, "repository", None)
    createBtAndAddToRepository(repository, repo_xml, title='bt1', dependency_list=('bt4',)),
    createBtAndAddToRepository(repository, repo_xml, title='bt2'),
    createBtAndAddToRepository(repository, repo_xml, title='bt3'),
    createBtAndAddToRepository(repository, repo_xml, title='bt4'),
    createBtAndAddToRepository(repository, repo_xml, title='bt5'),
    with open("%s/bt5list" % repository,"wb") as repo_xml_fd:
      repo_xml.writexml(repo_xml_fd)
      repo_xml_fd.close()

    # Install dummy_repository
    templates_tool.repository_dict[repository] = None
    templates_tool.updateRepositoryBusinessTemplateList([repository])

    def getInstalledBtList():
      return sorted([bt.getTitle() for bt in templates_tool.getInstalledBusinessTemplateList()])

    # Install manually 2 BT
    templates_tool.updateBusinessTemplateFromUrl("%s/bt2" % repository)
    self.assertEqual(getInstalledBtList(), ['bt2'])
    templates_tool.updateBusinessTemplateFromUrl("%s/bt3" % repository)
    self.assertEqual(getInstalledBtList(), ['bt2', 'bt3'])

    # First upgrade
    templates_tool.upgradeSite(bt5_list=['bt1'], keep_bt5_id_set=['bt2'], delete_orphaned=True)
    self.assertEqual(getInstalledBtList(), ['bt1', 'bt2', 'bt4'])
    # test_file has been installed with bt4
    erp5_test = self.portal.portal_skins['erp5_test']
    self.assertTrue(erp5_test.hasObject('test_file'))

    # Second upgrade
    templates_tool.upgradeSite(bt5_list=['bt5'], keep_bt5_id_set=['bt2'], delete_orphaned=True)
    self.assertEqual(getInstalledBtList(), ['bt2', 'bt5'])
    # test_file is now installed with bt5
    erp5_test = self.portal.portal_skins['erp5_test']
    self.assertTrue(erp5_test.hasObject('test_file'))
Beispiel #58
0
    def execute(my):

        node_names = []

        # find out which nodes are of interest
        if my.mode == "select":
            top_nodes = my.app.get_selected_top_nodes()
        else:
            top_nodes = my.app.get_top_nodes()

        # go through each top level node
        for top_node in top_nodes:
            if top_node in ['persp', 'top', 'front', 'side']:
                continue
            node_names.append(top_node)

        set_names = my.app.get_sets()
        node_names.extend(set_names)

        # sort the node_names
        node_names.sort()

        user = my.info.get_user()

        # get the pid of this process
        pid = os.getpid()

        # create an xml document
        xml_impl = getDOMImplementation()
        doc = xml_impl.createDocument(None, "session", None)
        root = doc.documentElement

        # get the name of the file
        file_path = my.app.get_file_path()
        file_node = doc.createElement("file")
        file_node.setAttribute("name", os.path.basename(file_path))
        file_node.setAttribute("dir", os.path.dirname(file_path))
        root.appendChild(file_node)

        project_node = doc.createElement("project")
        project_node.setAttribute("dir", my.app.get_project())
        root.appendChild(project_node)

        # max it drill down is 4 levels to discover tactic node
        my.process_nodes(doc, node_names, level=4)

        # add namespace info
        if my.app.name == "maya":

            cur_namespace = my.app.get_namespace_info('-cur')
            xml_node = doc.createElement("namespace")
            xml_node.setAttribute("name", cur_namespace)
            xml_node.setAttribute("current", "true")
            root.appendChild(xml_node)

            namespaces = my.app.get_namespace_info()
            if namespaces:
                for namespace in namespaces:
                    xml_node = doc.createElement("namespace")
                    xml_node.setAttribute("name", namespace)

                    root.appendChild(xml_node)

        # dump out the xml
        xml = doc.toprettyxml()

        # inform the server of the information of this session
        server = my.info.get_xmlrpc_server()
        ticket = my.info.get_ticket()
        project_code = my.info.get_project_code()
        server.update_session(ticket, project_code, user, pid, xml)
Beispiel #59
0
def doUnMerge(inputio,outdir=None):
    epub = ZipFile(inputio, 'r') # works equally well with inputio as a path or a blob
    outputios = []

    ## Find the .opf file.
    container = epub.read("META-INF/container.xml")
    containerdom = parseString(container)
    rootfilenodelist = containerdom.getElementsByTagName("rootfile")
    rootfilename = rootfilenodelist[0].getAttribute("full-path")

    contentdom = parseString(epub.read(rootfilename))

    ## Save the path to the .opf file--hrefs inside it are relative to it.
    relpath = get_path_part(rootfilename)
    #logger.debug("relpath:%s"%relpath)

    # spin through the manifest--only place there are item tags.
    # Correction--only place there *should* be item tags.  But
    # somebody found one that did.
    manifesttag=contentdom.getElementsByTagNameNS("*","manifest")[0]
    for item in manifesttag.getElementsByTagNameNS("*","item"):
        # look for our fake media-type for original rootfiles.
        if( item.getAttribute("media-type") == "origrootfile/xml" ):
            # found one, assume the dir containing it is a complete
            # original epub, do initial setup of epub.
            itemhref = relpath+unquote(item.getAttribute("href"))
            #logger.debug("Found origrootfile:%s"%itemhref)
            curepubpath = re.sub(r'([^\d/]+/)+$','',get_path_part(itemhref))
            savehref = itemhref[len(curepubpath):]
            #logger.debug("curepubpath:%s"%curepubpath)

            outputio = StringIO()
            outputepub = ZipFile(outputio, "w", compression=ZIP_STORED)
            outputepub.debug = 3
            outputepub.writestr("mimetype", "application/epub+zip")
            outputepub.close()

            ## Re-open file for content.
            outputepub = ZipFile(outputio, "a", compression=ZIP_DEFLATED)
            outputepub.debug = 3
            ## Create META-INF/container.xml file.  The only thing it does is
            ## point to content.opf
            containerdom = getDOMImplementation().createDocument(None, "container", None)
            containertop = containerdom.documentElement
            containertop.setAttribute("version","1.0")
            containertop.setAttribute("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")
            rootfiles = containerdom.createElement("rootfiles")
            containertop.appendChild(rootfiles)
            rootfiles.appendChild(newTag(containerdom,"rootfile",{"full-path":savehref,
                                                                  "media-type":"application/oebps-package+xml"}))
            outputepub.writestr("META-INF/container.xml",containerdom.toprettyxml(indent='   ',encoding='utf-8'))

            outputepub.writestr(savehref,epub.read(itemhref))

            for item2 in contentdom.getElementsByTagName("item"):
                item2href = relpath+unquote(item2.getAttribute("href"))
                if item2href.startswith(curepubpath) and item2href != itemhref:
                    save2href = item2href[len(curepubpath):]
                    #logger.debug("Found %s -> %s"%(item2href,save2href))
                    outputepub.writestr(save2href,epub.read(item2href))

            # declares all the files created by Windows.  otherwise, when
            # it runs in appengine, windows unzips the files as 000 perms.
            for zf in outputepub.filelist:
                zf.create_system = 0
            outputepub.close()

            outputios.append(outputio)

    if outdir:
        outfilenames=[]
        for count,epubIO in enumerate(outputios):
            filename="%s/%d.epub"%(outdir,count)
            logger.debug("write %s"%filename)
            outstream = open(filename,"wb")
            outstream.write(epubIO.getvalue())
            outstream.close()
            outfilenames.append(filename)
        return outfilenames
    else:
        return outputios
    def testStringEncodings(self):
        enum_policy_a = {
            'name': 'SampleEnumPolicy.A',
            'type': 'string-enum',
            'items': [{
                'name': 'tls1.2',
                'value': 'tls1.2'
            }]
        }
        enum_policy_b = {
            'name': 'SampleEnumPolicy.B',
            'type': 'string-enum',
            'items': [{
                'name': 'tls1.2',
                'value': 'tls1.2'
            }]
        }

        dom_impl = minidom.getDOMImplementation('')
        self.writer._doc = dom_impl.createDocument(None, 'policyDefinitions',
                                                   None)
        self.writer._active_policies_elem = self.writer._doc.documentElement
        self.writer._active_mandatory_policy_group_name = 'PolicyGroup'
        self.writer.WritePolicy(enum_policy_a)
        self.writer.WritePolicy(enum_policy_b)
        output = self.writer.GetTemplateText()
        expected_output = (
            '<?xml version="1.0" ?>\n'
            '<policyDefinitions>\n'
            '  <policy class="TestClass" displayName="$(string.SampleEnumPolicy_A)"'
            ' explainText="$(string.SampleEnumPolicy_A_Explain)"'
            ' key="Software\\Policies\\Test" name="SampleEnumPolicy.A"'
            ' presentation="$(presentation.SampleEnumPolicy.A)">\n'
            '    <parentCategory ref="PolicyGroup"/>\n'
            '    <supportedOn ref="SUPPORTED_TESTOS"/>\n'
            '    <elements>\n'
            '      <enum id="SampleEnumPolicy.A" valueName="SampleEnumPolicy.A">\n'
            '        <item displayName="$(string.tls1_2)">\n'
            '          <value>\n'
            '            <string>tls1.2</string>\n'
            '          </value>\n'
            '        </item>\n'
            '      </enum>\n'
            '    </elements>\n'
            '  </policy>\n'
            '  <policy class="TestClass" displayName="$(string.SampleEnumPolicy_B)"'
            ' explainText="$(string.SampleEnumPolicy_B_Explain)"'
            ' key="Software\\Policies\\Test" name="SampleEnumPolicy.B"'
            ' presentation="$(presentation.SampleEnumPolicy.B)">\n'
            '    <parentCategory ref="PolicyGroup"/>\n'
            '    <supportedOn ref="SUPPORTED_TESTOS"/>\n'
            '    <elements>\n'
            '      <enum id="SampleEnumPolicy.B" valueName="SampleEnumPolicy.B">\n'
            '        <item displayName="$(string.tls1_2)">\n'
            '          <value>\n'
            '            <string>tls1.2</string>\n'
            '          </value>\n'
            '        </item>\n'
            '      </enum>\n'
            '    </elements>\n'
            '  </policy>\n'
            '</policyDefinitions>')
        self.AssertXMLEquals(output, expected_output)