Example #1
0
def _xml_parse(required_headers, payload):
    try:
        doc = Document()
        lcia = doc.createElement("lcia")
        doc.appendChild(lcia)

        headers = doc.createElement("headers")
        lcia.appendChild(headers)

        for x in required_headers:
            node = doc.createElement(x)
            info = doc.createTextNode(str(payload["header"][x]))
            node.appendChild(info)
            headers.appendChild(node)

        data = doc.createElement("data")
        lcia.appendChild(data)

        for x in payload["data"]:
            node = doc.createElement(x)
            info = doc.createTextNode(str(payload["data"][x]))
            node.appendChild(info)
            data.appendChild(node)

        xml_string = doc.toprettyxml(indent="  ")
        return xml_string
    except KeyError:
        raise KeyError("Missing Header")
Example #2
0
    def storeToFile(self, suffix=""):
        if not self.dataToStore:
            return

        doc = Document()
        results = doc.createElement("results")
        doc.appendChild(results)
        for a in self.dataToStore:
            item = doc.createElement("item")
            for k, d in a.items():
                tag = doc.createElement(k)
                if k == "author":
                    tag2 = doc.createElement("name")
                    data = doc.createTextNode(d)
                    tag2.appendChild(data)
                    tag.appendChild(tag2)
                else:
                    data = doc.createTextNode(" ".join(d.split()))
                    tag.appendChild(data)
                item.appendChild(tag)
            results.appendChild(item)

        timestamp = time.strftime("%H%M%S_")
        f = open("output/" + timestamp + self.board + "_" + self.section + "_" + str(suffix) + ".xml", "w")
        f.write(doc.toprettyxml(indent="    ", encoding="utf-8"))
        f.close()
        self.dataToStore = []
Example #3
0
    def end_copy(self):

        try:
            self.user.put_object(self.dst_file, self.dstBucketName, self.dstObjectName)
            self.grant_public_permissions(self.dstBucketName, self.dstObjectName)

            doc = Document()
            cor = doc.createElement("CopyObjectResult")
            doc.appendChild(cor)

            lm = doc.createElement("LastModified")
            cor.appendChild(lm)
            lmText = doc.createTextNode(datetime(*self.src_ctm[:6]).isoformat())
            lm.appendChild(lmText)

            lm = doc.createElement("ETag")
            cor.appendChild(lm)
            lmText = doc.createTextNode(str(self.src_md5))
            lm.appendChild(lmText)

            x = doc.toxml();
            self.setHeader(self.request, 'x-amz-copy-source-version-id', "1")
            self.setHeader(self.request, 'x-amz-version-id', "1")
            self.send_xml(x)
            self.request.finish()

        except cbException, (ex):
            ex.sendErrorResponse(self.request, self.requestId)
            traceback.print_exc(file=sys.stdout)
Example #4
0
def xmlObjectDefinitionRepresentation(fileName, fileHash):
	doc = Document()
	dvObjectDefinition = doc.createElement('DIVAObjectDefinition')
	doc.appendChild(dvObjectDefinition)

	nextObject = doc.createElement('objectName')
	nextObject.appendChild(doc.createTextNode(fileName))
	dvObjectDefinition.appendChild(nextObject)

	nextObject = doc.createElement('categoryName')
	nextObject.appendChild(doc.createTextNode('ARCHIVE_DR'))
	dvObjectDefinition.appendChild(nextObject)

	nextObject = doc.createElement('comments')
	nextObject.appendChild(doc.createTextNode('MEDIASEALED FILE {}'.format(fileHash)))
	dvObjectDefinition.appendChild(nextObject)

	fileListObject = doc.createElement('fileList')
	dvObjectDefinition.appendChild(fileListObject)

	nextObject = doc.createElement('file')
	nextObject.appendChild(doc.createTextNode(fileName))
	nextObject.setAttribute('checksumType', 'MD5')
	nextObject.setAttribute('checksumValue', fileHash)	

	fileListObject.appendChild(nextObject)

	return ''.join(node.toprettyxml() for node in doc.childNodes)
Example #5
0
def questions_to_aiml(questions):
    punctuation = "\"`~!@#$%^&()-_=+[{]}\|;:',<.>/?"
    _puncStripRE = re.compile("[" + re.escape(punctuation) + "]")

    # Create the minidom document
    doc = Document()
    
    # Create the <aiml> base element
    aiml = doc.createElement("aiml")
    doc.appendChild(aiml)
    

    for question, answer in questions:        
        patterns = (re.sub(_puncStripRE, "", question), re.sub(_puncStripRE, "*", question))
        
        for p in patterns:
            category = doc.createElement("category") 
            pattern = doc.createElement("pattern") 
            pattern.appendChild(doc.createTextNode(p.upper()))  
            
            template = doc.createElement("template") 
            template.appendChild(doc.createTextNode(answer))
        
            category.appendChild(pattern)
            category.appendChild(template)
    
            aiml.appendChild(category)

    # Print our newly created XML
    return doc.toxml()
def parse_type_of(obj):
    """
    @return: A C{ParsedDocstring} that encodes the type of the given
    object.
    @rtype: L{ParsedDocstring}
    @param obj: The object whose type should be returned as DOM document.
    @type obj: any
    """
    # This is a bit hackish; oh well. :)
    from epydoc.markup.epytext import ParsedEpytextDocstring
    from xml.dom.minidom import Document
    doc = Document()
    epytext = doc.createElement('epytext')
    para = doc.createElement('para')
    doc.appendChild(epytext)
    epytext.appendChild(para)
    
    if type(obj) is types.InstanceType:
        link = doc.createElement('link')
        name = doc.createElement('name')
        target = doc.createElement('target')
        para.appendChild(link)
        link.appendChild(name)
        link.appendChild(target)
        name.appendChild(doc.createTextNode(str(obj.__class__.__name__)))
        target.appendChild(doc.createTextNode(str(obj.__class__)))        
    else:
        code = doc.createElement('code')
        para.appendChild(code)
        code.appendChild(doc.createTextNode(type(obj).__name__))
    return ParsedEpytextDocstring(doc)
Example #7
0
    def list_bucket(self):
        dirL = self.user.list_bucket(self.bucketName, self.request.args)
        doc = Document()

        # Create the <wml> base element
        xList = doc.createElement("ListBucketResult")
        xList.setAttribute("xmlns", "http://doc.s3.amazonaws.com/2006-03-01")
        doc.appendChild(xList)

        # Create the main <card> element
        xName = doc.createElement("Name")
        xList.appendChild(xName)
        xNameText = doc.createTextNode(str(self.bucketName))
        xName.appendChild(xNameText)

        xIsTruncated = doc.createElement("IsTruncated")
        xList.appendChild(xIsTruncated)
        xIsTText = doc.createTextNode('false')
        xIsTruncated.appendChild(xIsTText)

        for obj in dirL:
            xObj = obj.create_xml_element(doc)
            xList.appendChild(xObj)

        x = doc.toxml();

        self.send_xml(x)
        self.finish(self.request)
Example #8
0
    def create_fake_config_file(self):
        doc = Document()
        emc = doc.createElement("EMC")
        doc.appendChild(emc)

        storagetype = doc.createElement("StorageType")
        storagetypetext = doc.createTextNode("gold")
        emc.appendChild(storagetype)
        storagetype.appendChild(storagetypetext)

        ecomserverip = doc.createElement("EcomServerIp")
        ecomserveriptext = doc.createTextNode("1.1.1.1")
        emc.appendChild(ecomserverip)
        ecomserverip.appendChild(ecomserveriptext)

        ecomserverport = doc.createElement("EcomServerPort")
        ecomserverporttext = doc.createTextNode("10")
        emc.appendChild(ecomserverport)
        ecomserverport.appendChild(ecomserverporttext)

        ecomusername = doc.createElement("EcomUserName")
        ecomusernametext = doc.createTextNode("user")
        emc.appendChild(ecomusername)
        ecomusername.appendChild(ecomusernametext)

        ecompassword = doc.createElement("EcomPassword")
        ecompasswordtext = doc.createTextNode("pass")
        emc.appendChild(ecompassword)
        ecompassword.appendChild(ecompasswordtext)

        self.config_file_path = self.tempdir + '/' + config_file_name
        f = open(self.config_file_path, 'w')
        doc.writexml(f)
        f.close()
Example #9
0
def _note2musicxml(note):
    doc = Document()
    note_node = doc.createElement("note")
    if note==None:
        #note is a rest
        rest = doc.createElement("rest")
        note_node.appendChild(rest)
    else:
        #add pitch info
        pitch = doc.createElement("pitch")
        step = doc.createElement("step")
        step.appendChild(doc.createTextNode(note.name[:1]))
        pitch.appendChild(step)
        octave = doc.createElement("octave")
        octave.appendChild(doc.createTextNode(str(note.octave)))
        pitch.appendChild(octave)
        #check for alterations
        count = 0
        for i in note.name[1:]:
            if   i=="b": count-=1
            elif i=="#": count +=1
        if count != 0:
            alter = doc.createElement("alter")
            alter.appendChild(doc.createTextNode(str(count)))
            pitch.appendChild(alter)
            
        note_node.appendChild(pitch)

    return note_node
Example #10
0
def todaysNews():
    query = News.all()
    query.order("-createdAt")
    results = query.fetch(limit=1)

    mostRecentNews = results.pop()

    # Create the minidom level document
    doc = Document()
    newsElement = doc.createElement("news")
    doc.appendChild(newsElement)

    #headline
    headlineElement = doc.createElement("headline")
    headline = doc.createTextNode(mostRecentNews.headline)
    headlineElement.appendChild(headline)
    newsElement.appendChild(headlineElement)

    #content
    contentElement = doc.createElement("content")
    content = doc.createTextNode(mostRecentNews.content)
    contentElement.appendChild(content)
    newsElement.appendChild(contentElement)

    #date
    dateElement = doc.createElement("date")
    date = doc.createTextNode(str(mostRecentNews.createdAt))
    dateElement.appendChild(date)
    newsElement.appendChild(dateElement)

    out = doc.toxml()
    return out
Example #11
0
    def make_xml_string(self, path, requestId):
        doc = Document()

        # Create the <wml> base element
        xError = doc.createElement("Error")
        doc.appendChild(xError)

        # Create the main <card> element
        xCode = doc.createElement("Code")
        xCodeText = doc.createTextNode(self.code)
        xCode.appendChild(xCodeText)
        xError.appendChild(xCode)

        xMsg = doc.createElement("Message")
        xMsgText = doc.createTextNode(self.eMsg)
        xMsg.appendChild(xMsgText)
        xError.appendChild(xMsg)

        xRsc = doc.createElement("Resource")
        xRscText = doc.createTextNode(path)
        xRsc.appendChild(xRscText)
        xError.appendChild(xRsc)

        xRId = doc.createElement("RequestId")
        xRIdText = doc.createTextNode(str(requestId))
        xRId.appendChild(xRIdText)
        xError.appendChild(xRId)

        for k in self.custom_xml.keys():
            xId = doc.createElement(k)
            xText = doc.createTextNode(self.custom_xml[k])
            xId.appendChild(xText)
            xError.appendChild(xId)

        return doc.toxml()
def generate_ticket_body(subject_text, body_text, requester_email_text,
                         use_configured_assignee=True):
    doc = Document()
    # Create the outer ticket element
    ticket = doc.createElement("ticket")
    doc.appendChild(ticket)

    # Create the other data
    subject = doc.createElement('subject')
    subject.appendChild(doc.createTextNode(subject_text))
    ticket.appendChild(subject)

    requester = doc.createElement('requester-email')
    requester.appendChild(doc.createTextNode(requester_email_text))
    ticket.appendChild(requester)

    requester = doc.createElement('group-id')
    requester.appendChild(doc.createTextNode('86020'))
    ticket.appendChild(requester)

    if (use_configured_assignee and
        getattr(settings, "ZENDESK_ASSIGN_TO_USER_ID", None)):
        value = getattr(settings, "ZENDESK_ASSIGN_TO_USER_ID")
        assignee = doc.createElement('assignee-id')
        assignee.appendChild(doc.createTextNode(unicode(value)))
        ticket.appendChild(assignee)

    description = doc.createElement('description')
    description.appendChild(doc.createTextNode(body_text))
    ticket.appendChild(description)

    return doc.toxml()
Example #13
0
def record_add_field(rec, tag, ind1='', ind2='', subfields=[],
                     controlfield_value=''):
    doc = Document()
    datafield = doc.createElement('datafield')
    datafield.setAttribute('tag', tag)
    datafield.setAttribute('ind1', ind1)
    datafield.setAttribute('ind2', ind2)
    for subfield in subfields:
        field = doc.createElement('subfield')
        field.setAttribute('code', subfield[0])
        ## In order to be parsed it needs to a propper XML
        data = "<dummy>" + escape_for_xml(subfield[1]) + "</dummy>"
        try:
            data = parseString(data).firstChild
            for child in data.childNodes:
                field.appendChild(child.cloneNode(child))
        except ExpatError:
            field.appendChild(doc.createTextNode(str(subfield[1])))
        datafield.appendChild(field)
    if controlfield_value:
        controlfield = doc.createElement('controlfield')
        controlfield.setAttribute('tag', tag)
        controlfield.appendChild(doc.createTextNode(str(controlfield_value)))
        rec.appendChild(controlfield)
    else:
        rec.appendChild(datafield)
    return rec
def rows2xml(rows):
    #
    # http://www.postneo.com/projects/pyxml/
    #
    from xml.dom.minidom import Document
    doc = Document()
    table = doc.createElement('table')
    doc.appendChild(table)
    for i, r in enumerate(rows):
        if i == 0:
            #
            # Don't write column labels as a separate row.
            #
            continue
        row = doc.createElement('row')
        row.setAttribute('id', str(i))
        for j, c in enumerate(r):
            cell = doc.createElement('cell')
            name = doc.createElement('name')
            name.appendChild(doc.createTextNode(rows[0][j]))
            val = doc.createElement('val')
            val.appendChild(doc.createTextNode(c))

            cell.appendChild(name)
            cell.appendChild(val)
            row.appendChild(cell)

        table.appendChild(row)

    return doc
Example #15
0
def parseRss(l, info):
    feed = Document()
    rss = feed.createElement("rss")
    channel = feed.createElement("channel")
    title = feed.createElement("title")
    title_text = feed.createTextNode(info["title"])
    link = feed.createElement("link")
    link_text = feed.createTextNode(info["root"])
    title.appendChild(title_text)
    link.appendChild(link_text)
    channel.appendChild(title)
    channel.appendChild(link)
    for p in l:
        item = feed.createElement('item')
        pair = {\
            'title':p['title'], 'description':p['content'],\
            'link':info['root']+'/'+p['rlink']}
        for n in pair.keys():
            node = feed.createElement(n)
            node_text = feed.createTextNode(pair[n])
            node.appendChild(node_text)
            item.appendChild(node)
        channel.appendChild(item)
    rss.appendChild(channel)
    feed.appendChild(rss)
    return feed.toxml()
    def createXmlandWrite(self, dataToStore, filename):
        if not dataToStore:
            return 
        
        doc = Document()
        results = doc.createElement("results")
        doc.appendChild(results)
        for a in dataToStore:
            item = doc.createElement("item")
            for k, d in a.items():
                tag = doc.createElement(k)
                
                if k == "author":
                    tag2 = doc.createElement("name")
                    data = doc.createTextNode(d)
                    tag2.appendChild(data)
                    tag.appendChild(tag2)
                else:
                    data = doc.createTextNode(toUnicode(d))

                    tag.appendChild(data)
                item.appendChild(tag)
            results.appendChild(item)
        
        qwe = doc.toprettyxml(indent="    ", encoding = "UTF-8")
       

        writeToFile(qwe, 
                    "scf_"+filename, 
                    "/mnt/minerva1/nlp/projects/spinn3r/solr_data/xjerab13",
			#"/mnt/minerva1/nlp/projects/blogs_download2/sail_data_out",
			#"e:\\tmp\\tmp\\conv", 
                    extension=".xml", 
                    timestamp=True
                    )
Example #17
0
 def saveTextureList(self, *args, **kwargs):
   ''' write an xml file with a list of the scenes textures and timestamps '''
   fileNodes = pm.ls(type='file')
   sceneName = path.getSceneName()
   xmlFileName = sceneName+'_textureList'
   
   doc = Document()
   textureList = doc.createElement('textureList')
   textureList.setAttribute('sceneName', sceneName)
   doc.appendChild(textureList)
   
   for node in fileNodes:
     fileTextureName = pm.getAttr(node+'.fileTextureName')
     if os.path.isfile(fileTextureName):
       time = os.path.getmtime(fileTextureName)
       
       textureNode = doc.createElement('textureNode')
       textureNode.setAttribute('nodeName', node)
       textureList.appendChild(textureNode)
       
       texturePath = doc.createElement('path')
       texturePath.appendChild(doc.createTextNode(fileTextureName) )
       textureNode.appendChild(texturePath)
       
       textureTime = doc.createElement('time')   
       textureTime.appendChild(doc.createTextNode(str(time) ) )
       textureNode.appendChild(textureTime)
     
   f = open(self.settingsPath+xmlFileName+'.xml', 'w+')
   #f.write(doc.toprettyxml(indent='    ') ) #This is super slow !!!!!
   doc.writexml(f)
   f.close()
Example #18
0
	def toXML(self, includeChoice=False):
		doc = Document()

		pollNode = doc.createElement("poll")

		indexNode = doc.createElement("index")
		pollNode.appendChild(indexNode)
		indexText = doc.createTextNode(str(self.index))
		indexNode.appendChild(indexText)

		backgroundNode = doc.createElement("background")
		pollNode.appendChild(backgroundNode)
		backgroundText = doc.createTextNode(self.background)
		backgroundNode.appendChild(backgroundText)

		ownerNode = doc.createElement("owner");
		pollNode.appendChild(ownerNode)
		ownerText = doc.createTextNode(self.owner.name)
		ownerNode.appendChild(ownerText)

		keyNode = doc.createElement("key")
		pollNode.appendChild(keyNode)
		keyText = doc.createTextNode(str(self.key()))
		keyNode.appendChild(keyText)

		if includeChoice:
			choiceNode = doc.createElement("choices")
			pollNode.appendChild(choiceNode)


			for choice in self.choices:
				choiceNode.appendChild(choice.toXML())


		return pollNode
Example #19
0
def saveXML(outputList):

    doc = Document()
    taskList = doc.createElement("taskList")
    doc.appendChild(taskList)

    for elem in outputList:
        commandList, output = elem
        task = doc.createElement("task")
        for command in commandList:
            command = " ".join(updateCommand(command.strip().split(" ")))
            cmd = doc.createElement("command")
            cmd.appendChild(doc.createTextNode(command))
            task.appendChild(cmd)

        output = output.strip().split("\n")
        out = doc.createElement("output")
        for line in output:
            out.appendChild(doc.createTextNode(line))

        task.appendChild(out)
        taskList.appendChild(task)

    f = open("output_task.xml", "w")
    f.write(unescape(doc.toprettyxml()))
    f.close()
Example #20
0
def _note2musicxml(note):
    doc = Document()
    note_node = doc.createElement('note')
    if note == None:
        # note is a rest
        rest = doc.createElement('rest')
        note_node.appendChild(rest)
    else:
        # add pitch info
        pitch = doc.createElement('pitch')
        step = doc.createElement('step')
        step.appendChild(doc.createTextNode(note.name[:1]))
        pitch.appendChild(step)
        octave = doc.createElement('octave')
        octave.appendChild(doc.createTextNode(str(note.octave)))
        pitch.appendChild(octave)

        # check for alterations
        count = 0
        for i in note.name[1:]:
            if i == 'b':
                count -= 1
            elif i == '#':
                count += 1
        if count != 0:
            alter = doc.createElement('alter')
            alter.appendChild(doc.createTextNode(str(count)))
            pitch.appendChild(alter)
        note_node.appendChild(pitch)
    return note_node
Example #21
0
def constructLogXml(event, comment):
    eventString = str(event)
    commentString = str(comment)
    doc = Document()
    #Create root
    root = doc.createElement('log_entry')
    doc.appendChild(root)
    #Add event
    event = doc.createElement('event')
    root.appendChild(event)
    eventText = doc.createTextNode(eventString)
    event.appendChild(eventText)
    #Add timestamp
    time = doc.createElement('time')
    root.appendChild(time)
    timeText = doc.createTextNode(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    time.appendChild(timeText)
    #Add cell ID
    cell = doc.createElement('cell_id')
    root.appendChild(cell)
    cellText = doc.createTextNode('4')
    cell.appendChild(cellText)
    #add comment
    comment = doc.createElement('comment')
    root.appendChild(comment)
    commentText = doc.createTextNode(commentString)
    comment.appendChild(commentText)
    
    return doc.toxml(encoding="utf-8")
Example #22
0
    def createXmlHandler(self, handler):
        doc = Document()

        xml_handler = doc.createElement(WFConstants.TAG_NAME_END_HANDLER)
        xml_name_handler = doc.createElement(WFConstants.TAG_NAME_NAME)
        xml_name_handler_content = doc.createTextNode(handler.name)
        xml_name_handler.appendChild(xml_name_handler_content)

        xml_class_name_handler = doc.createElement(WFConstants.TAG_NAME_CLASS_NAME)
        xml_class_name_handler_content =  doc.createTextNode(handler.class_name)
        xml_class_name_handler.appendChild(xml_class_name_handler_content)

        xml_handler.appendChild(xml_name_handler)
        xml_handler.appendChild(xml_class_name_handler)

        for parameter in node.parameters:

            xml_param_handler = doc.createElement(WFConstants.TAG_NAME_PARAM)
            xml_param_handler.setAttribute(WFConstants.ATTRIBUTE_NAME_NAME, parameter.name)
            if not parameter.without_prefix:
                if parameter.is_constant:
                    prefix = "constant:"
                else:
                    prefix = "variable:"
                xml_param_handler.setAttribute(WFConstants.ATTRIBUTE_NAME_VALUE, prefix + parameter.value)
            else:
                xml_param_handler.setAttribute(WFConstants.ATTRIBUTE_NAME_VALUE, parameter.value)
            xml_handler.appendChild(xml_param_handler)

        return xml_handler
Example #23
0
def save_pairs(pairs, path):
    doc = Document()
    corpus = doc.createElement('entailment-corpus')
    doc.appendChild(corpus)
    
    i = 0
    for pair in pairs:
        try:
            text, hypothesis, entailment = pair
        except ValueError:
            print "Too many values: ", pair
            continue
        i += 1
        pair = doc.createElement('pair')
        pair.setAttribute('id', str(i))
        pair.setAttribute('value', str(entailment).upper())
        corpus.appendChild(pair)
        
        t = doc.createElement('t')
        pair.appendChild(t)
        
        t_text = doc.createTextNode(text)
        t.appendChild(t_text)
        
        h = doc.createElement('h')
        pair.appendChild(h)
        
        h_text = doc.createTextNode(hypothesis)
        h.appendChild(h_text)
    f = open(path, 'w')
    doc.writexml(f, addindent=' ', newl='\n')
	def build(self):
		doc = Document()
		root = doc.createElement('content')
		root.setAttribute('count', str(len(self.questionList)))
		doc.appendChild(root)

		index = 0
		for q in self.questionList:
			index += 1
			qnode = doc.createElement(q.qtype)
			qnode.setAttribute('id', str(index))
			que = doc.createElement('question')
			queText = doc.createTextNode(q.content)
			que.appendChild(queText)
			qnode.appendChild(que)

			ind = 0
			for item in q.items:
				ind += 1
				itemNode = doc.createElement('item')
				itemNode.setAttribute('id', str(ind))
				itemNode.appendChild(doc.createTextNode(item))
				qnode.appendChild(itemNode)
			root.appendChild(qnode)

		return doc.toprettyxml(indent='    ')
Example #25
0
    def positionToXml(self):
        doc = Document()

        xml_position_node = doc.createElement(WFConstants.TAG_NAME_POSITION)

        xml_name_node = doc.createElement(WFConstants.TAG_NAME_NAME)
        xml_name_node_content = doc.createTextNode(self.name)
        xml_name_node.appendChild(xml_name_node_content)

        xml_x_node = doc.createElement(WFConstants.TAG_NAME_X)
        xml_x_node_content = doc.createTextNode(self.x)
        xml_x_node.appendChild(xml_x_node_content)

        xml_y_node = doc.createElement(WFConstants.TAG_NAME_Y)
        xml_y_node_content = doc.createTextNode(self.y)
        xml_y_node.appendChild(xml_y_node_content)

        xml_width_node = doc.createElement(WFConstants.TAG_NAME_WIDTH)
        xml_width_node_content = doc.createTextNode(self.width)
        xml_width_node.appendChild(xml_width_node_content)

        xml_height_node = doc.createElement(WFConstants.TAG_NAME_HEIGHT)
        xml_height_node_content = doc.createTextNode(self.height)
        xml_height_node.appendChild(xml_height_node_content)

        xml_position_node.appendChild(xml_name_node)
        xml_position_node.appendChild(xml_x_node)
        xml_position_node.appendChild(xml_y_node)
        xml_position_node.appendChild(xml_width_node)
        xml_position_node.appendChild(xml_height_node)

        return xml_position_node
Example #26
0
    def post(self):
        global current_user
        form = cgi.FieldStorage()
        category_name = (form["category"].value).strip(" ")
        category_user = (form[category_name].value).strip(" ")
        uname = User(key_name=category_user)
        category = Category(key_name=category_name, parent=uname)
        allItems = db.query_descendants(category)

        doc = Document()
        # create category element
        cat = doc.createElement("CATEGORY")
        doc.appendChild(cat)
        # create name element
        name = doc.createElement("NAME")
        cat.appendChild(name)
        # create text node inside name
        n = doc.createTextNode(category_name)
        name.appendChild(n)

        for i in allItems:
            # create item element
            item = doc.createElement("ITEM")
            cat.appendChild(item)
            # create name element
            name = doc.createElement("NAME")
            item.appendChild(name)
            # create text node inside name
            n = doc.createTextNode(i.name)
            name.appendChild(n)

        self.response.out.write("%s" % doc.toprettyxml())
        self.response.out.write("<br><br><div>Go back to the <a href=" "/" ">welcome page</a><div>")
def make_mobile_xml(Pchtml,MobileUrl):
    #Pchtml = "http://sina2.com.cn"
    #MobileUrl="http://html5.sina2.com.cn"
    #Create minidom document
    doc = Document()
    #Create the <urlset> element
    #urlset = doc.createElement("urlset")
    #doc.appendChild(urlset)
    #Create the <url> element
    url = doc.createElement("url")
    doc.appendChild(url)
    #Create <loc> element
    paragraph1 = doc.createElement("loc")
    url.appendChild(paragraph1)
    locurl = doc.createTextNode(Pchtml)
    #locurl = doc.createCDATASection(Pchtml)
    paragraph1.appendChild(locurl)
    #Create data element
    data = doc.createElement("data")
    url.appendChild(data)
    #Create display element
    display = doc.createElement("display")
    data.appendChild(display)
    #Create html5_url element
    html5_url = doc.createElement("html5_url")
    display.appendChild(html5_url)
    #Create mobile url
    mobile_url = doc.createTextNode(MobileUrl)
    #mobile_url = doc.createCDATASection(MobileUrl)
    html5_url.appendChild(mobile_url)
    #print
    f.write(doc.toprettyxml(indent="  ",encoding="UTF-8"))
Example #28
0
    def wrapInMinimalHeader(self, title, text):
        """
        Wraps the text into  a minimal header and returns it as
        string
        """
        doc = Document()

        # create elements
        elMwiki = doc.createElement("mediawiki")
        elPage = doc.createElement("page")
        elTitle = doc.createElement("title")
        elRev = doc.createElement("revision")
        elText = doc.createElement("text")

        textstr = doc.createTextNode(text)
        titlestr = doc.createTextNode(title)

        doc.appendChild(elMwiki)
        elMwiki.setAttribute("xmlns", "http://www.mediawiki.org/xml/export-0.4/")
        elMwiki.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        elMwiki.setAttribute(
            "xsi:schemaLocation", "http://www.mediawiki.org/xml/export-0.4/ http://www.mediawiki.org/xml/export-0.4.xsd"
        )
        elMwiki.setAttribute("version", "0.4")
        elMwiki.setAttribute("xml:lang", "de")

        elMwiki.appendChild(elPage)
        elPage.appendChild(elTitle)
        elPage.appendChild(elRev)
        elRev.appendChild(elText)
        elText.appendChild(textstr)
        elTitle.appendChild(titlestr)

        return doc.toxml()  # don't prettify
Example #29
0
def main():
    _format, input, output = sys.argv[1:4]

    f = open(input)
    articles = json.loads(f.read())
    fwrt = open(output, 'w')
    if _format == 'csv':
        wrt = csv.writer(fwrt)
        for url, subject in articles:
            wrt.writerow([url, subject])
    elif _format == 'xml':
        doc = Document()
        e_articles = doc.createElement("articles")
        doc.appendChild(e_articles)
        for url, subject in articles:
            e_article = doc.createElement("article")
            e_article_name = doc.createElement("name")
            e_article_url = doc.createElement("url")
            e_article_name.appendChild(doc.createTextNode(subject))
            e_article_url.appendChild(doc.createTextNode(url))
            e_article.appendChild(e_article_name)
            e_article.appendChild(e_article_url)
            e_articles.appendChild(e_article)
        fwrt.write(doc.toprettyxml(indent="  "))
    fwrt.close()
Example #30
0
def createFeed(examples):
    doc = Document()
    feed = doc.createElementNS("http://www.w3.org/2005/Atom", "feed")
    feed.setAttribute("xmlns", "http://www.w3.org/2005/Atom") #ug, is this for real??
    for example in examples:
        s = os.stat("../examples/" + example["example"])
        example["modified"] = s.st_mtime
    
    examples.sort(key=lambda x:x["modified"])
    for example in sorted(examples, key=lambda x:x["modified"], reverse=True):
        entry = doc.createElementNS("http://www.w3.org/2005/Atom", "entry")
        
        title = doc.createElementNS("http://www.w3.org/2005/Atom", "title")
        title.appendChild(doc.createTextNode(example["title"] or example["example"]))
        entry.appendChild(title)
        
        link = doc.createElementNS("http://www.w3.org/2005/Atom", "link")
        link.setAttribute("href", example["example"])
        entry.appendChild(link)
    
        summary = doc.createElementNS("http://www.w3.org/2005/Atom", "summary")
        summary.appendChild(doc.createTextNode(example["shortdesc"] or example["example"]))
        entry.appendChild(summary)
        
        updated = doc.createElementNS("http://www.w3.org/2005/Atom", "updated")
        updated.appendChild(doc.createTextNode(
            time.strftime("%Y-%m-%dT%I:%M:%SZ",time.gmtime(example["modified"]))))
        entry.appendChild(updated)
        
        feed.appendChild(entry)

    doc.appendChild(feed)
    return doc
Example #31
0
def put_stationdata(client, cfg, recv_mq):
    data = get_data(client, "stnstatus", cfg)
    if data is None:
        # logging.DEBUG("data=None")
        return

    doc = Document()
    env = doc.createElement("env:Envelope")
    doc.appendChild(env)
    env.setAttribute("xmlns:env",
                     "http://pdps.in.audi.vwg/legacy_schema/20.7.3/envelope")

    herder = doc.createElement("Herder")
    doc.appendChild(herder)

    sender = doc.createElement("Sender")
    herder.appendChild(sender)

    location = doc.createElement("Location")
    sender.appendChild(location)
    sender_assembly_cycle = get_item(data, u"assembly_cycle")
    location.setAttribute("assembly_cycle", sender_assembly_cycle)
    location.setAttribute("assembly_line", "MES Battery Assembly Line")
    location.setAttribute("assembly_subline", "1")
    location.setAttribute("plant", "C4")
    location.setAttribute("plant_segment", "Battery")

    device = doc.createElement("Device")
    sender.appendChild(device)
    sender_hostname = get_item(data, u"hostname")
    device.setAttribute("hostname", sender_hostname)
    sender_manufacturer = get_item(data, u"manufacturer")
    device.setAttribute("manufacturer", sender_manufacturer)
    sender_type = get_item(data, u"type")
    device.setAttribute("type", sender_type)
    sender_opmode = get_item(data, u"opmode")
    device.setAttribute("opmode", sender_opmode)

    telegraminfo = doc.createElement("Telegraminfo")
    herder.appendChild(telegraminfo)
    sender_timestamp = get_item(data, u"opmode")
    telegraminfo.setAttribute("timestamp", sender_timestamp)
    sender_datatype = get_item(data, u"opmode")
    telegraminfo.setAttribute("datatype", sender_datatype)

    body = doc.createElement("Body")
    doc.appendChild(body)

    batterdata = doc.createElement("BatteryData")
    doc.appendChild(batterdata)
    cid = get_item(data, u"cid")
    batterdata.setAttribute("cid", cid)
    prt = get_item(data, u"teilnr.")
    batterdata.setAttribute("prt", prt)
    pt1 = get_item(data, u"gbt")
    batterdata.setAttribute("pt1", pt1)

    prc_sst = doc.createElement("PRC_SST")
    doc.appendChild(prc_sst)

    In = doc.createElement("Entry")
    jobnumber = get_item(data, u"in")
    In_info = doc.createTextNode(jobnumber)
    In.appendChild(In_info)
    prc_sst.appendChild(In)

    Out = doc.createElement("Leave")
    textdescription = get_item(data, u"out")
    Out_info = doc.createTextNode(textdescription)
    Out.appendChild(Out_info)
    prc_sst.appendChild(Out)

    Palletnumber = doc.createElement("palletnumber")
    palletnumber = get_item(data, u"palletnumber")
    Palletnumber_info = doc.createTextNode(palletnumber)
    Palletnumber.appendChild(Palletnumber_info)
    prc_sst.appendChild(Palletnumber)

    Palletcycletimescount = doc.createElement("palletcycletimescount")
    palletcycletimescount = get_item(data, u"palletcycletimesCount")
    Palletcycletimescount_info = doc.createTextNode(palletcycletimescount)
    Palletcycletimescount.appendChild(Palletcycletimescount_info)
    prc_sst.appendChild(Palletcycletimescount)

    Pallettype = doc.createElement("pallettype")
    pallettype = get_item(data, u"pallettype_m_or_n")
    Pallettype_info = doc.createTextNode(pallettype)
    Pallettype.appendChild(Pallettype_info)
    prc_sst.appendChild(Pallettype)

    Lastworkstation = doc.createElement("lastworkstation")
    lastworkstation = get_item(data, u"lastworkstation")
    Lastworkstation_info = doc.createTextNode(lastworkstation)
    Lastworkstation.appendChild(Lastworkstation_info)
    prc_sst.appendChild(Lastworkstation)

    Palletloaded = doc.createElement("palletloaded")
    palletloaded = get_item(data, u"palletloaded")
    Palletloaded_info = doc.createTextNode(palletloaded)
    Palletloaded.appendChild(Palletloaded_info)
    prc_sst.appendChild(Palletloaded)

    Palletworkok = doc.createElement("palletworkok")
    palletworkok = get_item(data, u"palletworkok")
    Palletworkok_info = doc.createTextNode(palletworkok)
    Palletworkok.appendChild(Palletworkok_info)
    prc_sst.appendChild(Palletworkok)

    Palletworknok = doc.createElement("palletworknok")
    palletworknok = get_item(data, u"palletworknok")
    Palletworknok_info = doc.createTextNode(palletworknok)
    Palletworknok.appendChild(Palletworknok_info)
    prc_sst.appendChild(Palletworknok)

    Palletscrapped = doc.createElement("palletscrapped")
    palletscrapped = get_item(data, u"palletscrapped")
    Palletscrapped_info = doc.createTextNode(palletscrapped)
    Palletscrapped.appendChild(Palletscrapped_info)
    prc_sst.appendChild(Palletscrapped)

    Palletworkposition = doc.createElement("palletworkposition")
    palletworkposition = get_item(data, u"palletworkposition")
    Palletworkposition_info = doc.createTextNode(palletworkposition)
    Palletworkposition.appendChild(Palletworkposition_info)
    prc_sst.appendChild(Palletworkposition)

    Repairstatus = doc.createElement("repairstatus")
    repairstatus = get_item(data, u"repairstatus")
    Repairstatus_info = doc.createTextNode(repairstatus)
    Repairstatus.appendChild(Repairstatus_info)
    prc_sst.appendChild(Repairstatus)

    Repairtimescount = doc.createElement("repairtimescount")
    repairtimescount = get_item(data, u"repairtimescount")
    Repairtimescount_info = doc.createTextNode(repairtimescount)
    Repairtimescount.appendChild(Repairtimescount_info)
    prc_sst.appendChild(Repairtimescount)

    Ilchecktimescount = doc.createElement("ilchecktimescount")
    ilchecktimescount = get_item(data, u"ilchecktimescount")
    Ilchecktimescount_info = doc.createTextNode(ilchecktimescount)
    Ilchecktimescount.appendChild(Ilchecktimescount_info)
    prc_sst.appendChild(Ilchecktimescount)

    Eolchecktimescount = doc.createElement("eolchecktimescount")
    eolchecktimescount = get_item(data, u"eolchecktimescount")
    Eolchecktimescount_info = doc.createTextNode(eolchecktimescount)
    Eolchecktimescount.appendChild(Eolchecktimescount_info)
    prc_sst.appendChild(Eolchecktimescount)

    Dateandtimeid = doc.createElement("dateandtimeid")
    dateandtimeid = get_item(data, u"dateandtimeid")
    Dateandtimeid_info = doc.createTextNode(dateandtimeid)
    Dateandtimeid.appendChild(Dateandtimeid_info)
    prc_sst.appendChild(Dateandtimeid)

    Batteryid = doc.createElement("batteryid")
    batteryid = get_item(data, u"opmode")
    Batteryid_info = doc.createTextNode(batteryid)
    Batteryid.appendChild(Batteryid_info)
    prc_sst.appendChild(Batteryid)

    Bzd_batterycase = doc.createElement("bzd_batterycase")
    bzd_batterycase = get_item(data, u"bzdBatteryCase")
    Bzd_batterycase_info = doc.createTextNode(bzd_batterycase)
    Bzd_batterycase.appendChild(Bzd_batterycase_info)
    prc_sst.appendChild(Bzd_batterycase)

    Bzd_batterypack = doc.createElement("bzd_batterypack")
    bzd_batterypack = get_item(data, u"bzdBatteryPack")
    Bzd_batterypack_info = doc.createTextNode(bzd_batterypack)
    Bzd_batterypack.appendChild(Bzd_batterypack_info)
    prc_sst.appendChild(Bzd_batterypack)

    Teilnr = doc.createElement("teilnr.")
    teilnr = get_item(data, u"teilnr.")
    Teilnr_info = doc.createTextNode(teilnr)
    Teilnr.appendChild(Teilnr_info)
    prc_sst.appendChild(Teilnr)

    Cid = doc.createElement("cid")
    cid = get_item(data, u"cid")
    Cid_info = doc.createTextNode(cid)
    Cid.appendChild(Cid_info)
    prc_sst.appendChild(Cid)

    Gbt = doc.createElement("gbt")
    gbt = get_item(data, u"gbt")
    Gbt_info = doc.createTextNode("dddd")
    Cid.appendChild(Gbt_info)
    prc_sst.appendChild(Cid)

    Gapfillermodule1 = doc.createElement("gapfillermodule1")
    gapfillermodule1 = get_item(data, u"gapfillermodule1")
    Gapfillermodule1_info = doc.createTextNode(gapfillermodule1)
    Gapfillermodule1.appendChild(Gapfillermodule1_info)
    prc_sst.appendChild(Gapfillermodule1)

    Gapfillermodule2 = doc.createElement("gapfillermodule2")
    gapfillermodule2 = get_item(data, u"gapfillermodule2")
    Gapfillermodule2_info = doc.createTextNode(gapfillermodule2)
    Gapfillermodule2.appendChild(Gapfillermodule2_info)
    prc_sst.appendChild(Gapfillermodule2)

    Gapfillermodule3 = doc.createElement("gapfillermodule3")
    gapfillermodule3 = get_item(data, u"gapfillermodule3")
    Gapfillermodule3_info = doc.createTextNode(gapfillermodule3)
    Gapfillermodule3.appendChild(Gapfillermodule3_info)
    prc_sst.appendChild(Gapfillermodule3)

    Gapfillermodule4 = doc.createElement("gapfillermodule4")
    gapfillermodule4 = get_item(data, u"gapfillermodule4")
    Gapfillermodule4_info = doc.createTextNode(gapfillermodule4)
    Gapfillermodule4.appendChild(Gapfillermodule4_info)
    prc_sst.appendChild(Gapfillermodule4)

    Gapfillermodule5 = doc.createElement("gapfillermodule5")
    gapfillermodule5 = get_item(data, u"gapfillermodule5")
    Gapfillermodule5_info = doc.createTextNode(gapfillermodule5)
    Gapfillermodule5.appendChild(Gapfillermodule5_info)
    prc_sst.appendChild(Gapfillermodule5)

    Gapfillermodule6 = doc.createElement("gapfillermodule6")
    gapfillermodule6 = get_item(data, u"gapfillermodule6")
    Gapfillermodule6_info = doc.createTextNode(gapfillermodule6)
    Gapfillermodule6.appendChild(Gapfillermodule6_info)
    prc_sst.appendChild(Gapfillermodule6)

    Gapfillermodule7 = doc.createElement("gapfillermodule7")
    gapfillermodule7 = get_item(data, u"gapfillermodule7")
    Gapfillermodule7_info = doc.createTextNode(gapfillermodule7)
    Gapfillermodule7.appendChild(Gapfillermodule7_info)
    prc_sst.appendChild(Gapfillermodule7)

    Gapfillermodule8 = doc.createElement("gapfillermodule8")
    gapfillermodule8 = get_item(data, u"gapfillermodule8")
    Gapfillermodule8_info = doc.createTextNode(gapfillermodule8)
    Gapfillermodule8.appendChild(Gapfillermodule8_info)
    prc_sst.appendChild(Gapfillermodule8)

    Gapfillermodule9 = doc.createElement("gapfillermodule9")
    gapfillermodule9 = get_item(data, u"gapfillermodule9")
    Gapfillermodule9_info = doc.createTextNode(gapfillermodule9)
    Gapfillermodule9.appendChild(Gapfillermodule9_info)
    prc_sst.appendChild(Gapfillermodule9)

    Gapfillermodule10 = doc.createElement("gapfillermodule10")
    gapfillermodule10 = get_item(data, u"gapfillermodule10")
    Gapfillermodule10_info = doc.createTextNode(gapfillermodule10)
    Gapfillermodule10.appendChild(Gapfillermodule10_info)
    prc_sst.appendChild(Gapfillermodule10)

    Gapfillermodule11 = doc.createElement("gapfillermodule11")
    gapfillermodule11 = get_item(data, u"gapfillermodule11")
    Gapfillermodule11_info = doc.createTextNode(gapfillermodule11)
    Gapfillermodule11.appendChild(Gapfillermodule11_info)
    prc_sst.appendChild(Gapfillermodule11)

    Gapfillermodule12 = doc.createElement("gapfillermodule12")
    gapfillermodule12 = get_item(data, u"gapfillermodule12")
    Gapfillermodule12_info = doc.createTextNode(gapfillermodule12)
    Gapfillermodule12.appendChild(Gapfillermodule12_info)
    prc_sst.appendChild(Gapfillermodule12)

    Gapfillermodule13 = doc.createElement("gapfillermodule13")
    gapfillermodule13 = get_item(data, u"gapfillermodule13")
    Gapfillermodule13_info = doc.createTextNode(gapfillermodule13)
    Gapfillermodule13.appendChild(Gapfillermodule13_info)
    prc_sst.appendChild(Gapfillermodule13)

    Gapfillermodule14 = doc.createElement("gapfillermodule14")
    gapfillermodule14 = get_item(data, u"gapfillermodule14")
    Gapfillermodule14_info = doc.createTextNode(gapfillermodule14)
    Gapfillermodule14.appendChild(Gapfillermodule14_info)
    prc_sst.appendChild(Gapfillermodule14)

    Gapfillermodule15 = doc.createElement("gapfillermodule15")
    gapfillermodule15 = get_item(data, u"gapfillermodule15")
    Gapfillermodule15_info = doc.createTextNode(gapfillermodule15)
    Gapfillermodule15.appendChild(Gapfillermodule15_info)
    prc_sst.appendChild(Gapfillermodule15)

    Recipeversion = doc.createElement("recipeversion")
    recipeversion = get_item(data, u"recipeversion")
    Recipeversion_info = doc.createTextNode(recipeversion)
    Recipeversion.appendChild(Recipeversion_info)
    prc_sst.appendChild(Recipeversion)

    Bomversion = doc.createElement("bomversion")
    bomversion = get_item(data, u"bomversion")
    Bomversion_info = doc.createTextNode(bomversion)
    Bomversion.appendChild(Bomversion_info)
    prc_sst.appendChild(Bomversion)

    Work_ok = doc.createElement("work_ok")
    work_ok = get_item(data, u"work_ok")
    Work_ok_info = doc.createTextNode(work_ok)
    Work_ok.appendChild(Work_ok_info)
    prc_sst.appendChild(Work_ok)

    Work_nok = doc.createElement("work_nok")
    work_nok = get_item(data, u"work_nok")
    Work_nok_info = doc.createTextNode(work_nok)
    Work_nok.appendChild(Work_nok_info)
    prc_sst.appendChild(Work_nok)

    Workerdecisionok = doc.createElement("workerdecisionok")
    workerdecisionok = get_item(data, u"workerdecisionok")
    Workerdecisionok_info = doc.createTextNode(workerdecisionok)
    Workerdecisionok.appendChild(Workerdecisionok_info)
    prc_sst.appendChild(Workerdecisionok)

    Workerdecisionnok = doc.createElement("workerdecisionnok")
    workerdecisionnok = get_item(data, u"workerdecisionnok")
    Workerdecisionnok_info = doc.createTextNode(workerdecisionnok)
    Workerdecisionnok.appendChild(Workerdecisionnok_info)
    prc_sst.appendChild(Workerdecisionnok)

    xml = open("reserve.xml", "w")
    doc.writexml(xml, indent='\t', newl='\n', addindent='\t', encoding='gbk')
    xml.close()

    with open("reserve.xml", "rt") as xml:
        line = xml.read()
        print(line)

    connect(recv_mq)
    queue.put(line)
    # logging.info(line)
    queue.close()
    print("3")
Example #32
0
def convertimgset(img_set="train"):
    imgdir=rootdir+"/WIDER_"+img_set+"/images"
    gtfilepath=rootdir+"/wider_face_split/wider_face_"+img_set+"_bbx_gt.txt"
    imagesdir=rootdir+"/images"
    vocannotationdir=rootdir+"/Annotations"
    labelsdir=rootdir+"/labels"
    if not os.path.exists(imagesdir):
        os.mkdir(imagesdir)
    if convet2yoloformat:
        if not os.path.exists(labelsdir):
            os.mkdir(labelsdir)
    if convert2vocformat:
        if not os.path.exists(vocannotationdir):
            os.mkdir(vocannotationdir)
    index=0
    with open(gtfilepath,'r') as gtfile:
        while(True ):#and len(faces)<10
            filename=gtfile.readline()[:-1]
            if(filename==""):
                break;
            sys.stdout.write("\r"+str(index)+":"+filename+"\t\t\t")
            sys.stdout.flush()
            imgpath=imgdir+"/"+filename
            img=cv2.imread(imgpath)
            if not img.data:
                break;
            imgheight=img.shape[0]
            imgwidth=img.shape[1]
            maxl=max(imgheight,imgwidth)
            paddingleft=(maxl-imgwidth)>>1
            paddingright=(maxl-imgwidth)>>1
            paddingbottom=(maxl-imgheight)>>1
            paddingtop=(maxl-imgheight)>>1
            saveimg=cv2.copyMakeBorder(img,paddingtop,paddingbottom,paddingleft,paddingright,cv2.BORDER_CONSTANT,value=0)
            showimg=saveimg.copy()
            numbbox=int(gtfile.readline())
            bboxes=[]
            for i in range(numbbox):
                line=gtfile.readline()
                line=line.split()
                line=line[0:4]               
                if(int(line[3])<=0 or int(line[2])<=0):
                    continue
                x=int(line[0])+paddingleft
                y=int(line[1])+paddingtop
                width=int(line[2])
                height=int(line[3])
                bbox=(x,y,width,height)
                x2=x+width
                y2=y+height
                #face=img[x:x2,y:y2]
                if width>=minsize2select and height>=minsize2select:
                    bboxes.append(bbox)
                    cv2.rectangle(showimg,(x,y),(x2,y2),(0,255,0))
                    #maxl=max(width,height)
                    #x3=(int)(x+(width-maxl)*0.5)
                    #y3=(int)(y+(height-maxl)*0.5)
                    #x4=(int)(x3+maxl)
                    #y4=(int)(y3+maxl)
                    #cv2.rectangle(img,(x3,y3),(x4,y4),(255,0,0))
                else:
                    cv2.rectangle(showimg,(x,y),(x2,y2),(0,0,255))              
            filename=filename.replace("/","_")
            if len(bboxes)==0:
                print "warrning: no face"
                continue 
            cv2.imwrite(imagesdir+"/"+filename,saveimg)
            if convet2yoloformat:
                height=saveimg.shape[0]
                width=saveimg.shape[1]
                txtpath=labelsdir+"/"+filename
                txtpath=txtpath[:-3]+"txt"
                ftxt=open(txtpath,'w')  
                for i in range(len(bboxes)):
                    bbox=bboxes[i]
                    xcenter=(bbox[0]+bbox[2]*0.5)/width
                    ycenter=(bbox[1]+bbox[3]*0.5)/height
                    wr=bbox[2]*1.0/width
                    hr=bbox[3]*1.0/height
                    txtline="0 "+str(xcenter)+" "+str(ycenter)+" "+str(wr)+" "+str(hr)+"\n"
                    ftxt.write(txtline)
                ftxt.close()
            if convert2vocformat:
                xmlpath=vocannotationdir+"/"+filename
                xmlpath=xmlpath[:-3]+"xml"
                doc = Document()
                annotation = doc.createElement('annotation')
                doc.appendChild(annotation)
                folder = doc.createElement('folder')
                folder_name = doc.createTextNode('widerface')
                folder.appendChild(folder_name)
                annotation.appendChild(folder)
                filenamenode = doc.createElement('filename')
                filename_name = doc.createTextNode(filename)
                filenamenode.appendChild(filename_name)
                annotation.appendChild(filenamenode)
                source = doc.createElement('source')
                annotation.appendChild(source)
                database = doc.createElement('database')
                database.appendChild(doc.createTextNode('wider face Database'))
                source.appendChild(database)
                annotation_s = doc.createElement('annotation')
                annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007'))
                source.appendChild(annotation_s)
                image = doc.createElement('image')
                image.appendChild(doc.createTextNode('flickr'))
                source.appendChild(image)
                flickrid = doc.createElement('flickrid')
                flickrid.appendChild(doc.createTextNode('-1'))
                source.appendChild(flickrid)
                owner = doc.createElement('owner')
                annotation.appendChild(owner)
                flickrid_o = doc.createElement('flickrid')
                flickrid_o.appendChild(doc.createTextNode('yanyu'))
                owner.appendChild(flickrid_o)
                name_o = doc.createElement('name')
                name_o.appendChild(doc.createTextNode('yanyu'))
                owner.appendChild(name_o)
                size = doc.createElement('size')
                annotation.appendChild(size)
                width = doc.createElement('width')
                width.appendChild(doc.createTextNode(str(saveimg.shape[1])))
                height = doc.createElement('height')
                height.appendChild(doc.createTextNode(str(saveimg.shape[0])))
                depth = doc.createElement('depth')
                depth.appendChild(doc.createTextNode(str(saveimg.shape[2])))
                size.appendChild(width)
                size.appendChild(height)
                size.appendChild(depth)
                segmented = doc.createElement('segmented')
                segmented.appendChild(doc.createTextNode('0'))
                annotation.appendChild(segmented)
                for i in range(len(bboxes)):
                    bbox=bboxes[i]
                    objects = doc.createElement('object')
                    annotation.appendChild(objects)
                    object_name = doc.createElement('name')
                    object_name.appendChild(doc.createTextNode('face'))
                    objects.appendChild(object_name)
                    pose = doc.createElement('pose')
                    pose.appendChild(doc.createTextNode('Unspecified'))
                    objects.appendChild(pose)
                    truncated = doc.createElement('truncated')
                    truncated.appendChild(doc.createTextNode('1'))
                    objects.appendChild(truncated)
                    difficult = doc.createElement('difficult')
                    difficult.appendChild(doc.createTextNode('0'))
                    objects.appendChild(difficult)
                    bndbox = doc.createElement('bndbox')
                    objects.appendChild(bndbox)
                    xmin = doc.createElement('xmin')
                    xmin.appendChild(doc.createTextNode(str(bbox[0])))
                    bndbox.appendChild(xmin)
                    ymin = doc.createElement('ymin')
                    ymin.appendChild(doc.createTextNode(str(bbox[1])))
                    bndbox.appendChild(ymin)
                    xmax = doc.createElement('xmax')
                    xmax.appendChild(doc.createTextNode(str(bbox[0]+bbox[2])))
                    bndbox.appendChild(xmax)
                    ymax = doc.createElement('ymax')
                    ymax.appendChild(doc.createTextNode(str(bbox[1]+bbox[3])))
                    bndbox.appendChild(ymax)
                f=open(xmlpath,"w")
                f.write(doc.toprettyxml(indent = ''))
                f.close()     
            #cv2.imshow("img",showimg)
            #cv2.waitKey()
            index=index+1
Example #33
0
def visualize(y, ori, name, test_folder, mode=1, text=None):
    if not os.path.exists(test_folder):
        os.mkdir(test_folder)
    # create svg document
    #mode = 1
    if y is None:
        mode = 0
    width = float(ori["width"])
    height = float(ori["height"])
    doc = Document()
    svg = doc.createElement('svg')
    svg.setAttribute('xmlns', "http://www.w3.org/2000/svg")
    svg.setAttribute('width', str(width))
    svg.setAttribute('height', str(height))
    svg.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink")

    doc.appendChild(svg)
    style = doc.createElement('style')
    svg.appendChild(style)
    style.setAttribute('xmlns', "http://www.w3.org/1999/xhtml")
    style.setAttribute('type', "text/css")

    style_text = doc.createTextNode('''
    .links line {
      stroke: #999;
      stroke-opacity: 0.6;
    }

    .nodes circle {
      stroke: #fff;
      stroke-width: 1.5px;
    }''')  #create node
    style.appendChild(style_text)

    background = doc.createElement('rect')
    svg.appendChild(background)
    background.setAttribute('width', '100%')
    background.setAttribute('height', '100%')
    background.setAttribute('style', "fill:rgb(255,255,255);")

    if not text is None:
        for i in range(len(text)):
            g_text = doc.createElement('g')
            g_text.setAttribute('class', "text")
            svg.appendChild(g_text)
            real_text = doc.createElement('text')
            real_text.setAttribute('x', str(50))
            real_text.setAttribute('y', str(20 + i * 15))
            real_content = doc.createTextNode(text[i])
            real_text.appendChild(real_content)
            g_text.appendChild(real_text)

    g_nodes = doc.createElement('g')
    g_nodes.setAttribute('class', "nodes")

    def getx(id):
        if mode == 1:
            x = y[id][0] * float(width)
        else:
            x = y[id][0]
        if x < 0:
            x = 0
        if x > width:
            x = width
        return x

    def gety(id):
        if mode == 1:
            y_value = y[id][1] * float(height)
        else:
            y_value = y[id][1]
        if y_value < 0:
            y_value = 0
        if y_value > height:
            y_value = height
        return y_value

    node_mapping = {}
    for node in ori['nodelist']:
        id = node[0]
        if mode == 0:
            cx = node[2]
            cy = node[3]
        else:
            cx = getx(id)
            cy = gety(id)
        if id in node_mapping:
            print("node mapping error" + str(id))
        else:
            node_mapping[id] = [cx, cy]
        node_group = node[1]
        r = node[4]
        fill = node[5]
        circle = doc.createElement('circle')
        circle.setAttribute('stroke', "#fff")
        circle.setAttribute('stroke-width', "1.5px")
        circle.setAttribute('r', str(r))
        circle.setAttribute('fill', fill)
        circle.setAttribute('node_id', str(id))
        circle.setAttribute('node_group', str(node_group))
        circle.setAttribute('cx', str(cx))
        circle.setAttribute('cy', str(cy))
        title = doc.createElement('title')
        title_text = doc.createTextNode(str(id))
        title.appendChild(title_text)
        circle.appendChild(title)
        g_nodes.appendChild(circle)
    g_links = doc.createElement('g')
    g_links.setAttribute('class', "links")
    for line in ori['linelist']:
        node1 = line[0]
        node2 = line[1]
        if not mode == 0:
            x1 = getx(node1)
            y1 = gety(node1)
            x2 = getx(node2)
            y2 = gety(node2)
        else:
            if node1 in node_mapping:
                if node2 in node_mapping:
                    x1 = node_mapping[node1][0]
                    y1 = node_mapping[node1][1]
                    x2 = node_mapping[node2][0]
                    y2 = node_mapping[node2][1]
                else:
                    print("link mapping error : " + str(node2))
            else:
                print("link mapping error : " + str(node1))
        link_ids = str(node1) + "_" + str(node2)
        line = doc.createElement('line')

        line.setAttribute('stroke', "#999")
        line.setAttribute("stroke-opacity", "0.6")
        line.setAttribute('stroke-width', "2")
        line.setAttribute('link_ids', link_ids)
        line.setAttribute('x1', str(x1))
        line.setAttribute('y1', str(y1))
        line.setAttribute('x2', str(x2))
        line.setAttribute('y2', str(y2))
        g_links.appendChild(line)

    svg.appendChild(g_links)
    svg.appendChild(g_nodes)
    #write to file
    f = open(test_folder + name + '.xml', 'w')
    doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')
    f.close()

    url = test_folder + name + '.xml'
    write_to = test_folder + name + '.png'
    cairosvg.svg2png(url=url, write_to=write_to)
def save_to_xml(save_path, im_height, im_width, objects_axis, label_name):
    im_depth = 0
    object_num = len(objects_axis)
    doc = Document()

    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)

    folder = doc.createElement('folder')
    folder_name = doc.createTextNode('VOC2007')
    folder.appendChild(folder_name)
    annotation.appendChild(folder)

    filename = doc.createElement('filename')
    filename_name = doc.createTextNode('000024.jpg')
    filename.appendChild(filename_name)
    annotation.appendChild(filename)

    source = doc.createElement('source')
    annotation.appendChild(source)

    database = doc.createElement('database')
    database.appendChild(doc.createTextNode('The VOC2007 Database'))
    source.appendChild(database)

    annotation_s = doc.createElement('annotation')
    annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007'))
    source.appendChild(annotation_s)

    image = doc.createElement('image')
    image.appendChild(doc.createTextNode('flickr'))
    source.appendChild(image)

    flickrid = doc.createElement('flickrid')
    flickrid.appendChild(doc.createTextNode('322409915'))
    source.appendChild(flickrid)

    owner = doc.createElement('owner')
    annotation.appendChild(owner)

    flickrid_o = doc.createElement('flickrid')
    flickrid_o.appendChild(doc.createTextNode('knautia'))
    owner.appendChild(flickrid_o)

    name_o = doc.createElement('name')
    name_o.appendChild(doc.createTextNode('yang'))
    owner.appendChild(name_o)


    size = doc.createElement('size')
    annotation.appendChild(size)
    width = doc.createElement('width')
    width.appendChild(doc.createTextNode(str(im_width)))
    height = doc.createElement('height')
    height.appendChild(doc.createTextNode(str(im_height)))
    depth = doc.createElement('depth')
    depth.appendChild(doc.createTextNode(str(im_depth)))
    size.appendChild(width)
    size.appendChild(height)
    size.appendChild(depth)
    segmented = doc.createElement('segmented')
    segmented.appendChild(doc.createTextNode('0'))
    annotation.appendChild(segmented)
    for i in range(object_num):
        objects = doc.createElement('object')
        annotation.appendChild(objects)
        object_name = doc.createElement('name')
        object_name.appendChild(doc.createTextNode(label_name[int(objects_axis[i][-1])]))
        objects.appendChild(object_name)
        pose = doc.createElement('pose')
        pose.appendChild(doc.createTextNode('Unspecified'))
        objects.appendChild(pose)
        truncated = doc.createElement('truncated')
        truncated.appendChild(doc.createTextNode('1'))
        objects.appendChild(truncated)
        difficult = doc.createElement('difficult')
        difficult.appendChild(doc.createTextNode('0'))
        objects.appendChild(difficult)
        bndbox = doc.createElement('bndbox')
        objects.appendChild(bndbox)
        
        x0 = doc.createElement('x0')
        x0.appendChild(doc.createTextNode(str((objects_axis[i][0]))))
        bndbox.appendChild(x0)
        y0 = doc.createElement('y0')
        y0.appendChild(doc.createTextNode(str((objects_axis[i][1]))))
        bndbox.appendChild(y0)

        x1 = doc.createElement('x1')
        x1.appendChild(doc.createTextNode(str((objects_axis[i][2]))))
        bndbox.appendChild(x1)
        y1 = doc.createElement('y1')
        y1.appendChild(doc.createTextNode(str((objects_axis[i][3]))))
        bndbox.appendChild(y1)
        
        x2 = doc.createElement('x2')
        x2.appendChild(doc.createTextNode(str((objects_axis[i][4]))))
        bndbox.appendChild(x2)
        y2 = doc.createElement('y2')
        y2.appendChild(doc.createTextNode(str((objects_axis[i][5]))))
        bndbox.appendChild(y2)

        x3 = doc.createElement('x3')
        x3.appendChild(doc.createTextNode(str((objects_axis[i][6]))))
        bndbox.appendChild(x3)
        y3 = doc.createElement('y3')
        y3.appendChild(doc.createTextNode(str((objects_axis[i][7]))))
        bndbox.appendChild(y3)
        
    f = open(save_path,'w')
    f.write(doc.toprettyxml(indent = ''))
    f.close() 
Example #35
0
class XMLReportGenerator(ReportGenerator):
    """
    This class generates a report with the method printToFile(fileName) which contains
    the information of all the vulnerabilities notified to this object through the
    method logVulnerability(vulnerabilityTypeName,level,url,parameter,info).
    The format of the file is XML and it has the following structure:
    <report type="security">
        <generatedBy id="Wapiti 2.3.0"/>
        <vulnerabilityTypeList>
            <vulnerabilityType name="SQL Injection">

        <vulnerabilityTypeList>
            <vulnerabilityType name="SQL Injection">
                <vulnerabilityList>
                    <vulnerability level="3">
                        <url>http://www.a.com</url>
                        <parameters>id=23</parameters>
                        <info>SQL Injection</info>
                    </vulnerability>
                </vulnerabilityList>
            </vulnerablityType>
        </vulnerabilityTypeList>
    </report>
    """

    __xmlDoc = None
    __infos = {}
    __flawTypes = {}

    __vulns = {}
    __anomalies = {}

    __infos = {}

    def __init__(self):
        self.__xmlDoc = Document()

    def setReportInfo(self, target, scope=None, date_string="", version=""):
        self.__infos["target"] = target
        self.__infos["date"] = date_string
        self.__infos["version"] = version
        if scope:
            self.__infos["scope"] = scope

    # Vulnerabilities
    def addVulnerabilityType(self, name,
                             description="",
                             solution="",
                             references={}):
        if name not in self.__flawTypes:
            self.__flawTypes[name] = {'desc': description,
                                      'sol': solution,
                                      'ref': references}
        if name not in self.__vulns:
            self.__vulns[name] = []

    def logVulnerability(self,
                         category=None,
                         level=0,
                         request=None,
                         parameter="",
                         info=""):
        """
        Store the information about the vulnerability to be printed later.
        The method printToFile(fileName) can be used to save in a file the
        vulnerabilities notified through the current method.
        """

        vuln_dict = {"method": request.method,
                     "path": request.file_path,
                     "info": info,
                     "level": level,
                     "parameter": parameter,
                     "http_request": request.http_repr,
                     "curl_command": request.curl_repr,
                     }
        if category not in self.__vulns:
            self.__vulns[category] = []
        self.__vulns[category].append(vuln_dict)

    # Anomalies
    def addAnomalyType(self, name,
                       description="",
                       solution="",
                       references={}):
        if name not in self.__flawTypes:
            self.__flawTypes[name] = {'desc': description,
                                      'sol': solution,
                                      'ref': references}
        if name not in self.__anomalies:
            self.__anomalies[name] = []

    def logAnomaly(self,
                   category=None,
                   level=0,
                   request=None,
                   parameter="",
                   info=""):
        """
        Store the information about the vulnerability to be printed later.
        The method printToFile(fileName) can be used to save in a file the
        vulnerabilities notified through the current method.
        """

        anom_dict = {"method": request.method,
                     "path": request.file_path,
                     "info": info,
                     "level": level,
                     "parameter": parameter,
                     "http_request": request.http_repr,
                     "curl_command": request.curl_repr,
                     }
        if category not in self.__anomalies:
            self.__anomalies[category] = []
        self.__anomalies[category].append(anom_dict)

    def generateReport(self, fileName):
        """
        Create a xml file with a report of the vulnerabilities which have been logged with
        the method logVulnerability(vulnerabilityTypeName,level,url,parameter,info)
        """

        report = self.__xmlDoc.createElement("report")
        report.setAttribute("type", "security")
        self.__xmlDoc.appendChild(report)

        # Add report infos
        report_infos = self.__xmlDoc.createElement("report_infos")
        generatorName = self.__xmlDoc.createElement("info")
        generatorName.setAttribute("name", "generatorName")
        generatorName.appendChild(self.__xmlDoc.createTextNode("wapiti"))
        report_infos.appendChild(generatorName)

        generatorVersion = self.__xmlDoc.createElement("info")
        generatorVersion.setAttribute("name", "generatorVersion")
        generatorVersion.appendChild(self.__xmlDoc.createTextNode(self.__infos["version"]))
        report_infos.appendChild(generatorVersion)

        scope = self.__xmlDoc.createElement("info")
        scope.setAttribute("name", "scope")
        scope.appendChild(self.__xmlDoc.createTextNode(self.__infos["scope"]))
        report_infos.appendChild(scope)

        dateOfScan = self.__xmlDoc.createElement("info")
        dateOfScan.setAttribute("name", "dateOfScan")
        dateOfScan.appendChild(self.__xmlDoc.createTextNode(self.__infos["date"]))
        report_infos.appendChild(dateOfScan)
        report.appendChild(report_infos)

        vulnerabilities = self.__xmlDoc.createElement("vulnerabilities")
        anomalies = self.__xmlDoc.createElement("anomalies")

        # Loop on each flaw classification
        for flawType in self.__flawTypes:
            container = None
            classification = ""
            flaw_dict = {}
            if flawType in self.__vulns:
                container = vulnerabilities
                classification = "vulnerability"
                flaw_dict = self.__vulns
            elif flawType in self.__anomalies:
                container = anomalies
                classification = "anomaly"
                flaw_dict = self.__anomalies

            # Child nodes with a description of the flaw type
            flawTypeNode = self.__xmlDoc.createElement(classification)
            flawTypeNode.setAttribute("name", flawType)
            flawTypeDesc = self.__xmlDoc.createElement("description")
            flawTypeDesc.appendChild(self.__xmlDoc.createCDATASection(self.__flawTypes[flawType]['desc']))
            flawTypeNode.appendChild(flawTypeDesc)
            flawTypeSolution = self.__xmlDoc.createElement("solution")
            flawTypeSolution.appendChild(self.__xmlDoc.createCDATASection(self.__flawTypes[flawType]['sol']))
            flawTypeNode.appendChild(flawTypeSolution)

            flawTypeReferences = self.__xmlDoc.createElement("references")
            for ref in self.__flawTypes[flawType]['ref']:
                referenceNode = self.__xmlDoc.createElement("reference")
                titleNode = self.__xmlDoc.createElement("title")
                urlNode = self.__xmlDoc.createElement("url")
                titleNode.appendChild(self.__xmlDoc.createTextNode(ref))
                url = self.__flawTypes[flawType]['ref'][ref]
                urlNode.appendChild(self.__xmlDoc.createTextNode(url))
                referenceNode.appendChild(titleNode)
                referenceNode.appendChild(urlNode)
                flawTypeReferences.appendChild(referenceNode)
            flawTypeNode.appendChild(flawTypeReferences)

            # And child nodes with each flaw of the current type
            entriesNode = self.__xmlDoc.createElement("entries")
            for flaw in flaw_dict[flawType]:
                entryNode = self.__xmlDoc.createElement("entry")
                methodNode = self.__xmlDoc.createElement("method")
                methodNode.appendChild(self.__xmlDoc.createTextNode(flaw["method"]))
                entryNode.appendChild(methodNode)
                pathNode = self.__xmlDoc.createElement("path")
                pathNode.appendChild(self.__xmlDoc.createTextNode(flaw["path"]))
                entryNode.appendChild(pathNode)
                levelNode = self.__xmlDoc.createElement("level")
                levelNode.appendChild(self.__xmlDoc.createTextNode(str(flaw["level"])))
                entryNode.appendChild(levelNode)
                parameterNode = self.__xmlDoc.createElement("parameter")
                parameterNode.appendChild(self.__xmlDoc.createTextNode(flaw["parameter"]))
                entryNode.appendChild(parameterNode)
                infoNode = self.__xmlDoc.createElement("info")
                infoNode.appendChild(self.__xmlDoc.createTextNode(flaw["info"]))
                entryNode.appendChild(infoNode)
                httpRequestNode = self.__xmlDoc.createElement("http_request")
                httpRequestNode.appendChild(self.__xmlDoc.createCDATASection(flaw["http_request"]))
                entryNode.appendChild(httpRequestNode)
                curlCommandNode = self.__xmlDoc.createElement("curl_command")
                curlCommandNode.appendChild(self.__xmlDoc.createCDATASection(flaw["curl_command"]))
                entryNode.appendChild(curlCommandNode)
                entriesNode.appendChild(entryNode)
            flawTypeNode.appendChild(entriesNode)
            container.appendChild(flawTypeNode)
        report.appendChild(vulnerabilities)
        report.appendChild(anomalies)

        f = open(fileName, "w")
        try:
            f.write(self.__xmlDoc.toprettyxml(indent="    ", encoding="UTF-8"))
        finally:
            f.close()
Example #36
0
def writeXml(tmp, imgname, w, h, objs, wxml):
    doc = Document()
    #owner
    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)
    #owner
    folder = doc.createElement('folder')
    annotation.appendChild(folder)
    foldename = os.path.dirname(imgname).split("/")[-1]
    folder_txt = doc.createTextNode(foldename)
    folder.appendChild(folder_txt)

    filename = doc.createElement('filename')
    annotation.appendChild(filename)
    imgInfor = os.path.basename(imgname).split(".")
    filename_txt = doc.createTextNode(imgInfor[0])
    filename.appendChild(filename_txt)

    pathname = doc.createElement('path')
    annotation.appendChild(pathname)
    pathname_txt = doc.createTextNode(imgname)
    pathname.appendChild(pathname_txt)

    #ones#
    source = doc.createElement('source')
    annotation.appendChild(source)

    database = doc.createElement('database')
    source.appendChild(database)
    database_txt = doc.createTextNode("VOC2007 Database")
    database.appendChild(database_txt)

    # annotation_new = doc.createElement('annotation')
    # source.appendChild(annotation_new)
    # annotation_new_txt = doc.createTextNode("PASCAL VOC2007")
    # annotation_new.appendChild(annotation_new_txt)

    image = doc.createElement('image')
    source.appendChild(image)
    image_txt = doc.createTextNode(os.path.basename(imgname).split(".")[0])
    image.appendChild(image_txt)
    #onee#
    #twos#
    size = doc.createElement('size')
    annotation.appendChild(size)

    width = doc.createElement('width')
    size.appendChild(width)
    width_txt = doc.createTextNode(str(w))
    width.appendChild(width_txt)

    height = doc.createElement('height')
    size.appendChild(height)
    height_txt = doc.createTextNode(str(h))
    height.appendChild(height_txt)

    depth = doc.createElement('depth')
    size.appendChild(depth)
    depth_txt = doc.createTextNode("3")
    depth.appendChild(depth_txt)
    #twoe#
    segmented = doc.createElement('segmented')
    annotation.appendChild(segmented)
    segmented_txt = doc.createTextNode("0")
    segmented.appendChild(segmented_txt)

    size = [w, h]

    for obj in objs:
        #threes#
        object_new = doc.createElement("object")
        annotation.appendChild(object_new)

        name = doc.createElement('name')
        object_new.appendChild(name)
        name_txt = doc.createTextNode(obj[0])
        name.appendChild(name_txt)

        pose = doc.createElement('pose')
        object_new.appendChild(pose)
        pose_txt = doc.createTextNode("Unspecified")
        pose.appendChild(pose_txt)

        truncated = doc.createElement('truncated')
        object_new.appendChild(truncated)
        truncated_txt = doc.createTextNode("0")
        truncated.appendChild(truncated_txt)

        difficult = doc.createElement(
            'Difficult'
        )  # difficult = doc.createElement('difficult') in VOC2007
        object_new.appendChild(difficult)
        difficult_txt = doc.createTextNode("0")
        difficult.appendChild(difficult_txt)
        #threes-1#
        bndbox = doc.createElement('bndbox')
        object_new.appendChild(bndbox)

        box = convert(size, float(obj[1]), float(obj[2]), float(obj[3]),
                      float(obj[4]))

        xmin = doc.createElement('xmin')
        bndbox.appendChild(xmin)
        xmin_txt = doc.createTextNode(str(box[0]))
        xmin.appendChild(xmin_txt)

        ymin = doc.createElement('ymin')
        bndbox.appendChild(ymin)
        ymin_txt = doc.createTextNode(str(box[1]))
        ymin.appendChild(ymin_txt)

        xmax = doc.createElement('xmax')
        bndbox.appendChild(xmax)
        xmax_txt = doc.createTextNode(str(box[2]))
        xmax.appendChild(xmax_txt)

        ymax = doc.createElement('ymax')
        bndbox.appendChild(ymax)
        ymax_txt = doc.createTextNode(str(box[3]))
        ymax.appendChild(ymax_txt)
        #threee-1#
        #threee#

    tempfile = tmp + "/" + "temp.xml"
    with open(tempfile, "w") as f:
        # print(doc.toprettyxml())
        f.write(doc.toprettyxml(indent='\t'))

    rewrite = open(tempfile, "r")
    lines = rewrite.read().split('\n')
    newlines = lines[
        1:len(lines) -
        1]  # ['<?xml version="1.0" ?>', '<annotation>', '</annotation>', '']

    fw = open(wxml, "w")
    for i in range(0, len(newlines)):
        fw.write(newlines[i] + '\n')

    fw.close()
    rewrite.close()
    os.remove(tempfile)
    return
Example #37
0
def make_v0(apps, apks, repodir, repodict, requestsdict,
            fdroid_signing_key_fingerprints):
    """
    aka index.jar aka index.xml
    """

    doc = Document()

    def addElement(name, value, doc, parent):
        el = doc.createElement(name)
        el.appendChild(doc.createTextNode(value))
        parent.appendChild(el)

    def addElementNonEmpty(name, value, doc, parent):
        if not value:
            return
        addElement(name, value, doc, parent)

    def addElementIfInApk(name, apk, key, doc, parent):
        if key not in apk:
            return
        value = str(apk[key])
        addElement(name, value, doc, parent)

    def addElementCDATA(name, value, doc, parent):
        el = doc.createElement(name)
        el.appendChild(doc.createCDATASection(value))
        parent.appendChild(el)

    def addElementCheckLocalized(name, app, key, doc, parent, default=''):
        '''Fill in field from metadata or localized block

        For name/summary/description, they can come only from the app source,
        or from a dir in fdroiddata.  They can be entirely missing from the
        metadata file if there is localized versions.  This will fetch those
        from the localized version if its not available in the metadata file.
        '''

        el = doc.createElement(name)
        value = app.get(key)
        lkey = key[:1].lower() + key[1:]
        localized = app.get('localized')
        if not value and localized:
            for lang in ['en-US'] + [x for x in localized.keys()]:
                if not lang.startswith('en'):
                    continue
                if lang in localized:
                    value = localized[lang].get(lkey)
                    if value:
                        break
        if not value and localized and len(localized) > 1:
            lang = list(localized.keys())[0]
            value = localized[lang].get(lkey)
        if not value:
            value = default
        el.appendChild(doc.createTextNode(value))
        parent.appendChild(el)

    root = doc.createElement("fdroid")
    doc.appendChild(root)

    repoel = doc.createElement("repo")

    repoel.setAttribute("name", repodict['name'])
    if 'maxage' in repodict:
        repoel.setAttribute("maxage", str(repodict['maxage']))
    repoel.setAttribute("icon", os.path.basename(repodict['icon']))
    repoel.setAttribute("url", repodict['address'])
    addElement('description', repodict['description'], doc, repoel)
    for mirror in repodict.get('mirrors', []):
        addElement('mirror', mirror, doc, repoel)

    repoel.setAttribute("version", str(repodict['version']))
    repoel.setAttribute("timestamp", '%d' % repodict['timestamp'].timestamp())

    pubkey, repo_pubkey_fingerprint = extract_pubkey()
    repoel.setAttribute("pubkey", pubkey.decode('utf-8'))
    root.appendChild(repoel)

    for command in ('install', 'uninstall'):
        for packageName in requestsdict[command]:
            element = doc.createElement(command)
            root.appendChild(element)
            element.setAttribute('packageName', packageName)

    for appid, appdict in apps.items():
        app = metadata.App(appdict)

        if app.Disabled is not None:
            continue

        # Get a list of the apks for this app...
        apklist = []
        apksbyversion = collections.defaultdict(lambda: [])
        for apk in apks:
            if apk.get('versionCode') and apk.get('packageName') == appid:
                apksbyversion[apk['versionCode']].append(apk)
        for versionCode, apksforver in apksbyversion.items():
            fdroidsig = fdroid_signing_key_fingerprints.get(appid,
                                                            {}).get('signer')
            fdroid_signed_apk = None
            name_match_apk = None
            for x in apksforver:
                if fdroidsig and x.get('signer', None) == fdroidsig:
                    fdroid_signed_apk = x
                if common.apk_release_filename.match(x.get('apkName', '')):
                    name_match_apk = x
            # choose which of the available versions is most
            # suiteable for index v0
            if fdroid_signed_apk:
                apklist.append(fdroid_signed_apk)
            elif name_match_apk:
                apklist.append(name_match_apk)
            else:
                apklist.append(apksforver[0])

        if len(apklist) == 0:
            continue

        apel = doc.createElement("application")
        apel.setAttribute("id", app.id)
        root.appendChild(apel)

        addElement('id', app.id, doc, apel)
        if app.added:
            addElement('added', app.added.strftime('%Y-%m-%d'), doc, apel)
        if app.lastUpdated:
            addElement('lastupdated', app.lastUpdated.strftime('%Y-%m-%d'),
                       doc, apel)

        addElementCheckLocalized('name', app, 'Name', doc, apel)
        addElementCheckLocalized('summary', app, 'Summary', doc, apel)

        if app.icon:
            addElement('icon', app.icon, doc, apel)

        addElementCheckLocalized('desc', app, 'Description', doc, apel,
                                 '<p>No description available</p>')

        addElement('license', app.License, doc, apel)
        if app.Categories:
            addElement('categories', ','.join(app.Categories), doc, apel)
            # We put the first (primary) category in LAST, which will have
            # the desired effect of making clients that only understand one
            # category see that one.
            addElement('category', app.Categories[0], doc, apel)
        addElement('web', app.WebSite, doc, apel)
        addElement('source', app.SourceCode, doc, apel)
        addElement('tracker', app.IssueTracker, doc, apel)
        addElementNonEmpty('changelog', app.Changelog, doc, apel)
        addElementNonEmpty('author', app.AuthorName, doc, apel)
        addElementNonEmpty('email', app.AuthorEmail, doc, apel)
        addElementNonEmpty('donate', app.Donate, doc, apel)
        addElementNonEmpty('bitcoin', app.Bitcoin, doc, apel)
        addElementNonEmpty('litecoin', app.Litecoin, doc, apel)
        addElementNonEmpty('flattr', app.FlattrID, doc, apel)

        # These elements actually refer to the current version (i.e. which
        # one is recommended. They are historically mis-named, and need
        # changing, but stay like this for now to support existing clients.
        addElement('marketversion', app.CurrentVersion, doc, apel)
        addElement('marketvercode', app.CurrentVersionCode, doc, apel)

        if app.Provides:
            pv = app.Provides.split(',')
            addElementNonEmpty('provides', ','.join(pv), doc, apel)
        if app.RequiresRoot:
            addElement('requirements', 'root', doc, apel)

        # Sort the apk list into version order, just so the web site
        # doesn't have to do any work by default...
        apklist = sorted(apklist,
                         key=lambda apk: apk['versionCode'],
                         reverse=True)

        if 'antiFeatures' in apklist[0]:
            app.AntiFeatures.extend(apklist[0]['antiFeatures'])
        if app.AntiFeatures:
            addElementNonEmpty('antifeatures', ','.join(app.AntiFeatures), doc,
                               apel)

        # Check for duplicates - they will make the client unhappy...
        for i in range(len(apklist) - 1):
            first = apklist[i]
            second = apklist[i + 1]
            if first['versionCode'] == second['versionCode'] \
               and first['sig'] == second['sig']:
                if first['hash'] == second['hash']:
                    raise FDroidException(
                        '"{0}/{1}" and "{0}/{2}" are exact duplicates!'.format(
                            repodir, first['apkName'], second['apkName']))
                else:
                    raise FDroidException(
                        'duplicates: "{0}/{1}" - "{0}/{2}"'.format(
                            repodir, first['apkName'], second['apkName']))

        current_version_code = 0
        current_version_file = None
        for apk in apklist:
            file_extension = common.get_file_extension(apk['apkName'])
            # find the APK for the "Current Version"
            if current_version_code < apk['versionCode']:
                current_version_code = apk['versionCode']
            if current_version_code < int(app.CurrentVersionCode):
                current_version_file = apk['apkName']

            apkel = doc.createElement("package")
            apel.appendChild(apkel)
            addElement('version', apk['versionName'], doc, apkel)
            addElement('versioncode', str(apk['versionCode']), doc, apkel)
            addElement('apkname', apk['apkName'], doc, apkel)
            addElementIfInApk('srcname', apk, 'srcname', doc, apkel)

            hashel = doc.createElement("hash")
            hashel.setAttribute('type', 'sha256')
            hashel.appendChild(doc.createTextNode(apk['hash']))
            apkel.appendChild(hashel)

            addElement('size', str(apk['size']), doc, apkel)
            addElementIfInApk('sdkver', apk, 'minSdkVersion', doc, apkel)
            addElementIfInApk('targetSdkVersion', apk, 'targetSdkVersion', doc,
                              apkel)
            addElementIfInApk('maxsdkver', apk, 'maxSdkVersion', doc, apkel)
            addElementIfInApk('obbMainFile', apk, 'obbMainFile', doc, apkel)
            addElementIfInApk('obbMainFileSha256', apk, 'obbMainFileSha256',
                              doc, apkel)
            addElementIfInApk('obbPatchFile', apk, 'obbPatchFile', doc, apkel)
            addElementIfInApk('obbPatchFileSha256', apk, 'obbPatchFileSha256',
                              doc, apkel)
            if 'added' in apk:
                addElement('added', apk['added'].strftime('%Y-%m-%d'), doc,
                           apkel)

            if file_extension == 'apk':  # sig is required for APKs, but only APKs
                addElement('sig', apk['sig'], doc, apkel)

                old_permissions = set()
                sorted_permissions = sorted(apk['uses-permission'])
                for perm in sorted_permissions:
                    perm_name = perm.name
                    if perm_name.startswith("android.permission."):
                        perm_name = perm_name[19:]
                    old_permissions.add(perm_name)
                addElementNonEmpty('permissions',
                                   ','.join(sorted(old_permissions)), doc,
                                   apkel)

                for permission in sorted_permissions:
                    permel = doc.createElement('uses-permission')
                    permel.setAttribute('name', permission.name)
                    if permission.maxSdkVersion is not None:
                        permel.setAttribute('maxSdkVersion',
                                            '%d' % permission.maxSdkVersion)
                        apkel.appendChild(permel)
                for permission_sdk_23 in sorted(apk['uses-permission-sdk-23']):
                    permel = doc.createElement('uses-permission-sdk-23')
                    permel.setAttribute('name', permission_sdk_23.name)
                    if permission_sdk_23.maxSdkVersion is not None:
                        permel.setAttribute(
                            'maxSdkVersion',
                            '%d' % permission_sdk_23.maxSdkVersion)
                        apkel.appendChild(permel)
                if 'nativecode' in apk:
                    addElement('nativecode',
                               ','.join(sorted(apk['nativecode'])), doc, apkel)
                addElementNonEmpty('features',
                                   ','.join(sorted(apk['features'])), doc,
                                   apkel)

        if current_version_file is not None \
                and common.config['make_current_version_link'] \
                and repodir == 'repo':  # only create these
            namefield = common.config['current_version_name_source']
            sanitized_name = re.sub(b'''[ '"&%?+=/]''', b'',
                                    app.get(namefield).encode('utf-8'))
            apklinkname = sanitized_name + os.path.splitext(
                current_version_file)[1].encode('utf-8')
            current_version_path = os.path.join(repodir,
                                                current_version_file).encode(
                                                    'utf-8', 'surrogateescape')
            if os.path.islink(apklinkname):
                os.remove(apklinkname)
            os.symlink(current_version_path, apklinkname)
            # also symlink gpg signature, if it exists
            for extension in (b'.asc', b'.sig'):
                sigfile_path = current_version_path + extension
                if os.path.exists(sigfile_path):
                    siglinkname = apklinkname + extension
                    if os.path.islink(siglinkname):
                        os.remove(siglinkname)
                    os.symlink(sigfile_path, siglinkname)

    if common.options.pretty:
        output = doc.toprettyxml(encoding='utf-8')
    else:
        output = doc.toxml(encoding='utf-8')

    with open(os.path.join(repodir, 'index.xml'), 'wb') as f:
        f.write(output)

    if 'repo_keyalias' in common.config:

        if common.options.nosign:
            logging.info(
                _("Creating unsigned index in preparation for signing"))
        else:
            logging.info(_("Creating signed index with this key (SHA256):"))
            logging.info("%s" % repo_pubkey_fingerprint)

        # Create a jar of the index...
        jar_output = 'index_unsigned.jar' if common.options.nosign else 'index.jar'
        p = FDroidPopen(['jar', 'cf', jar_output, 'index.xml'], cwd=repodir)
        if p.returncode != 0:
            raise FDroidException("Failed to create {0}".format(jar_output))

        # Sign the index...
        signed = os.path.join(repodir, 'index.jar')
        if common.options.nosign:
            # Remove old signed index if not signing
            if os.path.exists(signed):
                os.remove(signed)
        else:
            signindex.config = common.config
            signindex.sign_jar(signed)

    # Copy the repo icon into the repo directory...
    icon_dir = os.path.join(repodir, 'icons')
    iconfilename = os.path.join(icon_dir,
                                os.path.basename(common.config['repo_icon']))
    shutil.copyfile(common.config['repo_icon'], iconfilename)
Example #38
0
def showgt():
    landmarkfile = open(landmarkpath)
    bboxfile = open(bboxpath)
    numofimgs = int(landmarkfile.readline())
    _ = landmarkfile.readline()
    _ = bboxfile.readline()
    _ = bboxfile.readline()
    index = 0
    pbar = progress.start()
    if convet2yoloformat:
        if not os.path.exists(labelsdir):
            os.mkdir(labelsdir)
    if convert2vocformat:
        if not os.path.exists(vocannotationdir):
            os.mkdir(vocannotationdir)


#    while(index<numofimgs):
    for i in pbar(range(numofimgs)):
        #pbar.update(int((index/(numofimgs-1))*10000))
        landmarkline = landmarkfile.readline().split()
        filename = landmarkline[0]
        #sys.stdout.write("\r"+str(index)+":"+filename)
        #sys.stdout.flush()
        imgpath = imgdir + "/" + filename
        img = cv2.imread(imgpath)
        landmarkline = landmarkline[1:]
        landmark = [int(pt) for pt in landmarkline]
        bboxline = bboxfile.readline().split()
        imgpath2 = imgdir + "/" + bboxline[0]
        bboxline = bboxline[1:]
        bbox = [int(bb) for bb in bboxline]
        drawbboxandlandmarks(img, bbox, landmark)
        if convet2yoloformat:
            height = img.shape[0]
            width = img.shape[1]
            txtpath = labelsdir + "/" + filename
            txtpath = txtpath[:-3] + "txt"
            ftxt = open(txtpath, 'w')
            xcenter = (bbox[0] + bbox[2] * 0.5) / width
            ycenter = (bbox[1] + bbox[3] * 0.5) / height
            wr = bbox[2] * 1.0 / width
            hr = bbox[3] * 1.0 / height
            line = "0 " + str(xcenter) + " " + str(ycenter) + " " + str(
                wr) + " " + str(hr) + "\n"
            ftxt.write(line)
            ftxt.close()
        if convert2vocformat:
            xmlpath = vocannotationdir + "/" + filename
            xmlpath = xmlpath[:-3] + "xml"
            doc = Document()
            annotation = doc.createElement('annotation')
            doc.appendChild(annotation)
            folder = doc.createElement('folder')
            folder_name = doc.createTextNode('CelebA')
            folder.appendChild(folder_name)
            annotation.appendChild(folder)
            filenamenode = doc.createElement('filename')
            filename_name = doc.createTextNode(filename)
            filenamenode.appendChild(filename_name)
            annotation.appendChild(filenamenode)
            source = doc.createElement('source')
            annotation.appendChild(source)
            database = doc.createElement('database')
            database.appendChild(doc.createTextNode('CelebA Database'))
            source.appendChild(database)
            annotation_s = doc.createElement('annotation')
            annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007'))
            source.appendChild(annotation_s)
            image = doc.createElement('image')
            image.appendChild(doc.createTextNode('flickr'))
            source.appendChild(image)
            flickrid = doc.createElement('flickrid')
            flickrid.appendChild(doc.createTextNode('-1'))
            source.appendChild(flickrid)
            owner = doc.createElement('owner')
            annotation.appendChild(owner)
            flickrid_o = doc.createElement('flickrid')
            flickrid_o.appendChild(doc.createTextNode('tdr'))
            owner.appendChild(flickrid_o)
            name_o = doc.createElement('name')
            name_o.appendChild(doc.createTextNode('yanyu'))
            owner.appendChild(name_o)
            size = doc.createElement('size')
            annotation.appendChild(size)
            width = doc.createElement('width')
            width.appendChild(doc.createTextNode(str(img.shape[1])))
            height = doc.createElement('height')
            height.appendChild(doc.createTextNode(str(img.shape[0])))
            depth = doc.createElement('depth')
            depth.appendChild(doc.createTextNode(str(img.shape[2])))
            size.appendChild(width)
            size.appendChild(height)
            size.appendChild(depth)
            segmented = doc.createElement('segmented')
            segmented.appendChild(doc.createTextNode('0'))
            annotation.appendChild(segmented)
            for i in range(1):
                objects = doc.createElement('object')
                annotation.appendChild(objects)
                object_name = doc.createElement('name')
                object_name.appendChild(doc.createTextNode('face'))
                objects.appendChild(object_name)
                pose = doc.createElement('pose')
                pose.appendChild(doc.createTextNode('Unspecified'))
                objects.appendChild(pose)
                truncated = doc.createElement('truncated')
                truncated.appendChild(doc.createTextNode('1'))
                objects.appendChild(truncated)
                difficult = doc.createElement('difficult')
                difficult.appendChild(doc.createTextNode('0'))
                objects.appendChild(difficult)
                bndbox = doc.createElement('bndbox')
                objects.appendChild(bndbox)
                xmin = doc.createElement('xmin')
                xmin.appendChild(doc.createTextNode(str(bbox[0])))
                bndbox.appendChild(xmin)
                ymin = doc.createElement('ymin')
                ymin.appendChild(doc.createTextNode(str(bbox[1])))
                bndbox.appendChild(ymin)
                xmax = doc.createElement('xmax')
                xmax.appendChild(doc.createTextNode(str(bbox[0] + bbox[2])))
                bndbox.appendChild(xmax)
                ymax = doc.createElement('ymax')
                ymax.appendChild(doc.createTextNode(str(bbox[1] + bbox[3])))
                bndbox.appendChild(ymax)
            f = open(xmlpath, "w")
            f.write(doc.toprettyxml(indent=''))
            f.close()
        cv2.imshow("img", img)
        cv2.waitKey(1)
        index = index + 1
    pbar.finish()
Example #39
0
def create():
    indexNum = 0  #数字下标
    #print (os.getcwd()) E:\JAVA\NewWorkSpace\ApplePests\DataSetPretreat
    #if path exist return true else false ,function join merge dir path and file path
    #os.getcwd()return current path
    if os.path.exists(os.path.join(os.getcwd(), imgpath)):  #JPEGImages
        shutil.rmtree(imgpath)  #delete dir and file
    if os.path.exists(os.path.join(os.getcwd(), xmlpath_new)):  #Annotation
        shutil.rmtree(xmlpath_new)
    os.mkdir(os.path.join(os.getcwd(), imgpath))  #make new dir
    os.mkdir(os.path.join(os.getcwd(), xmlpath_new))
    for category in os.listdir(labels):  #return all file names
        labelCategoryPath = os.path.join(labels, category)
        pretreatCategoryPath = os.path.join(pretreat, category)
        for label in os.listdir(labelCategoryPath):
            pictureName = label.replace('.txt', '.jpg')  #预处理的图片名
            indexName = "%06d" % indexNum  #新文件名称
            picturePathIndexName = os.path.join(imgpath,
                                                indexName + ".jpg")  #新图片路径
            pretreatPicturePath = os.path.join(pretreatCategoryPath,
                                               pictureName)  #预处理的图片路径
            #拷贝文件并命名为pictureIndexName.jpg
            shutil.copy(pretreatPicturePath, picturePathIndexName)
            #open(picturePathIndexName, "wb").write(open(pretreatPicturePath, "rb").read())
            fidin = open(labelCategoryPath + '/' + label, 'r')
            objIndex = 0
            L = []
            for data in islice(fidin, 1, None):
                objIndex += 1
                data = data.strip('\n')
                datas = data.split(' ')
                if 5 != len(datas):
                    print('bounding box information error')
                    continue
                L.append(datas)
            #imageFile = imgpath + pictureName
            #img = cv2.imread(imageFile)
            img = Image.open(picturePathIndexName)
            imgSize = img.size
            imgSize = imgSize + (3, )
            #xmlName = each.replace('.txt', '.xml')
            #f = open(xmlpath_new + indexName + ".xml", "w")
            f = open(os.path.join(xmlpath_new, indexName + ".xml"), "w")
            doc = Document()
            annotation = doc.createElement('annotation')
            doc.appendChild(annotation)

            folder = doc.createElement('folder')
            folder.appendChild(doc.createTextNode(foldername))
            annotation.appendChild(folder)

            filename = doc.createElement('filename')
            filename.appendChild(doc.createTextNode(indexName + ".jpg"))
            annotation.appendChild(filename)

            source = doc.createElement('source')
            database = doc.createElement('database')
            database.appendChild(doc.createTextNode('My Database'))
            source.appendChild(database)
            source_annotation = doc.createElement('annotation')
            source_annotation.appendChild(doc.createTextNode(foldername))
            source.appendChild(source_annotation)
            image = doc.createElement('image')
            image.appendChild(doc.createTextNode('flickr'))
            source.appendChild(image)
            flickrid = doc.createElement('flickrid')
            flickrid.appendChild(doc.createTextNode('NULL'))
            source.appendChild(flickrid)
            annotation.appendChild(source)

            owner = doc.createElement('owner')
            flickrid = doc.createElement('flickrid')
            flickrid.appendChild(doc.createTextNode('NULL'))
            owner.appendChild(flickrid)
            name = doc.createElement('name')
            name.appendChild(doc.createTextNode('idaneel'))
            owner.appendChild(name)
            annotation.appendChild(owner)

            size = doc.createElement('size')
            width = doc.createElement('width')
            width.appendChild(doc.createTextNode(str(imgSize[0])))
            size.appendChild(width)
            height = doc.createElement('height')
            height.appendChild(doc.createTextNode(str(imgSize[1])))
            size.appendChild(height)
            depth = doc.createElement('depth')
            depth.appendChild(doc.createTextNode(str(imgSize[2])))
            size.appendChild(depth)
            annotation.appendChild(size)

            segmented = doc.createElement('segmented')
            segmented.appendChild(doc.createTextNode(str(0)))
            annotation.appendChild(segmented)
            for i in range(len(L)):
                annotation.appendChild(insertObject(doc, L, i))
            try:
                f.write(doc.toprettyxml(indent='    '))
                f.close()
                fidin.close()
            except:
                pass
            indexNum += 1
Example #40
0
def create():
    for walk in os.walk(labels):
        for each in walk[2]:
            fidin = open(walk[0] + '/' + each, 'r')
            objIndex = 0
            for data in islice(fidin, 1, None):
                objIndex += 1
                data = data.strip('\n')
                datas = data.split(' ')
                if 5 != len(datas):
                    print 'bounding box information error'
                    continue
                # changed by dejian,li
                #pictureName = each.replace('.txt', '.jpg')    # changed by dejian,li
                pictureName = each.replace('.txt', '.jpg')
                print pictureName
                # imgpath = '/home/lord/programs/BBox-Label-Tool-master/Images/2/'
                imageFile = imgpath + pictureName
                img = cv2.imread(imageFile)
                if img == None:
                    pictureName = each.replace('.txt', '.JPG')
                    #print pictureName
                    # imgpath = '/home/lord/programs/BBox-Label-Tool-master/Images/2/'
                    imageFile = imgpath + pictureName
                    #print imageFile
                    img = cv2.imread(imageFile)
                imgSize = img.shape
                if 1 == objIndex:
                    xmlName = each.replace('.txt', '.xml')
                    f = open(xmlpath_new + xmlName, "w")
                    doc = Document()
                    annotation = doc.createElement('annotation')
                    doc.appendChild(annotation)

                    folder = doc.createElement('folder')
                    folder.appendChild(doc.createTextNode(foldername))
                    annotation.appendChild(folder)

                    filename = doc.createElement('filename')
                    filename.appendChild(doc.createTextNode(pictureName))
                    annotation.appendChild(filename)

                    source = doc.createElement('source')
                    database = doc.createElement('database')
                    database.appendChild(doc.createTextNode('My Database'))
                    source.appendChild(database)
                    source_annotation = doc.createElement('annotation')
                    source_annotation.appendChild(
                        doc.createTextNode(foldername))
                    source.appendChild(source_annotation)
                    image = doc.createElement('image')
                    image.appendChild(doc.createTextNode('flickr'))
                    source.appendChild(image)
                    flickrid = doc.createElement('flickrid')
                    flickrid.appendChild(doc.createTextNode('NULL'))
                    source.appendChild(flickrid)
                    annotation.appendChild(source)

                    owner = doc.createElement('owner')
                    flickrid = doc.createElement('flickrid')
                    flickrid.appendChild(doc.createTextNode('NULL'))
                    owner.appendChild(flickrid)
                    name = doc.createElement('name')
                    name.appendChild(doc.createTextNode('idaneel'))
                    owner.appendChild(name)
                    annotation.appendChild(owner)

                    size = doc.createElement('size')
                    width = doc.createElement('width')
                    width.appendChild(doc.createTextNode(str(imgSize[1])))
                    size.appendChild(width)
                    height = doc.createElement('height')
                    height.appendChild(doc.createTextNode(str(imgSize[0])))
                    size.appendChild(height)
                    depth = doc.createElement('depth')
                    depth.appendChild(doc.createTextNode(str(imgSize[2])))
                    size.appendChild(depth)
                    annotation.appendChild(size)

                    segmented = doc.createElement('segmented')
                    segmented.appendChild(doc.createTextNode(str(0)))
                    annotation.appendChild(segmented)
                    annotation.appendChild(insertObject(doc, datas))
                else:
                    annotation.appendChild(insertObject(doc, datas))
            try:
                f.write(doc.toprettyxml(indent='    '))
                f.close()
                fidin.close()
            except:
                pass
Example #41
0
def vendors(request):

    vens = []

    #pull vendors, filter by entity
    newdoc = Document();
    request = newdoc.createElement('request')
    newdoc.appendChild(request)
    control = newdoc.createElement('control')
    request.appendChild(control)
    senderid = newdoc.createElement('senderid')
    control.appendChild(senderid).appendChild(newdoc.createTextNode(acc_keys.int_sender_id()))
    senderpassword = newdoc.createElement('password')
    control.appendChild(senderpassword).appendChild(newdoc.createTextNode(acc_keys.int_sender_pass()))
    controlid = newdoc.createElement('controlid')
    control.appendChild(controlid).appendChild(newdoc.createTextNode(str(int(time.time()))))
    uniqueid = newdoc.createElement('uniqueid')
    control.appendChild(uniqueid).appendChild(newdoc.createTextNode("false"))
    dtdversion = newdoc.createElement('dtdversion')
    control.appendChild(dtdversion).appendChild(newdoc.createTextNode("3.0"))
    includewhitespace = newdoc.createElement('includewhitespace')
    control.appendChild(includewhitespace).appendChild(newdoc.createTextNode("false"))

    operation = newdoc.createElement('operation')
    request.appendChild(operation)

    authentication = newdoc.createElement('authentication')
    operation.appendChild(operation)

    s = Session.objects.order_by('-session_time')
    ses = s[0].sessionid

    sessionid = newdoc.createElement('sessionid')
    authentication.appendChild(sessionid).appendChild(newdoc.createTextNode(ses))

    content = newdoc.createElement('content')
    operation.appendChild(content)

    function = newdoc.createElement('function')
    content.appendChild(function).setAttributeNode(newdoc.createAttribute('controlid'))
    function.attributes["controlid"].value = "1"

    read = newdoc.createElement('readByQuery')
    function.appendChild(read)

    objectt = newdoc.createElement('object')
    read.appendChild(objectt).appendChild(newdoc.createTextNode('VENDOR'))

    fields = newdoc.createElement('fields')
    read.appendChild(objectt).appendChild(newdoc.createTextNode('*'))

    query = newdoc.createElement('query')
    read.appendChild(query)

    pagesize = newdoc.createElement('pagesize')
    read.appendChild(pagesize).appendChild(newdoc.createTextNode('3'))

    print(request.toprettyxml())
    #print(request)
    # Post the request
    #result = XMLRequestClient.post(request)
    '''
    for vendor in result.getElementsByTagName('vendor'):
        for tag in vendor.getElementsByTagName('DISPLAYCONTACT.PRINTAS'):
            ven = tag[0].firstChild.nodeValue
            vens.append(ven)
    '''

    #paginate
    #finish pagination
    #send list
    context = {vens}
    return render(request, 'intacct/vendors.html', context)
Example #42
0
def show_annotations():
    if not os.path.exists(Annotationsdir):
        os.mkdir(Annotationsdir)
    if not os.path.exists(labelsdir):
        os.mkdir(labelsdir)
    for i in range(10):
        annotationfilepath = annotationdir + "/FDDB-fold-%0*d-ellipseList.txt" % (
            2, i + 1)
        annotationfile = open(annotationfilepath)
        while (True):
            filename = annotationfile.readline()[:-1] + ".jpg"
            if not filename:
                break
            line = annotationfile.readline()
            if not line:
                break
            print(filename)
            facenum = (int)(line)
            img = cv2.imread(origimagedir + "/" + filename)
            filename = filename.replace('/', '_')
            cv2.imwrite(imagesdir + "/" + filename, img)
            w = img.shape[1]
            h = img.shape[0]
            if bsavetxtanno:
                labelpath = labelsdir + "/" + filename.replace(
                    '/', '_')[:-3] + "txt"
                labelfile = open(labelpath, 'w')
            if bsavexmlanno:
                xmlpath = Annotationsdir + "/" + filename.replace(
                    '/', '_')[:-3] + "txt"
                xmlpath = xmlpath[:-3] + "xml"
                doc = Document()
                annotation = doc.createElement('annotation')
                doc.appendChild(annotation)
                folder = doc.createElement('folder')
                folder_name = doc.createTextNode('fddb')
                folder.appendChild(folder_name)
                annotation.appendChild(folder)
                filenamenode = doc.createElement('filename')
                filename_name = doc.createTextNode(filename)
                filenamenode.appendChild(filename_name)
                annotation.appendChild(filenamenode)
                source = doc.createElement('source')
                annotation.appendChild(source)
                database = doc.createElement('database')
                database.appendChild(doc.createTextNode('fddb Database'))
                source.appendChild(database)
                annotation_s = doc.createElement('annotation')
                annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007'))
                source.appendChild(annotation_s)
                image = doc.createElement('image')
                image.appendChild(doc.createTextNode('flickr'))
                source.appendChild(image)
                flickrid = doc.createElement('flickrid')
                flickrid.appendChild(doc.createTextNode('-1'))
                source.appendChild(flickrid)
                owner = doc.createElement('owner')
                annotation.appendChild(owner)
                flickrid_o = doc.createElement('flickrid')
                flickrid_o.appendChild(doc.createTextNode('yanyu'))
                owner.appendChild(flickrid_o)
                name_o = doc.createElement('name')
                name_o.appendChild(doc.createTextNode('yanyu'))
                owner.appendChild(name_o)
                size = doc.createElement('size')
                annotation.appendChild(size)
                width = doc.createElement('width')
                width.appendChild(doc.createTextNode(str(img.shape[1])))
                height = doc.createElement('height')
                height.appendChild(doc.createTextNode(str(img.shape[0])))
                depth = doc.createElement('depth')
                depth.appendChild(doc.createTextNode(str(img.shape[2])))
                size.appendChild(width)
                size.appendChild(height)
                size.appendChild(depth)
                segmented = doc.createElement('segmented')
                segmented.appendChild(doc.createTextNode('0'))
                annotation.appendChild(segmented)
            for j in range(facenum):
                line = annotationfile.readline().strip().split()
                major_axis_radius = (float)(line[0])
                minor_axis_radius = (float)(line[1])
                angle = (float)(line[2])
                center_x = (float)(line[3])
                center_y = (float)(line[4])
                score = (float)(line[5])
                angle = angle / 3.1415926 * 180
                cv2.ellipse(img, ((int)(center_x), (int)(center_y)),
                            ((int)(major_axis_radius),
                             (int)(minor_axis_radius)), angle, 0., 360.,
                            (255, 0, 0))
                if convert2rects:
                    mask = np.zeros((img.shape[0], img.shape[1]),
                                    dtype=np.uint8)
                    cv2.ellipse(mask, ((int)(center_x), (int)(center_y)),
                                ((int)(major_axis_radius),
                                 (int)(minor_axis_radius)), angle, 0., 360.,
                                (255, 255, 255))
                    #cv2.imshow("mask",mask)
                    contours, hierarchy = cv2.findContours(
                        mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
                    for k in range(len(contours)):
                        r = cv2.boundingRect(contours[k])
                        x_min = r[0]
                        y_min = r[1]
                        x_max = r[0] + r[2]
                        y_max = r[1] + r[3]
                        xcenter = r[0] + r[2] / 2
                        ycenter = r[1] + r[3] / 2
                        if bsavetxtanno:
                            labelline = "0" + "\t" + str(
                                xcenter * 1.0 / w) + '\t' + str(
                                    ycenter * 1.0 / h) + '\t' + str(
                                        r[2] * 1.0 / w) + '\t' + str(
                                            r[3] * 1.0 / h) + '\n'
                            labelfile.write(labelline)
                        if bsavexmlanno:
                            object = doc.createElement('object')
                            annotation.appendChild(object)
                            object_name = doc.createElement('name')
                            object_name.appendChild(doc.createTextNode('face'))
                            object.appendChild(object_name)
                            pose = doc.createElement('pose')
                            pose.appendChild(doc.createTextNode('Unspecified'))
                            object.appendChild(pose)
                            truncated = doc.createElement('truncated')
                            truncated.appendChild(doc.createTextNode('1'))
                            object.appendChild(truncated)
                            difficult = doc.createElement('difficult')
                            difficult.appendChild(doc.createTextNode('0'))
                            object.appendChild(difficult)
                            bndbox = doc.createElement('bndbox')
                            object.appendChild(bndbox)
                            xmin = doc.createElement('xmin')
                            xmin.appendChild(doc.createTextNode(str(x_min)))
                            bndbox.appendChild(xmin)
                            ymin = doc.createElement('ymin')
                            ymin.appendChild(doc.createTextNode(str(y_min)))
                            bndbox.appendChild(ymin)
                            xmax = doc.createElement('xmax')
                            xmax.appendChild(doc.createTextNode(str(x_max)))
                            bndbox.appendChild(xmax)
                            ymax = doc.createElement('ymax')
                            ymax.appendChild(doc.createTextNode(str(y_max)))
                            bndbox.appendChild(ymax)
                        cv2.rectangle(img, (int(x_min), int(y_min)),
                                      (int(x_max), int(y_max)), (0, 0, 255))
            if bsavetxtanno:
                labelfile.close()
            if bsavexmlanno:
                f = open(xmlpath, "w")
                f.write(doc.toprettyxml(indent=''))
                f.close()
            cv2.imshow("img", img)
            cv2.waitKey(1)
Example #43
0
def generate_xml(name, split_lines, img_size, class_ind):
    doc = Document()  # 创建DOM文档对象
    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)
    title = doc.createElement('folder')
    title_text = doc.createTextNode('KITTI')
    title.appendChild(title_text)
    annotation.appendChild(title)
    img_name = name + '.png'
    title = doc.createElement('filename')
    title_text = doc.createTextNode(img_name)
    title.appendChild(title_text)
    annotation.appendChild(title)
    source = doc.createElement('source')
    annotation.appendChild(source)
    title = doc.createElement('database')
    title_text = doc.createTextNode('The KITTI Database')
    title.appendChild(title_text)
    source.appendChild(title)
    title = doc.createElement('annotation')
    title_text = doc.createTextNode('KITTI')
    title.appendChild(title_text)
    source.appendChild(title)
    size = doc.createElement('size')
    annotation.appendChild(size)
    title = doc.createElement('width')
    title_text = doc.createTextNode(str(img_size[1]))
    title.appendChild(title_text)
    size.appendChild(title)
    title = doc.createElement('height')
    title_text = doc.createTextNode(str(img_size[0]))
    title.appendChild(title_text)
    size.appendChild(title)
    title = doc.createElement('depth')
    title_text = doc.createTextNode(str(img_size[2]))
    title.appendChild(title_text)
    size.appendChild(title)
    for split_line in split_lines:
        line = split_line.strip().split()
        if line[0] in class_ind:
            object = doc.createElement('object')
            annotation.appendChild(object)
            title = doc.createElement('name')
            title_text = doc.createTextNode(line[0])
            title.appendChild(title_text)
            object.appendChild(title)
            bndbox = doc.createElement('bndbox')
            object.appendChild(bndbox)
            title = doc.createElement('xmin')
            title_text = doc.createTextNode(str(int(float(line[4]))))
            title.appendChild(title_text)
            bndbox.appendChild(title)
            title = doc.createElement('ymin')
            title_text = doc.createTextNode(str(int(float(line[5]))))
            title.appendChild(title_text)
            bndbox.appendChild(title)
            title = doc.createElement('xmax')
            title_text = doc.createTextNode(str(int(float(line[6]))))
            title.appendChild(title_text)
            bndbox.appendChild(title)
            title = doc.createElement('ymax')
            title_text = doc.createTextNode(str(int(float(line[7]))))
            title.appendChild(title_text)
            bndbox.appendChild(title)
    # 将DOM对象doc写入文件
    f = open('Annotations/' + name + '.xml', 'w')
    f.write(doc.toprettyxml(indent=''))
    f.close()
Example #44
0
    def generate_name_id(value,
                         sp_nq,
                         sp_format=None,
                         cert=None,
                         debug=False,
                         nq=None):
        """
        Generates a nameID.

        :param value: fingerprint
        :type: string

        :param sp_nq: SP Name Qualifier
        :type: string

        :param sp_format: SP Format
        :type: string

        :param cert: IdP Public Cert to encrypt the nameID
        :type: string

        :param debug: Activate the xmlsec debug
        :type: bool

        :param nq: IDP Name Qualifier
        :type: string

        :returns: DOMElement | XMLSec nameID
        :rtype: string
        """
        doc = Document()
        name_id_container = doc.createElementNS(
            OneLogin_Saml2_Constants.NS_SAML, 'container')
        name_id_container.setAttribute("xmlns:saml",
                                       OneLogin_Saml2_Constants.NS_SAML)

        name_id = doc.createElement('saml:NameID')
        if sp_nq is not None:
            name_id.setAttribute('SPNameQualifier', sp_nq)
        if nq is not None:
            name_id.setAttribute('NameQualifier', nq)
        if sp_format is not None:
            name_id.setAttribute('Format', sp_format)
        name_id.appendChild(doc.createTextNode(value))
        name_id_container.appendChild(name_id)

        if cert is not None:
            xml = name_id_container.toxml()
            elem = fromstring(xml)

            error_callback_method = None
            if debug:
                error_callback_method = print_xmlsec_errors
            xmlsec.set_error_callback(error_callback_method)

            # Load the public cert
            mngr = xmlsec.KeysMngr()
            file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
            key_data = xmlsec.Key.load(file_cert.name,
                                       xmlsec.KeyDataFormatCertPem, None)
            key_data.name = basename(file_cert.name)
            mngr.addKey(key_data)
            file_cert.close()

            # Prepare for encryption
            enc_data = EncData(xmlsec.TransformAes128Cbc,
                               type=xmlsec.TypeEncElement)
            enc_data.ensureCipherValue()
            key_info = enc_data.ensureKeyInfo()
            # enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaPkcs1)
            enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaOaep)
            enc_key.ensureCipherValue()

            # Encrypt!
            enc_ctx = xmlsec.EncCtx(mngr)
            enc_ctx.encKey = xmlsec.Key.generate(xmlsec.KeyDataAes, 128,
                                                 xmlsec.KeyDataTypeSession)

            edata = enc_ctx.encryptXml(enc_data, elem[0])

            newdoc = parseString(
                tostring(edata, encoding='unicode').encode('utf-8'))

            if newdoc.hasChildNodes():
                child = newdoc.firstChild
                child.removeAttribute('xmlns')
                child.removeAttribute('xmlns:saml')
                child.setAttribute('xmlns:xenc',
                                   OneLogin_Saml2_Constants.NS_XENC)
                child.setAttribute('xmlns:dsig',
                                   OneLogin_Saml2_Constants.NS_DS)

            nodes = newdoc.getElementsByTagName("*")
            for node in nodes:
                if node.tagName == 'ns0:KeyInfo':
                    node.tagName = 'dsig:KeyInfo'
                    node.removeAttribute('xmlns:ns0')
                    node.setAttribute('xmlns:dsig',
                                      OneLogin_Saml2_Constants.NS_DS)
                else:
                    node.tagName = 'xenc:' + node.tagName

            encrypted_id = newdoc.createElement('saml:EncryptedID')
            encrypted_data = newdoc.replaceChild(encrypted_id,
                                                 newdoc.firstChild)
            encrypted_id.appendChild(encrypted_data)
            return newdoc.saveXML(encrypted_id)
        else:
            return doc.saveXML(name_id)
Example #45
0
doc = Document()
wordbook = doc.createElement('wordbook')
match = re.compile(u'(\d+)\.(.*?)([\u4e00-\u9fa5].*)')
with open('d:\\a.txt', 'r') as myfile:
    content = myfile.readlines()
    for line in content:
        # print line
        item = doc.createElement('item')
        word = doc.createElement('word')
        trans = doc.createElement('trans')
        phonetic = doc.createElement('phonetic')
        tags = doc.createElement('tags')
        progress = doc.createElement('progress')

        matches = match.findall(line.decode())
        word.appendChild(doc.createCDATASection(matches[0][1]))
        trans.appendChild(doc.createCDATASection(matches[0][2]))
        progress.appendChild(doc.createTextNode('0'))
        phonetic.appendChild(doc.createTextNode(''))
        tags.appendChild(doc.createTextNode(''))
        item.appendChild(word)
        item.appendChild(trans)
        item.appendChild(phonetic)
        item.appendChild(tags)
        item.appendChild(progress)
        wordbook.appendChild(item)
    doc.appendChild(wordbook)
objxml = open('d:\\word.xml', 'w')
objxml.write(doc.toprettyxml(indent="  "))
objxml.close()
Example #46
0
def makexml(txtPath, xmlPath, picPath):  #读取txt路径,xml保存路径,数据集图片所在路径
    dict = {
        '1': "apple",  #字典对类型进行转换
        '2': "egg",
        '3': "mihoutao",
        '4': "qingmang",
        '5': "xihulu",
        '6': "xihongshi",
        '7': "bocai",
        '8': "shengcai",
        '9': "youcai",
        '10': "hongyuanjiao"
    }
    files = os.listdir(txtPath)
    for i, name in enumerate(files):
        xmlBuilder = Document()
        annotation = xmlBuilder.createElement("annotation")  # 创建annotation标签
        xmlBuilder.appendChild(annotation)
        txtFile = open(txtPath + name)
        txtList = txtFile.readlines()
        img = cv2.imread(picPath + name[0:-4] + ".jpg")
        Pheight, Pwidth, Pdepth = img.shape
        for i in txtList:
            oneline = i.strip().split(" ")

            folder = xmlBuilder.createElement("folder")  #folder标签
            folderContent = xmlBuilder.createTextNode("VOC2007")
            folder.appendChild(folderContent)
            annotation.appendChild(folder)

            filename = xmlBuilder.createElement("filename")  #filename标签
            filenameContent = xmlBuilder.createTextNode(name[0:-4] + ".jpg")
            filename.appendChild(filenameContent)
            annotation.appendChild(filename)

            size = xmlBuilder.createElement("size")  # size标签
            width = xmlBuilder.createElement("width")  # size子标签width
            widthContent = xmlBuilder.createTextNode(str(Pwidth))
            width.appendChild(widthContent)
            size.appendChild(width)
            height = xmlBuilder.createElement("height")  # size子标签height
            heightContent = xmlBuilder.createTextNode(str(Pheight))
            height.appendChild(heightContent)
            size.appendChild(height)
            depth = xmlBuilder.createElement("depth")  # size子标签depth
            depthContent = xmlBuilder.createTextNode(str(Pdepth))
            depth.appendChild(depthContent)
            size.appendChild(depth)
            annotation.appendChild(size)

            object = xmlBuilder.createElement("object")
            picname = xmlBuilder.createElement("name")
            nameContent = xmlBuilder.createTextNode(dict[oneline[0]])
            picname.appendChild(nameContent)
            object.appendChild(picname)
            pose = xmlBuilder.createElement("pose")
            poseContent = xmlBuilder.createTextNode("Unspecified")
            pose.appendChild(poseContent)
            object.appendChild(pose)
            truncated = xmlBuilder.createElement("truncated")
            truncatedContent = xmlBuilder.createTextNode("0")
            truncated.appendChild(truncatedContent)
            object.appendChild(truncated)
            difficult = xmlBuilder.createElement("difficult")
            difficultContent = xmlBuilder.createTextNode("0")
            difficult.appendChild(difficultContent)
            object.appendChild(difficult)
            bndbox = xmlBuilder.createElement("bndbox")
            xmin = xmlBuilder.createElement("xmin")
            mathData = int(((float(oneline[1])) * Pwidth + 1) -
                           (float(oneline[3])) * 0.5 * Pwidth)
            xminContent = xmlBuilder.createTextNode(str(mathData))
            xmin.appendChild(xminContent)
            bndbox.appendChild(xmin)
            ymin = xmlBuilder.createElement("ymin")
            mathData = int(((float(oneline[2])) * Pheight + 1) -
                           (float(oneline[4])) * 0.5 * Pheight)
            yminContent = xmlBuilder.createTextNode(str(mathData))
            ymin.appendChild(yminContent)
            bndbox.appendChild(ymin)
            xmax = xmlBuilder.createElement("xmax")
            mathData = int(((float(oneline[1])) * Pwidth + 1) +
                           (float(oneline[3])) * 0.5 * Pwidth)
            xmaxContent = xmlBuilder.createTextNode(str(mathData))
            xmax.appendChild(xmaxContent)
            bndbox.appendChild(xmax)
            ymax = xmlBuilder.createElement("ymax")
            mathData = int(((float(oneline[2])) * Pheight + 1) +
                           (float(oneline[4])) * 0.5 * Pheight)
            ymaxContent = xmlBuilder.createTextNode(str(mathData))
            ymax.appendChild(ymaxContent)
            bndbox.appendChild(ymax)
            object.appendChild(bndbox)

            annotation.appendChild(object)

        f = open(xmlPath + name[0:-4] + ".xml", 'w')
        xmlBuilder.writexml(f,
                            indent='\t',
                            newl='\n',
                            addindent='\t',
                            encoding='utf-8')
        f.close()
def ConvertVOCXml(file_path="",file_name=""):
   tree = ET.parse(file_name)
   root = tree.getroot()
   # print(root.tag)

   num=0 #计数
   #读xml操作

   frame_lists=[]
   output_file_name=""
   for child in root:

      if(child.tag=="frame"):
          # 创建dom文档
         doc = Document()
         # 创建根节点
         annotation = doc.createElement('annotation')
         # 根节点插入dom树
         doc.appendChild(annotation)

         #print(child.tag, child.attrib["num"])
         pic_id= child.attrib["num"].zfill(5)
         #print(pic_id)
         output_file_name=root.attrib["name"]+"__img"+pic_id+".xml"
        #  print(output_file_name)

         folder = doc.createElement("folder")
         folder.appendChild(doc.createTextNode("VOC2007"))
         annotation.appendChild(folder)

         filename = doc.createElement("filename")
         pic_name=root.attrib["name"]+"__img"+pic_id+".jpg"
         filename.appendChild(doc.createTextNode(pic_name))
         annotation.appendChild(filename)

         sizeimage = doc.createElement("size")
         imagewidth = doc.createElement("width")
         imageheight = doc.createElement("height")
         imagedepth = doc.createElement("depth")

         imagewidth.appendChild(doc.createTextNode("960"))
         imageheight.appendChild(doc.createTextNode("540"))
         imagedepth.appendChild(doc.createTextNode("3"))

         sizeimage.appendChild(imagedepth)
         sizeimage.appendChild(imagewidth)
         sizeimage.appendChild(imageheight)
         annotation.appendChild(sizeimage)

         target_list=child.getchildren()[0]  #获取target_list
         #print(target_list.tag)
         object=None
         for target in target_list:
             if(target.tag=="target"):
                 #print(target.tag)
                 object = doc.createElement('object')
                 bndbox = doc.createElement("bndbox")

                 for target_child in target:
                     if(target_child.tag=="box"):
                         xmin = doc.createElement("xmin")
                         ymin = doc.createElement("ymin")
                         xmax = doc.createElement("xmax")
                         ymax = doc.createElement("ymax")
                         xmin_value=int(float(target_child.attrib["left"]))
                         ymin_value=int(float(target_child.attrib["top"]))
                         box_width_value=int(float(target_child.attrib["width"]))
                         box_height_value=int(float(target_child.attrib["height"]))
                         xmin.appendChild(doc.createTextNode(str(xmin_value)))
                         ymin.appendChild(doc.createTextNode(str(ymin_value)))
                         if(xmin_value+box_width_value>960):
                            xmax.appendChild(doc.createTextNode(str(960)))
                         else:
                            xmax.appendChild(doc.createTextNode(str(xmin_value+box_width_value)))
                         if(ymin_value+box_height_value>540):
                            ymax.appendChild(doc.createTextNode(str(540)))
                         else:
                            ymax.appendChild(doc.createTextNode(str(ymin_value+box_height_value)))

                     if(target_child.tag=="attribute"):
                         name = doc.createElement('name')
                         pose=doc.createElement('pose')
                         truncated=doc.createElement('truncated')
                         difficult=doc.createElement('difficult')

                         name.appendChild(doc.createTextNode("car"))
                         pose.appendChild(doc.createTextNode("Left"))  #随意指定
                         truncated.appendChild(doc.createTextNode("0"))  #随意指定
                         difficult.appendChild(doc.createTextNode("0"))  #随意指定

                         
                         object.appendChild(name)
                         object.appendChild(pose)
                         object.appendChild(truncated)
                         object.appendChild(difficult)
                         
                 bndbox.appendChild(xmin)
                 bndbox.appendChild(ymin)
                 bndbox.appendChild(xmax)
                 bndbox.appendChild(ymax)
                 object.appendChild(bndbox)
                 annotation.appendChild(object)


         file_path_out=os.path.join(file_path,output_file_name)
         f = open(file_path_out, 'w')
         f.write(doc.toprettyxml(indent=' ' * 4))
         f.close()
         num=num+1
   return num
Example #48
0
class RSS2Feed(object):
    """An RSS 2.0 feed."""

    class FeedError(Exception):
        """Error encountered while producing a feed."""

    def __init__(self, title, link, description):
        """Initialize the feed with the specified attributes.

        :param title: brief title for the feed
        :param link: URL for the page containing the syndicated content
        :param description: longer description for the feed
        """
        self._document = Document()
        rss_element = self._document.createElement('rss')
        rss_element.setAttribute('version', '2.0')
        self._document.appendChild(rss_element)
        self._channel = self._document.createElement('channel')
        rss_element.appendChild(self._channel)
        self._channel.appendChild(self._create_text_element('title', title))
        self._channel.appendChild(self._create_text_element('link', link))
        self._channel.appendChild(self._create_text_element('description', description))

    def _create_text_element(self, type_, text):
        """Create a text element and return it."""
        element = self._document.createElement(type_)
        element.appendChild(self._document.createTextNode(text))
        return element

    def append_item(self, title=None, link=None, description=None, pub_date=None):
        """Append the specified item to the feed.

        :param title: brief title for the item
        :param link: URL for the page for the item
        :param description: longer drescription for the item
        :param pub_date: UTC timestamp or datetime instance of the item's publication date
        """
        # Either title or description *must* be present
        if title is None and description is None:
            raise self.FeedError("Either title or description must be provided.")
        element = self._document.createElement('item')
        if not title is None:
            element.appendChild(self._create_text_element('title', title))
        if not link is None:
            element.appendChild(self._create_text_element('link', link))
        if not description is None:
            element.appendChild(self._create_text_element('description', description))
        if not pub_date is None:
            try:
                timestamp = int(pub_date)
            except TypeError:
                timestamp = timegm(pub_date.utctimetuple())
            element.appendChild(self._create_text_element('pubDate', formatdate(timestamp)))
        self._channel.appendChild(element)

    def get_xml(self):
        """Return the XML for the feed.

        :returns: XML representation of the RSS feed
        """
        return self._document.toxml()
Example #49
0
def _composition2musicxml(comp):
    doc = Document()
    score = doc.createElement("score-partwise")
    score.setAttribute("version", "2.0")

    # set title information
    if comp.title:
        title = doc.createElement("movement-title")
        title.appendChild(doc.createTextNode(str(comp.title)))
        score.appendChild(title)
    identification = doc.createElement("identification")

    # set author information
    if comp.author:
        author = doc.createElement("creator")
        author.setAttribute("type", "composer")
        author.appendChild(doc.createTextNode(str(comp.author)))
        identification.appendChild(author)

    # set additional info
    encoding = doc.createElement("encoding")
    software = doc.createElement("software")
    software.appendChild(doc.createTextNode("mingus"))
    encoding.appendChild(software)
    enc_date = doc.createElement("encoding-date")
    enc_date.appendChild(doc.createTextNode(str(datetime.date.today())))
    encoding.appendChild(enc_date)
    identification.appendChild(encoding)
    score.appendChild(identification)

    # add tracks
    part_list = doc.createElement("part-list")
    score.appendChild(part_list)
    for t in comp:
        track = _track2musicxml(t)
        score_part = doc.createElement("score-part")
        track.setAttribute("id", str(id(t)))
        score_part.setAttribute("id", str(id(t)))
        part_name = doc.createElement("part-name")
        part_name.appendChild(doc.createTextNode(t.name))
        score_part.appendChild(part_name)
        if t.instrument:

            # add instrument info
            score_inst = doc.createElement("score-instrument")
            score_inst.setAttribute("id", str(id(t.instrument)))
            name = doc.createElement("instrument-name")
            name.appendChild(doc.createTextNode(str(t.instrument.name)))
            score_inst.appendChild(name)
            score_part.appendChild(score_inst)

            # add midi instruments
            if isinstance(t.instrument, MidiInstrument):
                midi = doc.createElement("midi-instrument")
                midi.setAttribute("id", str(id(t.instrument)))
                channel = doc.createElement("midi-channel")
                channel.appendChild(doc.createTextNode(str(1)))  # what about
                # the MIDI
                # channels?
                program = doc.createElement("midi-program")
                program.appendChild(
                    doc.createTextNode(str(t.instrument.instrument_nr)))
                midi.appendChild(channel)
                midi.appendChild(program)
                score_part.appendChild(midi)
        part_list.appendChild(score_part)
        track.setAttribute("id", str(id(t)))
        score.appendChild(track)
    return score
Example #50
0
def mask2xml(boxes, img_name, img_dir, img_size):
    #创建dom文档
    doc = Document()
    #创建根节点
    annotation = doc.createElement('annotation')
    #根节点插入dom树
    doc.appendChild(annotation)
    #插入folder
    folder = doc.createElement('folder')
    folder_text = doc.createTextNode('imgs')
    folder.appendChild(folder_text)
    annotation.appendChild(folder)
    #插入filename
    filename = doc.createElement('filename')
    filename_text = doc.createTextNode(img_name)
    filename.appendChild(filename_text)
    annotation.appendChild(filename)
    #插入文件路径
    path = doc.createElement('path')
    path_text = doc.createTextNode(img_dir + "\\" + img_name)
    path.appendChild(path_text)
    annotation.appendChild(path)
    #插入sorce
    source = doc.createElement('source')
    database = doc.createElement('database')
    database_text = doc.createTextNode('Unknown')
    database.appendChild(database_text)
    source.appendChild(database)
    annotation.appendChild(source)
    #插入图片大小
    size = doc.createElement('size')
    width = doc.createElement('width')
    width_text = doc.createTextNode(str(img_size[1]))
    width.appendChild(width_text)
    size.appendChild(width)
    height = doc.createElement('height')
    height_text = doc.createTextNode(str(img_size[0]))
    height.appendChild(height_text)
    size.appendChild(height)
    depth = doc.createElement('depth')
    depth_text = doc.createTextNode(str(img_size[2]))
    depth.appendChild(depth_text)
    size.appendChild(depth)
    annotation.appendChild(size)
    #插入segmented
    segmented = doc.createElement('segmented')
    segmented_text = doc.createTextNode('0')
    segmented.appendChild(segmented_text)
    annotation.appendChild(segmented)
    #插入object
    for box in boxes:
        object = doc.createElement('object')
        name = doc.createElement('name')
        name_text = doc.createTextNode('G0')
        name.appendChild(name_text)
        object.appendChild(name)
        pose = doc.createElement('pose')
        pose_text = doc.createTextNode('Unspecified')
        pose.appendChild(pose_text)
        object.appendChild(pose)
        truncated = doc.createElement('truncated')
        truncated_text = doc.createTextNode('0')
        truncated.appendChild(truncated_text)
        object.appendChild(truncated)
        difficult = doc.createElement('difficult')
        difficult_text = doc.createTextNode('0')
        difficult.appendChild(difficult_text)
        object.appendChild(difficult)
        bndbox = doc.createElement('bndbox')
        x, y, w, h = box
        xmin = doc.createElement('xmin')
        xmin_text = doc.createTextNode(str(x))
        xmin.appendChild(xmin_text)
        bndbox.appendChild(xmin)
        ymin = doc.createElement('ymin')
        ymin_text = doc.createTextNode(str(y))
        ymin.appendChild(ymin_text)
        bndbox.appendChild(ymin)
        xmax = doc.createElement('xmax')
        xmax_text = doc.createTextNode(str(x+w))
        xmax.appendChild(xmax_text)
        bndbox.appendChild(xmax)
        ymax = doc.createElement('ymax')
        ymax_text = doc.createTextNode(str(y+h))
        ymax.appendChild(ymax_text)
        bndbox.appendChild(ymax)
        object.appendChild(bndbox)
        annotation.appendChild(object)

    with open(img_dir+"\\"+img_name.replace('jpg','xml'), "wb+") as f:
        #print(img_dir+"\\"+img_name.replace('jpg','xml'))
        f.write(doc.toprettyxml(indent='\t', encoding='utf-8'))
Example #51
0
def create_session():
    try:
        # Write the XML request with the minidom  module
        newdoc = Document()
        request = newdoc.createElement('request')
        newdoc.appendChild(request)
        control = newdoc.createElement('control')
        request.appendChild(control)
        senderid = newdoc.createElement('senderid')
        control.appendChild(senderid).appendChild(
            newdoc.createTextNode(acc_keys.int_sender_id()))
        senderpassword = newdoc.createElement('password')
        control.appendChild(senderpassword).appendChild(
            newdoc.createTextNode(acc_keys.int_sender_pass()))
        controlid = newdoc.createElement('controlid')
        control.appendChild(controlid).appendChild(
            newdoc.createTextNode(str(int(time.time()))))
        uniqueid = newdoc.createElement('uniqueid')
        control.appendChild(uniqueid).appendChild(
            newdoc.createTextNode("false"))
        dtdversion = newdoc.createElement('dtdversion')
        control.appendChild(dtdversion).appendChild(
            newdoc.createTextNode("3.0"))
        includewhitespace = newdoc.createElement('includewhitespace')
        control.appendChild(includewhitespace).appendChild(
            newdoc.createTextNode("false"))

        operation = newdoc.createElement('operation')
        request.appendChild(operation)

        authentication = newdoc.createElement('authentication')
        operation.appendChild(authentication)

        login = newdoc.createElement('login')
        authentication.appendChild(login)

        userid = newdoc.createElement('userid')
        login.appendChild(userid).appendChild(
            newdoc.createTextNode(acc_keys.int_user()))

        companyid = newdoc.createElement('companyid')
        login.appendChild(companyid).appendChild(
            newdoc.createTextNode(acc_keys.int_company_id()))

        password = newdoc.createElement('password')
        login.appendChild(password).appendChild(
            newdoc.createTextNode(acc_keys.int_user_pass()))

        content = newdoc.createElement('content')
        operation.appendChild(content)

        function = newdoc.createElement('function')
        content.appendChild(function).setAttributeNode(
            newdoc.createAttribute('controlid'))
        function.attributes["controlid"].value = "1"

        create = newdoc.createElement('getAPISession')
        function.appendChild(create)

        #print(request.toprettyxml())

        # Post the request
        result = XMLRequestClient.post(request)

        # Print the XML response to the console
        #print(result.toprettyxml())

        find = result.getElementsByTagName('sessionid')
        sessionid = find[0].firstChild.nodeValue
        return sessionid

    except Exception as inst:
        print("Uh oh, something is wrong")
        print(type(inst))
        print(inst.args)
Example #52
0
def _bar2musicxml(bar):
    doc = Document()
    bar_node = doc.createElement("measure")

    # bar attributes
    attributes = doc.createElement("attributes")

    # calculate divisions by using the LCM
    l = []
    for nc in bar:
        l.append(int(value.determine(nc[1])[0]))
    lcm = _lcm(terms=l) * 4
    divisions = doc.createElement("divisions")
    divisions.appendChild(doc.createTextNode(str(lcm)))
    attributes.appendChild(divisions)
    if bar.key.key in major_keys or bar.key.key in minor_keys:
        key = doc.createElement("key")
        fifths = doc.createElement("fifths")

        # now we are going to guess which is the key of the bar
        fifths.appendChild(doc.createTextNode(str(bar.key.signature)))
        mode = doc.createElement("mode")
        mode.appendChild(doc.createTextNode(bar.key.mode))
        key.appendChild(fifths)
        key.appendChild(mode)
        attributes.appendChild(key)
    time = doc.createElement("time")
    beats = doc.createElement("beats")
    beattype = doc.createElement("beat-type")
    beats.appendChild(doc.createTextNode(str(bar.meter[0])))
    beattype.appendChild(doc.createTextNode(str(bar.meter[1])))
    time.appendChild(beats)
    time.appendChild(beattype)
    attributes.appendChild(time)
    bar_node.appendChild(attributes)
    chord = doc.createElement("chord")
    for nc in bar:
        time = value.determine(nc[1])
        beat = time[0]
        note_cont = nc[2]
        is_chord = False
        if note_cont:
            # is a note_container with 2 or more notes a chord?
            if len(note_cont) > 1:
                is_chord = True
        else:
            note_cont = [None]
        for n in note_cont:
            note = _note2musicxml(n)
            if is_chord:
                note.appendChild(chord)

            # convert the duration of the note
            duration = doc.createElement("duration")
            duration.appendChild(
                doc.createTextNode(str(int(lcm * (4.0 / beat)))))
            note.appendChild(duration)

            # check for dots
            dot = doc.createElement("dot")
            for i in range(0, time[1]):
                note.appendChild(dot)
            if beat in value.musicxml:
                type_node = doc.createElement("type")
                type_node.appendChild(doc.createTextNode(value.musicxml[beat]))
                note.appendChild(type_node)

            # check for non-standard ratio
            if time[2] != 1 and time[3] != 1:
                modification = doc.createElement("time-modification")
                actual = doc.createElement("actual-notes")
                actual.appendChild(doc.createTextNode(str(time[2])))
                normal = doc.createElement("normal-notes")
                normal.appendChild(doc.createTextNode(str(time[3])))
                modification.appendChild(actual)
                modification.appendChild(normal)
                note.appendChild(modification)
            bar_node.appendChild(note)
    return bar_node
Example #53
0
def serializeProjects(projectList):
    """ Method to serialize a list of projects to the appropriate format """
    doc = Document()
    # Create the base element
    packageConfiguration = doc.createElement("projectConfiguration")
    doc.appendChild(packageConfiguration)

    # Iterate on the list of packages
    for p in projectList:
        # Project element
        pack = doc.createElement("project")
        packageConfiguration.appendChild(pack)
        pack.setAttribute("name", p.Name())
        try:
            short_name = p.AFSVolumeShortName()
            if short_name != None:
                pack.setAttribute("shortName", short_name)
        except:
            None
            # Just ignore short name in this case

        # Release area
        if p.ReleaseArea() != None and p.ReleaseArea(
        ) != os.environ["LHCBRELEASES"]:
            e = doc.createElement("releaseArea")
            ptext = doc.createTextNode(p.ReleaseArea())
            e.appendChild(ptext)
            pack.appendChild(e)

        # DistLocation
        if p.DistLocation() != None and p.DistLocation(
        ) != os.environ["LHCBTAR"]:
            e = doc.createElement("distLocation")
            ptext = doc.createTextNode(p.DistLocation())
            e.appendChild(ptext)
            pack.appendChild(e)

        # BaseName
        if p.BaseName() != None and p.BaseName() != "":
            e = doc.createElement("baseName")
            ptext = doc.createTextNode(p.BaseName())
            e.appendChild(ptext)
            pack.appendChild(e)

        # LCGTarballName
        if p._lcgtarballname != None:
            e = doc.createElement("LCGTarballName")
            ptext = doc.createTextNode(p._lcgtarballname)
            e.appendChild(ptext)
            pack.appendChild(e)

        # AFS Volume Name
        if p._afsvolumename != p.NAME():
            e = doc.createElement("afsVolumeName")
            ptext = doc.createTextNode(p._afsvolumename)
            e.appendChild(ptext)
            pack.appendChild(e)

        # AFS Volume Root
        if p._afsvolumeroot != "lhcb":
            e = doc.createElement("afsVolumeRoot")
            ptext = doc.createTextNode(p._afsvolumeroot)
            e.appendChild(ptext)
            pack.appendChild(e)

        # AFS Librarian Group
        if p._afslibgroup != "z5":
            e = doc.createElement("afsLibrarianGroup")
            ptext = doc.createTextNode(p._afslibgroup)
            e.appendChild(ptext)
            pack.appendChild(e)

        # Has binary
        if p._hasbinary != True:
            e = doc.createElement("hasBinary")
            ptext = doc.createTextNode("false")
            e.appendChild(ptext)
            pack.appendChild(e)

        # setenvAlias
        if p._setenvalias != True:
            e = doc.createElement("setenvAlias")
            ptext = doc.createTextNode("false")
            e.appendChild(ptext)
            pack.appendChild(e)

        # setenvAlias
        if p._setupalias != True:
            e = doc.createElement("setupAlias")
            ptext = doc.createTextNode("false")
            e.appendChild(ptext)
            pack.appendChild(e)

        # steeringPackage
        if p._steeringpackage != p._name + "Sys":
            e = doc.createElement("steeringPackage")
            ptext = doc.createTextNode(p._steeringpackage)
            e.appendChild(ptext)
            pack.appendChild(e)

        # steeringPackage
        if p._fullsize != 5000000:
            e = doc.createElement("fullSize")
            ptext = doc.createTextNode(str(p._fullsize))
            e.appendChild(ptext)
            pack.appendChild(e)

        # steeringPackage
        if p._extraexe != {}:
            for it in sorted(p._extraexe.iteritems()):
                e = doc.createElement("extraexe")
                e.setAttribute("name", it[0])
                ptext = doc.createTextNode(it[1][0])
                e.appendChild(ptext)
                pack.appendChild(e)

    return doc
Example #54
0
    def Serialize(self):
        if not self._message:
            raise ICException(
                "iC message not sent, cannot serialize",
                '%s::%s' % (self.__class__.__name__, current_function()))

        # Create an XML document object
        doc = Document()

        # Root node
        cacheFidx = '%d' % self._message.GetFidx()
        root = doc.createElement(ICMESSAGE_ROOTNODE)
        root.setAttribute(ICMESSAGE_VERSIONNODE, ICMESSAGE_VERSION)
        root.setAttribute(ICMESSAGE_FRAMENODE, cacheFidx)
        doc.appendChild(root)

        # Classifiers
        for cname in self._message.classifiers.map:
            classifier = self._message.classifiers.Get(cname)
            cnode = doc.createElement(ICMESSAGE_CLASSISIFERNODE)
            cnode.setAttribute(ICMESSAGE_NAMENODE, classifier.GetChName())
            cnode.setAttribute(ICMESSAGE_DESCNODE,
                               classifier.GetChDescription())

            root.appendChild(cnode)

            # Attribute: Value Type
            vtype = classifier.GetValueType()
            pvtype = ICTYPES_ENTRY_UNDEF

            if vtype == ICClassifier.ValueUndef:
                pvtype = ICTYPES_ENTRY_UNDEF
            elif vtype == ICClassifier.ValueProb:
                pvtype = ICTYPES_ENTRY_PROB
            elif vtype == ICClassifier.ValueDist:
                pvtype = ICTYPES_ENTRY_DIST
            elif vtype == ICClassifier.ValueCLbl:
                pvtype = ICTYPES_ENTRY_CLBL
            elif vtype == ICClassifier.ValueRCoe:
                pvtype = ICTYPES_ENTRY_RCOE

            cnode.setAttribute(ICMESSAGE_VTYPENODE, pvtype)

            # Attribute: Label Type
            ltype = classifier.GetLabelType()
            pltype = ICTYPES_LABEL_UNDEF

            if ltype == ICClassifier.LabelClass:
                pltype = ICTYPES_LABEL_CLASS
            elif ltype == ICClassifier.LabelUndef:
                pltype = ICTYPES_LABEL_UNDEF
            elif ltype == ICClassifier.LabelBiosig:
                pltype = ICTYPES_LABEL_BIOSIG
            elif ltype == ICClassifier.LabelCustom:
                pltype = ICTYPES_LABEL_CUSTOM

            cnode.setAttribute(ICMESSAGE_LTYPENODE, pltype)

            # Loop over classes
            for theclassname in classifier.classes.map:
                theclass = classifier.classes.Get(theclassname)
                knode = doc.createElement(ICMESSAGE_CLASSNODE)
                textnode = doc.createTextNode(theclass.GetChValue())
                knode.appendChild(textnode)
                knode.setAttribute(ICMESSAGE_LABELNODE, theclass.GetChLabel())
                cnode.appendChild(knode)

        return doc.toxml()
Example #55
0
class WriteXML(object):
    def __init__(self, root):
        self.xmlroot = root
        self.doc = Document()

    def get_xmlroot(self):
        return self.xmlroot

    def set_xmlroot(self, root):
        self.xmlroot = root

        # Layout 填充
    def CreateLayout(self, layout, layoutObject):

        name = self.doc.createElement("name")
        name_text = self.doc.createTextNode(layoutObject.name)
        name.appendChild(name_text)
        area = self.doc.createElement("area")
        area_text = self.doc.createTextNode("%d,%d,%d,%d" % layoutObject.area)
        area.appendChild(area_text)

        layout.appendChild(name)
        layout.appendChild(area)

    # Screen 填充
    def CreateScreen(self, screen, screenObject):

        name = self.doc.createElement("name")
        name_text = self.doc.createTextNode(screenObject.name)
        name.appendChild(name_text)
        area = self.doc.createElement("area")
        area_text = self.doc.createTextNode("%d,%d,%d,%d" % screenObject.area)
        area.appendChild(area_text)

        screen.appendChild(name)
        screen.appendChild(area)

    # Widget 填充
    def CreateWidget(self, widget, widgetObject):

        name = self.doc.createElement("name")
        name_text = self.doc.createTextNode(widgetObject.name)
        name.appendChild(name_text)
        area = self.doc.createElement("area")
        area_text = self.doc.createTextNode("%d,%d,%d,%d" % widgetObject.area)
        area.appendChild(area_text)
        params = self.doc.createElement("params")
        params_text = self.doc.createTextNode(
            "%s,%s,%s" % (widgetObject.params[0], widgetObject.params[1],
                          widgetObject.params[2]))
        params.appendChild(params_text)
        texture = self.doc.createElement("texture")
        texture_text = self.doc.createTextNode(widgetObject.texture)
        texture.appendChild(texture_text)

        widget.appendChild(name)
        widget.appendChild(area)
        widget.appendChild(params)
        widget.appendChild(texture)

    # each i_layout contains name area and screen_list
    def WriteXML(self, layoutObject_list):

        for xml in layoutObject_list:
            self.doc = Document()
            GUILayout = self.doc.createElement("GUILayout")
            self.doc.appendChild(GUILayout)

            for layoutObject in xml.layout_list:

                Layout = self.doc.createElement("Layout")
                Layout.setAttribute('type', layoutObject.type)
                GUILayout.appendChild(Layout)

                self.CreateLayout(Layout, layoutObject)

                # each i_screen contains name area and sidget_list
                for screenObject in layoutObject.screen_list:

                    Screen = self.doc.createElement("Screen")
                    Layout.appendChild(Screen)
                    self.CreateScreen(Screen, screenObject)

                    # each i_widget contains name area params and textureID
                    for widgetObject in screenObject.widget_list:

                        textureName = xml.name + '_' + layoutObject.name + '_' + widgetObject.name
                        widgetObject.texture = textureName
                        Widget = self.doc.createElement("Widget")
                        Screen.appendChild(Widget)
                        Widget.setAttribute('type', widgetObject.type)
                        self.CreateWidget(Widget, widgetObject)

            filename = self.xmlroot + xml.name + ".layout"
            print filename
            f = open(filename, 'w')
            self.doc.writexml(f,
                              indent='\t',
                              newl='\n',
                              addindent='\t',
                              encoding='utf-8')
            f.close()
Example #56
0
    def generate_file(self):
        # DECLARO VARIABLES Y DOC PARA FORMAR EL XML
        mensaje = ""
        doc = Document()
        doc1 = Document()
        cod_num = '12345678'
        serie = '001001'
        ids = self._context['active_ids']
        print "ID DOCUMENTO 1:", ids
        for record in self:
            id_m = record.id
            id_ambiente = record.ambiente
            if id_ambiente == 'pruebas':
                if (not os.environ.get('PYTHONHTTPSVERIFY', '')
                        and getattr(ssl, '_create_unverified_context', None)):
                    ssl._create_default_https_context = ssl._create_unverified_context
                ambiente = '1'
                #CSV:28-12-2017: WS ON-LINE PRUEBAS
                #url = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl'
                #url1 = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl'
                url = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl'
                url1 = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl'
                if url:
                    client = Client(url, timeout=10)
                else:
                    raise Warning(('Atencion !'),
                                  ('No responde SRI intente mas tarde!'))
                if url1:
                    client1 = Client(url1, timeout=10)
                else:
                    raise Warning(('Atencion !'),
                                  ('No responde SRI intente mas tarde!'))

            elif id_ambiente == 'produccion':
                if (not os.environ.get('PYTHONHTTPSVERIFY', '')
                        and getattr(ssl, '_create_unverified_context', None)):
                    ssl._create_default_https_context = ssl._create_unverified_context

                ambiente = '2'
                #CSV:28-12-2017: WS ON-LINE PRODUCCION
                #url = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl'
                #url1 = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl'
                url = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl'
                url1 = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl'
                client = Client(url, timeout=10)
                client1 = Client(url1, timeout=10)
                if client and client1:
                    print "OK SRI"
                else:
                    raise Warning(('Atencion !'),
                                  ('No responde SRI intente mas tarde!'))
#CARGO ARCHIVO FIRMA DIGITAL
        if self._uid:
            arcfd = self.env.user.company_id
            print "OBJETO USER", arcfd
            firmadig = arcfd.name
            print "TIPO", type(firmadig)
            if firmadig:
                print "FIRMA DIGITAL", firmadig
            else:
                raise Warning(
                    'Atencion !, Suba el archivo de Firma Digital en su Usuario!'
                )

        id_formulario = record.formulario
        if id_formulario == 'normal':
            temision = '1'
        elif id_formulario == 'contingencia':
            temision = '2'
#
# OBTENER DATOS DE LA FACTURA
        id_header = self._context['active_id']
        print "ID DOCUMENTO:", id_header
        #CSV:28-12-2017:ONLINE
        #factura = self.env['account.invoice'].browse([id_header])
        for factura in self.env['account.invoice'].browse(ids):
            doc = Document()
            doc1 = Document()
            res_sri = False
            vals_accinvws1 = {}
            print "Factura", factura.id
            t_comp = factura.type
            print "TIPO COMPROBANTE", t_comp
            if factura.state_factelectro == 'autorizado' or factura.type not in (
                    'in_invoice'):
                continue
            if factura.state_factelectro not in ('autorizado', 'firmado'):
                # PARA INSTANCIAR OBJETO AUTORIZACION
                auth = self.env['account.authorization'].browse(
                    [factura.deduction_id.authorization_id.id])
                print "Autorizacion", auth
                secuencia = factura.deduction_id.number
                print "secuencia", secuencia
                #FECHA EMISION DE COMPROBANTE ELECTRONICO
                fechasf = factura.date_emision
                lfecha = fechasf.split('-')
                print "list fecha", lfecha
                fecha = lfecha[2] + "/" + lfecha[1] + "/" + lfecha[0]
                print "FECHA EMISION ELECTRONICA", fecha
                #FECHA EMISION FACTURA
                fechasfe = factura.date_invoice
                lfechae = fechasfe.split('-')
                print "list fecha factura", lfechae
                fechafact = lfechae[2] + "/" + lfechae[1] + "/" + lfechae[0]
                print "FECHA FACTURA", fechafact
                #DIRECCION CLIENTE/PROVEEDOR COMPROBANTE
                dfactu = factura.partner_id.street
                if dfactu:
                    dfactu = self.delete_ascii(factura.partner_id.street)
                dfactu2 = factura.partner_id.street2
                if dfactu2:
                    dfactu2 = self.delete_ascii(factura.partner_id.street2)
                cmail = factura.partner_id.email
                if cmail:
                    cliemail = cmail
                else:
                    raise Warning(
                        ('Atencion !'),
                        ('Ingrese el Email del cliente en la ficha!'))
                if dfactu and dfactu2:
                    dfactuf = str(dfactu) + " " + str(dfactu2)
                elif dfactu and not dfactu2:
                    dfactuf = str(dfactu)
                elif dfactu2 and not dfactu:
                    dfactuf = str(dfactu2)
                else:
                    dfactuf = ''
                print "DIR FACTU", dfactuf
                t_comp = factura.type
                print "TIPO COMPROBANTE", t_comp
                cod_ident = factura.partner_id.cod_type_ident
                print "COD IDENT", cod_ident
                name_rzc = factura.partner_id.name
                id_rzc = factura.partner_id.part_number
                tot_simp = factura.amount_untaxed
                print "TOTAL SI", tot_simp
                invdet_des = self.env['account.invoice.line'].search([
                    ('invoice_id', '=', factura.id)
                ])
                print "LISTA DETALLE DE LA FACTURA", invdet_des
                descuentt = 0
                for det_fact in invdet_des:
                    id_line = det_fact.id
                    print "ID LINE", id_line
                    if det_fact.discount > 0:
                        descuentt += round(
                            ((det_fact.price_unit * det_fact.quantity) *
                             det_fact.discount) / 100, 2)
                    else:
                        descuentt = det_fact.discount
                #tot_desc = factura.amount_discount
                tot_desc = descuentt
                print "TOTAL DES", tot_desc
                #DIRECCION SUCURSAL EMITE COMPROBANTE
                id_pars = self.env['res.partner'].search([
                    ('ref', '=', 'COEBIT'),
                    ('company_id', '=', self.env.user.company_id.id)
                ])
                print "ID PART", id_pars.id
                id_pars_add = self.env['res.partner'].search([('id', '=',
                                                               id_pars.id)])

                if id_pars_add:
                    d_suc1 = id_pars_add.street
                    d_suc2 = id_pars_add.street2
                    if d_suc1 and d_suc2:
                        dsucuf = str(d_suc1.encode('UTF-8')) + " " + str(
                            d_suc2.encode('UTF-8'))
                    elif d_suc1 and not d_suc2:
                        dsucuf = str(d_suc1.encode('UTF-8'))
                    elif d_suc2 and not d_suc1:
                        dsucuf = str(d_suc2.encode('UTF-8'))
                    else:
                        dsucuf = ''
                else:
                    raise Warning(
                        ('Atencion !'),
                        ('Ingrese Informacion de la sucursal CALLE1/CALLE2'))

                print "DIRECCION SUCUR", dsucuf

                if factura.partner_id.obli_contab:
                    obli_contab = factura.partner_id.obli_contab
                    if obli_contab == 'SI':
                        cod_posfis = factura.partner_id.cod_posfis
                    else:
                        cod_posfis = '000'
                else:
                    raise Warning(('Atencion !'), (
                        'Ingrese Informacion Fiscal en la ficha del cliente/proveedor!'
                    ))

                if factura.is_inv_elect:
                    fent = factura.emission_point
                    femi = factura.emission_series
                else:
                    if factura.authorization_id.serie_entity:
                        fent = str(
                            factura.authorization_id.serie_entity).strip()
                        print "ENTIDAD", fent
                    else:
                        raise Warning(('Atencion !'),
                                      ('Ingrese Serie entidad de la factura!'))
                    if factura.authorization_id.serie_emission:
                        femi = str(
                            factura.authorization_id.serie_emission).strip()
                        print "EMISION", femi
                    else:
                        raise Warning(('Atencion !'),
                                      ('Ingrese Serie emision de la factura!'))
        #********************************************************************************************************
                if factura.deduction_id.authorization_id.serie_entity:
                    fentp = str(factura.deduction_id.authorization_id.
                                serie_entity).strip()
                else:
                    raise Warning(('Atencion !'), (
                        'Ingrese Serie entidad proveedor para emitir su comprobante!'
                    ))
                if factura.deduction_id.authorization_id.serie_emission:
                    femip = str(factura.deduction_id.authorization_id.
                                serie_emission).strip()
                else:
                    raise Warning(('Atencion !'), (
                        'Ingrese Serie emision proveedor para emitir su comprobante!'
                    ))
                if factura.number_seq:
                    comprobante_n = str(factura.number_seq).strip()
                else:
                    raise Warning(('Atencion !'), (
                        'Ingrese Numero de comprobante sustento de esta retencion!'
                    ))
                cod_ds = factura.document_type.code

                # OBTENER DATOS DE LOS IMPUESTOS
                tax_id = self.env['account.invoice.tax'].search([
                    ('invoice_id', '=', factura.id),
                    ('deduction_id', '=', False)
                ])
                print "LISTA IMPUESTOS", tax_id
                for imp in tax_id:
                    print "LISTA IMPUESTOS 1", imp.tax_code_id
                    print "LISTA IMPUESTOS 2", imp.tax_code_id.cod_imp_fe
        # OBTENER DATOS DE LAS RETENCIONES
                ret_id = self.env['account.invoice.tax'].search([
                    ('invoice_id', '=', factura.id),
                    ('deduction_id', '!=', False)
                ])
                print "LISTA RETENCIONES", ret_id
                for rett in ret_id:
                    print "LISTA IMPUESTOS 1", rett.tax_code_id
                    print "LISTA IMPUESTOS 2", rett.tax_code_id.cod_imp_fe
                ret_det = self.env['account.invoice.tax'].browse(ret_id)
                # OBTENER DATOS DETALLE DE LA FACTURA
                invdet_id = self.env['account.invoice.line'].search([
                    ('invoice_id', '=', factura.id)
                ])
                print "LISTA DETALLE DE LA FACTURA", invdet_id
                invdet_det = self.env['account.invoice.line'].browse(invdet_id)
                print "OBJETO LINE DETALLADO", invdet_det
                cod_comp = '07'

                # OBTENGO DATOS DEL FORM
                version = record.version
                print "version: ", version
                compania = record.company
                print "compania: ", compania
                # Obtener Informacion de la compania
                lineas = self.env['res.company'].browse([compania.id])[0]
                empresa = lineas.partner_id.name
                ruc_empresa = lineas.partner_id.part_number
                user = self.env.user
                print "USER**", user
                direccion = ''
                if user.company_id.partner_id.street and user.company_id.partner_id.street2:
                    direccion = str(
                        user.company_id.partner_id.street) + ' Y ' + str(
                            user.company_id.partner_id.street2)
                elif user.company_id.partner_id.street and not user.company_id.partner_id.street2:
                    direccion = str(user.company_id.partner_id.street)
                elif user.company_id.partner_id.street2 and not user.company_id.partner_id.street:
                    direccion = str(user.company_id.partner_id.street2)
                print "direccion", direccion

                if id_formulario == 'normal':
                    temision = '1'
                    # FORMAR CLAVE ACCESO COMPROBANTE NORMAL
                    clav = str(lfecha[2] + lfecha[1] + lfecha[0] + cod_comp +
                               ruc_empresa.strip() + ambiente + fentp + femip +
                               secuencia.strip() + cod_num + temision)
                    clavea = self.modulo11(clav)
                    print "CLAVE MOD 11", clavea
                    clavef = clav.strip() + clavea.strip()
                    print "CLAVE FINAL N", clavef
                    ids_accfacel = self.env['account.factura.electronica']
                    vals_r = {
                        'name': 'Comprobante Retencion',
                        'clave_acceso': clavef,
                        'cod_comprobante': cod_comp,
                        'factelect_id': factura.id
                    }
        #                 accfactelect_id = ids_accfacel.create(cr,uid,vals_r)
                elif id_formulario == 'contingencia':
                    temision = '2'
                    cconti = record.contingencia
                    if len(cconti) < 37:
                        raise Warning(('Atencion !'), (
                            'Clave de contingencia debe tener 37 caracteres numericos!'
                        ))
                    else:
                        # FORMAR CLAVE ACCESO COMPROBANTE CONTINGENCIA
                        clav = str(lfecha[2] + lfecha[1] + lfecha[0] +
                                   cod_comp + cconti.strip() + temision)
                        clavea = self.modulo11(clav)
                        print "CLAVE MOD 11", clavea
                        clavef = clav.strip() + clavea.strip()
                        print "CLAVE FINAL C", clavef
                        ids_accfacel = self.env['account.factura.electronica']
                        vals_r = {
                            'name': 'Comprobante Retencion',
                            'clave_contingencia': cconti,
                            'contingencia': True,
                            'cod_comprobante': cod_comp,
                            'factelect_id': factura.id
                        }
        #                     accfactelect_id = ids_accfacel.create(cr,uid,vals_r)
        # TAG CONTENEDOR COMPROBANTE
                mainform = doc.createElement('comprobanteRetencion')
                doc.appendChild(mainform)
                mainform.setAttribute('id', 'comprobante')
                mainform.setAttribute('version', version)
                # TAGS HIJOS DEL CONTENEDOR COMPROBANTE
                infoTributaria = doc.createElement("infoTributaria")
                mainform.appendChild(infoTributaria)

                infoFactura = doc.createElement("infoCompRetencion")
                mainform.appendChild(infoFactura)

                impuestos = doc.createElement("impuestos")
                mainform.appendChild(impuestos)

                infoAdicional = doc.createElement("infoAdicional")
                mainform.appendChild(infoAdicional)
                # TAGS HIJOS DEL TAG INFOTRIBUTARIA
                ambiente_id = doc.createElement("ambiente")
                infoTributaria.appendChild(ambiente_id)
                nambiente_id = doc.createTextNode(ambiente.strip())
                ambiente_id.appendChild(nambiente_id)

                tipoemi_id = doc.createElement("tipoEmision")
                infoTributaria.appendChild(tipoemi_id)
                ntipoemi_id = doc.createTextNode(temision.strip())
                tipoemi_id.appendChild(ntipoemi_id)

                social = doc.createElement("razonSocial")
                infoTributaria.appendChild(social)
                psocial = doc.createTextNode(empresa.rstrip())
                social.appendChild(psocial)

                comercial = doc.createElement("nombreComercial")
                infoTributaria.appendChild(comercial)
                pcomercial = doc.createTextNode(empresa.rstrip())
                comercial.appendChild(pcomercial)

                ruc = doc.createElement("ruc")
                infoTributaria.appendChild(ruc)
                pruc = doc.createTextNode(ruc_empresa.rstrip())
                ruc.appendChild(pruc)

                clave = doc.createElement("claveAcceso")
                infoTributaria.appendChild(clave)
                nclave_id = doc.createTextNode(clavef.strip())
                clave.appendChild(nclave_id)

                codoc = doc.createElement("codDoc")
                infoTributaria.appendChild(codoc)
                ncodoc_id = doc.createTextNode(cod_comp.strip())
                codoc.appendChild(ncodoc_id)

                estab = doc.createElement("estab")
                infoTributaria.appendChild(estab)
                nestab_id = doc.createTextNode(fentp.strip())
                estab.appendChild(nestab_id)

                ptoemi = doc.createElement("ptoEmi")
                infoTributaria.appendChild(ptoemi)
                nptoemi_id = doc.createTextNode(femip.strip())
                ptoemi.appendChild(nptoemi_id)

                secuencial = doc.createElement("secuencial")
                infoTributaria.appendChild(secuencial)
                nsecuencial_id = doc.createTextNode(secuencia.strip())
                secuencial.appendChild(nsecuencial_id)

                dirmatr = doc.createElement("dirMatriz")
                infoTributaria.appendChild(dirmatr)
                ndirmatr_id = doc.createTextNode(direccion.strip())
                dirmatr.appendChild(ndirmatr_id)
                # TAGS HIJOS DEL TAG INFOFACTURA
                femision = doc.createElement("fechaEmision")
                infoFactura.appendChild(femision)
                nfemision_id = doc.createTextNode(fecha.strip())
                femision.appendChild(nfemision_id)

                destable = doc.createElement("dirEstablecimiento")
                infoFactura.appendChild(destable)
                ndestable_id = doc.createTextNode(dsucuf.strip())
                destable.appendChild(ndestable_id)

                contesp = doc.createElement("contribuyenteEspecial")
                infoFactura.appendChild(contesp)
                ncontesp_id = doc.createTextNode(cod_posfis.strip())
                contesp.appendChild(ncontesp_id)

                oblicont = doc.createElement("obligadoContabilidad")
                infoFactura.appendChild(oblicont)
                noblicont_id = doc.createTextNode(obli_contab.strip())
                oblicont.appendChild(noblicont_id)

                tidencomp = doc.createElement(
                    "tipoIdentificacionSujetoRetenido")
                infoFactura.appendChild(tidencomp)
                ntidencomp_id = doc.createTextNode(cod_ident.strip())
                tidencomp.appendChild(ntidencomp_id)

                rasocomp = doc.createElement("razonSocialSujetoRetenido")
                infoFactura.appendChild(rasocomp)
                nrasocomp_id = doc.createTextNode(name_rzc.strip())
                rasocomp.appendChild(nrasocomp_id)

                identcomp = doc.createElement("identificacionSujetoRetenido")
                infoFactura.appendChild(identcomp)
                nidentcomp_id = doc.createTextNode(id_rzc.strip())
                identcomp.appendChild(nidentcomp_id)

                pfiscal = doc.createElement("periodoFiscal")
                infoFactura.appendChild(pfiscal)
                npfiscal_id = doc.createTextNode(str(factura.period_id.code))
                pfiscal.appendChild(npfiscal_id)

                for impuesto in ret_id:
                    print "RET COD1", impuesto
                    print "RET COD2", impuesto.tax_code_id
                    print "RET COD3", impuesto.tax_code_id.cod_imp_fe
                    if impuesto.tax_code_id.cod_imp_fe == '1':
                        cod_retfe = impuesto.base_code_id.code
                        if cod_retfe:
                            print "ok retencion"
                        else:
                            raise Warning(('Atencion !'), (
                                'No hay configurado codigo base de la retencion de esta factura!'
                            ))
                    else:
                        cod_retfe = impuesto.tax_code_id.cod_tarifa
                        if cod_retfe:
                            print "ok retencion"
                        else:
                            raise Warning(('Atencion !'), (
                                "No hay configurado codigo tarifa en impuestos codigos '%s' !"
                            ) % str(impuesto.tax_code_id.name))
                    totalimp = doc.createElement("impuesto")
                    impuestos.appendChild(totalimp)
                    # TAG SE REPITE CODIGO IMPUESTOS SEGUN LA FACTURA
                    fcodigo = doc.createElement("codigo")
                    totalimp.appendChild(fcodigo)
                    nfcodigo_id = doc.createTextNode(
                        impuesto.tax_code_id.cod_imp_fe)
                    fcodigo.appendChild(nfcodigo_id)

                    codpor = doc.createElement("codigoRetencion")
                    totalimp.appendChild(codpor)
                    ncodpor_id = doc.createTextNode(cod_retfe)
                    codpor.appendChild(ncodpor_id)

                    basimp = doc.createElement("baseImponible")
                    totalimp.appendChild(basimp)
                    vbaseimp = Decimal(abs(impuesto.base_amount)).quantize(
                        Decimal('0.00'))
                    nbasimp_id = doc.createTextNode(str(vbaseimp))
                    basimp.appendChild(nbasimp_id)

                    dtarifa = doc.createElement("porcentajeRetener")
                    totalimp.appendChild(dtarifa)
                    v_tar_imp = Decimal(impuesto.tax_code_id.tarifa).quantize(
                        Decimal('0.00'))
                    ndtarifa_id = doc.createTextNode(str(v_tar_imp))
                    dtarifa.appendChild(ndtarifa_id)

                    fvalor = doc.createElement("valorRetenido")
                    totalimp.appendChild(fvalor)
                    vamount = Decimal(abs(impuesto.amount)).quantize(
                        Decimal('0.00'))
                    nfvalor_id = doc.createTextNode(str(vamount))
                    fvalor.appendChild(nfvalor_id)

                    cdm = doc.createElement("codDocSustento")
                    totalimp.appendChild(cdm)
                    ncdm_id = doc.createTextNode(cod_ds.strip())
                    cdm.appendChild(ncdm_id)

                    ndm = doc.createElement("numDocSustento")
                    totalimp.appendChild(ndm)
                    nndm_id = doc.createTextNode(
                        str(femi + fent + comprobante_n).strip())
                    ndm.appendChild(nndm_id)

                    feds = doc.createElement("fechaEmisionDocSustento")
                    totalimp.appendChild(feds)
                    nfeds_id = doc.createTextNode(fecha.strip())
                    feds.appendChild(nfeds_id)

                cadicional = doc.createElement('campoAdicional')
                infoAdicional.appendChild(cadicional)
                cadicional.setAttribute('nombre', 'mail')
                cadicional_id = doc.createTextNode(cliemail)
                cadicional.appendChild(cadicional_id)

                cadicional1 = doc.createElement('campoAdicional')
                infoAdicional.appendChild(cadicional1)
                cadicional1.setAttribute('nombre', 'Direccion')
                cadicional_id1 = doc.createTextNode(dfactuf)
                cadicional1.appendChild(cadicional_id1)

                print "DOC**", doc
                out = base64.encodestring(doc.toxml())
                name = "%s.xml" % (clavef)
                record.name = name
                print "NOMBRE COMPROBANTE GUARDAR", name
                record.data = out
                f = open(
                    '/home/oddo/' + firmadig + '/' +
                    'FACTURA_ELECTRONICA/FACTURASF/' + name, 'w')
                f.write(doc.toxml())
                f.close()
                #**********************************************************************************************************
                if firmadig == 'MISSION PETROLEUM S.A.':
                    print "ENTRO MISSION PETROLEUM S.A."
                    res = jarWrapper(
                        '/opt/addons_mission/o2s_felectronica/wizard/XadesBes.jar',
                        '/opt/addons_mission/o2s_felectronica/wizard/' +
                        firmadig + '/' + 'firmaMissionPetroleum2018.p12',
                        'mission2020', '/home/oddo/' + firmadig + '/' +
                        'FACTURA_ELECTRONICA/FACTURASF/' + name,
                        '/home/oddo/' + firmadig + '/' +
                        'FACTURA_ELECTRONICA/FACTURAF', name)
                    print "RES", res
                    w = open(
                        '/home/oddo/' + firmadig + '/' +
                        'FACTURA_ELECTRONICA/FACTURAF/' + name, 'rb')
                    q = w.read()
#***********************************************************************************************************
                res_sri = client.service.validarComprobante(
                    base64.encodestring(q))
            # print "RESPUESTA*****", res_sri

    #             print "ESTADO*****", res_sri[0]
    #CSV: AUMENTO PARA EL CASO DE SOLO CONSULTAR
            if factura.state_factelectro == 'firmado':
                clavef = factura.num_autoreten
                print "factura.num_autoreten", factura.num_autoreten
                print "factura.state_factelectro", factura.state_factelectro
                autorizada = 0
                while autorizada != 1:
                    res_autcomp = client1.service.autorizacionComprobante(
                        clavef)
                    # print "OBJETO AUTORIZA1***", res_autcomp
                    #                     print "TIPO RESPUESTA", type(res_autcomp)
                    #                     print "TAMAÑO RESPUESTA", len(res_autcomp)
                    #                     print "OBJETO autorizaciones***", res_autcomp.autorizaciones
                    #                     print "TIPO autorizaciones", type(res_autcomp.autorizaciones)
                    #                     print "TAMAÑO autorizaciones", len(res_autcomp.autorizaciones)
                    if len(res_autcomp.autorizaciones) > 0:
                        if len(res_autcomp.autorizaciones.autorizacion[0]) > 0:
                            estado_ws = res_autcomp.autorizaciones.autorizacion[
                                0]['estado']
                            print "estado_ws", estado_ws
                            autorizada = 1
                            if str(estado_ws).strip() == 'AUTORIZADO':
                                #******************************XML ENVIO POR MAIL CLIENTE*************************
                                numaut_ws = res_autcomp.autorizaciones.autorizacion[
                                    0]['numeroAutorizacion']
                                print "numaut_ws", numaut_ws
                                fechaut_ws = res_autcomp.autorizaciones.autorizacion[
                                    0]['fechaAutorizacion']
                                print "fechaut_ws", fechaut_ws
                                if ambiente == '2':
                                    ambiente_ws = 'PRODUCCION'
                                elif ambiente == '1':
                                    ambiente_ws = 'PRUEBAS'
                                print "ambiente_ws", ambiente_ws
                                comprobante_ws = res_autcomp.autorizaciones.autorizacion[
                                    0]['comprobante']
                                #print "comprobante", comprobante

                                # TAGS XML ENVIO POR MAIL AL CLIENTE
                                autorizacion = doc1.createElement(
                                    'autorizacion')
                                doc1.appendChild(autorizacion)
                                # TAGS HIJOS DEL TAG AUTORIZACION
                                estado = doc1.createElement("estado")
                                autorizacion.appendChild(estado)
                                naestado_id = doc.createTextNode(
                                    str(estado_ws).strip())
                                estado.appendChild(naestado_id)

                                numaut = doc1.createElement(
                                    "numeroAutorizacion")
                                autorizacion.appendChild(numaut)
                                nanumaut_id = doc.createTextNode(
                                    str(numaut_ws).strip())
                                numaut.appendChild(nanumaut_id)

                                fechaut = doc1.createElement(
                                    "fechaAutorizacion")
                                autorizacion.appendChild(fechaut)
                                nafechaut_id = doc.createTextNode(
                                    str(fechaut_ws).strip())
                                fechaut.appendChild(nafechaut_id)

                                ambienteaut = doc1.createElement("ambiente")
                                autorizacion.appendChild(ambienteaut)
                                naambienteaut_id = doc.createTextNode(
                                    str(ambiente_ws).strip())
                                ambienteaut.appendChild(naambienteaut_id)

                                comprobanteaut = doc1.createElement(
                                    "comprobante")
                                autorizacion.appendChild(comprobanteaut)
                                nacomprobanteaut_id = doc.createTextNode(
                                    str(comprobante_ws).strip())
                                comprobanteaut.appendChild(nacomprobanteaut_id)

                                out1 = base64.encodestring(doc1.toxml())
                                data_fname = "%s.xml" % (clavef)
                                f1 = open(
                                    '/home/oddo/' + firmadig + '/' +
                                    'FACTURA_ELECTRONICA/AUTORIZADO/' +
                                    data_fname, 'w')
                                f1.write(doc1.toxml())
                                f1.close()
                                #CSV 07-06-2017 PARA ADJUNTARLO************************
                                archivo = '/home/oddo/' + firmadig + '/' + 'FACTURA_ELECTRONICA/AUTORIZADO/' + data_fname
                                res_model = 'account.invoice'
                                id = ids and type(ids) == type(
                                    []) and ids[0] or ids
                                self.load_doc(out1, factura.id, data_fname,
                                              archivo, res_model)
                                #**************************************************************************************
                                num_aut = res_autcomp.autorizaciones.autorizacion[
                                    0]['numeroAutorizacion']
                                #ids_atracci = self.env['account.invoice']
                                vals_accinv = {
                                    'num_autoreten': num_aut,
                                    'state_factelectro': 'autorizado',
                                    'date_aut':
                                    time.strftime('%Y-%m-%d %H:%M:%S'),
                                    'inf_electronica': 'autorizado'
                                }
                                factura.write(vals_accinv)
                                #accfactelect_id = ids_accfacel.create(vals_r)
                                mensaje = str(estado_ws)
                                record.mensaje = mensaje
                            else:
                                if res_autcomp.autorizaciones.autorizacion[-1][
                                        'estado'] == 'AUTORIZADO':
                                    num_aut = res_autcomp.autorizaciones.autorizacion[
                                        -1]['numeroAutorizacion']
                                    #ids_atracci = self.env['account.invoice']
                                    vals_accinv = {
                                        'num_autoreten':
                                        num_aut,
                                        'state_factelectro':
                                        'autorizado',
                                        'date_aut':
                                        time.strftime('%Y-%m-%d %H:%M:%S'),
                                        'inf_electronica':
                                        'autorizado'
                                    }
                                    factura.write(vals_accinv)
                                    #accfactelect_id = ids_accfacel.create(vals_r)
                                    mensaje = str(res_autcomp.autorizaciones.
                                                  autorizacion[-1]['estado'])
                                    record.mensaje = mensaje
                                else:
                                    mensaje = str(res_autcomp)
                                    record.mensaje = mensaje
                                    vals_inf_elect = {
                                        'inf_electronica': mensaje
                                    }
                                    factura.write(vals_inf_elect)
                        #print "MENSAJE", mensaje
            if res_sri and res_sri['estado'] == 'RECIBIDA':
                #CSV:29-12-2017: AUMENTO PARA ENVIAR ARCHIVO FIRMADO CLIENTE Y SRI PRIMER WEB SERVICES
                #CSV: PARA ADJUNTARLO************************
                w = open(
                    '/home/oddo/' + firmadig + '/' +
                    'FACTURA_ELECTRONICA/FACTURAF/' + name, 'rb')
                q = w.read()
                out2 = base64.encodestring(q)
                data_fname = name
                archivo = '/home/oddo/' + firmadig + '/' + 'FACTURA_ELECTRONICA/FACTURAF/' + name
                res_model = 'account.invoice'
                id = ids and type(ids) == type([]) and ids[0] or ids
                self.load_doc(out2, factura.id, data_fname, archivo, res_model)
                #Escribo en la factura*
                num_autws1 = clavef
                #ids_atracci = self.env['account.invoice']
                val_aut = {'name': num_autws1}
                auth.write(val_aut)
                vals_accinvws1 = {
                    'num_autoreten': num_autws1,
                    'state_factelectro': 'firmado',
                    'date_aut': time.strftime('%Y-%m-%d %H:%M:%S'),
                    'inf_electronica': 'firmado'
                }
                factura.write(vals_accinvws1)
                accfactelect_id = ids_accfacel.create(vals_r)
                mensaje = str('firmado')
                record.mensaje = mensaje
            elif res_sri and res_sri['estado'] == 'DEVUELTA':
                mensaje = str(res_sri)
                record.mensaje = mensaje
                vals_inf_elect = {'inf_electronica': mensaje}
                factura.write(vals_inf_elect)
                print "NO SE ENVIO"
        return True
    # Group messages by rule_type
    for rule_type, messages_by_ruletype in groupby(messages, lambda msg: msg['rule_type']):
        for rule, messages_by_rule in groupby(messages_by_ruletype, lambda msg: msg['alias'] if msg['alias'] else msg['rule']):
            testcase = doc.createElement("testcase")
            testcase.setAttribute("name", rule)
            testcase.setAttribute("classname", rule_type)
            failure = doc.createElement("failure")
            # Generate an ASCII table from the collected messages
            header = "{: <10s}   {: <17s}   {: <37s}".format("Severity", "File", "Message").rstrip()
            body = []
            for msg in messages_by_rule:
                severity = msg['severity']
                for severity, file, message in zip_longest(wrap(msg['severity'], 10), wrap(msg['file']+", line "+msg['line'], 17), wrap(msg['message'], 37), fillvalue=""):
                    body.append("{: <10s}   {: <17s}   {: <37s}".format(severity, file, message).rstrip())
                body.append("")

            content_text ="\n".join([header, "-"*70, *body])
            content = doc.createTextNode(content_text)
            failure.appendChild(content)
            testcase.appendChild(failure)
            testsuite.appendChild(testcase)
    doc.appendChild(testsuite)
    print(doc.toprettyxml())
    sys.exit(1 if nr_of_failures and args.fail_on_error else 0)


except Exception as e:
    # parser.error("Failed to parse the report. Error: {}".format(e))
    raise e

Example #58
0
            if (value != None):
                if (isinstance(value, Bag)):
                    if (key == "Authors"):
                        authors = ""

                        if (isinstance(value.Author, list)):
                            for author in value.Author:
                                authors += author + "; "
                        else:
                            authors += value.Author

                        fieldElement = doc.createElement("field")
                        fieldElement.setAttribute("name", "authors")

                        textElement = doc.createTextNode(authors)

                        fieldElement.appendChild(textElement)
                        bookElement.appendChild(fieldElement)

                    elif (key == "Reviews"):
                        fieldElement = doc.createElement("field")
                        fieldElement.setAttribute("name", "hasreviews")
                        textElement = doc.createTextNode("true")
                        fieldElement.appendChild(textElement)
                        bookElement.appendChild(fieldElement)

                        if (isinstance(value.CustomerReview, list)):
                            for review in value.CustomerReview:
                                fieldElement = doc.createElement("field")
                                fieldElement.setAttribute("name", "Review")
Example #59
0
 def saveXML(self):
     if self.rawdata:
         root = self.rawdata.getElementsByTagName('ComicInfo')[0]
         for row in (['Series',
                      self.data['Series']], ['Volume', self.data['Volume']],
                     ['Number', self.data['Number']
                      ], ['Writer', ', '.join(self.data['Writers'])],
                     ['Penciller', ', '.join(self.data['Pencillers'])
                      ], ['Inker', ', '.join(self.data['Inkers'])],
                     ['Colorist', ', '.join(self.data['Colorists'])
                      ], ['Summary', self.data['Summary']], [
                          'ScanInformation', 'MCD(' + self.data['MUid'] +
                          ')' if self.data['MUid'] else ''
                      ]):
             if self.rawdata.getElementsByTagName(row[0]):
                 node = self.rawdata.getElementsByTagName(row[0])[0]
                 if row[1]:
                     node.firstChild.replaceWholeText(row[1])
                 else:
                     root.removeChild(node)
             elif row[1]:
                 main = self.rawdata.createElement(row[0])
                 root.appendChild(main)
                 text = self.rawdata.createTextNode(row[1])
                 main.appendChild(text)
     else:
         doc = Document()
         root = doc.createElement('ComicInfo')
         root.setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema')
         root.setAttribute('xmlns:xsi',
                           'http://www.w3.org/2001/XMLSchema-instance')
         doc.appendChild(root)
         for row in (['Series',
                      self.data['Series']], ['Volume', self.data['Volume']],
                     ['Number', self.data['Number']
                      ], ['Writer', ', '.join(self.data['Writers'])],
                     ['Penciller', ', '.join(self.data['Pencillers'])
                      ], ['Inker', ', '.join(self.data['Inkers'])],
                     ['Colorist', ', '.join(self.data['Colorists'])
                      ], ['Summary', self.data['Summary']], [
                          'ScanInformation', 'MCD(' + self.data['MUid'] +
                          ')' if self.data['MUid'] else ''
                      ]):
             if row[1]:
                 main = doc.createElement(row[0])
                 root.appendChild(main)
                 text = doc.createTextNode(row[1])
                 main.appendChild(text)
         self.rawdata = doc
     if self.source.endswith('.xml'):
         with open(self.source, 'w', encoding='utf-8') as f:
             self.rawdata.writexml(f, encoding='utf-8')
     else:
         workdir = mkdtemp('', 'KCC-')
         tmpXML = os.path.join(workdir, 'ComicInfo.xml')
         with open(tmpXML, 'w', encoding='utf-8') as f:
             self.rawdata.writexml(f, encoding='utf-8')
         if is_zipfile(self.source):
             removeFromZIP(self.source, 'ComicInfo.xml')
             with ZipFile(self.source, mode='a',
                          compression=ZIP_DEFLATED) as zip_file:
                 zip_file.write(tmpXML, arcname=tmpXML.split(os.sep)[-1])
         elif rarfile.is_rarfile(self.source):
             raise NotImplementedError
         elif is_7zfile(self.source):
             output = Popen('7za a "' + self.source + '" "' + tmpXML + '"',
                            stdout=PIPE,
                            stderr=STDOUT,
                            stdin=PIPE,
                            shell=True)
             extracted = False
             for line in output.stdout:
                 if b"Everything is Ok" in line:
                     extracted = True
             if not extracted:
                 rmtree(workdir)
                 raise OSError('Failed to modify 7ZIP file.')
         rmtree(workdir)
Example #60
0
class MathMLPrinter(Printer):
    """Prints an expression to the MathML markup language

    Whenever possible tries to use Content markup and not Presentation markup.

    References: https://www.w3.org/TR/MathML3/
    """
    printmethod = "_mathml"
    _default_settings = {"order": None, "encoding": "utf-8"}

    def __init__(self, settings=None):
        Printer.__init__(self, settings)
        from xml.dom.minidom import Document
        self.dom = Document()

    def doprint(self, expr):
        """
        Prints the expression as MathML.
        """
        mathML = Printer._print(self, expr)
        unistr = mathML.toxml()
        xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
        res = xmlbstr.decode()
        return res

    def mathml_tag(self, e):
        """Returns the MathML tag for an expression."""
        translate = {
            'Add': 'plus',
            'Mul': 'times',
            'Derivative': 'diff',
            'Number': 'cn',
            'int': 'cn',
            'Pow': 'power',
            'Symbol': 'ci',
            'Integral': 'int',
            'Sum': 'sum',
            'sin': 'sin',
            'cos': 'cos',
            'tan': 'tan',
            'cot': 'cot',
            'asin': 'arcsin',
            'asinh': 'arcsinh',
            'acos': 'arccos',
            'acosh': 'arccosh',
            'atan': 'arctan',
            'atanh': 'arctanh',
            'acot': 'arccot',
            'atan2': 'arctan',
            'log': 'ln',
            'Equality': 'eq',
            'Unequality': 'neq',
            'GreaterThan': 'geq',
            'LessThan': 'leq',
            'StrictGreaterThan': 'gt',
            'StrictLessThan': 'lt',
        }

        for cls in e.__class__.__mro__:
            n = cls.__name__
            if n in translate:
                return translate[n]
        # Not found in the MRO set
        n = e.__class__.__name__
        return n.lower()

    def _print_Mul(self, expr):

        if _coeff_isneg(expr):
            x = self.dom.createElement('apply')
            x.appendChild(self.dom.createElement('minus'))
            x.appendChild(self._print_Mul(-expr))
            return x

        from sympy.simplify import fraction
        numer, denom = fraction(expr)

        if denom is not S.One:
            x = self.dom.createElement('apply')
            x.appendChild(self.dom.createElement('divide'))
            x.appendChild(self._print(numer))
            x.appendChild(self._print(denom))
            return x

        coeff, terms = expr.as_coeff_mul()
        if coeff is S.One and len(terms) == 1:
            # XXX since the negative coefficient has been handled, I don't
            # think a coeff of 1 can remain
            return self._print(terms[0])

        if self.order != 'old':
            terms = Mul._from_args(terms).as_ordered_factors()

        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement('times'))
        if (coeff != 1):
            x.appendChild(self._print(coeff))
        for term in terms:
            x.appendChild(self._print(term))
        return x

    def _print_Add(self, expr, order=None):
        args = self._as_ordered_terms(expr, order=order)
        lastProcessed = self._print(args[0])
        plusNodes = []
        for arg in args[1:]:
            if _coeff_isneg(arg):
                # use minus
                x = self.dom.createElement('apply')
                x.appendChild(self.dom.createElement('minus'))
                x.appendChild(lastProcessed)
                x.appendChild(self._print(-arg))
                # invert expression since this is now minused
                lastProcessed = x
                if (arg == args[-1]):
                    plusNodes.append(lastProcessed)
            else:
                plusNodes.append(lastProcessed)
                lastProcessed = self._print(arg)
                if (arg == args[-1]):
                    plusNodes.append(self._print(arg))
        if len(plusNodes) == 1:
            return lastProcessed
        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement('plus'))
        while len(plusNodes) > 0:
            x.appendChild(plusNodes.pop(0))
        return x

    def _print_MatrixBase(self, m):
        x = self.dom.createElement('matrix')
        for i in range(m.rows):
            x_r = self.dom.createElement('matrixrow')
            for j in range(m.cols):
                x_r.appendChild(self._print(m[i, j]))
            x.appendChild(x_r)
        return x

    def _print_Rational(self, e):
        if e.q == 1:
            # don't divide
            x = self.dom.createElement('cn')
            x.appendChild(self.dom.createTextNode(str(e.p)))
            return x
        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement('divide'))
        # numerator
        xnum = self.dom.createElement('cn')
        xnum.appendChild(self.dom.createTextNode(str(e.p)))
        # denominator
        xdenom = self.dom.createElement('cn')
        xdenom.appendChild(self.dom.createTextNode(str(e.q)))
        x.appendChild(xnum)
        x.appendChild(xdenom)
        return x

    def _print_Limit(self, e):
        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement(self.mathml_tag(e)))

        x_1 = self.dom.createElement('bvar')
        x_2 = self.dom.createElement('lowlimit')
        x_1.appendChild(self._print(e.args[1]))
        x_2.appendChild(self._print(e.args[2]))

        x.appendChild(x_1)
        x.appendChild(x_2)
        x.appendChild(self._print(e.args[0]))
        return x

    def _print_ImaginaryUnit(self, e):
        return self.dom.createElement('imaginaryi')

    def _print_EulerGamma(self, e):
        return self.dom.createElement('eulergamma')

    def _print_GoldenRatio(self, e):
        """We use unicode #x3c6 for Greek letter phi as defined here
        http://www.w3.org/2003/entities/2007doc/isogrk1.html"""
        x = self.dom.createElement('cn')
        x.appendChild(self.dom.createTextNode(u"\N{GREEK SMALL LETTER PHI}"))
        return x

    def _print_Exp1(self, e):
        return self.dom.createElement('exponentiale')

    def _print_Pi(self, e):
        return self.dom.createElement('pi')

    def _print_Infinity(self, e):
        return self.dom.createElement('infinity')

    def _print_Negative_Infinity(self, e):
        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement('minus'))
        x.appendChild(self.dom.createElement('infinity'))
        return x

    def _print_Integral(self, e):
        def lime_recur(limits):
            x = self.dom.createElement('apply')
            x.appendChild(self.dom.createElement(self.mathml_tag(e)))
            bvar_elem = self.dom.createElement('bvar')
            bvar_elem.appendChild(self._print(limits[0][0]))
            x.appendChild(bvar_elem)

            if len(limits[0]) == 3:
                low_elem = self.dom.createElement('lowlimit')
                low_elem.appendChild(self._print(limits[0][1]))
                x.appendChild(low_elem)
                up_elem = self.dom.createElement('uplimit')
                up_elem.appendChild(self._print(limits[0][2]))
                x.appendChild(up_elem)
            if len(limits[0]) == 2:
                up_elem = self.dom.createElement('uplimit')
                up_elem.appendChild(self._print(limits[0][1]))
                x.appendChild(up_elem)
            if len(limits) == 1:
                x.appendChild(self._print(e.function))
            else:
                x.appendChild(lime_recur(limits[1:]))
            return x

        limits = list(e.limits)
        limits.reverse()
        return lime_recur(limits)

    def _print_Sum(self, e):
        # Printer can be shared because Sum and Integral have the
        # same internal representation.
        return self._print_Integral(e)

    def _print_Symbol(self, sym):
        ci = self.dom.createElement(self.mathml_tag(sym))

        def join(items):
            if len(items) > 1:
                mrow = self.dom.createElement('mml:mrow')
                for i, item in enumerate(items):
                    if i > 0:
                        mo = self.dom.createElement('mml:mo')
                        mo.appendChild(self.dom.createTextNode(" "))
                        mrow.appendChild(mo)
                    mi = self.dom.createElement('mml:mi')
                    mi.appendChild(self.dom.createTextNode(item))
                    mrow.appendChild(mi)
                return mrow
            else:
                mi = self.dom.createElement('mml:mi')
                mi.appendChild(self.dom.createTextNode(items[0]))
                return mi

        # translate name, supers and subs to unicode characters
        greek_letters = set(greeks)  # make a copy

        def translate(s):
            if s in greek_unicode:
                return greek_unicode.get(s)
            else:
                return s

        name, supers, subs = split_super_sub(sym.name)
        name = translate(name)
        supers = [translate(sup) for sup in supers]
        subs = [translate(sub) for sub in subs]

        mname = self.dom.createElement('mml:mi')
        mname.appendChild(self.dom.createTextNode(name))
        if len(supers) == 0:
            if len(subs) == 0:
                ci.appendChild(self.dom.createTextNode(name))
            else:
                msub = self.dom.createElement('mml:msub')
                msub.appendChild(mname)
                msub.appendChild(join(subs))
                ci.appendChild(msub)
        else:
            if len(subs) == 0:
                msup = self.dom.createElement('mml:msup')
                msup.appendChild(mname)
                msup.appendChild(join(supers))
                ci.appendChild(msup)
            else:
                msubsup = self.dom.createElement('mml:msubsup')
                msubsup.appendChild(mname)
                msubsup.appendChild(join(subs))
                msubsup.appendChild(join(supers))
                ci.appendChild(msubsup)
        return ci

    def _print_Pow(self, e):
        # Here we use root instead of power if the exponent is the reciprocal of an integer
        if e.exp.is_Rational and e.exp.p == 1:
            x = self.dom.createElement('apply')
            x.appendChild(self.dom.createElement('root'))
            if e.exp.q != 2:
                xmldeg = self.dom.createElement('degree')
                xmlci = self.dom.createElement('ci')
                xmlci.appendChild(self.dom.createTextNode(str(e.exp.q)))
                xmldeg.appendChild(xmlci)
                x.appendChild(xmldeg)
            x.appendChild(self._print(e.base))
            return x

        x = self.dom.createElement('apply')
        x_1 = self.dom.createElement(self.mathml_tag(e))
        x.appendChild(x_1)
        x.appendChild(self._print(e.base))
        x.appendChild(self._print(e.exp))
        return x

    def _print_Number(self, e):
        x = self.dom.createElement(self.mathml_tag(e))
        x.appendChild(self.dom.createTextNode(str(e)))
        return x

    def _print_Derivative(self, e):
        x = self.dom.createElement('apply')
        diff_symbol = self.mathml_tag(e)
        if requires_partial(e):
            diff_symbol = 'partialdiff'
        x.appendChild(self.dom.createElement(diff_symbol))

        x_1 = self.dom.createElement('bvar')
        for sym in e.variables:
            x_1.appendChild(self._print(sym))

        x.appendChild(x_1)
        x.appendChild(self._print(e.expr))
        return x

    def _print_Function(self, e):
        x = self.dom.createElement("apply")
        x.appendChild(self.dom.createElement(self.mathml_tag(e)))
        for arg in e.args:
            x.appendChild(self._print(arg))
        return x

    def _print_Basic(self, e):
        x = self.dom.createElement(self.mathml_tag(e))
        for arg in e:
            x.appendChild(self._print(arg))
        return x

    def _print_AssocOp(self, e):
        x = self.dom.createElement('apply')
        x_1 = self.dom.createElement(self.mathml_tag(e))
        x.appendChild(x_1)
        for arg in e.args:
            x.appendChild(self._print(arg))
        return x

    def _print_Relational(self, e):
        x = self.dom.createElement('apply')
        x.appendChild(self.dom.createElement(self.mathml_tag(e)))
        x.appendChild(self._print(e.lhs))
        x.appendChild(self._print(e.rhs))
        return x

    def _print_list(self, seq):
        """MathML reference for the <list> element:
        http://www.w3.org/TR/MathML2/chapter4.html#contm.list"""
        dom_element = self.dom.createElement('list')
        for item in seq:
            dom_element.appendChild(self._print(item))
        return dom_element

    def _print_int(self, p):
        dom_element = self.dom.createElement(self.mathml_tag(p))
        dom_element.appendChild(self.dom.createTextNode(str(p)))
        return dom_element

    def apply_patch(self):
        # Applying the patch of xml.dom.minidom bug
        # Date: 2011-11-18
        # Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom-\
        #                   toprettyxml-and-silly-whitespace/#best-solution
        # Issue: http://bugs.python.org/issue4147
        # Patch: http://hg.python.org/cpython/rev/7262f8f276ff/

        from xml.dom.minidom import Element, Text, Node, _write_data

        def writexml(self, writer, indent="", addindent="", newl=""):
            # indent = current indentation
            # addindent = indentation to add to higher levels
            # newl = newline string
            writer.write(indent + "<" + self.tagName)

            attrs = self._get_attributes()
            a_names = list(attrs.keys())
            a_names.sort()

            for a_name in a_names:
                writer.write(" %s=\"" % a_name)
                _write_data(writer, attrs[a_name].value)
                writer.write("\"")
            if self.childNodes:
                writer.write(">")
                if (len(self.childNodes) == 1
                        and self.childNodes[0].nodeType == Node.TEXT_NODE):
                    self.childNodes[0].writexml(writer, '', '', '')
                else:
                    writer.write(newl)
                    for node in self.childNodes:
                        node.writexml(writer, indent + addindent, addindent,
                                      newl)
                    writer.write(indent)
                writer.write("</%s>%s" % (self.tagName, newl))
            else:
                writer.write("/>%s" % (newl))

        self._Element_writexml_old = Element.writexml
        Element.writexml = writexml

        def writexml(self, writer, indent="", addindent="", newl=""):
            _write_data(writer, "%s%s%s" % (indent, self.data, newl))

        self._Text_writexml_old = Text.writexml
        Text.writexml = writexml

    def restore_patch(self):
        from xml.dom.minidom import Element, Text
        Element.writexml = self._Element_writexml_old
        Text.writexml = self._Text_writexml_old