Example #1
0
def write_xml_file(data, sub_output_folder):
    doc = Document()
    doc.appendChild(doc.createComment(TMP_BUILD_VERSION))
    caseVars_E = doc.createElement("CaseVars")
    doc.appendChild(caseVars_E)
    for group, values in data.items():
        # if the group is empty, annotation it.
        if not values:
            caseVars_E.appendChild(doc.createComment("<Group name=\"%s\"/>" % group))
            continue

        group_E = doc.createElement("Group")
        group_E.setAttribute("name", group)
        for name, value in sorted(values.items()):
            item_E = doc.createElement("Item")
            item_E.setAttribute("desc", "")
            item_E.setAttribute("name", name)
            item_E.setAttribute("type", "String")
            value_text = doc.createTextNode(str(value))
            item_E.appendChild(value_text)
            group_E.appendChild(item_E)

        caseVars_E.appendChild(group_E)

    output_folder = os.path.join(OUTPUT_FOLDER, sub_output_folder)
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    output_file = os.path.join(output_folder, SHEET_NAME) + ".xml"
    with open(output_file, 'w', encoding='utf-8') as f:
        doc.writexml(f, newl='\n', addindent='\t', encoding='utf-8')
Example #2
0
 def formXml(self):
     """Form the XML to be written to RssFeeds.xml"""
     #create the document
     doc = Document()
     #create root element
     rssfeedsTag = doc.createElement('rssfeeds')
     doc.appendChild(rssfeedsTag)
     #create comments
     c1Tag = doc.createComment(
         'RSS feeds. To have multiple feeds, just add a feed to the set. You can also have multiple sets.'
     )
     c2Tag = doc.createComment(
         'To use different sets in your skin, each must be called from skin with a unique id.'
     )
     rssfeedsTag.appendChild(c1Tag)
     rssfeedsTag.appendChild(c2Tag)
     for setNum in sorted(self.feedsList.keys()):
         #create sets
         setTag = doc.createElement('set')
         #create attributes
         setTag.setAttribute('id', self.feedsList[setNum]['attrs']['id'])
         #only write rtl tags if they've been explicitly set
         if 'rtl' in self.feedsList[setNum]['attrs']:
             setTag.setAttribute('rtl',
                                 self.feedsList[setNum]['attrs']['rtl'])
         rssfeedsTag.appendChild(setTag)
         #create feed elements
         for feed in self.feedsList[setNum]['feedslist']:
             feedTag = doc.createElement('feed')
             feedTag.setAttribute('updateinterval', feed['updateinterval'])
             feedUrl = doc.createTextNode(feed['url'])
             feedTag.appendChild(feedUrl)
             setTag.appendChild(feedTag)
     return doc.toprettyxml(indent='  ', encoding='UTF-8')
Example #3
0
 def formXml(self):
     """Form the XML to be written to RssFeeds.xml"""
     #create the document
     doc = Document()
     #create root element
     rssfeedsTag = doc.createElement('rssfeeds')
     doc.appendChild(rssfeedsTag)
     #create comments
     c1Tag = doc.createComment('RSS feeds. To have multiple feeds, just add a feed to the set. You can also have multiple sets.')
     c2Tag = doc.createComment('To use different sets in your skin, each must be called from skin with a unique id.')
     rssfeedsTag.appendChild(c1Tag)
     rssfeedsTag.appendChild(c2Tag)
     for setNum in sorted(self.feedsList.keys()):
         #create sets
         setTag = doc.createElement('set')
         #create attributes
         setTag.setAttribute('id', self.feedsList[setNum]['attrs']['id'])
         #only write rtl tags if they've been explicitly set
         if 'rtl' in self.feedsList[setNum]['attrs']:
             setTag.setAttribute('rtl', self.feedsList[setNum]['attrs']['rtl'])
         rssfeedsTag.appendChild(setTag)
         #create feed elements
         for feed in self.feedsList[setNum]['feedslist']:
             feedTag = doc.createElement('feed')
             feedTag.setAttribute('updateinterval', feed['updateinterval'])
             feedUrl = doc.createTextNode(feed['url'])
             feedTag.appendChild(feedUrl)
             setTag.appendChild(feedTag)
     return doc.toprettyxml(indent = '  ', encoding = 'UTF-8')
    def updateFontXML(self):
        dataDoc = Document()
        dataDoc.appendChild(dataDoc.createComment(xHeader + self.fontName))

        fontElem = dataDoc.createElement(xFont)
        dataDoc.appendChild(fontElem)

        fontElem.setAttribute(xSize, str(self.fontSize))
        fontElem.setAttribute(xName, self.fontName)

        crElem = dataDoc.createElement(xCRInfo)
        fontElem.appendChild(crElem)

        if (self.crInfo != ''):
            crElem.appendChild(dataDoc.createTextNode(self.crInfo))

        for char in self.glyphMap:
            charData = self.glyphMap[char]
            glyphElem = dataDoc.createElement(xGlyph)
            fontElem.appendChild(glyphElem)

            glyphElem.setAttribute('char', char)
            glyphElem.setAttribute(xROff, str(charData.rOffset))
            glyphElem.setAttribute(
                xBBox, '(' + ','.join([str(round(b, 2)) for b in charData.bbox]) + ')')

            glyphElem.appendChild(dataDoc.createTextNode(charData.pathStr))

        f = open(self.dataFilePath, "w")
        f.write(dataDoc.toxml(encoding="utf-8"))
        f.close()
Example #5
0
def write_bouquet(file, bouquet):
    doc = Document()
    root = doc.createElement("zapit")
    doc.appendChild(root)
    comment = doc.createComment(_COMMENT)
    doc.appendChild(comment)

    for bq in bouquet.bouquets:
        bq_elem = doc.createElement("Bouquet")
        bq_elem.setAttribute("name", bq.name)
        bq_elem.setAttribute("hidden", "1" if bq.hidden else "0")
        bq_elem.setAttribute("locked", "1" if bq.locked else "0")
        bq_elem.setAttribute("epg", "0")
        root.appendChild(bq_elem)

        for srv in bq.services:
            tr_id, on, ssid = srv.fav_id.split(":")
            srv_elem = doc.createElement("S")
            srv_elem.setAttribute("i", ssid)
            srv_elem.setAttribute("n", srv.service)
            srv_elem.setAttribute("t", tr_id)
            srv_elem.setAttribute("on", on)
            srv_elem.setAttribute("s", srv.pos.replace(".", ""))
            srv_elem.setAttribute("frq", srv.freq[:-3])
            srv_elem.setAttribute("l", "0")  # temporary !!!
            bq_elem.appendChild(srv_elem)

    doc.writexml(open(file, "w"),
                 addindent="    ",
                 newl="\n",
                 encoding="UTF-8")
def _replace_loop_placeholder(paragraph: Element, placeholder_text: str):
    """Replace paragraph containing mustache loop

    :param paragraph:
    :param placeholder_text:
    """
    parent_node = paragraph.parentNode
    if parent_node.tagName == 'w:body':
        # If placeholder is within body replace paragraph with xml comment
        # containing mustache loop
        comment = Document.createComment(parent_node, placeholder_text)
        parent_node.replaceChild(comment, paragraph)
    elif parent_node.tagName == 'w:tc':
        # If placeholder is within a table, replace row it resides with xml
        # comment containing mustache loop
        row = parent_node.parentNode
        table = row.parentNode
        comment = Document.createComment(table, placeholder_text)
        table.replaceChild(comment, row)
def _replace_loop_placeholder(paragraph: Element, placeholder_text: str):
    """Replace paragraph containing mustache loop

    :param paragraph:
    :param placeholder_text:
    """
    parent_node = paragraph.parentNode
    if parent_node.tagName == 'w:body':
        # If placeholder is within body replace paragraph with xml comment
        # containing mustache loop
        comment = Document.createComment(parent_node, placeholder_text)
        parent_node.replaceChild(comment, paragraph)
    elif parent_node.tagName == 'w:tc':
        # If placeholder is within a table, replace row it resides with xml
        # comment containing mustache loop
        row = parent_node.parentNode
        table = row.parentNode
        comment = Document.createComment(table, placeholder_text)
        table.replaceChild(comment, row)
Example #8
0
def convert_file(playlist):
    '''
    Playlist parser
    '''
    channel_count = 0
    EOL = '\n'
    header = playlist.readline()
    # Catching an exeption if the 1-st string in a *nix-formatted .m3u is empty
    try:
        if header[-2] == '\r':
            EOL = '\r' + EOL # Windows EOL convention
    except IndexError: pass
    if '#EXTM3U' in header:
        xml_config = Document()
        comment = xml_config.createComment(' This file is created by m3u2xml convertor ')
        xml_config.appendChild(comment)
        demo = xml_config.createElement('demo')
        xml_config.appendChild(demo)
        channels = xml_config.createElement('channels')
        demo.appendChild(channels)
        groups = xml_config.createElement('groups')
        demo.appendChild(groups)
        channel_info = []
        groups_list = {}
        # Extra protocols can be added if necessary
        PROTOCOLS = ['udp', 'http', 'rtmpe', 'rtp', 'rtsp']
        try:
            start_number = int(_START_No)
        except ValueError:
            start_number = 1
        for line in playlist:
            if line.split(':')[0] == '#EXTINF':
                channel_info.append(line.split(',')[-1].replace(EOL, '').decode(_ENC))
                if 'group-title=' in line and _ADDON.getSetting('groups') == 'true':
                    current_group = re.search(
                    r'group-title=".*?"', line).group().replace('group-title=', '').replace('\"', '').decode(_ENC)
                    groups_list[current_group] = []
            elif line.split(':')[0] in PROTOCOLS:
                if _ADDON.getSetting('useproxy') == 'true':
                    channel_info.append(_PROXY + line.replace(EOL, '').replace(':/', '').replace('@', ''))
                else:
                    channel_info.append(line.replace(EOL, ''))
                channel_num = start_number + channel_count
                chan_rec_create(xml_config, channels, channel_info, channel_num)
                if groups_list:
                    groups_list[current_group].append(channel_num)
                channel_count += 1
                channel_info = []
        if groups_list:
            groups_create(xml_config, demo, groups_list)
        out_xml = codecs.open(_PVR_CONFIG, encoding='utf-8', mode='w')
        xml_config.writexml(out_xml, newl='\n')
        out_xml.close()
    playlist.close()
    return channel_count
Example #9
0
    def write_refs_to_xml(path, services):
        header = '<?xml version="1.0" encoding="utf-8"?>\n<!--  {} -->\n<!-- {} -->\n<channels>\n'.format(
            "Created in DemonEditor.", datetime.now().strftime("%d.%m.%Y %H:%M:%S"))
        doc = Document()
        lines = [header]

        for srv in services:
            srv_type = srv.type
            if srv_type is BqServiceType.IPTV:
                channel_child = doc.createElement("channel")
                channel_child.setAttribute("id", str(srv.num))
                data = srv.data.strip().split(":")
                channel_child.appendChild(doc.createTextNode(":".join(data[:10])))
                comment = doc.createComment(srv.name)
                lines.append("{} {}\n".format(str(channel_child.toxml()), str(comment.toxml())))
            elif srv_type is BqServiceType.MARKER:
                comment = doc.createComment(srv.name)
                lines.append("{}\n".format(str(comment.toxml())))

        lines.append("</channels>")
        doc.unlink()

        with open(path, "w", encoding="utf-8") as f:
            f.writelines(lines)
Example #10
0
def write_satellites(satellites, data_path):
    """ Creation satellites.xml file """
    doc = Document()
    comment = doc.createComment(__COMMENT)
    doc.appendChild(comment)
    root = doc.createElement("satellites")
    doc.appendChild(root)

    for sat in satellites:
        #    Create Element
        sat_child = doc.createElement("sat")
        sat_child.setAttribute("name", sat.name)
        sat_child.setAttribute("flags", sat.flags)
        sat_child.setAttribute("position", sat.position)

        for tr in sat.transponders:
            transponder_child = doc.createElement("transponder")
            transponder_child.setAttribute("frequency", tr.frequency)
            transponder_child.setAttribute("symbol_rate", tr.symbol_rate)
            transponder_child.setAttribute(
                "polarization", get_key_by_value(POLARIZATION,
                                                 tr.polarization))
            transponder_child.setAttribute(
                "fec_inner",
                get_key_by_value(FEC, tr.fec_inner) or "0")
            transponder_child.setAttribute(
                "system",
                get_key_by_value(SYSTEM, tr.system) or "0")
            transponder_child.setAttribute(
                "modulation",
                get_key_by_value(MODULATION, tr.modulation) or "0")
            if tr.pls_mode:
                transponder_child.setAttribute("pls_mode", tr.pls_mode)
            if tr.pls_code:
                transponder_child.setAttribute("pls_code", tr.pls_code)
            if tr.is_id:
                transponder_child.setAttribute("is_id", tr.is_id)
            if tr.t2mi_plp_id:
                transponder_child.setAttribute("t2mi_plp_id", tr.t2mi_plp_id)
            sat_child.appendChild(transponder_child)
        root.appendChild(sat_child)
    doc.writexml(
        open(data_path, "w"),
        # indent="",
        addindent="    ",
        newl='\n',
        encoding="iso-8859-1")
    doc.unlink()
Example #11
0
def writeDataToXml(student_dict, xmlpath):
    doc = Document()
    root_node = doc.createElement('root')
    doc.appendChild(root_node)

    stu_node = doc.createElement('students')
    root_node.appendChild(stu_node)

    note_node = doc.createComment(comment)
    stu_node.appendChild(note_node)

    dict_node = doc.createTextNode(json.dumps(student_dict, ensure_ascii=False))
    stu_node.appendChild(dict_node)

    with open(xmlpath, "w", encoding='utf8') as file:
        transform = html.unescape(doc.toprettyxml(indent=''))
        file.write(transform)
Example #12
0
    def getXMLFile(self):
        self.traversalFileFolder(self.sourcedir)
        doc = Document()
        doc.appendChild(doc.createComment("Simple xml document__chapter 8"))

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

        source = doc.createElement('source')
        data_storage.appendChild(source)
        source_data = doc.createTextNode(
            self.sourcedir[self.sourcedir.index('/') + 1:])
        source.appendChild(source_data)

        classtype = doc.createElement('classtype')
        data_storage.appendChild(classtype)

        listlabel = list(self.filedict.keys())
        listlabel.sort()
        for key in listlabel:
            self.labeldict[key] = listlabel.index(key)
            classlabel = doc.createElement(key)
            classtype.appendChild(classlabel)
            label = doc.createElement('label')
            label_text = doc.createTextNode(str(listlabel.index(key)))
            label.appendChild(label_text)
            classlabel.appendChild(label)

            values = self.filedict[key]
            for value in values:
                li = doc.createElement('li')
                li_text = doc.createTextNode(value)
                li.appendChild(li_text)
                classlabel.appendChild(li)

        file_object = open(self.outfile, 'w')
        file_object.write(doc.toprettyxml())
        file_object.close()


# inputfolder = r'./baidunews'
# outputfile = r'baidunewslist.xml'
# XD = XMLData(inputfolder,outputfile)
# XD.getXMLFile()
Example #13
0
def student_to_html(list, xls_name):
    doc = Document()  # 空文档
    root = doc.createElement('root')  # 根节点
    child = doc.createElement('values')  # 创建节点
    root.appendChild(child)
    doc.appendChild(root)
    comment_node = doc.createComment(
        'comment is here!')  # 如果不加这一行, 那个value 的那个在同一行
    child.appendChild(comment_node)
    nodetxt = doc.createTextNode(str(list))
    child.appendChild(nodetxt)
    print(doc.toprettyxml(indent='\t', encoding='utf-8'))

    with open(os.path.join(xml_folder, xls_name + '.xml'), 'w') as f:
        doc.writexml(f,
                     indent='\t',
                     addindent='\t',
                     newl='\n',
                     encoding="utf-8")
Example #14
0
def insert_to_xml(xls_data, xls_name):
    xml_out = xls_name + '.xml'
    doc = Document()
    # 创建节点
    root_node = doc.createElement('root')
    child_node = doc.createElement(xls_name)
    # 插入节点
    doc.appendChild(root_node)
    root_node.appendChild(child_node)
    # 创建节点
    # comment_node = doc.createComment('学生信息表	"id" : [名字, 数学, 语文, 英文]')
    # comment_node = doc.createComment('城市信息')
    comment_node = doc.createComment('数字信息')
    child_node.appendChild(comment_node)

    txt_node = doc.createTextNode(str(xls_data))
    child_node.appendChild(txt_node)

    with open(xml_out, 'wb') as f:
        f.write(doc.toprettyxml(indent='\t', encoding='utf-8'))
Example #15
0
 def cloneNode(srcNode: Node, dstDom: Document) -> Node:
     """
     从源node克隆一个到目标dom
     :param srcNode: 源node
     :param dstDom: 目标dom
     :return: 新node
     """
     if srcNode.nodeType == Node.TEXT_NODE:
         return dstDom.createTextNode(srcNode.data)
     elif srcNode.nodeType == Node.COMMENT_NODE:
         return dstDom.createComment(srcNode.data)
     elif srcNode.nodeType == Node.ELEMENT_NODE:
         newNode = dstDom.createElement(srcNode.tagName)
         attrs = srcNode._get_attributes()
         for a_name in attrs.keys():
             newNode.setAttribute(a_name, attrs[a_name].value)
         DomXmlUtil.elementAddChildNodes(srcNode.childNodes, dstDom,
                                         newNode)
         return newNode
     pass
Example #16
0
def write_xlsx_to_xml(datadict, savename):
    # 创建dom文档
    doc = Document()
    # 创建根节点
    root = doc.createElement('root')
    # 创建student节点
    student = doc.createElement('student')
    # 根节点插入dom树
    doc.appendChild(root)
    # 将student子节点加入根节点
    root.appendChild(student)
    # 加入注释
    comment = doc.createComment('\n    学生信息表\n    "id" : [名字,数学,语文,英语]\n')
    student.appendChild(comment)
    # 加入内容
    text_node = doc.createTextNode(str(datadict))
    student.appendChild(text_node)
    # 保存为xml文件
    with open(savename, 'w', encoding='utf-8') as f:
        doc.writexml(f, addindent='  ', newl='\n', encoding='utf-8')
Example #17
0
def XlsSaveXml(path1, path2):
    data = get_data(path1)
    for key, value in data.items():
        # dic = {}
        # for L in value:
        #     num = L.pop(0)
        #     dic[num] = L
        text_data = json.dumps(value, ensure_ascii=False)
        # print(text_data)
        # print(type(text_data))
        dom = Document()
        root = dom.createElement('root')
        dom.appendChild(root)
        city = dom.createElement(key)
        root.appendChild(city)
        comment = dom.createComment('\n数字信息\n')
        city.appendChild(comment)
        text = dom.createTextNode(text_data)
        city.appendChild(text)
        with open(path2, 'w', encoding='utf-8') as f:
            dom.writexml(f, newl='\n', encoding='UTF-8')
Example #18
0
def XlsSaveXml(path1, path2):
    data = get_data(path1)
    for key, value in data.items():
        dic = {}
        for L in value:
            num = L.pop(0)
            dic[num] = L
        text_data = json.dumps(dic, ensure_ascii=False)
        print(text_data)
        print(type(text_data))
        dom = Document()
        root = dom.createElement('root')
        dom.appendChild(root)
        stu = dom.createElement(key)
        root.appendChild(stu)
        comment = dom.createComment('\n学生信息表\n"id":[名字,数学,语文,英文]\n')
        stu.appendChild(comment)
        text = dom.createTextNode(text_data)
        stu.appendChild(text)
        with open(path2, 'w', encoding='utf-8') as f:
            dom.writexml(f, newl='\n', encoding='UTF-8')
Example #19
0
def write_webtv(file, bouquet):
    doc = Document()
    root = doc.createElement("webtvs")
    doc.appendChild(root)
    comment = doc.createComment(_COMMENT)
    doc.appendChild(comment)

    for bq in bouquet.bouquets:
        for srv in bq.services:
            url, description, urlkey, account, usrname, psw, s_type, iconsrc, iconsrc_b, group = srv.fav_id.split(
                "::")
            srv_elem = doc.createElement("webtv")
            srv_elem.setAttribute("title", srv.service)
            srv_elem.setAttribute("url", url)

            if description != "None":
                srv_elem.setAttribute("description", description)
            if urlkey != "None":
                srv_elem.setAttribute("urlkey", urlkey)
            if account != "None":
                srv_elem.setAttribute("account", account)
            if usrname != "None":
                srv_elem.setAttribute("usrname", usrname)
            if psw != "None":
                srv_elem.setAttribute("psw", psw)
            if s_type != "None":
                srv_elem.setAttribute("type", s_type)
            if iconsrc != "None":
                srv_elem.setAttribute("iconsrc", iconsrc)
            if iconsrc_b != "None":
                srv_elem.setAttribute("iconsrc_b", iconsrc_b)
            if group != "None":
                srv_elem.setAttribute("group", group)

            root.appendChild(srv_elem)

    doc.writexml(open(file, "w"),
                 addindent="    ",
                 newl="\n",
                 encoding="UTF-8")
Example #20
0
def write_student_to_xml(dic=None, to_path=None):
    if dic is None or to_path is None:
        return None

    doc = Document()
    root_node = doc.createElement("root")
    doc.appendChild(root_node)

    stu_node = doc.createElement("students")
    root_node.appendChild(stu_node)

    note_node = doc.createComment("\n\t学生信息表\n\t\"id\" : [名字, 数学, 语文, 英文]\n\t")
    stu_node.appendChild(note_node)

    # data = json.dumps(dic, ensure_ascii=False, indent=1)
    dic_node = doc.createTextNode(stringer.dict_to_json(dic, "\t\t"))
    stu_node.appendChild(dic_node)

    file = open(to_path, "w")
    file.write(doc.toprettyxml())
    # doc.writexml(file,'    ','    ','\n','utf-8')
    file.close()
    def getXMLFile(self):
        self.traversalFileFolder(self.sourcedir)
        doc = Document()
        doc.appendChild(doc.createComment("Simple xml document__chapter 8"))

        data_storage = doc.createElement("data_storage")
        doc.appendChild(data_storage)

        source = doc.createElement("source")
        data_storage.appendChild(source)
        source_data = doc.createTextNode(self.sourcedir[self.sourcedir.index("/") + 1 :])
        source.appendChild(source_data)

        classtype = doc.createElement("classtype")
        data_storage.appendChild(classtype)

        listlabel = list(self.filedict.keys())
        listlabel.sort()
        for key in listlabel:
            classlabel = doc.createElement(key)
            classtype.appendChild(classlabel)
            label = doc.createElement("label")
            label_text = doc.createTextNode(str(listlabel.index(key)))
            label.appendChild(label_text)
            classlabel.appendChild(label)

            values = self.filedict[key]
            for value in values:
                li = doc.createElement("li")
                li_text = doc.createTextNode(value)
                li.appendChild(li_text)
                classlabel.appendChild(li)

        file_object = open(self.outfile, "w")
        file_object.write(doc.toprettyxml())
        file_object.close()
Example #22
0
class T(basecanvas.T):
    def __init__(self, fname):
        basecanvas.T.__init__(self)
        self.__out_fname = fname
        self.__xmin, self.__xmax, self.__ymin, self.__ymax = 0, 0, 0, 0
        self.__doc = Document()
        self.__doc.appendChild(
            self.__doc.createComment('Created by PyChart ' + version.version +
                                     ' ' + version.copyright))
        self.__svg = self.__doc.createElement('svg')  # the svg doc
        self.__doc.appendChild(self.__svg)
        self.__defs = self.__doc.createElement('defs')  # for clip paths
        self.__svg.appendChild(self.__defs)
        self.__currElt = self.__svg
        self.gsave()  # create top-level group for dflt styles
        self._updateStyle(
            font_family=theme.default_font_family,
            font_size=theme.default_font_size,
            font_style='normal',
            font_weight='normal',
            font_stretch='normal',
            fill='none',
            stroke='rgb(0,0,0)',  #SVG dflt none, PS dflt blk
            stroke_width=theme.default_line_width,
            stroke_linejoin='miter',
            stroke_linecap='butt',
            stroke_dasharray='none')

    def _updateStyle(self, **addstyledict):
        elt = _protectCurrentChildren(self.__currElt)

        # fetch the current styles for this node
        mystyledict = _parseStyleStr(elt.getAttribute('style'))

        # concat all parent style strings to get dflt styles for this node
        parent, s = elt.parentNode, ''
        while parent.nodeType != Document.nodeType:
            # prepend parent str so later keys will override earlier ones
            s = parent.getAttribute('style') + s
            parent = parent.parentNode
        dfltstyledict = _parseStyleStr(s)

        # Do some pre-processing on the caller-supplied add'l styles
        # Convert '_' to '-' so caller can specify style tags as python
        # variable names, eg. stroke_width => stroke-width.
        # Also convert all RHS values to strs
        for key in addstyledict.keys():
            k = re.sub('_', '-', key)
            addstyledict[k] = str(addstyledict[key])  # all vals => strs
            if (k != key): del addstyledict[key]

        for k in addstyledict.keys():
            if (mystyledict.has_key(k) or  # need to overwrite it
                (not dfltstyledict.has_key(k)) or  # need to set it
                    dfltstyledict[k] !=
                    addstyledict[k]):  # need to override it
                mystyledict[k] = addstyledict[k]

        s = _makeStyleStr(mystyledict)
        if s: elt.setAttribute('style', s)

        self.__currElt = elt

    ####################################################################
    # methods below define the pychart backend device API

    # First are a set of methods to start, construct and finalize a path

    def newpath(self):  # Start a new path
        if (self.__currElt.nodeName != 'g'):
            raise OverflowError, "No containing group for newpath"
        # Just insert a new 'path' element into the document
        p = self.__doc.createElement('path')
        self.__currElt.appendChild(p)
        self.__currElt = p

    # This set of methods add data to an existing path element,
    # simply add to the 'd' (data) attribute of the path elt

    def moveto(self, x, y):  #
        if (self.__currElt.nodeName != 'path'):
            raise OverflowError, "No path for moveto"
        d = ' '.join([self.__currElt.getAttribute('d'), 'M', ` x `, ` -y
                      `]).strip()
        self.__currElt.setAttribute('d', d)

    def lineto(self, x, y):
        if (self.__currElt.nodeName != 'path'):
            raise OverflowError, "No path for lineto"
        d = ' '.join([self.__currElt.getAttribute('d'), 'L', ` x `, ` -y
                      `]).strip()
        self.__currElt.setAttribute('d', d)

    def path_arc(self, x, y, radius, ratio, start_angle, end_angle):
        # mimic PS 'arc' given radius, yr/xr (=eccentricity), start and
        # end angles.  PS arc draws from CP (if exists) to arc start,
        # then draws arc in counterclockwise dir from start to end
        # SVG provides an arc command that draws a segment of an
        # ellipse (but not a full circle) given these args:
        # A xr yr rotate majorArcFlag counterclockwiseFlag xe ye
        # We don't use rotate(=0) and flipped axes => all arcs are clockwise

        if (self.__currElt.nodeName != 'path'):
            raise OverflowError, "No path for path_arc"

        self.comment('x=%g, y=%g, r=%g, :=%g, %g-%g' %
                     (x, y, radius, ratio, start_angle, end_angle))

        xs = x + radius * math.cos(2 * math.pi / 360. * start_angle)
        ys = y + ratio * radius * math.sin(2 * math.pi / 360. * start_angle)
        xe = x + radius * math.cos(2 * math.pi / 360. * end_angle)
        ye = y + ratio * radius * math.sin(2 * math.pi / 360. * end_angle)
        if (end_angle < start_angle):  # make end bigger than start
            while end_angle <= start_angle:  # '<=' so 360->0 becomes 360->720
                end_angle += 360
        full_circ = (end_angle - start_angle >= 360)  # draw a full circle?

        d = self.__currElt.getAttribute('d')
        d += ' %s %g %g' % (d and 'L' or 'M', xs, -ys
                            )  # draw from CP, if exists
        if (radius > 0):  # skip, eg. 0-radius 'rounded' corners which blowup
            if (full_circ):
                # If we're drawing a full circle, move to the end coord
                # and draw half a circle to the reflected xe,ye
                d += ' M %g %g A %g %g 0 1 0 %g %g' % (
                    xe, -ye, radius, radius * ratio, 2 * x - xe, -(2 * y - ye))
            # Draw arc from the CP (either reflected xe,ye for full circle else
            # xs,ys) to the end coord - note with full_circ the
            # 'bigArcFlag' value is moot, with exactly 180deg left to draw
            d += ' A %g %g 0 %d 0 %g %g' % (
                radius, radius * ratio, end_angle - start_angle > 180, xe, -ye)
        self.__currElt.setAttribute('d', d.strip())

    def curveto(self, x1, y1, x2, y2, x3, y3):
        # Equivalent of PostScript's x1 y1 x2 y2 x3 y3 curveto which
        # draws a cubic bezier curve from curr pt to x3,y3 with ctrl points
        # x1,y1, and x2,y2
        # In SVG this is just d='[M x0 y0] C x1 y1 x2 y2 x3 y3'
        #! I can't find an example of this being used to test it
        if (self.__currElt.nodeNode != 'path'):
            raise OverflowError, "No path for curveto"
        d = ' '.join([
            self.__currElt.getAttribute('d'),
            'C',
            ` x1 `,
            ` -y1 `,
            ` x2 `,
            ` -y2 `,
            ` x3 `,
            ` -y3 `,
        ]).strip()
        self.__currElt.setAttribute('d', d)

    def closepath(self):  # close back to start of path
        if (self.__currElt.nodeName != 'path'):
            raise OverflowError, "No path for closepath"
        d = ' '.join([self.__currElt.getAttribute('d'), 'Z']).strip()
        self.__currElt.setAttribute('d', d)

    # Next we have three methods for finalizing a path element,
    # either fill it, clip to it, or draw it (stroke)
    # canvas.polygon() can generate fill/clip cmds with
    # no corresponding path so just ignore them
    def stroke(self):
        if (self.__currElt.nodeName != 'path'):
            self.comment('No path - ignoring stroke')
            return
        self._updateStyle(fill='none')
        self.__currElt = self.__currElt.parentNode

    def fill(self):
        if (self.__currElt.nodeName != 'path'):
            self.comment('No path - ignoring fill')
            return
        self._updateStyle(stroke='none')
        self.__currElt = self.__currElt.parentNode

    def clip_sub(self):
        if (self.__currElt.nodeName != 'path'):
            self.comment('No path - ignoring clip')
            return

        # remove the current path from the tree ...
        p = self.__currElt
        self.__currElt = p.parentNode
        self.__currElt.removeChild(p)

        # ... add it to a clipPath elt in the defs section
        clip = self.__doc.createElement('clipPath')
        clipid = 'clip' + ` len(self.__defs.childNodes) `
        clip.setAttribute('id', clipid)
        clip.appendChild(p)
        self.__defs.appendChild(clip)

        # ... update the local style to point to it
        self._updateStyle(clip_path='url(#%s)' % clipid)

    # The text_xxx routines specify the start/end and contents of text
    def text_begin(self):
        if (self.__currElt.nodeName != 'g'):
            raise ValueError, "No group for text block"
        t = self.__doc.createElement('text')
        self.__currElt.appendChild(t)
        self.__currElt = t

    def text_moveto(self, x, y, angle):
        if (self.__currElt.nodeName != 'text'):
            raise ValueError, "No text for moveto"
        self.__currElt.setAttribute('x', ` x `)
        self.__currElt.setAttribute('y', ` -y `)
        if (angle):
            self.__currElt.setAttribute('transform',
                                        'rotate(%g,%g,%g)' % (-angle, x, -y))

    def text_show(self, font_name, size, color, str):
        if (self.__currElt.nodeName != 'text'):
            raise ValueError, "No text for show"

        # PyChart constructs a postscript font name, for example:
        #
        # Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique
        # Helvetica-Narrow Times-Roman Times-Italic
        # Symbol Palatino-Roman Bookman-Demi Courier AvantGarde-Book
        #
        # We need to deconstruct this to get the font-family (the
        # piece before the '-'), and other characteristics.
        # Note that 'Courier' seems to correspond to SVGs 'CourierNew'
        # and that the SVG Symbol font is Unicode where the ascii text
        # 'Symbol' doesn't create greek characters like 'Sigma ...' -
        # should really pass a unicode string, or provide translation
        #
        # SVG defines:
        # font-style = normal (aka roman) | italic | oblique
        # font-weight = normal | bold (aka demi?)
        # font-stretch = normal | wider | narrower | ultra-condensed |
        #	extra-condensed | condensed | semi-condensed |
        #	semi-expanded | expanded | extra-expanded | ultra-expanded
        # ('narrow' seems to correspond to 'condensed')

        m = re.match(r'([^-]*)(-.*)?', font_name)
        font_name, modifiers = m.groups()
        if font_name == 'Courier': font_name = 'CourierNew'
        font_style = font_weight = font_stretch = 'normal'
        if modifiers:
            if re.search('Italic', modifiers): font_style = 'italic'
            elif re.search('Oblique', modifiers): font_style = 'oblique'
            if re.search('Bold|Demi', modifiers): font_weight = 'bold'
            if re.search('Narrow', modifiers): font_stretch = 'condensed'
        #! translate ascii symbol font chars -> unicode (see www.unicode.org)
        #! http://www.unicode.org/Public/MAPPINGS/VENDORS/ADOBE/symbol.txt
        #! but xml Text element writes unicode chars as '?' to XML file...
        str = re.sub(r'\\([()])', r'\1', str)  # unescape brackets
        self._updateStyle(fill=_svgcolor(color),
                          stroke='none',
                          font_family=font_name,
                          font_size=size,
                          font_style=font_style,
                          font_weight=font_weight,
                          font_stretch=font_stretch)
        self.__currElt.appendChild(self.__doc.createTextNode(str))

    def text_end(self):
        if (self.__currElt.nodeName != 'text'):
            raise ValueError, "No text for close"
        self.__currElt = self.__currElt.parentNode

    # Three methods that change the local style of elements
    # If applied to a group, they persist until the next grestore,
    # If applied within a path element, they only affect that path -
    # although this may not in general correspond to (say) PostScript
    # behavior, it appears to correspond to reflect mode of use of this API
    def set_fill_color(self, color):
        self._updateStyle(fill=_svgcolor(color))

    def set_stroke_color(self, color):
        self._updateStyle(stroke=_svgcolor(color))

    def set_line_style(self, style):  # see line_style.py
        linecap = {0: 'butt', 1: 'round', 2: 'square'}
        linejoin = {0: 'miter', 1: 'round', 2: 'bevel'}
        if style.dash: dash = ','.join(map(str, style.dash))
        else: dash = 'none'
        self._updateStyle(stroke_width=style.width,
                          stroke=_svgcolor(style.color),
                          stroke_linecap=linecap[style.cap_style],
                          stroke_linejoin=linejoin[style.join_style],
                          stroke_dasharray=dash)

    # gsave & grestore respectively push & pop a new context to hold
    # new style and transform parameters.  push/pop transformation are
    # similar but explicitly specify a coordinate transform at the
    # same time
    def gsave(self):
        if (self.__currElt.nodeName not in ['g', 'svg']):
            raise ValueError, "No group for gsave"
        g = self.__doc.createElement('g')
        self.__currElt.appendChild(g)
        self.__currElt = g

    def grestore(self):
        if (self.__currElt.nodeName != 'g'):
            raise ValueError, "No group for grestore"
        # first pop off any auto-generated groups (see protectCurrentChildren)
        while (self.__currElt.hasAttribute('auto')):
            self.__currElt.removeAttribute('auto')
            self.__currElt = self.__currElt.parentNode
        # then pop off the original caller-generated group
        self.__currElt = self.__currElt.parentNode

    def push_transformation(self, baseloc, scale, angle, in_text=0):
        #? in_text arg appears to always be ignored

        # In some cases this gets called after newpath, with
        # corresonding pop_transformation called after the path is
        # finalized so we check specifically for that, and generate
        # an enclosing group to hold the incomplete path element
        # We could add the transform directly to the path element
        # (like we do with line-style etc) but that makes it harder
        # to handle the closing 'pop' and might lead to inconsitency
        # with PostScript if the closing pop doesn't come right after
        # the path element

        elt = self.__currElt
        if elt.nodeName == 'g':
            elt = None
        elif (elt.nodeName == 'path' and not elt.hasAttribute('d')):
            g = elt.parentNode
            g.removeChild(elt)
            self.__currElt = g
        else:
            raise ValueError, "Illegal placement of push_transformation"

        t = ''
        if baseloc:
            t += 'translate(%g,%g) ' % (baseloc[0], -baseloc[1])
        if angle:
            t += 'rotate(%g) ' % -angle
        if scale:
            t += 'scale(%g,%g) ' % tuple(scale)

        self.gsave()
        self.__currElt.setAttribute('transform', t.strip())
        if elt:  # elt has incomplete 'path' or None
            self.__currElt.appendChild(elt)
            self.__currElt = elt

    def pop_transformation(self, in_text=0):  #? in_text unused?
        self.grestore()

    # If verbose, add comments to the output stream (helps debugging)
    def comment(self, str):
        if _comment_p:
            self.__currElt.appendChild(self.__doc.createComment(str))

    # The verbatim method is currently not supported - presumably with
    # the SVG backend the user would require access to the DOM since
    # we're not directly outputting plain text here
    def verbatim(self, str):
        self.__currElt.appendChild(
            self.__doc.createComment('verbatim not implemented: ' + str))

    # The close() method finalizes the SVG document and flattens the
    # DOM document to XML text to the specified file (or stdout)
    def close(self):
        basecanvas.T.close(self)
        self.grestore()  # matching the gsave in __init__
        if (self.__currElt.nodeName != 'svg'):
            raise ValueError, "Incomplete document at close!"

        # Don't bother to output an empty document - this can happen
        # when we get close()d immediately by theme reinit
        if (len(self.__svg.childNodes[-1].childNodes) == 0):
            return

        fp, need_close = self.open_output(self.__out_fname)
        bbox = theme.adjust_bounding_box(
            [self.__xmin, self.__ymin, self.__xmax, self.__ymax])
        self.__svg.setAttribute(
            'viewBox', '%g %g %g %g' %
            (xscale(bbox[0]), -yscale(bbox[3]), xscale(bbox[2]) -
             xscale(bbox[0]), yscale(bbox[3]) - yscale(bbox[1])))
        self.__doc.writexml(fp, '', '  ', '\n')
        if need_close:
            fp.close()
Example #23
0
    def save(self, outfile):
        """
        Save the current working SPN to a file of a given name
        in the current dir. vdict contains the labels and data 
        of the vector vars, mdict is the matrices.
        """
        import re
        import datetime
        from xml.dom.minidom import Document

        # Open file, build header
        f = open(outfile, 'w')
        doc = Document()
        # write header with program, date/time:
        comm = doc.createComment('Created by SPNlib on %s' \
                % str(datetime.datetime.now().strftime("%d-%m-%Y at %H:%M")))
        doc.appendChild(comm)
        pnml = doc.createElement("pnml")
        pnml.setAttribute("xmlns",
                          'http://www.pnml.org/version-2009/grammar/pnml')
        doc.appendChild(pnml)
        net = doc.createElement("net")
        net.setAttribute("id", "SPN")
        # Important: set net type: stochastic
        net.setAttribute("type", "Stochastic")
        pnml.appendChild(net)

        # build file body
        c1 = 0  # places count
        pdict = {}
        c2 = 0  # trans count
        c3 = 0  # inhib count
        c4 = 0  # test count

        # Set places, markings:
        for spe in self.vdict['p']:
            s = doc.createElement("place")
            s.setAttribute("id", spe)
            if self.vdict['c'] != None:
                s.setAttribute("capacity", str(self.vdict['c'][c1]))
            pdict[c1] = spe
            m = doc.createElement("initialMarking")
            v = doc.createElement("value")
            amount = doc.createTextNode(str(int(self.vdict['m'][c1])))
            v.appendChild(amount)
            m.appendChild(v)
            s.appendChild(m)
            net.appendChild(s)
            c1 += 1

        # Set transitions, rates:
        for reac in self.vdict['t']:
            r = doc.createElement("transition")
            r.setAttribute("id", reac)
            rate = doc.createElement("rate")
            v = doc.createElement("value")
            amount = doc.createTextNode(str(self.vdict['r'][c2]))
            v.appendChild(amount)
            rate.appendChild(v)
            r.appendChild(rate)
            net.appendChild(r)
            c2 += 1

        # Set Inhibitory arcs:
        try:
            if len(self.mdict['inhib']) != 0:
                for iarc in self.mdict['inhib']:
                    for h in range(0, c1):
                        if iarc[0, h] != 0:
                            inhib = doc.createElement("arc")
                            inhib.setAttribute("source", self.vdict['p'][h])
                            inhib.setAttribute("target", self.vdict['t'][c3])
                            inhib.setAttribute("type", "inhibitory")
                            inis = doc.createTextNode(str(iarc[0, h]))
                            va = doc.createElement("value")
                            va.appendChild(inis)
                            inhib.appendChild(va)
                            net.appendChild(inhib)
                    c3 += 1
        except TypeError:
            pass

        # Set Test arcs:
        try:
            if len(self.mdict['test']) != 0:
                for tarc in self.mdict['test']:
                    for bx in range(0, c1):
                        if tarc[0, bx] != 0:
                            tar = doc.createElement("arc")
                            tar.setAttribute("source", self.vdict['p'][bx])
                            tar.setAttribute("target", self.vdict['t'][c4])
                            tar.setAttribute("type", "test")
                            tis = doc.createTextNode(str(tarc[0, bx]))
                            val = doc.createElement("value")
                            val.appendChild(tis)
                            tar.appendChild(val)
                            net.appendChild(tar)
                    c4 += 1
        except TypeError:
            pass

        # row counting for pre/post
        rcr = 0
        rco = 0
        for bin in self.mdict['pre']:
            # here all from = place, all to = transitions
            for q in range(0, c1):
                if bin[0, q] != 0:
                    a = doc.createElement("arc")
                    a.setAttribute("source", self.vdict['p'][q])
                    a.setAttribute("target", self.vdict['t'][rcr])
                    stoich = doc.createTextNode(str(bin[0, q]))
                    v = doc.createElement("value")
                    v.appendChild(stoich)
                    a.appendChild(v)
                    net.appendChild(a)
            # row count pre
            rcr += 1
        for bin in self.mdict['post']:
            # here all from = trans, all to = place
            # bin = row
            for q in range(0, c1):
                # for each col
                if bin[0, q] != 0:
                    a = doc.createElement("arc")
                    a.setAttribute("source", self.vdict['t'][rco])
                    a.setAttribute("target", self.vdict['p'][q])
                    # c1 is count of places
                    # i.e. for LV, 0 and 1 (p1, p2)
                    # bin is row of post, e.g. [2,0] (row 0)
                    # this stoich of 2
                    stoich = doc.createTextNode(str(bin[0, q]))
                    v = doc.createElement("value")
                    v.appendChild(stoich)
                    a.appendChild(v)
                    net.appendChild(a)
                    q += 1
            # row count post
            rco += 1

        # write file
        out = doc.toprettyxml(indent="  ", encoding="UTF-8")
        f.write(out)
        f.close()
Example #24
0
def createSignatureDoc(chains, signatures, streamtags, triggerbits,
                       triggergroups):

    rel13_tag = True
    if len(streamtags) == 0 and len(triggerbits) == 0:
        rel13_tag = False

    # create dom document
    doc = Document()

    doctype = DocumentType("CHAIN_LIST")
    doctype.systemId = "chainlist.dtd"
    doc.appendChild(doctype)

    # comment fields
    C = []
    C.append(
        doc.createComment("xml script created %s on %s" %
                          (time.asctime(), socket.gethostname())))
    for c in C:
        doc.appendChild(c)

    # chain list
    firstChain = dict(zip(get_chain_record("keys"), chains[0]))
    chainList = doc.createElement("CHAIN_LIST")
    chainList.setAttribute("hlt_master_table.name", firstChain["menu.name"])
    chainList.setAttribute("hlt_master_table.version",
                           str(firstChain["menu.version"]))
    chainList.setAttribute("hlt_trigger_menu.name", firstChain["menu.name"])
    chainList.setAttribute("hlt_trigger_menu.version",
                           str(firstChain["menu.name"]))
    chainList.setAttribute("hlt_prescale_set.name", firstChain["pres.name"])
    chainList.setAttribute("hlt_prescale_set.version",
                           str(firstChain["pres.version"]))
    doc.appendChild(chainList)

    # chains
    prevLevel = ""
    prevChainCounter = 0
    prevSigCounter = 0
    prevTE = ""
    streamTagRecords = []
    isFirstChain = True

    streamtagDict = {}

    for record in streamtags:
        stream = dict(zip(get_streamtag_record("keys"), record))
        Lvl_ChCount = "%s_%i" % (str(
            stream["chain.level"]), int(stream["chain.counter"]))
        streamtag = doc.createElement("STREAMTAG")
        streamtag.setAttribute("obeyLB", str(stream["stream.obeylb"]))
        streamtag.setAttribute("prescale", str(stream["stream.pres"]))
        streamtag.setAttribute("stream", str(stream["stream.name"]))
        streamtag.setAttribute("type", str(stream["stream.type"]))
        if not Lvl_ChCount in streamtagDict:
            streamtagDict[Lvl_ChCount] = []
        streamtagDict[Lvl_ChCount].append(streamtag)

    triggerbitDict = {}
    for record in triggerbits:
        triggerbit = dict(zip(get_triggerbit_record("keys"), record))
        Lvl_ChCount = "%s_%i" % (str(
            triggerbit["chain.level"]), int(triggerbit["chain.counter"]))
        triggertype = doc.createElement("TRIGGERTYPE")
        triggertype.setAttribute("bit", str(triggerbit["triggerbit"]))
        if not Lvl_ChCount in triggerbitDict:
            triggerbitDict[Lvl_ChCount] = []
        triggerbitDict[Lvl_ChCount].append(triggertype)

    triggergroupDict = {}
    for record in triggergroups:
        print record
        group = dict(zip(get_triggergroup_record("keys"), record))
        Lvl_ChCount = "%s_%i" % (str(
            group["chain.level"]), int(group["chain.counter"]))
        if not Lvl_ChCount in triggergroupDict:
            triggergroupDict[Lvl_ChCount] = []
        triggergroup = doc.createElement("GROUP")
        triggergroup.setAttribute("name", str(group["group.name"]))
        triggergroupDict[Lvl_ChCount].append(triggergroup)

    signatureDict = {}
    for record in signatures:
        signature = dict(zip(get_signature_record("keys"), record))
        Lvl_ChCount = "%s_%i" % (str(
            signature["chain.level"]), int(signature["chain.counter"]))
        if not Lvl_ChCount in signatureDict:
            signatureDict[Lvl_ChCount] = {}
        if not signature["sign.counter"] in signatureDict[Lvl_ChCount]:
            sig = doc.createElement("SIGNATURE")
            sig.setAttribute("signature_counter",
                             str(signature["sign.counter"]))
            sig.setAttribute("logic", str(signature["sign.logic"]))
            signatureDict[Lvl_ChCount][signature["sign.counter"]] = sig
        # trigger elements in signature
        te = doc.createElement("TRIGGERELEMENT")
        te.setAttribute("te_name", signature["te.name"])
        signatureDict[Lvl_ChCount][signature["sign.counter"]].appendChild(te)

    # chains
    for record in chains:
        chain = dict(zip(get_chain_record("keys"), record))
        Lvl_ChCount = "%s_%i" % (str(
            chain["chain.level"]), int(chain["chain.counter"]))

        ch = doc.createElement("CHAIN")
        chainList.appendChild(ch)
        ch.setAttribute("chain_name", chain["chain.name"])
        ch.setAttribute("chain_counter", "%i" % chain["chain.counter"])
        ch.setAttribute("lower_chain_name", chain["chain.lowname"])
        ch.setAttribute("level", chain["chain.level"])
        ch.setAttribute("prescale", "%i" % chain["chain.pres"])
        ch.setAttribute("pass_through", "%i" % chain["chain.pass"])

        if rel13_tag:
            streamtagList = doc.createElement("STREAMTAG_LIST")
            ch.appendChild(streamtagList)
            if not Lvl_ChCount in streamtagDict:
                print "*** error: chain %s in level %s has no streamtag defined" \
                      % ( str(signature["chain.name"]), str(signature["chain.level"]) )
                print streamtagDict.keys()
                sys.exit(1)
            else:
                for streamtag in streamtagDict[Lvl_ChCount]:
                    streamtagList.appendChild(streamtag)

            triggertypeList = doc.createElement("TRIGGERTYPE_LIST")
            ch.appendChild(triggertypeList)
            if not Lvl_ChCount in triggerbitDict:
                print "*** error: chain %s in level %s has no triggertype defined" \
                      % ( str(signature["chain.name"]), str(signature["chain.level"]) )
                print triggerbitDict.keys()
                sys.exit(1)
            else:
                for triggertype in triggerbitDict[Lvl_ChCount]:
                    triggertypeList.appendChild(triggertype)

            triggergroupList = doc.createElement("GROUP_LIST")
            ch.appendChild(triggergroupList)
            if Lvl_ChCount in triggergroupDict:
                for triggergroup in triggergroupDict[Lvl_ChCount]:
                    triggergroupList.appendChild(triggergroup)

        # signatures in chain
        sigList = doc.createElement("SIGNATURE_LIST")
        ch.appendChild(sigList)
        if Lvl_ChCount in signatureDict:
            sigInChainDict = signatureDict[Lvl_ChCount]
            sigCounters = sigInChainDict.keys()
            sigCounters.sort()
            for sigC in sigCounters:
                sigList.appendChild(sigInChainDict[sigC])

    return doc
Example #25
0
    rowIndex = 0
    id = 0

    fExe = open(workPath + "//cmd", 'w')
    for row in reader:
        if (rowIndex == 0):
            header = row  #.split(',')
            N = size(header)
        else:
            cols = row  #.split(',')
            if (verbose):
                print cols[0]

            # Create the minidom document
            doc = Document()
            cc1 = doc.createComment("license:")
            cc2 = doc.createComment(
                "strictly confidential. Propietary Information")
            doc.appendChild(cc1)
            doc.appendChild(cc2)
            # Create the <main> base element
            top = doc.createElement("dvg_sns")
            doc.appendChild(top)
            top.setAttribute("id", str(id))
            top.setIdAttribute("id")
            id = id + 1
            top.setAttribute("testName", cols[0])
            if (individualTestDir == True):
                workPathTemp = workPath + cols[0]
                shutil.rmtree(workPathTemp, True)
                os.mkdir(workPathTemp)
Example #26
0
def write_services(path, services):
    doc = Document()
    root = doc.createElement("zapit")
    root.setAttribute("api", "4")
    doc.appendChild(root)
    comment = doc.createComment(
        " File was created in DemonEditor. Enjoy watching! ")
    doc.appendChild(comment)

    sats = {}
    for srv in services:
        flag = srv[0]
        if flag in sats:
            sats.get(flag).append(srv)
        else:
            srv_list = [srv]
            sats[flag] = srv_list

    for sat in sats:
        tr_atr = sat.split(":")
        sat_elem = doc.createElement("sat")
        sat_elem.setAttribute("name", tr_atr[0])
        sat_elem.setAttribute("position", tr_atr[1].replace(".", ""))
        sat_elem.setAttribute("diseqc", tr_atr[2])
        sat_elem.setAttribute("uncommited", tr_atr[3])
        root.appendChild(sat_elem)

        transponers = {}
        for srv in sats.get(sat):
            flag = srv[-1]
            if flag in transponers:
                transponers.get(flag).append(srv)
            else:
                srv_list = [srv]
                transponers[flag] = srv_list

        for tr in transponers:
            tr_elem = doc.createElement("TS")
            tr_atr = tr.split(":")
            for i, value in enumerate(tr_atr):
                if value == "None":
                    continue
                tr_elem.setAttribute(_TR_ATTR_NAMES[i], value)
            sat_elem.appendChild(tr_elem)

            for srv in transponers.get(tr):
                srv_elem = doc.createElement("S")
                srv_elem.setAttribute("i", srv.ssid)
                srv_elem.setAttribute("n", srv.service)

                srv_attrs = srv.data_id.split(":")
                api = srv_attrs.pop(0)

                if api == "3":
                    root.setAttribute("api", "3")  # !!!
                for i, value in enumerate(srv_attrs):
                    if value == "None":
                        continue
                    srv_elem.setAttribute(_SRV_ATTR_NAMES[i], value)

                tr_elem.appendChild(srv_elem)

    doc.writexml(open(path + _FILE, "w"),
                 addindent="    ",
                 newl="\n",
                 encoding="UTF-8")
    doc.unlink()
Example #27
0
    def writeXacro(self):

        # Create document
        doc = Document()

        # Create comment
        comment = doc.createComment(
            'WARNING: This file was auto-generated by csv2xacro_node.py. It should not be edited by hand.'
        )
        doc.appendChild(comment)

        # Create root label
        root = doc.createElement('robot')
        root.setAttribute('name', 'duckietown')
        root.setAttribute('xmlns:xacro', 'http://www.ros.org/wiki/xacro')
        doc.appendChild(root)

        # Create Parameters comment
        comment = doc.createComment('Parameters')
        root.appendChild(comment)

        # Create tile width
        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'tile_width')
        tempChild.setAttribute('value', str(self.tile_width))
        root.appendChild(tempChild)

        # Create tag offsets
        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_0')
        tempChild.setAttribute(
            'value', '%s %s' % (str(self.tag_offset), str(self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_1')
        tempChild.setAttribute(
            'value', '%s %s' % (str(self.tag_curb), str(self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_2')
        tempChild.setAttribute(
            'value', '%s %s' % (str(-self.tag_curb), str(self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_3')
        tempChild.setAttribute(
            'value', '%s %s' % (str(-self.tag_offset), str(self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_4')
        tempChild.setAttribute(
            'value', '%s %s' % (str(-self.tag_offset), str(-self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_5')
        tempChild.setAttribute(
            'value', '%s %s' % (str(-self.tag_curb), str(-self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_6')
        tempChild.setAttribute(
            'value', '%s %s' % (str(self.tag_curb), str(-self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name', 'pos_7')
        tempChild.setAttribute(
            'value', '%s %s' % (str(self.tag_offset), str(-self.tag_curb)))
        root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('Include the tile and tag macros')
        root.appendChild(comment)

        # Create file name
        tempChild = doc.createElement('xacro:include')
        tempChild.setAttribute(
            'filename',
            '$(find duckietown_description)/urdf/macros.urdf.xacro')
        root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment(
            'The world frame is at the lower left corner of duckietown')
        root.appendChild(comment)

        # Create link
        tempChild = doc.createElement('link')
        tempChild.setAttribute('name', 'world')
        root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('Describe the tiles')
        root.appendChild(comment)

        # Create tiles
        header = True
        x_max = 0
        y_max = 0
        for row in self.tile_csv:
            if header or row[0].isspace():
                header = False
                continue
            x = row[0].strip('" ')
            if int(x) > x_max:
                x_max = int(x)
            y = row[1].strip('" ')
            if int(y) > y_max:
                y_max = int(y)
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x', row[0].strip('" '))
            tempChild.setAttribute('y', row[1].strip('" '))
            tempChild.setAttribute('type', row[2].strip('" '))
            tempChild.setAttribute('rotation', row[3].strip('" '))
            root.appendChild(tempChild)

        # Check that the map has the right number of tiles
        if not ((x_max + 1) *
                (y_max + 1) == root.getElementsByTagName('xacro:tile').length):
            raise Exception("Map should be exactly rectangular.")

        # Create comment
        comment = doc.createComment('Empty border tiles')
        root.appendChild(comment)

        # Create empty border tiles
        for x in range(x_max + 2):
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x', str(x))
            tempChild.setAttribute('y', str(y_max + 1))
            tempChild.setAttribute('visible', 'false')
            root.appendChild(tempChild)

        for y in range(y_max + 1):
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x', str(x_max + 1))
            tempChild.setAttribute('y', str(y))
            tempChild.setAttribute('visible', 'false')
            root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('Describe the tags')
        root.appendChild(comment)

        # Create tags
        header = True
        for row in self.tag_csv:
            if header or row[0].isspace():
                header = False
                continue
            tempChild = doc.createElement('xacro:tag')
            tempChild.setAttribute('id', row[0].strip('" '))
            tempChild.setAttribute('x', row[1].strip('" '))
            tempChild.setAttribute('y', row[2].strip('" '))
            tempChild.setAttribute('pos', "${pos_" + row[3].strip('" ') + "}")
            tempChild.setAttribute('rotation', row[4].strip('" '))
            root.appendChild(tempChild)

        # Write to file
        doc.writexml(self.map_xml, indent='    ', addindent='    ', newl='\n')

        # Close file
        self.map_xml.close()
        self.tile_csv_file.close()
        self.tag_csv_file.close()
Example #28
0
def generation_Pserver(directory):
    """
    generate the package 'test' for the Package Server tests
    """
    
    makedirs ("%s/test" %(directory))#create the directory of the test's package
    
    doc=Document()

    comment = doc.createComment("DOCTYPE package SYSTEM \"package_v1.dtd\"")
    doc.appendChild(comment)
    
    package = doc.createElement("package")
    package.setAttribute("id","test")
    doc.appendChild(package)
    
    name = doc.createElement("name")
    package.appendChild(name)
    
    natext = doc.createTextNode("TestPackage")
    name.appendChild(natext)
    
    version = doc.createElement("version")
    package.appendChild(version)
    
    numeric = doc.createElement("numeric")
    version.appendChild(numeric)
    
    nutext = doc.createTextNode("")
    numeric.appendChild(nutext)
    
    label = doc.createElement("label")
    version.appendChild(label)
    
    latext = doc.createTextNode("2.0.0.9")
    label.appendChild(latext)
    
    description = doc.createElement("description")
    package.appendChild(description)
    
    dtext = doc.createTextNode("Ceci est le package de test")
    description.appendChild(dtext)
    
    commands = doc.createElement("commands")
    commands.setAttribute("reboot","1")
    package.appendChild(commands)
    
    Precommands = doc.createElement("Precommands")
    commands.appendChild(Precommands)
    
    Ptext = doc.createTextNode("")
    Precommands.appendChild(Ptext)
    
    installInit = doc.createElement("installInit")
    commands.appendChild(installInit)
    
    itext = doc.createTextNode("")
    installInit.appendChild(itext)
    
    
    command = doc.createElement("command")
    command.setAttribute("name","commande")
    commands.appendChild(command)
    
    ctext = doc.createTextNode("./install.bat")
    command.appendChild(ctext)
    
    postCommandSuccess = doc.createElement("postCommandSuccess")
    commands.appendChild(postCommandSuccess)
    
    Stext = doc.createTextNode("")
    postCommandSuccess.appendChild(Stext)
    
    postCommandFailure = doc.createElement("postCommandFailure")
    commands.appendChild(postCommandFailure)
    
    Ftext = doc.createTextNode("")
    postCommandFailure.appendChild(Ftext)
    
    
    fichier=open("%s/test/conf.xml" %(directory),"w")
    doc.writexml(fichier,indent="   ",addindent="    ",newl="\n", encoding="utf-8")
    
    chdir("%s/test" %(directory))
    instalfile=open("install.bat","w")
    instalfile.write("I can\'t be installed")
    instalfile.close()
Example #29
0
def createSequenceDoc(sequences):

    # create dom document
    doc = Document()

    # comment fields
    C = []
    C.append(
        doc.createComment("xml script created %s on %s" %
                          (time.asctime(), socket.gethostname())))
    for c in C:
        doc.appendChild(c)

    # document type
    doctype = DocumentType("SEQUENCE_LIST")
    doctype.systemId = "sequencelistnewformat.dtd"
    doc.appendChild(doctype)

    # sequence list
    seqList = doc.createElement("SEQUENCE_LIST")
    seqList.setAttribute("hlt_setup.name", "dummy")
    seqList.setAttribute("hlt_setup.version", "%i" % 1)
    doc.appendChild(seqList)

    # sequences

    # algorithms
    algoDict = {}
    for record in sequences:
        sequence = dict(zip(get_sequence_record("keys"), record))
        if sequence["te.inp.counter"] > 1:
            continue
        algSpec = "%s/%s" % (sequence["cp.name"], sequence["cp.alias"])
        if not sequence["te.name"] in algoDict:
            algoDict[sequence["te.name"]] = {}
        algoDict[sequence["te.name"]][sequence["cp.counter"]] = algSpec

    # input TEs
    inpTEdict = {}
    for record in sequences:
        sequence = dict(zip(get_sequence_record("keys"), record))
        outTE = str(sequence["te.name"])  # determines the sequence
        if sequence["te.inp.type"] == "input":
            inpTECount = int(sequence["te.inp.counter"])
        else:
            inpTECount = "topo"
        if not outTE in inpTEdict:
            inpTEdict[outTE] = {}
        if inpTECount in inpTEdict[outTE]:
            if inpTEdict[outTE][inpTECount] != sequence["te.inp.name"]:
                print "*** error: at position %s two different input TEs '%s' and '%s' were encountered => abort ***" \
                      % (str(inpTECount),sequence["te.inp.name"],inpTEdict[outTE][inpTECount])
                sys.exit(1)
        inpTEdict[outTE][inpTECount] = sequence["te.inp.name"]

    # put the SEQUENCE together
    for outTE in algoDict:

        thisTEsInpTEs = inpTEdict[outTE]
        hasTopoStartFrom = "topo" in thisTEsInpTEs
        counters = thisTEsInpTEs.keys()
        if hasTopoStartFrom:
            counters.remove("topo")
        counters.sort()
        inpTEStringDict = inpTEdict[outTE][counters[0]]
        for c in counters[1:]:
            inpTEStringDict += " " + inpTEdict[outTE][c]

        thisTEsAlgs = algoDict[outTE]
        algCounters = thisTEsAlgs.keys()
        algCounters.sort()
        algoString = " ".join([thisTEsAlgs[x] for x in algCounters])
        seq = doc.createElement("SEQUENCE")
        seq.setAttribute("input", inpTEStringDict)
        if hasTopoStartFrom:
            seq.setAttribute("topo_start_from", thisTEsInpTEs["topo"])
        seq.setAttribute("algorithm", algoString)
        seq.setAttribute("output", outTE)
        seqList.appendChild(seq)

    return doc
    def save(self, outfile):
        """
        Save the current working SPN to a file of a given name
        in the current dir. vdict contains the labels and data 
        of the vector vars, mdict is the matrices.
        """       
        import re
        import datetime
        from xml.dom.minidom import Document

        # Open file, build header
        f = open(outfile, 'w')
        doc = Document()
        # write header with program, date/time:
        comm = doc.createComment('Created by SPNlib on %s' \
                % str(datetime.datetime.now().strftime("%d-%m-%Y at %H:%M")))
        doc.appendChild(comm)
        pnml = doc.createElement("pnml")
        pnml.setAttribute("xmlns", 'http://www.pnml.org/version-2009/grammar/pnml')
        doc.appendChild(pnml)
        net = doc.createElement("net")
        net.setAttribute("id", "SPN")
        # Important: set net type: stochastic
        net.setAttribute("type", "Stochastic")
        pnml.appendChild(net)
        
        # build file body
        c1 = 0 # places count
        pdict = {}
        c2 = 0 # trans count
        c3 = 0 # inhib count
        c4 = 0 # test count

        # Set places, markings:
        for spe in self.vdict['p']:
            s = doc.createElement("place")
            s.setAttribute("id", spe)
            if self.vdict['c'] != None:
                s.setAttribute("capacity",str(self.vdict['c'][c1]))
            pdict[c1] = spe
            m = doc.createElement("initialMarking")
            v = doc.createElement("value")
            amount = doc.createTextNode(str(int(self.vdict['m'][c1])))
            v.appendChild(amount)
            m.appendChild(v)
            s.appendChild(m)
            net.appendChild(s)
            c1 += 1
        
        # Set transitions, rates:
        for reac in self.vdict['t']:
            r = doc.createElement("transition")
            r.setAttribute("id", reac)
            rate = doc.createElement("rate")
            v = doc.createElement("value")
            amount = doc.createTextNode(str(self.vdict['r'][c2]))
            v.appendChild(amount)
            rate.appendChild(v)
            r.appendChild(rate)
            net.appendChild(r)
            c2+=1

        # Set Inhibitory arcs:
        try:
            if len(self.mdict['inhib']) != 0:
                for iarc in self.mdict['inhib']:
                    for h in range(0,c1):
                        if iarc[0,h] != 0:
                           inhib = doc.createElement("arc")
                           inhib.setAttribute("source",self.vdict['p'][h])
                           inhib.setAttribute("target",self.vdict['t'][c3])
                           inhib.setAttribute("type","inhibitory")
                           inis = doc.createTextNode(str(iarc[0,h]))
                           va = doc.createElement("value")
                           va.appendChild(inis)
                           inhib.appendChild(va)
                           net.appendChild(inhib)
                    c3+=1
        except TypeError:
            pass
        
        # Set Test arcs:
        try:
            if len(self.mdict['test']) != 0:
                for tarc in self.mdict['test']:
                    for bx in range(0,c1):
                        if tarc[0,bx] != 0:
                           tar = doc.createElement("arc")
                           tar.setAttribute("source",self.vdict['p'][bx])
                           tar.setAttribute("target",self.vdict['t'][c4])
                           tar.setAttribute("type","test")
                           tis = doc.createTextNode(str(tarc[0,bx]))
                           val = doc.createElement("value")
                           val.appendChild(tis)
                           tar.appendChild(val)
                           net.appendChild(tar)
                    c4+=1         
        except TypeError:
            pass

        # row counting for pre/post
        rcr = 0
        rco = 0
        for bin in self.mdict['pre']:
        # here all from = place, all to = transitions
            for q in range(0,c1):
                if bin[0,q] != 0:
                    a = doc.createElement("arc")
                    a.setAttribute("source", self.vdict['p'][q])
                    a.setAttribute("target", self.vdict['t'][rcr])
                    stoich = doc.createTextNode(str(bin[0,q]))
                    v = doc.createElement("value")
                    v.appendChild(stoich)
                    a.appendChild(v)
                    net.appendChild(a)
            # row count pre
            rcr+=1
        for bin in self.mdict['post']:
        # here all from = trans, all to = place
        # bin = row
            for q in range(0,c1):
                # for each col
                if bin[0,q] != 0:
                    a = doc.createElement("arc")
                    a.setAttribute("source", self.vdict['t'][rco])
                    a.setAttribute("target", self.vdict['p'][q])
                    # c1 is count of places
                    # i.e. for LV, 0 and 1 (p1, p2)
                    # bin is row of post, e.g. [2,0] (row 0)
                    # this stoich of 2
                    stoich = doc.createTextNode(str(bin[0,q]))
                    v = doc.createElement("value")
                    v.appendChild(stoich)
                    a.appendChild(v)                   
                    net.appendChild(a)
                    q+=1
            # row count post
            rco+=1 
        
        # write file 
        out = doc.toprettyxml(indent="  ", encoding="UTF-8")
        f.write(out)
        f.close()
Example #31
0
# Initialize types
xmldoc = Document()
# in case we don't have a key line (bad!), assume some default field indices
index_feature_name = 0
index_target = 1
index_diameter = 2
index_lat = 3
index_long = 4
# 5 is not used yet
index_feature_type = 6
# 7 is not used yet
index_approval = 8
index_origin = 9

# Add introductory comments
introcomment1 = xmldoc.createComment(
    "Landmark coordinates from USGS Astrogeology Research Program")
introcomment2 = xmldoc.createComment(
    "https://planetarynames.wr.usgs.gov/AdvancedSearch")
introcomment3 = xmldoc.createComment(
    "Landmarks to be displayed in the user interface. ")
xmldoc.appendChild(introcomment1)
xmldoc.appendChild(introcomment2)
xmldoc.appendChild(introcomment3)

# Create the base XML element
landmarks = xmldoc.createElement("landmark-list")
#landmarks.setAttribute("xmlns", "http://mars-sim.sourceforge.net/landmarks")
#landmarks.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
#landmarks.setAttribute("xsi:schemaLocation", "http://mars-sim.sourceforge.net/landmarks schema/landmarks.xsd")

xmldoc.appendChild(landmarks)
Example #32
0
class RssApiWriter(ApiWriter):
    """Output the search results as an RSS data feed."""

    OurNamespace = "fp"  #TODO change to afg?

    def __init__(self, content_type):
        """No special initialization."""
        self.doc = None
        self.rss = None
        self.channel = None
        ApiWriter.__init__(self, content_type)

    def setup(self, request, result_set):
        """
    Create the RSS preamble, everything before the results list.
    """
        self.doc = Document()
        self.rss = self.doc.createElement('rss')
        self.rss.setAttribute('version', '2.0')
        self.rss.setAttribute('xmlns:georss', "http://www.georss.org/georss")
        self.rss.setAttribute('xmlns:gml', "http://www.opengis.net/gml")
        self.rss.setAttribute('xmlns:atom', "http://www.w3.org/2005/Atom")
        self.rss.setAttribute('xmlns:' + self.OurNamespace,
                              "http://www.allforgood.org/")
        self.doc.appendChild(self.rss)
        channel = self.doc.createElement('channel')
        self.rss.appendChild(channel)

        def create_text_element(parent, name, content=None, attrs=None):
            elem = self.doc.createElement(name)
            if attrs:
                for k, v in attrs.items():
                    elem.setAttribute(k, v)

            parent.appendChild(elem)
            if content != None:
                elem.appendChild(self.doc.createTextNode(str(content)))
            return elem

        create_text_element(channel, 'title', 'All for Good search results')
        create_text_element(channel, 'link', 'http://www.allforgood.org/')

        atom_link = self.doc.createElement('atom:link')
        channel.appendChild(atom_link)
        atom_link.setAttribute('href', result_set.request_url)
        atom_link.setAttribute('rel', 'self')
        atom_link.setAttribute('type', str(self.content_type))

        create_text_element(channel, 'description',
                            'All for Good search results')
        create_text_element(channel, 'language', content='en-us')
        create_text_element(channel, 'pubDate')  #TODO: fill this in
        create_text_element(channel,
                            'lastBuildDate',
                            content=result_set.last_build_date)

        if result_set.is_hoc:
            facets_node = create_text_element(channel, 'facets')
            for facet, facet_list in result_set.hoc_facets.items():
                if facet_list:
                    facet_node = create_text_element(facets_node, 'facet',
                                                     None, {'name': facet})
                    facet_name = facet_value = ''
                    for fv in facet_list:
                        if not facet_name:
                            facet_name = fv
                            facet_value = ''
                        elif not facet_value:
                            facet_value = fv
                            facet_value_node = create_text_element(
                                facet_node, 'count', facet_value,
                                {'name': facet_name})
                            facet_name = facet_value = ''

            if not result_set.is_cal:
                create_text_element(channel,
                                    'TotalMatch',
                                    content=str(result_set.total_match))
                create_text_element(channel,
                                    'TotalOpportunities',
                                    content=str(
                                        result_set.total_opportunities))

        self.channel = channel

    def add_result(self, result, result_set={}):
        """
    Add an <item/> stanza to the results.  The stanza will include the required
    RSS elements, plus our own namespaced elements.
    """
        def build_result_element(field_info, result):

            content = ''
            name = field_info[0]
            if not hasattr(result, name) and len(field_info) > 1:
                name = field_info[1]

            if hasattr(result, name):
                try:
                    content = str(getattr(result, name, ''))
                except UnicodeEncodeError:
                    content = getattr(result, name,
                                      '').encode('ascii', 'ignore')

            if name == "enddate":
                if custom_date_format(content) == 'Present':
                    content = ''
            elif name == "description":
                if result_set.args.get('fulldesc', '') != '1':
                    content = content[:300]
            elif name in ["eventrangestart", "eventrangeend"]:
                content = content.replace('T', ' ').strip('Z')

            return (name, content, None)

        item = self.doc.createElement('item')
        self.channel.appendChild(item)

        #standard RSS fields
        standard_fields = [('title', ), ('link', 'xml_url'),
                           ('description', 'snippet'), ('pubDate', ),
                           ('guid', 'xml_url')]
        added_list = []
        for field in standard_fields:
            (name, content, comment) = build_result_element(field, result)
            if len(name) < 3:
                continue

            if name == 'xml_url':
                name = 'link'
            else:
                name = API_FIELD_NAMES_MAP.get(name, name)

            if name in added_list:
                continue
            added_list.append(name)

            if comment:
                item.appendChild(self.doc.createComment(comment))
            subitem = self.doc.createElement(name)
            if content:
                text = self.doc.createTextNode(content)
                subitem.appendChild(text)
            item.appendChild(subitem)

        #and now our namespaced fields
        namespaced_fields = FIELD_TUPLES

        added_list = []
        for field_info in namespaced_fields:
            (name, content, comment) = build_result_element(field_info, result)

            name = self.OurNamespace + ':' + API_FIELD_NAMES_MAP.get(
                name, name)

            if (not result_set.is_hoc and not result_set.is_rss
                ) and name.lower() not in STANDARD_FIELDS:
                continue

            if result_set.is_cal and name.lower() not in CALENDAR_FIELDS:
                continue

            if name in added_list:
                continue
            added_list.append(name)

            if comment:
                item.appendChild(self.doc.createComment(comment))

            subitem = self.doc.createElement(name)
            if content:
                if len(field_info) > 1 and isinstance(
                        content, basestring) and content.find('\t') > 0:
                    content = content.split('\t')

                if isinstance(content, list):
                    for value in content:
                        subsubitem = self.doc.createElement(self.OurNamespace +
                                                            ':' +
                                                            field_info[1])
                        text = self.doc.createTextNode(value)
                        subsubitem.appendChild(text)
                        subitem.appendChild(subsubitem)
                else:
                    text = self.doc.createTextNode(content)
                    subitem.appendChild(text)

            item.appendChild(subitem)

    def finalize(self):
        """Return a string from the XML document."""
        #return self.doc.toxml(encoding='utf-8')
        return self.doc.toprettyxml(indent='  ', newl='\n', encoding='utf-8')
Example #33
0
# Initialize types 
xmldoc = Document()
# in case we don't have a key line (bad!), assume some default field indices
index_feature_name = 0
index_target = 1
index_diameter = 2
index_lat = 3
index_long = 4
# 5 is not used yet
index_feature_type = 6
# 7 is not used yet
index_approval = 8
index_origin = 9

# Add introductory comments 
introcomment1 = xmldoc.createComment("Landmark coordinates from USGS Astrogeology Research Program")
introcomment2 = xmldoc.createComment("http://planetarynames.wr.usgs.gov/AdvancedSearch")
introcomment3 = xmldoc.createComment("Landmarks to be displayed in the user interface. ")
xmldoc.appendChild(introcomment1)
xmldoc.appendChild(introcomment2)
xmldoc.appendChild(introcomment3)
 
# Create the base XML element
landmarks = xmldoc.createElement("landmark-list")
#landmarks.setAttribute("xmlns", "http://mars-sim.sourceforge.net/landmarks")
#landmarks.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
#landmarks.setAttribute("xsi:schemaLocation", "http://mars-sim.sourceforge.net/landmarks schema/landmarks.xsd")

xmldoc.appendChild(landmarks)

# Open and parse the search results file (TSV), get the data key and data
Example #34
0
class T(basecanvas.T):
    def __init__(self, fname):
        basecanvas.T.__init__(self)
        self.__out_fname = fname
        self.__xmin, self.__xmax, self.__ymin, self.__ymax = 0,0,0,0
        self.__doc = Document()
        self.__doc.appendChild(self.__doc.createComment
             ('Created by PyChart ' + version.version + ' ' + version.copyright))
        self.__svg = self.__doc.createElement('svg') # the svg doc
        self.__doc.appendChild(self.__svg)
        self.__defs = self.__doc.createElement('defs') # for clip paths
        self.__svg.appendChild(self.__defs)
        self.__currElt = self.__svg
        self.gsave()       # create top-level group for dflt styles
        self._updateStyle(font_family = theme.default_font_family,
                          font_size = theme.default_font_size,
                          font_style = 'normal',
                          font_weight = 'normal',
                          font_stretch = 'normal',
                          fill = 'none',
                          stroke = 'rgb(0,0,0)', #SVG dflt none, PS dflt blk
                          stroke_width = theme.default_line_width,
                          stroke_linejoin = 'miter',
                          stroke_linecap = 'butt',
                          stroke_dasharray = 'none')
        
    def _updateStyle(self, **addstyledict): 
        elt = _protectCurrentChildren(self.__currElt)

        # fetch the current styles for this node
        mystyledict = _parseStyleStr(elt.getAttribute('style'))

        # concat all parent style strings to get dflt styles for this node
        parent,s = elt.parentNode,''
        while parent.nodeType != Document.nodeType :
            # prepend parent str so later keys will override earlier ones
            s = parent.getAttribute('style') + s
            parent = parent.parentNode
        dfltstyledict = _parseStyleStr(s)

        # Do some pre-processing on the caller-supplied add'l styles
        # Convert '_' to '-' so caller can specify style tags as python
        # variable names, eg. stroke_width => stroke-width.
        # Also convert all RHS values to strs 
        for key in addstyledict.keys():
            k = re.sub('_','-',key)
            addstyledict[k] = str(addstyledict[key]) # all vals => strs
            if (k != key) : del addstyledict[key]

        for k in addstyledict.keys() :
            if (mystyledict.has_key(k) or # need to overwrite it
                (not dfltstyledict.has_key(k)) or # need to set it
                dfltstyledict[k] != addstyledict[k]) : # need to override it
                mystyledict[k] = addstyledict[k]
        
        s = _makeStyleStr(mystyledict)
        if s : elt.setAttribute('style',s)

        self.__currElt = elt

    ####################################################################
    # methods below define the pychart backend device API

    # First are a set of methods to start, construct and finalize a path
    
    def newpath(self):                  # Start a new path
        if (self.__currElt.nodeName != 'g') :
            raise OverflowError, "No containing group for newpath"
        # Just insert a new 'path' element into the document
        p = self.__doc.createElement('path')
        self.__currElt.appendChild(p)
        self.__currElt = p

    # This set of methods add data to an existing path element,
    # simply add to the 'd' (data) attribute of the path elt
    
    def moveto(self, x, y):             # 
        if (self.__currElt.nodeName != 'path') :
            raise OverflowError, "No path for moveto"
        d = ' '.join([self.__currElt.getAttribute('d'),'M',`x`,`-y`]).strip()
        self.__currElt.setAttribute('d', d)
    def lineto(self, x, y):
        if (self.__currElt.nodeName != 'path') :
            raise OverflowError, "No path for lineto"
        d = ' '.join([self.__currElt.getAttribute('d'),'L',`x`,`-y`]).strip()
        self.__currElt.setAttribute('d', d)
    def path_arc(self, x, y, radius, ratio, start_angle, end_angle):
        # mimic PS 'arc' given radius, yr/xr (=eccentricity), start and
        # end angles.  PS arc draws from CP (if exists) to arc start,
        # then draws arc in counterclockwise dir from start to end
        # SVG provides an arc command that draws a segment of an
        # ellipse (but not a full circle) given these args:
        # A xr yr rotate majorArcFlag counterclockwiseFlag xe ye
        # We don't use rotate(=0) and flipped axes => all arcs are clockwise

        if (self.__currElt.nodeName != 'path') :
            raise OverflowError, "No path for path_arc"

        self.comment('x=%g, y=%g, r=%g, :=%g, %g-%g' 
                     % (x,y,radius,ratio,start_angle,end_angle))

        xs = x+radius*math.cos(2*math.pi/360.*start_angle)
        ys = y+ratio*radius*math.sin(2*math.pi/360.*start_angle)
        xe = x+radius*math.cos(2*math.pi/360.*end_angle)
        ye = y+ratio*radius*math.sin(2*math.pi/360.*end_angle)
        if (end_angle < start_angle) :  # make end bigger than start
            while end_angle <= start_angle: # '<=' so 360->0 becomes 360->720
                end_angle += 360
        full_circ = (end_angle - start_angle >= 360) # draw a full circle?
            
        d = self.__currElt.getAttribute('d')
        d += ' %s %g %g' % (d and 'L' or 'M',xs,-ys) # draw from CP, if exists
        if (radius > 0) : # skip, eg. 0-radius 'rounded' corners which blowup
            if (full_circ) :
                # If we're drawing a full circle, move to the end coord
                # and draw half a circle to the reflected xe,ye
                d += ' M %g %g A %g %g 0 1 0 %g %g'%(xe,-ye,
                                                     radius,radius*ratio,
                                                     2*x-xe,-(2*y-ye))
            # Draw arc from the CP (either reflected xe,ye for full circle else
            # xs,ys) to the end coord - note with full_circ the
            # 'bigArcFlag' value is moot, with exactly 180deg left to draw
            d += ' A %g %g 0 %d 0 %g %g' % (radius,radius*ratio,
                                            end_angle-start_angle>180,
                                            xe,-ye)
        self.__currElt.setAttribute('d',d.strip())
    def curveto(self, x1,y1,x2,y2,x3,y3):
        # Equivalent of PostScript's x1 y1 x2 y2 x3 y3 curveto which
        # draws a cubic bezier curve from curr pt to x3,y3 with ctrl points
        # x1,y1, and x2,y2
        # In SVG this is just d='[M x0 y0] C x1 y1 x2 y2 x3 y3'
        #! I can't find an example of this being used to test it
        if (self.__currElt.nodeNode != 'path') :
            raise OverflowError, "No path for curveto"
        d = ' '.join([self.__currElt.getAttribute('d'),'C',
                      `x1`,`-y1`,`x2`,`-y2`,`x3`,`-y3`,]).strip()
        self.__currElt.setAttribute('d', d)
    def closepath(self):                # close back to start of path
        if (self.__currElt.nodeName != 'path') :
            raise OverflowError, "No path for closepath"
        d = ' '.join([self.__currElt.getAttribute('d'),'Z']).strip()
        self.__currElt.setAttribute('d', d)

    # Next we have three methods for finalizing a path element,
    # either fill it, clip to it, or draw it (stroke)
    # canvas.polygon() can generate fill/clip cmds with
    # no corresponding path so just ignore them
    def stroke(self):
        if (self.__currElt.nodeName != 'path') :
            self.comment('No path - ignoring stroke')
            return
        self._updateStyle(fill='none')
        self.__currElt = self.__currElt.parentNode
    def fill(self):
        if (self.__currElt.nodeName != 'path') :
            self.comment('No path - ignoring fill')
            return
        self._updateStyle(stroke='none')
        self.__currElt = self.__currElt.parentNode
    def clip_sub(self):
        if (self.__currElt.nodeName != 'path') :
            self.comment('No path - ignoring clip')
            return

        # remove the current path from the tree ...
        p = self.__currElt
        self.__currElt=p.parentNode
        self.__currElt.removeChild(p)

        # ... add it to a clipPath elt in the defs section
        clip = self.__doc.createElement('clipPath')
        clipid = 'clip'+`len(self.__defs.childNodes)`
        clip.setAttribute('id',clipid)
        clip.appendChild(p)
        self.__defs.appendChild(clip)

        # ... update the local style to point to it
        self._updateStyle(clip_path = 'url(#%s)'%clipid)

    # The text_xxx routines specify the start/end and contents of text
    def text_begin(self):
        if (self.__currElt.nodeName != 'g') :
            raise ValueError, "No group for text block"
        t = self.__doc.createElement('text')
        self.__currElt.appendChild(t)
        self.__currElt = t
    def text_moveto(self, x, y, angle):
        if (self.__currElt.nodeName != 'text') :
            raise ValueError, "No text for moveto"
        self.__currElt.setAttribute('x',`x`)
        self.__currElt.setAttribute('y',`-y`)
        if (angle) :
            self.__currElt.setAttribute('transform',
                                        'rotate(%g,%g,%g)' % (-angle,x,-y))
    def text_show(self, font_name, size, color, str):
        if (self.__currElt.nodeName != 'text') :
            raise ValueError, "No text for show"

        # PyChart constructs a postscript font name, for example:
        #
        # Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique
        # Helvetica-Narrow Times-Roman Times-Italic
        # Symbol Palatino-Roman Bookman-Demi Courier AvantGarde-Book
        #
        # We need to deconstruct this to get the font-family (the
        # piece before the '-'), and other characteristics.
        # Note that 'Courier' seems to correspond to SVGs 'CourierNew'
        # and that the SVG Symbol font is Unicode where the ascii text
        # 'Symbol' doesn't create greek characters like 'Sigma ...' -
        # should really pass a unicode string, or provide translation
        #
        # SVG defines:
        # font-style = normal (aka roman) | italic | oblique
        # font-weight = normal | bold (aka demi?)
        # font-stretch = normal | wider | narrower | ultra-condensed |
        #	extra-condensed | condensed | semi-condensed |
        #	semi-expanded | expanded | extra-expanded | ultra-expanded
        # ('narrow' seems to correspond to 'condensed')

        m = re.match(r'([^-]*)(-.*)?',font_name)
        font_name,modifiers = m.groups()
        if font_name == 'Courier' : font_name = 'CourierNew'
        font_style = font_weight = font_stretch = 'normal'
        if modifiers :
            if re.search('Italic',modifiers) : font_style = 'italic'
            elif re.search('Oblique',modifiers) : font_style = 'oblique'
            if re.search('Bold|Demi',modifiers) : font_weight = 'bold'
            if re.search('Narrow',modifiers) : font_stretch = 'condensed'
        #! translate ascii symbol font chars -> unicode (see www.unicode.org)
        #! http://www.unicode.org/Public/MAPPINGS/VENDORS/ADOBE/symbol.txt
        #! but xml Text element writes unicode chars as '?' to XML file...
        str = re.sub(r'\\([()])',r'\1',str) # unescape brackets
        self._updateStyle(fill=_svgcolor(color),
                          stroke='none',
                          font_family=font_name,
                          font_size=size,
                          font_style=font_style,
                          font_weight=font_weight,
                          font_stretch=font_stretch)
        self.__currElt.appendChild(self.__doc.createTextNode(str))
    def text_end(self):
        if (self.__currElt.nodeName != 'text') :
            raise ValueError, "No text for close"
        self.__currElt = self.__currElt.parentNode


    # Three methods that change the local style of elements
    # If applied to a group, they persist until the next grestore,
    # If applied within a path element, they only affect that path -
    # although this may not in general correspond to (say) PostScript
    # behavior, it appears to correspond to reflect mode of use of this API
    def set_fill_color(self, color):
        self._updateStyle(fill=_svgcolor(color))
    def set_stroke_color(self, color):
        self._updateStyle(stroke=_svgcolor(color))
    def set_line_style(self, style):  # see line_style.py
        linecap = {0:'butt', 1:'round', 2:'square'}
        linejoin = {0:'miter', 1:'round', 2:'bevel'}
        if style.dash: dash = ','.join(map(str,style.dash))
        else : dash = 'none'
        self._updateStyle(stroke_width = style.width,
                          stroke = _svgcolor(style.color),
                          stroke_linecap = linecap[style.cap_style],
                          stroke_linejoin = linejoin[style.join_style],
                          stroke_dasharray = dash)

    # gsave & grestore respectively push & pop a new context to hold
    # new style and transform parameters.  push/pop transformation are
    # similar but explicitly specify a coordinate transform at the
    # same time
    def gsave(self):
        if (self.__currElt.nodeName not in ['g','svg']) :
            raise ValueError, "No group for gsave"
        g = self.__doc.createElement('g')
        self.__currElt.appendChild(g)
        self.__currElt = g
    def grestore(self):
        if (self.__currElt.nodeName != 'g'):
            raise ValueError, "No group for grestore"
        # first pop off any auto-generated groups (see protectCurrentChildren)
        while (self.__currElt.hasAttribute('auto')) :
            self.__currElt.removeAttribute('auto')
            self.__currElt = self.__currElt.parentNode
        # then pop off the original caller-generated group
        self.__currElt = self.__currElt.parentNode

    def push_transformation(self, baseloc, scale, angle, in_text=0):
        #? in_text arg appears to always be ignored

        # In some cases this gets called after newpath, with
        # corresonding pop_transformation called after the path is
        # finalized so we check specifically for that, and generate
        # an enclosing group to hold the incomplete path element
        # We could add the transform directly to the path element
        # (like we do with line-style etc) but that makes it harder
        # to handle the closing 'pop' and might lead to inconsitency
        # with PostScript if the closing pop doesn't come right after
        # the path element

        elt = self.__currElt
        if elt.nodeName == 'g':
            elt = None
        elif (elt.nodeName == 'path' and not elt.hasAttribute('d')) :
            g = elt.parentNode
            g.removeChild(elt)
            self.__currElt = g
        else:
            raise ValueError, "Illegal placement of push_transformation"
            
        t = ''
        if baseloc :
            t += 'translate(%g,%g) '%(baseloc[0],-baseloc[1])
        if angle :
            t += 'rotate(%g) '%-angle
        if scale :
            t += 'scale(%g,%g) '%tuple(scale)
            
        self.gsave()
        self.__currElt.setAttribute('transform',t.strip())
        if elt:                         # elt has incomplete 'path' or None
            self.__currElt.appendChild(elt)
            self.__currElt = elt

    def pop_transformation(self, in_text=0): #? in_text unused?
        self.grestore()

    # If verbose, add comments to the output stream (helps debugging)
    def comment(self, str):
        if _comment_p : 
            self.__currElt.appendChild(self.__doc.createComment(str))

    # The verbatim method is currently not supported - presumably with
    # the SVG backend the user would require access to the DOM since
    # we're not directly outputting plain text here
    def verbatim(self, str):
        self.__currElt.appendChild(self.__doc.createComment('verbatim not implemented: ' + str))

    # The close() method finalizes the SVG document and flattens the
    # DOM document to XML text to the specified file (or stdout)
    def close(self):
        basecanvas.T.close(self)
        self.grestore()           # matching the gsave in __init__
        if (self.__currElt.nodeName != 'svg') :
            raise ValueError, "Incomplete document at close!"

        # Don't bother to output an empty document - this can happen
        # when we get close()d immediately by theme reinit
        if (len(self.__svg.childNodes[-1].childNodes) == 0) :
            return
            
        fp, need_close = self.open_output(self.__out_fname)
        bbox = theme.adjust_bounding_box([self.__xmin, self.__ymin,
                                          self.__xmax, self.__ymax])
        self.__svg.setAttribute('viewBox','%g %g %g %g'
                                % (xscale(bbox[0]),
                                   -yscale(bbox[3]),
                                   xscale(bbox[2])-xscale(bbox[0]),
                                   yscale(bbox[3])-yscale(bbox[1])))
        self.__doc.writexml(fp,'','  ','\n')
        if need_close:
            fp.close()
Example #35
0
def generation_Pserver(directory):
    """
    generate the package 'test' for the Package Server tests
    """

    makedirs ("%s/test" %(directory))#create the directory of the test's package

    doc=Document()

    comment = doc.createComment("DOCTYPE package SYSTEM \"package_v1.dtd\"")
    doc.appendChild(comment)

    package = doc.createElement("package")
    package.setAttribute("id","test")
    doc.appendChild(package)

    name = doc.createElement("name")
    package.appendChild(name)

    natext = doc.createTextNode("TestPackage")
    name.appendChild(natext)

    version = doc.createElement("version")
    package.appendChild(version)

    numeric = doc.createElement("numeric")
    version.appendChild(numeric)

    nutext = doc.createTextNode("")
    numeric.appendChild(nutext)

    label = doc.createElement("label")
    version.appendChild(label)

    latext = doc.createTextNode("2.0.0.9")
    label.appendChild(latext)

    description = doc.createElement("description")
    package.appendChild(description)

    dtext = doc.createTextNode("Ceci est le package de test")
    description.appendChild(dtext)

    commands = doc.createElement("commands")
    commands.setAttribute("reboot","1")
    package.appendChild(commands)

    Precommands = doc.createElement("Precommands")
    commands.appendChild(Precommands)

    Ptext = doc.createTextNode("")
    Precommands.appendChild(Ptext)

    installInit = doc.createElement("installInit")
    commands.appendChild(installInit)

    itext = doc.createTextNode("")
    installInit.appendChild(itext)


    command = doc.createElement("command")
    command.setAttribute("name","commande")
    commands.appendChild(command)

    ctext = doc.createTextNode("./install.bat")
    command.appendChild(ctext)

    postCommandSuccess = doc.createElement("postCommandSuccess")
    commands.appendChild(postCommandSuccess)

    Stext = doc.createTextNode("")
    postCommandSuccess.appendChild(Stext)

    postCommandFailure = doc.createElement("postCommandFailure")
    commands.appendChild(postCommandFailure)

    Ftext = doc.createTextNode("")
    postCommandFailure.appendChild(Ftext)


    fichier=open("%s/test/conf.xml" %(directory),"w")
    doc.writexml(fichier,indent="   ",addindent="    ",newl="\n", encoding="utf-8")

    chdir("%s/test" %(directory))
    instalfile=open("install.bat","w")
    instalfile.write("I can\'t be installed")
    instalfile.close()
Example #36
0
 def get_document(head_time_str='xml'):
     """return document for xml writing"""
     document = Document()
     document.appendChild(document.createComment(head_time_str))
     return document
        # resolution of the actual extractor class based on the tool command line argument.
        options.extractor_class = options.available_extractors[options.tool]
    except KeyError:
        parser.error('Tool "%s" not found. Available tools are: %s' % 
                     (options.tool, ', '.join(options.available_extractors.keys())))
    
    # instanciation of the actual extractor
    extractor = options.extractor_class()
    try:
        # the extract() method should return a list of Rule objects
        rules = extractor.extract(*args) or []
    except ExtractorArgumentError, err:
        # extractors can raise OptionError if the arguments are inconsistent
        parser.error(err)
    
    # XML document construction
    doc = Document()
    doc.appendChild(doc.createComment('EXTRACTED "%s" RULES FOR SONAR' % options.tool))
    rules_elt = doc.createElement('rules')
    for rule in rules:
        rules_elt.appendChild(rule.to_xml_element())
    doc.appendChild(rules_elt)
    
    # write to standard output
    if options.format:
        doc.writexml(sys.stdout, addindent='  ', newl='\n', encoding='utf-8')
    else:  
        doc.writexml(sys.stdout, encoding='utf-8')
        sys.stdout.write('\n')

Example #38
0
    def writeXacro(self):

        # Create document
        doc = Document()

        # Create comment
        comment = doc.createComment('WARNING: This file was auto-generated by csv2xacro_node.py. It should not be edited by hand.')
        doc.appendChild(comment)

        # Create root label
        root = doc.createElement('robot')
        root.setAttribute( 'name', 'duckietown' )
        root.setAttribute('xmlns:xacro', 'http://www.ros.org/wiki/xacro')
        doc.appendChild(root)

        # Create Parameters comment
        comment = doc.createComment('Parameters')
        root.appendChild(comment)

        # Create tile width
        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','tile_width')
        tempChild.setAttribute('value',str(self.tile_width))
        root.appendChild(tempChild)

        # Create tag offsets
        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_0')
        tempChild.setAttribute('value','%s %s'%(str(self.tag_offset), str(self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_1')
        tempChild.setAttribute('value','%s %s'%(str(self.tag_curb), str(self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_2')
        tempChild.setAttribute('value','%s %s'%(str(-self.tag_curb), str(self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_3')
        tempChild.setAttribute('value','%s %s'%(str(-self.tag_offset), str(self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_4')
        tempChild.setAttribute('value','%s %s'%(str(-self.tag_offset), str(-self.tag_curb)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_5')
        tempChild.setAttribute('value','%s %s'%(str(-self.tag_curb), str(-self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_6')
        tempChild.setAttribute('value','%s %s'%(str(self.tag_curb), str(-self.tag_offset)))
        root.appendChild(tempChild)

        tempChild = doc.createElement('xacro:property')
        tempChild.setAttribute('name','pos_7')
        tempChild.setAttribute('value','%s %s'%(str(self.tag_offset), str(-self.tag_curb)))
        root.appendChild(tempChild)


        # Create comment
        comment = doc.createComment('Include the tile and tag macros')
        root.appendChild(comment)

        # Create file name
        tempChild = doc.createElement('xacro:include')
        tempChild.setAttribute('filename','$(find duckietown_description)/urdf/macros.urdf.xacro')
        root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('The world frame is at the lower left corner of duckietown')
        root.appendChild(comment)

        # Create link
        tempChild = doc.createElement('link')
        tempChild.setAttribute('name','world')
        root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('Describe the tiles')
        root.appendChild(comment)

        # Create tiles
        header = True
        x_max = 0
        y_max = 0
        for row in self.tile_csv:
            if header or row[0].isspace():
                header = False
                continue
            x = row[0].strip('" ')
            if int(x) > x_max:
                x_max = int(x)
            y = row[1].strip('" ')
            if int(y) > y_max:
                y_max = int(y)
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x',row[0].strip('" '))
            tempChild.setAttribute('y',row[1].strip('" '))
            tempChild.setAttribute('type',row[2].strip('" '))
            tempChild.setAttribute('rotation',row[3].strip('" '))
            root.appendChild(tempChild)

        # Check that the map has the right number of tiles
        if not ((x_max+1)*(y_max+1) == root.getElementsByTagName('xacro:tile').length):
            raise Exception("Map should be exactly rectangular.")

        # Create comment
        comment = doc.createComment('Empty border tiles')
        root.appendChild(comment)

        # Create empty border tiles
        for x in range(x_max + 2):
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x',str(x))
            tempChild.setAttribute('y',str(y_max + 1))
            tempChild.setAttribute('visible','false')
            root.appendChild(tempChild)

        for y in range(y_max + 1):
            tempChild = doc.createElement('xacro:tile')
            tempChild.setAttribute('x',str(x_max + 1))
            tempChild.setAttribute('y',str(y))
            tempChild.setAttribute('visible','false')
            root.appendChild(tempChild)

        # Create comment
        comment = doc.createComment('Describe the tags')
        root.appendChild(comment)

        # Create tags
        header = True
        for row in self.tag_csv:
            if header or row[0].isspace():
                header = False
                continue
            tempChild = doc.createElement('xacro:tag')
            tempChild.setAttribute('id', row[0].strip('" '))
            tempChild.setAttribute('x', row[1].strip('" '))
            tempChild.setAttribute('y', row[2].strip('" '))
            tempChild.setAttribute('pos', "${pos_" + row[3].strip('" ') + "}")
            tempChild.setAttribute('rotation', row[4].strip('" '))
            root.appendChild(tempChild)

        # Write to file
        doc.writexml(self.map_xml,indent='    ',addindent='    ',newl='\n')

        # Close file
        self.map_xml.close()
        self.tile_csv_file.close()
        self.tag_csv_file.close()
Example #39
0
	def create_xml(self, display_time, transition_time = 5):
		xmldoc = Document()
		background = xmldoc.createElement('background')
		comment = xmldoc.createComment("Created by BAckground Xml Creater\n [https://github.com/abilng/gnome-baxc]")
		xmldoc.appendChild(comment)		
		xmldoc.appendChild(background)

		starttime = xmldoc.createElement('starttime')
		sTime = datetime.datetime.now()
		year = xmldoc.createElement('year')
		year.appendChild(xmldoc.createTextNode('%s' % sTime.year))
		starttime.appendChild(year)
		month = xmldoc.createElement('month')
		month.appendChild(xmldoc.createTextNode('%s' % sTime.month))
		starttime.appendChild(month)
		day = xmldoc.createElement('day')
		day.appendChild(xmldoc.createTextNode('%s' % sTime.day))
		starttime.appendChild(day)
		hour = xmldoc.createElement('hour')
		hour.appendChild(xmldoc.createTextNode('%s' % sTime.hour))
		starttime.appendChild(hour)
		minute = xmldoc.createElement('minute')
		minute.appendChild(xmldoc.createTextNode('%s' % sTime.minute))
		starttime.appendChild(minute)
		second = xmldoc.createElement('second')
		second.appendChild(xmldoc.createTextNode('%s' % sTime.second))
		starttime.appendChild(second)
		background.appendChild(starttime)

		for i in range(len(self.images)):
			currentImage = self.images[i]
			try:
				next = self.images[i + 1]
			except IndexError:
				next = self.images[0]

			static = xmldoc.createElement('static')

			duration = xmldoc.createElement('duration')
			duration.appendChild(xmldoc.createTextNode("%s.0" % display_time))
			static.appendChild(duration)

			file = xmldoc.createElement('file')
			file.appendChild(xmldoc.createTextNode(str(currentImage)))
			static.appendChild(file)

			background.appendChild(static)

			transition = xmldoc.createElement('transition')

			duration = xmldoc.createElement('duration')
			duration.appendChild(xmldoc.createTextNode("%s.0" % transition_time))
			transition.appendChild(duration)

			transitionFrom = xmldoc.createElement('from')
			transitionFrom.appendChild(xmldoc.createTextNode(str(currentImage)))
			transition.appendChild(transitionFrom)

			transitionTo = xmldoc.createElement('transitionTo')
			transitionTo.appendChild(xmldoc.createTextNode(str(next)))
			transition.appendChild(transitionTo)

			background.appendChild(transition)

		return xmldoc.toxml()
Example #40
0
    rowIndex = 0
    id = 0

    fExe = open(workPath + "//cmd", "w")
    for row in reader:
        if rowIndex == 0:
            header = row  # .split(',')
            N = size(header)
        else:
            cols = row  # .split(',')
            if verbose:
                print cols[0]

                # Create the minidom document
            doc = Document()
            cc1 = doc.createComment("license:")
            cc2 = doc.createComment("strictly confidential. Propietary Information")
            doc.appendChild(cc1)
            doc.appendChild(cc2)
            # Create the <main> base element
            top = doc.createElement("dvg_sns")
            doc.appendChild(top)
            top.setAttribute("id", str(id))
            top.setIdAttribute("id")
            id = id + 1
            top.setAttribute("testName", cols[0])
            if individualTestDir == True:
                workPathTemp = workPath + cols[0]
                shutil.rmtree(workPathTemp, True)
                os.mkdir(workPathTemp)
            else:
def CreateXMLFile(runlist,
                  options,
                  origQuery,
                  datapath,
                  xmlfname,
                  xmllabel,
                  svnversion='Unknown'):
    """
    """

    with timer('create RunStreamAndNeventsList'):

        # show number of events per stream per run ?
        ShowNumberOfEventsPerStreamPerRun = False
        ShowNumberOfEventsPerStreamSummary = True

        # find streams
        runstreamevents, runnrliststr = CreateRunStreamAndNeventsList(
            runlist)  # { runnr: { stream: [(LUMIBLOCKNR, NREVENTS)] } }

    with timer('prepare document'):
        ####################################

        ## create XML file of GRL

        ####################################

        doc = Document()

        docType = DocumentType('LumiRangeCollection')
        docType.systemId = 'http://atlas-runquery.cern.ch/LumiRangeCollection.dtd'
        doc.appendChild(docType)

        # number of comments
        txt = ' Good-runs-list created by %s on %s ' % (
            sys.argv[0].split('/')[-1], str(datetime.datetime.now()))
        doc.appendChild(doc.createComment(txt))

        # root element
        lrc = doc.createElement('LumiRangeCollection')
        doc.appendChild(lrc)

        # NamedLumiRange
        namedLR = doc.createElement('NamedLumiRange')
        lrc.appendChild(namedLR)

        # name of NamedLumiRange
        namedLR.appendChild(TextElement('Name', xmllabel, doc))

        # version of NamedLumiRange
        namedLR.appendChild(TextElement('Version', '2.1', doc))

        # metadata of NamedLumiRange
        metadata = {
            'Query': origQuery.split('/')[0],
            'RQTSVNVersion': svnversion,
            'RunList': runnrliststr
        }

        for md in metadata:
            mdelm = TextElement('Metadata', metadata[md], doc)
            mdelm.setAttribute('Name', md)
            namedLR.appendChild(mdelm)

    with timer('ShowNumberOfEventsPerStreamSummary'):
        if ShowNumberOfEventsPerStreamSummary:
            strsummdelm = doc.createElement('Metadata')
            strsummdelm.setAttribute('Name', 'StreamListInfo')
            namedLR.appendChild(strsummdelm)

    # lumiblock collections of NamedLumiRange
    streams_sum = {}
    streams_byrun = {}
    with timer('Loop over all runs'):
        for run in runlist:
            lbc = doc.createElement('LumiBlockCollection')
            # run number
            runnrelm = TextElement('Run', str(run.runNr), doc)

            if len(run.stats['SMK']['random']) == 2:
                (rd0, rd1) = run.stats['SMK']['random'][0:2]
                # protect against missing information
                if rd0 == 'n.a.': rd0 = 0
                if rd1 == 'n.a.': rd1 = 0
                runnrelm.setAttribute('PrescaleRD0', 0x1 << (3 + rd0))
                runnrelm.setAttribute('PrescaleRD1', 0x1 << (3 + rd1))
            else:
                (rd0, rd1, rd2, rd3) = run.stats['SMK']['random'][0:4]
                # protect against missing information
                if rd0 == 'n.a.': rd0 = 0
                if rd1 == 'n.a.': rd1 = 0
                if rd2 == 'n.a.': rd2 = 0
                if rd3 == 'n.a.': rd3 = 0
                runnrelm.setAttribute('Cut0', rd0)
                runnrelm.setAttribute('Cut1', rd1)
                runnrelm.setAttribute('Cut2', rd2)
                runnrelm.setAttribute('Cut3', rd3)

            lbc.appendChild(runnrelm)

            # streams (initialisation)
            streams = {}
            streams_byrun[run.runNr] = streams
            if runstreamevents.has_key(
                    run.runNr
            ):  # protection in case the run does not have any stream
                for stream in runstreamevents[run.runNr].keys():
                    if 'physics_' == stream[:8]:
                        streams[stream] = [0, 0]  # only for physics streams
                        if not streams_sum.has_key(stream):
                            streams_sum[stream] = [0, 0]
                        # total number of events in stream
                        for (nlb, nev) in runstreamevents[run.runNr][stream]:
                            streams[stream][0] += nev

            # lumiblock ranges

            for lbrange in run.data.getLBRanges(activeOnly=True):
                lbrelm = TextElement('LBRange', '', doc)
                lbrelm.setAttribute('Start', lbrange[1])
                lbrelm.setAttribute('End', lbrange[2] - 1)
                lbc.appendChild(lbrelm)
                # count nevents in streams
                if runstreamevents.has_key(
                        run.runNr
                ):  # protection in case the run does not have any stream
                    for stream, lbnevts in runstreamevents[run.runNr].items():
                        if 'physics_' == stream[:8]:
                            for (nlb, nev) in lbnevts:
                                if nlb >= lbrange[1] and nlb < lbrange[2]:
                                    streams[stream][1] += nev

            # append stream element
            s = streams.keys()
            s.sort()
            strselm = doc.createElement('StreamsInRun')

            for stream in s:
                nevts = streams[stream]
                if ShowNumberOfEventsPerStreamPerRun:
                    strelm = TextElement('Stream', '', doc)
                    strelm.setAttribute('Name', stream)
                    strelm.setAttribute('TotalNumOfEvents', nevts[0])
                    strelm.setAttribute('NumOfSelectedEvents', nevts[1])
                    strselm.appendChild(strelm)
                eff = 0
                if nevts[0] > 0: eff = nevts[1] / float(nevts[0]) * 100.0

                # collect total number of events
                streams_sum[stream][0] += nevts[0]
                streams_sum[stream][1] += nevts[1]

            # append streams
            if ShowNumberOfEventsPerStreamPerRun: lbc.appendChild(strselm)

            # append LumiBlickCollection
            namedLR.appendChild(lbc)

    with timer('Streams'):
        for stream in sorted(streams_sum.keys()):
            nevts = streams_sum[stream]
            if ShowNumberOfEventsPerStreamSummary:
                strelm = TextElement('Stream', '', doc)
                strelm.setAttribute('Name', stream)
                strelm.setAttribute('TotalNumOfEvents', nevts[0])
                strelm.setAttribute('NumOfSelectedEvents', nevts[1])
                strsummdelm.appendChild(strelm)

    with timer('Save GRL'):

        filename = '%s/%s' % (datapath, xmlfname)
        #print "Writing",filename
        xmlfile = open(filename, mode="w")
        xmlfile.write(doc.toprettyxml('   '))
        xmlfile.close()

    with timer('Create HTML'):

        ####################################

        ## create HTML

        ####################################

        # provide also pretty html text output
        htmltext = ''
        hspace = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
        htmltext += '<table style=&quot;width: auto; border: 0px solid; border-width: margin: 0 0 0 0; 0px; border-spacing: 0px; border-collapse: separate; padding: 0px;&quot; font-family: sans-serif; font-size: 85%%&quot;>\n'
        htmltext += '<tr><td colspan=&quot;2&quot;><b><font color=&quot;#999999&quot;>' + txt.strip(
        ) + '</font></b></td></tr>\n'
        htmltext += '<tr><td style=&quot;vertical-align:top&quot;>SVN&nbsp;Version: </td><td> ' + svnversion + '</td></tr>\n'
        htmltext += '<tr><td style=&quot;vertical-align:top&quot;>Query&nbsp;string:</td><td><b>' + origQuery.split(
            '/')[0] + '</b></td></tr>\n'
        htmltext += '<tr><td style=&quot;vertical-align:top&quot;>Run list:</td><td>' + runnrliststr + '</td></tr>\n'
        htmltext += '</table>'
        htmltext += '<hr color=&quot;#000000&quot; size=1><font color=&quot;#777777&quot;>\n'
        htmltext += '<table style=&quot;width: auto; border: 0px solid; border-width: margin: 0 0 0 0; 0px; border-spacing: 0px; border-collapse: separate; padding: 0px;&quot; font-family: sans-serif; font-size: 90%%&quot;>\n'

        # lumiblock collections of NamedLumiRange
        for run in runlist:
            # run number
            htmltext += '<tr><td style=&quot;text-align:left;height:25px;vertical-align:bottom&quot;>Run <b>%i</b>:</td><td></td></tr>\n' % run.runNr

            # lumiblock ranges

            for lbrange in run.data.getLBRanges(activeOnly=True):
                htmltext += '<tr><td></td><td style=&quot;text-align:left&quot;>LB range: [%5i-%5i]</td></tr>\n' % (
                    lbrange[1], lbrange[2] - 1)

            # append stream element
            htmltext += '<tr><td></td><td style=&quot;text-align:left&quot;></td></tr>'
            htmltext += '<tr><td></td><td style=&quot;text-align:left&quot;><table style=&quot;width: auto; border: 0px solid; border-width: margin: 0 0 0 0; 0px; border-spacing: 0px; border-collapse: separate; padding: 0px;font-family: sans-serif; font-size: 90%&quot;><tr><td>Stream name</td><td>#Events total</td><td>&nbsp;&nbsp;&nbsp;#Events selected</td><td>&nbsp;&nbsp;&nbsp;Sel. fraction (%)</td></tr>\n'

            streams = streams_byrun[run.runNr]
            for stream in sorted(streams.keys()):
                nevts = streams[stream]
                eff = (nevts[1] / float(nevts[0]) *
                       100.0) if (nevts[0] > 0) else 0
                htmltext += '<tr><td style=&quot;text-align:left&quot;><i>%s</i></td><td style=&quot;text-align:right&quot;>%s</td><td style=&quot;text-align:right&quot;>%s</td><td style=&quot;text-align:right&quot;>%.4g</td></tr>\n' % (
                    stream, prettyNumber(nevts[0]), prettyNumber(
                        nevts[1]), eff)

            htmltext += '</table></td></tr>\n'

        # append stream element
        htmltext += '</table>'
        htmltext += '<hr color=&quot;#000000&quot; size=1><font color=&quot;#777777&quot;>\n'
        htmltext += '<b>Stream summary for all selected runs:</b><br>\n'
        htmltext += '<table style=&quot;width: auto; border: 0px solid; border-width: margin: 0 0 0 0; 0px; border-spacing: 0px; border-collapse: separate; padding: 0px;font-family: sans-serif; font-size: 95%&quot;><tr><td>Stream name</td><td>#Events total</td><td>&nbsp;&nbsp;&nbsp;#Events selected</td><td>&nbsp;&nbsp;&nbsp;Sel. fraction (%)</td></tr>\n'
        for stream in sorted(streams_sum.keys()):
            nevts = streams_sum[stream]
            eff = 0
            if nevts[0] > 0: eff = nevts[1] / float(nevts[0]) * 100.0
            htmltext += '<tr><td style=&quot;text-align:left&quot;><i>%s</i></td><td style=&quot;text-align:right&quot;>%s</td><td style=&quot;text-align:right&quot;>%s</td><td style=&quot;text-align:right&quot;>%.4g</td></tr>\n' % (
                stream, prettyNumber(nevts[0]), prettyNumber(nevts[1]), eff)
        htmltext += '</table>\n'

    #print """========================================================
    #%r
    #===========================================================
    #""" % htmltext

    # provide also text output
    return htmltext
    def create_classifier_file(self):
        """
        Write the cascade classifier information into a xml file.
        """
        #create instance of DOM
        doc = Document()

        #create root element
        cascade_classifier_xml = doc.createElement('cascade_frontal_face')
        cascade_classifier_xml.setAttribute('type_id', 'yao_cascade_classifier')
        doc.appendChild(cascade_classifier_xml)

        #sample size
        sample_size = doc.createElement('size')
        sample_size.setAttribute('w', str(self.sample_width))
        sample_size.setAttribute('h', str(self.sample_height))
        cascade_classifier_xml.appendChild(sample_size)

        #stage count
        stage_count = 0

        for strong_Classifier in self.cascade_classifiers:
            #stage information
            stage_info = doc.createElement('stages')
            stage_info.setAttribute('threshold', str(strong_Classifier.threshold))
            stage_comment = doc.createComment('stage-'+str(stage_count))
            stage_info.appendChild(stage_comment)
            cascade_classifier_xml.appendChild(stage_info)

            stage_count += 1
            #tree node count
            tree_count = 0

            for weak_classifier in strong_Classifier.classifiers:
                #decision tree node information
                tree_info = doc.createElement('trees')
                tree_comment = doc.createComment('tree-'+str(tree_count))
                tree_info.appendChild(tree_comment)
                stage_info.appendChild(tree_info)

                tree_count += 1

                #feature information
                feature_info = doc.createElement('features')
                #feature type
                feature_type = doc.createElement('feature_type')
                feature_type.setAttribute('type', str(weak_classifier.feature.type))
                feature_info.appendChild(feature_type)
                #feature position
                feature_pos = doc.createElement('pos')
                feature_pos.setAttribute('x', str(weak_classifier.feature.x))
                feature_pos.setAttribute('y', str(weak_classifier.feature.y))
                feature_info.appendChild(feature_pos)
                #feature size
                feature_size = doc.createElement('size')
                feature_info.appendChild(feature_size)
                feature_size.setAttribute('w', str(weak_classifier.feature.w))
                feature_size.setAttribute('h', str(weak_classifier.feature.h))
                #feature scaled size
                feature_scaled = doc.createElement('scaled')
                feature_info.appendChild(feature_scaled)
                feature_scaled.setAttribute('x_axis', str(weak_classifier.feature.axis_x_scaled))
                feature_scaled.setAttribute('y_axis', str(weak_classifier.feature.axis_y_scaled))
                tree_info.appendChild(feature_info)

                #threshold
                threshold = doc.createElement('threshold')
                threshold_node = doc.createTextNode(str(weak_classifier.threshold))
                threshold.appendChild(threshold_node)
                tree_info.appendChild(threshold)

                #flag
                flag = doc.createElement('flag')
                flag_node = doc.createTextNode(str(weak_classifier.flag))
                flag.appendChild(flag_node)
                tree_info.appendChild(flag)

                #widget
                widget = doc.createElement('widget')
                widget_node = doc.createTextNode(str(weak_classifier.widget))
                widget.appendChild(widget_node)
                tree_info.appendChild(widget)

        #write to file
        f = open('cascade_classifier.xml','w')
        f.write(doc.toprettyxml(indent = ' '))
        f.close()
Example #43
0
def excel_write_xml(work, path):
    """根据excel中的keys值生成xml文件,并保存在该路径下"""
    keys = []
    quote_keys = read_excel_keys(work, path, "引用")
    keys.append(quote_keys)
    cur_page_keys = read_excel_keys(work, path, "当前页")
    keys.append(cur_page_keys)
    all_page_keys = read_excel_keys(work, path, "所有页")
    keys.append(all_page_keys)
    date_keys = read_excel_keys(work, path, "日期")
    keys.append(date_keys)
    evaluate_keys = read_excel_keys(work, path, "合格率")
    keys.append(evaluate_keys)
    measure_keys = read_excel_keys(work, path, "测点")
    keys.append(measure_keys)
    txt_keys = read_excel_keys(work, path, "文本框")
    keys.append(txt_keys)
    number_keys = read_excel_keys(work, path, "数字")
    keys.append(number_keys)
    time_keys = read_excel_keys(work, path, "时间")
    keys.append(time_keys)
    check_keys = read_excel_keys(work, path, "复选框")
    keys.append(check_keys)
    com_box_keys = read_excel_keys(work, path, "下拉框")
    keys.append(com_box_keys)
    pic_keys = read_excel_keys(work, path, "图片")
    keys.append(pic_keys)

    xmldom = Document()
    pos = get_page(work, path)
    grid = xmldom.createElement("grid")
    items = xmldom.createElement("items")
    scope = xmldom.createElement("range")
    ran_des = xmldom.createComment("表单范围")
    tab_name = xmldom.createComment(os.path.basename(path))
    # row = dom.createAttribute("maxRows")
    # row.nodeValue = pos[0]
    # scope.setAttributeNode(row)
    xmldom.appendChild(grid)
    grid.appendChild(items)
    grid.appendChild(ran_des)
    scope.setAttribute("maxRows", str(pos[0]+1))
    scope.setAttribute("maxCols", str(pos[1]+1))
    if ("记录表" in os.path.basename(path)) and ("鉴定" not in os.path.basename(path)):
        sheet = xmldom.createElement("sheet")
        sheet.setAttribute("Authority", "1111")
        grid.appendChild(sheet)
    grid.appendChild(scope)
    items.appendChild(tab_name)

    for key in keys:
        if key:
            for unit in key:
                if str(unit)[:3] == "%QC":
                    item = add_item(xmldom, items, unit, "表单基础信息")
                    item.setAttribute("Type", "QuoteCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%CP":
                    item = add_item(xmldom, items, unit, "当前页")
                    item.setAttribute("Type", "CurPageCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%AP":
                    item = add_item(xmldom, items, unit, "所有页")
                    item.setAttribute("Type", "AllPageCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%DT":
                    item = add_item(xmldom, items, unit, "表单日期")
                    item.setAttribute("Type", "DateCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%EP":
                    item = add_item(xmldom, items, unit, "带合格率的测点单元格")
                    item.setAttribute("Type", "EvaluateCell")
                    item.setAttribute("Enable", "true")
                    item.setAttribute("ShowType", "1")
                    item.setAttribute("Text", "应测 %d 点(处),实测 %d 点(处),合格 %d 点(处),合格率 %.1f %%,数据详见检表")
                elif str(unit)[:3] == "%MP":
                    item = add_item(xmldom, items, unit, "测点单元格")
                    item.setAttribute("Type", "MeasureCell")
                    item.setAttribute("InputType", "ArrayNumber")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%TC":
                    item = add_item(xmldom, items, unit, "文本内容")
                    if ("记录表" in os.path.basename(path)) and ("外观" not in os.path.basename(path)):
                        write_formula(work, path, unit, item)
                    item.setAttribute("Type", "TextCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%NM":
                    item = add_item(xmldom, items, unit, "数字单元格")
                    item.setAttribute("Type", "NumberCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%TI":
                    item = add_item(xmldom, items, unit, "时间单元格")
                    item.setAttribute("Type", "TimeCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%CH":
                    item = add_item(xmldom, items, unit, "表单复选框")
                    item.setAttribute("Type", "CheckBoxCell")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%CB":
                    item = add_item(xmldom, items, unit, "表单下拉框")
                    item.setAttribute("Type", "ComboBoxCell")
                    item.setAttribute("Options", " @@合格@@不合格")
                    item.setAttribute("Enable", "true")
                elif str(unit)[:3] == "%PT":
                    item = add_item(xmldom, items, unit, "表单图片")
                    item.setAttribute("Type", "PictureCell")
                    item.setAttribute("Enable", "true")
    sign_keys = read_excel_sign(work, path)
    if sign_keys:
        keys_lists = list(sign_keys.keys())
        sign_com = xmldom.createComment("表单签名签章")
        sign_info = xmldom.createComment("签名权限码40001001业主 40001002监理 40001003施工 Role自动签名角色名称")
        items.appendChild(sign_com)
        items.appendChild(sign_info)

        for keys in keys_lists:
            if ("施工" in keys) or (keys in ["质检人:", "检查人:", "质检负责人:", "质检人签名:", "检查人签名:",
                                           "质检负责人签名:", "检验负责人:", "检测:", "记录:", "复核:"]):
                item = xmldom.createElement("item")
                item.setAttribute("Sign", "40001003")
                item.setAttribute("Id", sign_keys[keys])
                item.setAttribute("Type", "PictureCell")
                item.setAttribute("Enable", "true")
                if (("施工" in keys) and ("质检负责人" not in keys)) or (keys in ["质检人:", "检查人:",  "质检人签名:", "检查人签名:",
                                                                           "检测:", "记录:", "复核:"]):
                    item.setAttribute("Role", "检查人")
                elif "质检负责人" in keys:
                    item.setAttribute("Role", "质检负责人")
                items.appendChild(item)
            elif ("监理" in keys) or (keys in ["监理员:", "监理员签名:", "专业监理工程师:", "专业监理工程师签名:",
                                             "总监理工程师:", "总监理工程师签名:"]):
                item = xmldom.createElement("item")
                item.setAttribute("Sign", "40001002")
                item.setAttribute("Id", sign_keys[keys])
                item.setAttribute("Type", "PictureCell")
                item.setAttribute("Enable", "true")
                if ("监理" in keys) and ("监理1" not in keys) and ("监理2" not in keys) and ("专业监理工程师" not in keys):
                    item.setAttribute("Role", "监理员")
                elif "监理1" in keys:
                    item.setAttribute("Role", "监理员")
                elif "监理2" in keys:
                    item.setAttribute("Role", "专业监理工程师")
                else:
                    item.setAttribute("Role", keys)
                items.appendChild(item)

    f = open("{}.xml".format(os.path.splitext(path)[0]), encoding='utf-8', mode='w')
    xmldom.writexml(f, addindent="\t", newl="\n", encoding="UTF-8")
    # f.write(str(xmldom.toxml(encoding="utf-8")))
    f.close()
    print("{}生成xml文件完成。".format(os.path.basename(path)))
Example #44
0
class RssApiWriter(ApiWriter):
  """Output the search results as an RSS data feed."""
  
  OurNamespace = "fp" #TODO change to afg?

  def __init__(self, content_type):
    """No special initialization."""
    self.doc = None
    self.rss = None
    self.channel = None
    ApiWriter.__init__(self, content_type)
    
  def setup(self, request, result_set):
    """
    Create the RSS preamble, everything before the results list.
    """
    self.doc = Document()
    self.rss = self.doc.createElement('rss')
    self.rss.setAttribute('version','2.0')
    self.rss.setAttribute('xmlns:georss', "http://www.georss.org/georss")
    self.rss.setAttribute('xmlns:gml', "http://www.opengis.net/gml")
    self.rss.setAttribute('xmlns:atom', "http://www.w3.org/2005/Atom")
    self.rss.setAttribute('xmlns:' + self.OurNamespace,
                          "http://www.allforgood.org/")
    self.doc.appendChild(self.rss)
    channel = self.doc.createElement('channel')
    self.rss.appendChild(channel)
    
    def create_text_element(parent, name, content=None, attrs = None):
      elem = self.doc.createElement(name)
      if attrs:
        for k, v in attrs.items():
          elem.setAttribute(k, v)

      parent.appendChild(elem)
      if content != None:
        elem.appendChild(self.doc.createTextNode(str(content)))
      return elem
    
    create_text_element(channel, 'title', 'All for Good search results')
    create_text_element(channel, 'link', 'http://www.allforgood.org/')
    
    atom_link = self.doc.createElement('atom:link')
    channel.appendChild(atom_link)
    atom_link.setAttribute('href', result_set.request_url)
    atom_link.setAttribute('rel', 'self')
    atom_link.setAttribute('type', str(self.content_type))
    
    create_text_element(channel,
                        'description',
                        'All for Good search results')
    create_text_element(channel, 'language', content='en-us')
    create_text_element(channel, 'pubDate') #TODO: fill this in
    create_text_element(channel,
                        'lastBuildDate',
                        content=result_set.last_build_date)

    if result_set.is_hoc:
      facets_node = create_text_element(channel, 'facets')
      for facet, facet_list in result_set.hoc_facets.items():
        if facet_list:
          facet_node = create_text_element(facets_node, 'facet', None, {'name' : facet})
          facet_name = facet_value = ''
          for fv in facet_list:
            if not facet_name:
              facet_name = fv
              facet_value = ''
            elif not facet_value:
              facet_value = fv
              facet_value_node = create_text_element(facet_node, 'count', facet_value, {'name' : facet_name})
              facet_name = facet_value = ''
          
      if not result_set.is_cal:
        create_text_element(channel,
                            'TotalMatch',
                            content=str(result_set.total_match))
        create_text_element(channel,
                            'TotalOpportunities',
                            content=str(result_set.total_opportunities))

    self.channel = channel
    
  def add_result(self, result, result_set = {}):
    """
    Add an <item/> stanza to the results.  The stanza will include the required
    RSS elements, plus our own namespaced elements.
    """
    def build_result_element(field_info, result):

      content = ''
      name = field_info[0]
      if not hasattr(result, name) and len(field_info) > 1:
        name = field_info[1]

      if hasattr(result, name):
        try:
          content = str(getattr(result, name, ''))
        except UnicodeEncodeError:
          content = getattr(result, name, '').encode('ascii', 'ignore')

      if name == "enddate": 
        if custom_date_format(content) == 'Present':
          content = ''
      elif name == "description":
        if result_set.args.get('fulldesc', '') != '1':
          content = content[:300]
      elif name in ["eventrangestart", "eventrangeend"]:
        content = content.replace('T', ' ').strip('Z')

    
      return (name, content, None)
    
    item = self.doc.createElement('item')
    self.channel.appendChild(item)
    
    #standard RSS fields
    standard_fields = [
      ('title',),
      ('link', 'xml_url'),
      ('description', 'snippet'),
      ('pubDate',), 
      ('guid', 'xml_url')
    ]
    added_list = []
    for field in standard_fields:
      (name, content, comment) = build_result_element(field, result)
      if len(name) < 3:
        continue

      if name == 'xml_url':
        name = 'link'
      else:
        name = API_FIELD_NAMES_MAP.get(name, name)

      if name in added_list:
        continue
      added_list.append(name)

      if comment:
        item.appendChild(self.doc.createComment(comment))
      subitem = self.doc.createElement(name)
      if content:
        text = self.doc.createTextNode(content)
        subitem.appendChild(text)
      item.appendChild(subitem)

    #and now our namespaced fields
    namespaced_fields = FIELD_TUPLES

    added_list = []
    for field_info in namespaced_fields:
      (name, content, comment) = build_result_element(field_info, result)

      name = self.OurNamespace + ':' + API_FIELD_NAMES_MAP.get(name, name)

      if (not result_set.is_hoc and not result_set.is_rss) and name.lower() not in STANDARD_FIELDS:
        continue

      if result_set.is_cal and name.lower() not in CALENDAR_FIELDS:
        continue

      if name in added_list:
        continue
      added_list.append(name)

      if comment:
        item.appendChild(self.doc.createComment(comment))

      subitem = self.doc.createElement(name)
      if content:
        if len(field_info) > 1 and isinstance(content, basestring) and content.find('\t') > 0:
          content = content.split('\t')

        if isinstance(content, list):
          for value in content:
            subsubitem = self.doc.createElement(self.OurNamespace + ':' + field_info[1])
            text = self.doc.createTextNode(value)
            subsubitem.appendChild(text)
            subitem.appendChild(subsubitem)
        else:
          text = self.doc.createTextNode(content)
          subitem.appendChild(text)
          
      item.appendChild(subitem)
      
  def finalize(self):
    """Return a string from the XML document."""
    #return self.doc.toxml(encoding='utf-8')
    return self.doc.toprettyxml(indent='  ', newl='\n', encoding='utf-8')