Exemplo n.º 1
0
 def from_juniper(self, data, device):
     """Parse results from a Juniper device."""
     devname = device.nodeName
     if self.verbose:
         print "parsing JunOS commands for %s " % devname
     if self.debug:
         print '-->from_juniper(data=%s, device=%r)' % (data, devname)
     if self.debug:
         for xml in data:
             ET.dump(xml)
     ns = '{http://xml.juniper.net/xnm/1.1/xnm}'
     children = self.__children_with_namespace(ns)
     confresxml = data[1]
     success = 0
     error = 0
     msg = ''
     for res in confresxml.getiterator(ns + 'load-configuration-results'):
         for succ in res.getiterator(ns + 'load-success'):
             success += 1
             msg = "Success!"
         for err in res.getiterator(ns + 'error'):
             error += 1
             msg = "ERROR: "
             elin = children(err, 'line-number')[0].text
             emes = children(err, 'message')[0].text
             ecol = children(err, 'column')[0].text
             etok = children(err, 'token')[0].text
             msg = msg + emes + " in '" + etok + "'\n    line:"+elin+",col:"+ecol
             msg = "%s %s in %r\n    line: %s, col: %s" % (msg, emes, etok,
                                                           elin, ecol)
     if success:
         self.data[devname] = [{'dev': device, 'cmd': 'load-configuration', 'out': 'Success'}]
     if error:
         self.data[devname] = [{'dev': device, 'cmd': 'load-configuration', 'out': msg}]
     return True
Exemplo n.º 2
0
def main():
    options, args = parse_args()
    rootElement = Element('packages')

    packages = {}

    print "Searching for packages.config files:"

    for dirpath, subdirs, filenames in walk('src'):
        for filename in filenames:
            if filename == 'packages.config':
                filepath = join(dirpath, filename)
                print "    " + filepath
                et = parse(filepath)
                for packageElement in et.findall('package'):
                    pkgId = packageElement.get('id')
                    pkgVersion = packageElement.get('version')
                    packages[pkgId, pkgVersion] = packageElement

    print
    print "Writing projectdata/packages.config:"
    rootElement.extend([value for (key,value) in sorted(packages.items())])
    indent(rootElement)
    tree = ElementTree(rootElement)
    dump(tree)
    tree.write('projectdata/packages.config')
Exemplo n.º 3
0
    def to_juniper(self, device=None, commands=None, extra=None):
        """
        Configure a Juniper device using JunoScript.

        :returns:
            list
        """
        if self.verbose:
            print "generating JunOS commands"
        files = self.files
        cmds = [Element('lock-configuration')]
        for fname in files:
            # fname is required to contain the full path
            lc = Element('load-configuration', action='replace', format='text')
            body = SubElement(lc, 'configuration-text')
            if self.debug:
                print "fname: " + fname
            body.text = file(fname).read()
            cmds.append(lc)
        #commands = self.commands
        if len(commands) > 0:
            lc = Element('load-configuration', action='replace', format='text')
            body = SubElement(lc, 'configuration-text')
            body.text = '\n'.join(commands)
            cmds.append(lc)
        cmds.append(Element('commit-configuration'))
        if self.debug:
            for xml in cmds:
                ET.dump(xml)
        return cmds
Exemplo n.º 4
0
    def from_juniper(self, data, device, commands=None):
        # If we've set foce_cli, use from_base() instead
        if self.force_cli:
            return self.from_base(data, device, commands)

        devname = device.nodeName
        ns = '{http://xml.juniper.net/xnm/1.1/xnm}'
        if self.verbose:
            print 'parsing JunOS commands for %s' % devname
        if self.debug:
            print '-->from_juniper(data=%s, device=%r)' % (data, devname)

        cmds = self.commands
        outs = []
        for i, xml in enumerate(data):
            cmd = cmds[i]
            outarr = xml_print(xml, iterations=10)
            out = '\n'.join(outarr)
            d = {'cmd': cmd, 'out': out, 'dev': device}
            outs.append(d)
            if self.debug:
                print '\ndata["%s"]:' % i
                ET.dump(xml)
        self.data[devname] = outs
        return True
Exemplo n.º 5
0
 def from_juniper(self, data, device, commands=None):
     """Parse results from a Juniper device."""
     devname = device.nodeName
     if self.verbose:
         print "parsing JunOS commands for %s " % devname
     if self.debug:
         print '-->from_juniper(data=%s, device=%r)' % (data, devname)
     if self.debug:
         for xml in data:
             ET.dump(xml)
     ns = '{http://xml.juniper.net/xnm/1.1/xnm}'
     children = self.__children_with_namespace(ns)
     confresxml = data[1]
     success = 0
     error = 0
     msg = ''
     for res in confresxml.getiterator(ns + 'load-configuration-results'):
         for succ in res.getiterator(ns + 'load-success'):
             success += 1
             msg = "Success!"
         for err in res.getiterator(ns + 'error'):
             error += 1
             msg = "ERROR: "
             elin = children(err, 'line-number')[0].text
             emes = children(err, 'message')[0].text
             ecol = children(err, 'column')[0].text
             etok = children(err, 'token')[0].text
             msg = msg + emes + " in '" + etok + "'\n    line:"+elin+",col:"+ecol
             msg = "%s %s in %r\n    line: %s, col: %s" % (msg, emes, etok,
                                                           elin, ecol)
     if success:
         self.data[devname] = [{'dev': device, 'cmd': 'load-configuration', 'out': 'Success'}]
     if error:
         self.data[devname] = [{'dev': device, 'cmd': 'load-configuration', 'out': msg}]
     return True
Exemplo n.º 6
0
def getMovieDetailsByTitle(title):

    url = "http://www.omdbapi.com/?t=" + title + "&plot=short&r=json"
    response = requests.get(url)

    if (response.ok):

        print "fetching data from omdbapi.com"
        jData = json.loads(response.content)
        #print jData +'\n'

        root = ET.Element("Movie")
        name = ET.SubElement(root, "Name")
        releaseDate = ET.SubElement(root, "ReleaseDate")
        genre = ET.SubElement(root, "Genre")
        director = ET.SubElement(root, "Director")
        rating = ET.SubElement(root, "Rating")
        plot = ET.SubElement(root, "Plot")

        print jData["Released"]
        name.text = title
        releaseDate.text = datetime.datetime.strptime(
            jData["Released"], "%d %b %Y").strftime("%Y-%m-%d")
        genre.text = jData["Genre"].split(',')[0]
        director.text = jData["Director"].split(',')[0]
        rating.text = jData["imdbRating"]

        tree = ET.ElementTree(root)
        ET.dump(root)
Exemplo n.º 7
0
  def __init__(self, node):
    ElementTree.dump(node) # DEBUG

    # Extract the <memberdef> attributes:
    self.__dict__ = extract_attrs(node)

    # Parse the basic tags:
    for node_name in MEMBER_TAGS:
      self.__dict__[node_name] = extract_text(node.find(node_name))

    # Parse the <param> tags:
    if self.argsstring == '' or self.argsstring == '(void)':
      self.params = []
    else:
      self.params = parse_param_tags(node.findall('param'))

    # Parse the <detaileddescription> tag:
    detaileddescription = node.find('detaileddescription')
    self.exceptions = parse_parameterlist_tag(
      detaileddescription.find('./para/parameterlist[@kind="exception"]'))
    self.returns = parse_simplesect_tag(
      detaileddescription.find('./para/simplesect[@kind="return"]'))
    self.warning = parse_simplesect_tag(
      detaileddescription.find('./para/simplesect[@kind="warning"]'))

    # Parse the <inbodydescription> tag:
    parse_inbodydescription_tag(node.find('inbodydescription'))

    # Parse the <location> tag:
    location = parse_location_tag(node.find('location'))
Exemplo n.º 8
0
def add_tag(root,
            BBox={"name", "xmin", "ymin", "xmax", "ymax"},
            tag="object",
            insertPlace=6):
    index = insertPlace
    object = ET.Element(tag)
    name = ET.SubElement(object, "name")
    pose = ET.SubElement(object, "pose")
    truncated = ET.SubElement(object, "truncated")
    difficult = ET.SubElement(object, "difficult")
    bndbox = ET.SubElement(object, "bndbox")
    name.text = BBox["name"]
    xmin = ET.SubElement(bndbox, "xmin")
    ymin = ET.SubElement(bndbox, "ymin")
    xmax = ET.SubElement(bndbox, "xmax")
    ymax = ET.SubElement(bndbox, "ymax")
    xmin.text = BBox["xmin"]
    ymin.text = BBox["ymin"]
    xmax.text = BBox["xmax"]
    ymax.text = BBox["ymax"]
    pose.text = "Unspecified"
    truncated.text = "0"
    difficult.text = "0"
    ET.dump(object)
    root.insert(index, object)
    return root
Exemplo n.º 9
0
def main():
    try:
        ids_file, doc_file = sys.argv[1:][-2:]
    except (
            ValueError,
            IndexError,
    ):
        print("Usage: {} IDS_FILE DOC_FILE".format(__file__))
        return

    ids = get_ids(ids_file)
    doc, nsmap = parse_doc(doc_file)
    root = doc.getroot()
    ndoc = etree.Element('{{{}}}RDF'.format(nsmap['rdf']))
    for ns, uri in nsmap.items():
        etree.register_namespace(ns, uri)

    for el in doc.findall('{{{}}}Description'.format(nsmap['rdf'])):
        ref = el.get('{{{}}}about'.format(nsmap['rdf']))
        if ref in ids:
            ndoc.append(el)

            for subref in el.findall('{{{}}}hasTopConcept'.format(
                    nsmap['skos'])):

                subref_id = subref.get('{{{}}}resource'.format(nsmap['rdf']))
                subel = doc.find('Description[@about="{}"]'.format(subref_id))
                if subel:
                    ndoc.append(subel)

    etree.dump(ndoc)
Exemplo n.º 10
0
 def dump(self,elem=None,uplevel=0):
     if elem is None: return ET.dump(self)
     else:
         if uplevel > 0:
             pm = self.parent_map
             for i in range(uplevel): elem = pm[elem]
         ET.dump(elem)
Exemplo n.º 11
0
    def to_juniper(self, device=None, commands=None, extra=None):
        """
        Configure a Juniper device using JunoScript.

        :returns:
            list
        """
        if self.verbose:
            print "generating JunOS commands"
        files = self.files
        cmds = [Element('lock-configuration')]
        for fname in files:
            # fname is required to contain the full path
            lc = Element('load-configuration', action='replace', format='text')
            body = SubElement(lc, 'configuration-text')
            if self.debug:
                print "fname: " + fname
            body.text = file(fname).read()
            cmds.append(lc)
        #commands = self.commands
        if len(commands) > 0:
            lc = Element('load-configuration', action='replace', format='text')
            body = SubElement(lc, 'configuration-text')
            body.text = '\n'.join(commands)
            cmds.append(lc)
        cmds.append(Element('commit-configuration'))
        if self.debug:
            for xml in cmds:
                ET.dump(xml)
        return cmds
Exemplo n.º 12
0
    def __init__(self, node):
        ElementTree.dump(node)  # DEBUG

        # Extract the <memberdef> attributes:
        self.__dict__ = extract_attrs(node)

        # Parse the basic tags:
        for node_name in MEMBER_TAGS:
            self.__dict__[node_name] = extract_text(node.find(node_name))

        # Parse the <param> tags:
        if self.argsstring == '' or self.argsstring == '(void)':
            self.params = []
        else:
            self.params = parse_param_tags(node.findall('param'))

        # Parse the <detaileddescription> tag:
        detaileddescription = node.find('detaileddescription')
        self.exceptions = parse_parameterlist_tag(
            detaileddescription.find(
                './para/parameterlist[@kind="exception"]'))
        self.returns = parse_simplesect_tag(
            detaileddescription.find('./para/simplesect[@kind="return"]'))
        self.warning = parse_simplesect_tag(
            detaileddescription.find('./para/simplesect[@kind="warning"]'))

        # Parse the <inbodydescription> tag:
        parse_inbodydescription_tag(node.find('inbodydescription'))

        # Parse the <location> tag:
        location = parse_location_tag(node.find('location'))
Exemplo n.º 13
0
def main():
    options, args = parse_args()
    rootElement = Element('packages')

    packages = {}

    print "Searching for packages.config files:"

    for dirpath, subdirs, filenames in walk('src'):
        for filename in filenames:
            if filename == 'packages.config':
                filepath = join(dirpath, filename)
                print "    " + filepath
                et = parse(filepath)
                for packageElement in et.findall('package'):
                    pkgId = packageElement.get('id')
                    pkgVersion = packageElement.get('version')
                    packages[pkgId, pkgVersion] = packageElement

    print
    print "Writing projectdata/packages.config:"
    rootElement.extend([value for (key, value) in sorted(packages.items())])
    indent(rootElement)
    tree = ElementTree(rootElement)
    dump(tree)
    tree.write('projectdata/packages.config')
Exemplo n.º 14
0
    def from_juniper(self, data, device, commands=None):
        # If we've set foce_cli, use from_base() instead
        if self.force_cli:
            return self.from_base(data, device, commands)

        devname = device.nodeName
        ns = '{http://xml.juniper.net/xnm/1.1/xnm}'
        if self.verbose:
            print 'parsing JunOS commands for %s' % devname
        if self.debug:
            print '-->from_juniper(data=%s, device=%r)' % (data, devname)

        cmds = self.commands
        outs = []
        for i, xml in enumerate(data):
            cmd = cmds[i]
            outarr = xml_print(xml, iterations=10)
            out = '\n'.join(outarr)
            d = {'cmd': cmd, 'out': out, 'dev': device}
            outs.append(d)
            if self.debug:
                print '\ndata["%s"]:' % i
                ET.dump(xml)
        self.data[devname] = outs
        return True
Exemplo n.º 15
0
 def dump(self, elem=None, uplevel=0):
     if elem is None: return ET.dump(self)
     else:
         if uplevel > 0:
             pm = self.parent_map
             for i in range(uplevel):
                 elem = pm[elem]
         ET.dump(elem)
Exemplo n.º 16
0
    def writefile(self, filename: str, data: list):
        roomswithstudents = data
        rooms = ET.Element('rooms')
        for rm in roomswithstudents:
            room = ET.SubElement(rooms, 'room')
            roomname = ET.SubElement(room, 'roomname')
            roomname.text = str(rm.name)

        mydata = ET.ElementTree(rooms)
        ET.dump(mydata)
        mydata.write(filename + '.xml', xml_declaration=True)
Exemplo n.º 17
0
def create_xml_edge(edge_id, from_node, to_node, numLanes="2"):
    ''' See sumo edge definition for more definition of road types:
        http://www.sumo.dlr.de/userdoc/Networks/Building_Networks_from_own_XML-descriptions.html#Type_Descriptions
        Don't forget about priority
    '''
    edge = ET.Element("edge", id=edge_id, to=to_node, numLanes=numLanes)
    # Since from is a weirdly parsed keyword, it has to be set separately

    edge.set("from", from_node)
    ET.dump(edge)
    return edge
Exemplo n.º 18
0
    def _submit_delivery_form(self,
                              form_date,
                              case_id,
                              nutrition_status=None,
                              case_id_2=None):

        form = ElementTree.Element('data')
        form.attrib['xmlns'] = XMLNS_DELIVERY_FORM
        form.attrib['xmlns:jrm'] = 'http://openrosa.org/jr/xforms'

        meta = ElementTree.Element('meta')
        add_element(meta, 'timeEnd', form_date.isoformat())
        form.append(meta)

        child_repeat1 = ElementTree.Element('child')
        child_open_child_health_repeat1 = ElementTree.Element(
            'case_open_child_health_3')
        case_repeat1 = ElementTree.Element('case')
        case_repeat1.attrib['date_modified'] = form_date.isoformat()
        case_repeat1.attrib['case_id'] = case_id
        case_repeat1.attrib[
            'xmlns'] = 'http://commcarehq.org/case/transaction/v2'
        if nutrition_status is not None:
            case_update_repeat1 = ElementTree.Element('update')
            add_element(case_update_repeat1, 'zscore_grading_wfa',
                        nutrition_status)
            case_repeat1.append(case_update_repeat1)
        child_open_child_health_repeat1.append(case_repeat1)
        child_repeat1.append(child_open_child_health_repeat1)
        add_element(child_repeat1, 'zscore_grading_wfa', nutrition_status)
        form.append(child_repeat1)

        if case_id_2 is not None:
            child_repeat2 = ElementTree.Element('child')
            child_open_child_health_repeat2 = ElementTree.Element(
                'case_open_child_health_3')
            case_repeat2 = ElementTree.Element('case')
            case_repeat2.attrib['date_modified'] = form_date.isoformat()
            case_repeat2.attrib['case_id'] = case_id_2
            case_repeat2.attrib[
                'xmlns'] = 'http://commcarehq.org/case/transaction/v2'
            case_update_repeat2 = ElementTree.Element('update')
            add_element(case_update_repeat2, 'zscore_grading_wfa',
                        nutrition_status)
            case_repeat2.append(case_update_repeat2)
            child_open_child_health_repeat2.append(case_repeat2)
            child_repeat2.append(child_open_child_health_repeat2)
            add_element(child_repeat2, 'zscore_grading_wfa',
                        NUTRITION_STATUS_SEVERE)
            form.append(child_repeat2)

        ElementTree.dump(form)
        self._submit_form(form)
Exemplo n.º 19
0
def find_something(filename, regex):
    """ Prints the OSM elements matching the regex, and a link to view them online. Returns None."""
    import re
    flag = False
    for event, elem in ET.iterparse(filename, events=('start',)):
        if elem.tag == 'way':
            for tag in elem.iter('tag'):
                if tag.attrib['k'] == 'name':
                    if re.search(regex, ET.tostring(tag)):
                        print "Check ID online at: http://www.openstreetmap.org/way/" + elem.attrib['id'] + '\n'
                        ET.dump(elem)
                        flag = True
    if not flag:
        print "No matching Element was found."
Exemplo n.º 20
0
def find_something(filename, regex):
    """ Prints the OSM elements matching the regex, and a link to view them online. Returns None."""
    import re
    flag = False
    for event, elem in ET.iterparse(filename, events=('start', )):
        if elem.tag == 'way':
            for tag in elem.iter('tag'):
                if tag.attrib['k'] == 'name':
                    if re.search(regex, ET.tostring(tag)):
                        print "Check ID online at: http://www.openstreetmap.org/way/" + elem.attrib[
                            'id'] + '\n'
                        ET.dump(elem)
                        flag = True
    if not flag:
        print "No matching Element was found."
Exemplo n.º 21
0
    def interpret_dictionary_data(self, dictionary_data=None):
        """
        re-interpret the dictionary data as XML element trees.
        :return: <xml.Element> data.
        """
        if not isinstance(dictionary_data, dict):
            raise ValueError(
                "[InterpretDictionaryData] :: Must have a dictionary type as input parameter."
            )

        self.xml_data = ET.Element("DataInformation")
        items = ET.SubElement(self.xml_data, 'Data')

        for k_item, k_value in dictionary_data.items():
            item = ET.SubElement(items, k_item)
            if not isinstance(k_value, dict):
                ET.SubElement(item, k_value)
            else:
                for k_name, v_items in k_value.items():
                    array_key = ET.SubElement(item, k_name)
                    if isinstance(v_items, str):
                        ET.SubElement(array_key, v_items)
                    elif isinstance(v_items, (tuple, list)):
                        for it_name in v_items:
                            ET.SubElement(array_key, str(it_name))
                    elif isinstance(v_items, dict):
                        for it_name, it_val in v_items.items():
                            it_elem = ET.SubElement(array_key, str(it_name))
                            ET.SubElement(it_elem, str(it_val))
        return ET.dump(self.xml_data)
Exemplo n.º 22
0
def Encode(mac, enc):

    root = ET.Element("object")

    obj_type = ET.SubElement(root, "public")
    obj_type.set("name", "public")
    obj_type.text = "0"

    macfield = ET.SubElement(root, "mac")
    macfield.set("name", "mac")
    macfield.text = mac

    encfield = ET.SubElement(root, "cipher_text")
    encfield.set("name", "cipher_text")
    encfield.text = enc
    ET.dump(root)
    return ET.tostring(root)
Exemplo n.º 23
0
def main():

    parser = get_parser()
    args = parser.parse_args()
    rc = 0

    result = ET.Element("testsuites", name=args.testsuites_name);

    for fname in find_all("results.xml", args.directory):
        if args.debug : print("Reading file %s" % fname)
        tree = ET.parse(fname)
        for ts in tree.iter("testsuite"):
            if args.debug:
                print("Ts name : %s, package : %s" % ( ts.get('name'), ts.get('package')))
            use_element = None
            for existing in result:
                if existing.get('name') == ts.get('name') and existing.get('package') == ts.get('package'):
                    if args.debug:
                        print("Already found")
                    use_element = existing
                    break
            if use_element is None:
                result.append(ts)
            else:
                #for tc in ts.getiterator("testcase"):
                use_element.extend(list(ts));

    if args.debug:
        ET.dump(result)

    testsuite_count = 0
    testcase_count = 0
    for testsuite in result.iter('testsuite'):
        testsuite_count += 1
        for testcase in testsuite.iter('testcase'):
            testcase_count += 1
            for failure in testcase.iter('failure'):
                if args.set_rc:
                    rc = 1
                print("Failure in testsuite: '%s' classname: '%s' testcase: '%s' with parameters '%s'" % (testsuite.get('name'), testcase.get('classname'), testcase.get('name'), testsuite.get('package')))

    print("Ran a total of %d TestSuites and %d TestCases" % (testsuite_count, testcase_count))


    ET.ElementTree(result).write(args.output_file, encoding="UTF-8")
    return rc
def main():
    #===========================================================================
    # import sys
    # if len(sys.argv) != 2:
    #     print "Usage: %s xml_name" % sys.argv[0]
    #     sys.exit(0)
    # xml_name = sys.argv[1]
    #===========================================================================

    xml_files = get_curr_dir_xml_files()

    import sys
    sys.stdout = file("out.xml", "w")
    #===========================================================================
    #building output xml tree
    #===========================================================================
    xml_data = ET.Element("root")

    for xml_name in xml_files:
        parser = XMLParser(xml_name)

        msg = str(parser)
        msg = msg.decode("gbk")

        filename, title, author, date, epigraph = msg.split("\t")

        channel = ET.Element("channel")

        tag_filename = ET.SubElement(channel, "filename")
        tag_filename.text = filename

        tag_title = ET.SubElement(channel, "title")
        tag_title.text = title

        tag_author = ET.SubElement(channel, "author")
        tag_author.text = author

        tag_date = ET.SubElement(channel, "date")
        tag_date.text = date

        tag_epigraph = ET.SubElement(channel, "epigraph")
        tag_epigraph.text = epigraph

        xml_data.append(channel)

    ET.dump(xml_data)
Exemplo n.º 25
0
    def create_playlist(playlist_file_path, file_paths):
        root = et.Element("playlist")
        root.set("xmlns", "http://xspf.org/ns/0/")
        root.set("xmlns:vlc", "http://www.videolan.org/vlc/playlist/ns/0/")
        root.set("version", "1")

        track_list = et.Element("trackList")
        root.append(track_list)

        title = et.Element("title")
        title.text = str(playlist_file_path)
        root.append(title)

        extension = et.Element("extension")
        extension.set("application", "http://www.videolan.org/vlc/playlist/0")
        root.append(extension)

        index = 0
        for file_path in file_paths:
            # check that the file exists
            if not os.path.isfile(file_path):
                continue

            track = et.Element("track")

            location_elem = et.SubElement(track, 'location')
            location_elem.text = "file://" + str(file_path)

            extension_elem = et.SubElement(track, 'extension')
            extension_elem.set('application', 'http://www.videolan.org/vlc/playlist/0')

            id_elem = et.SubElement(extension_elem, 'vlc:id')
            id_elem.text = str(index)
            track_list.append(track)

            new_vlc_elem = et.Element('vlc:item')
            new_vlc_elem.set('tid', str(index))
            extension.append(new_vlc_elem)

            index += 1

        et.dump(root)
        tree = et.ElementTree(root)
        with open(playlist_file_path, 'wb') as f:
            tree.write(f)
Exemplo n.º 26
0
 def cell(self, cell_doc):
     logging.debug(dom.tostring(cell_doc))
     value_attr_id = dom.QName(self.ODS_NS['office'], 'value')
     date_attr_id = dom.QName(self.ODS_NS['office'], 'date-value')
     type_attr_id = dom.QName(self.ODS_NS['office'], 'value-type')
     # Get the type
     try:
         type_name = cell_doc.attrib[type_attr_id]
     except KeyError:
         return stingray.cell.EmptyCell('', self)
     value = None
     # Date value as attribute?
     if not value:
         try:
             value = cell_doc.attrib[date_attr_id]
         except KeyError:
             pass
     # Other value as attribute?
     if not value:
         try:
             value = cell_doc.attrib[value_attr_id]
         except KeyError:
             pass
     # No value attributes, get *all* the text content.
     if not value:
         value = "".join(x for x in cell_doc.itertext())
     if not value:
         # TODO: Proper warning.
         dom.dump(cell_doc)
     logging.debug(type_name, repr(value))
     if type_name == "string":
         return stingray.cell.TextCell(value, self)
     elif type_name == "float":
         return stingray.cell.NumberCell(float(value), self)
     elif type_name == "date":
         theDate = datetime.datetime.strptime(value,
                                              ODS_Workbook.date_format)
         return stingray.cell.FloatDateCell(theDate, self)
     elif type_name == "boolean":
         return stingray.cell.BooleanCell(float(value.upper() == 'TRUE'),
                                          self)
     elif type_name == "empty":
         return stingray.cell.EmptyCell('', self)
     else:
         raise Exception("Unknown cell {0}".format(dom.tostring(cell_doc)))
Exemplo n.º 27
0
def EncodePublic(sig, obj):
    root = ET.Element("object")

    obj_type = ET.SubElement(root, "public")
    obj_type.set("name", "public")
    obj_type.text = "1"

    sigfield = ET.SubElement(root, "sig")
    sigfield.set("name", "sig")
    sigfield.text = sig

    sigfield = ET.SubElement(root, "hashed_data")
    sigfield.set("name", "hashed_data")
    sigfield.text = HashToString(sha1(obj).digest())

    txtfield = ET.SubElement(root, "plain_text")
    txtfield.set("name", "plain_text")
    txtfield.text = obj
    ET.dump(root)
    return ET.tostring(root)
Exemplo n.º 28
0
def write():
	xmltree =  ET.ElementTree() #在内存中创建一个xmltree
	person = ET.Element("person") #生成根节点
	#ctrl+shift+b
	xmltree._setroot(person)
	#在xml对象中设置了根节点
	people = ET.SubElement(person,'people',{"name":"Jack"})
	#SubElement 创建子节点 然后把节点名称和属性 在函数参数的第二个和第三个部分写到
	age = ET.Element("age") #利用ET.Element() 在people子节点下创建相应的子节点
	age.text = "18"	#为字节点赋值
	people.append(age) #把子节点添加到people父节点中
	sex = ET.Element("sex")
	sex.text = "male"
	people.append(sex)
	salary = ET.Element("salary")
	salary.text = "30000"
	people.append(salary)

	ET.dump(indent(person))
	xmltree.write("write.xml")
Exemplo n.º 29
0
def main():

    parser = get_parser()
    args = parser.parse_args()
    rc = 0;

    result = ET.Element("testsuites", name=args.testsuites_name);

    for fname in find_all("results.xml", args.directory):
        if args.debug : print("Reading file %s" % fname)
        tree = ET.parse(fname)
        for ts in tree.getiterator("testsuite"):
            if args.debug : print("Ts name : %s, package : %s" % ( ts.get('name'), ts.get('package')))
            use_element = None
            for existing in result:
                if ((existing.get('name') == ts.get('name') and (existing.get('package') == ts.get('package')))):
                    if args.debug : print("Already found")
                    use_element=existing
                    break
            if use_element is None:
                result.append(ts)
            else:
                #for tc in ts.getiterator("testcase"):
                use_element.extend(list(ts));

    if args.debug : ET.dump(result)

    for testsuite_count, testsuite in enumerate(result.iter('testsuite'),1):
        for testcase_count, testcase in enumerate(testsuite.iter('testcase'),1):
            for failure in testcase.iter('failure'):
                if args.set_rc: rc=1
                print("Failure in testsuite: '%s' classname: '%s' testcase: '%s' with parameters '%s'" % (testsuite.get('name'), testcase.get('classname'), testcase.get('name'), testsuite.get('package')))

    print("Ran a total of %d TestSuites and %d TestCases" % (testsuite_count, testcase_count))


    ET.ElementTree(result).write(args.output_file, encoding="UTF-8")
    return rc
Exemplo n.º 30
0
def CreateObjectXML(object_file):
    my_type = GetType(object_file)

    root = ET.Element("object")
    f = file(object_file, "rb")
    data = f.read()
    f.close()
    if (not IsText(my_type)):
        data = data.encode("base64")
    plain_text = ET.SubElement(root, "plain_text_obj")
    plain_text.set("name", "plain_text_obj")
    plain_text.text = data

    obj_type = ET.SubElement(root, "obj_type")
    obj_type.set("name", "obj_type")
    obj_type.text = my_type

    obj_type = ET.SubElement(root, "id")
    obj_type.set("name", "id")
    obj_type.text = GetID(object_file)

    ET.dump(root)
    return ET.tostring(root)
def get_photoset_metadata(photoset):
	 
    photoset_info_tree = ET.ElementTree(flickr.photosets_getInfo(api_key=api_key, photoset_id=photoset))	    
    photoset_tree = ET.ElementTree(flickr.photosets_getPhotos(api_key=api_key, photoset_id=photoset))	

    ET.dump(photoset_info_tree)
    ET.dump(photoset_tree)

    photo_ids = []	
    data = []
    data_row = []
    
    for title in photoset_info_tree.iter('title'):
      set_title = unicode(title.text, "utf-8")  
       
    # grab all photo ids in set
    for node in photoset_tree.iter('photo'):
      
      # get each photo
      photo = flickr.photos_getInfo(photo_id=node.get('id'), api_key=api_key)
      photo_tree = ET.ElementTree(photo)

      ET.dump(photo_tree)

      data_row.append(set_title.encode('utf8'))
   	 
      for title in photo_tree.iter('title'):
         data_row.append(title.text.encode('utf8'))
	   
      try:
         geodata = flickr.photos_geo_getLocation(photo_id=node.get('id'), api_key=api_key)
         geodata_tree = ET.ElementTree(geodata)
      	
         for geonode in geodata_tree.iter('location'):            
            data_row.append(geonode.get('latitude').encode('utf8'))
            data_row.append(geonode.get('longitude').encode('utf8'))
            data_row.append(geonode.get('accuracy').encode('utf8'))
         for geonode in geodata_tree.iter('country'):
            data_row.append(geonode.text.encode('utf8'))         
         for geonode in geodata_tree.iter('region'):
            data_row.append(geonode.text.encode('utf8'))
         for geonode in geodata_tree.iter('county'):
            data_row.append(geonode.text.encode('utf8'))
         for geonode in geodata_tree.iter('locality'):
            data_row.append(geonode.text.encode('utf8'))
         for geonode in geodata_tree.iter('neighbourhood'):
            data_row.append(geonode.text.encode('utf8'))
      except Exception as e:
         e = True
        
      writer.writerow(data_row)
      print data_row     
    
      data_row = []
Exemplo n.º 32
0
    def _send(self, data):
        """Send OMP data to the manager and read the result.

        `data` may be either an unicode string, an utf-8 encoded
        string or an etree Element. The result is as an etree Element.

        :param data: data to send.
        :type data: str | ElementTree

        :return: XML tree element.
        :rtype: `ElementTree`
        """

        # Make sure the data is a string.
        if etree.iselement(data):
            data = etree.dump(data)
        if isinstance(data, unicode):
            data = data.encode('utf-8')

        # Synchronize access to the socket.
        with self.__socket_lock:

            # Send the data to the server.
            self.socket.sendall(data)

            # Get the response from the server.
            data = ""
            tree = None
            while True:
                chunk = self.socket.recv(1024)
                if not chunk:
                    break
                data += chunk
                try:
                    tree = etree.fromstring(data)
                except Exception:
                    continue
                break
            if tree is None:
                tree = etree.fromstring(data)

            # Return the parsed response.
            return tree
Exemplo n.º 33
0
    def _send(self, data):
        """Send OMP data to the manager and read the result.

        `data` may be either an unicode string, an utf-8 encoded
        string or an etree Element. The result is as an etree Element.

        :param data: data to send.
        :type data: str | ElementTree

        :return: XML tree element.
        :rtype: `ElementTree`
        """

        # Make sure the data is a string.
        if etree.iselement(data):
            data = etree.dump(data)
        if isinstance(data, unicode):
            data = data.encode('utf-8')

        # Synchronize access to the socket.
        with self.__socket_lock:

            # Send the data to the server.
            self.socket.sendall(data)

            # Get the response from the server.
            data = ""
            tree = None
            while True:
                chunk = self.socket.recv(1024)
                if not chunk:
                    break
                data += chunk
                try:
                    tree = etree.fromstring(data)
                except Exception:
                    continue
                break
            if tree is None:
                tree = etree.fromstring(data)

            # Return the parsed response.
            return tree
Exemplo n.º 34
0
    def dump(self):
        """Print element.
		
		:rtype: str
		"""
        return etree.dump(self._elem)
import xml.etree.cElementTree as ET
"""Small script to convert the JSON output from html-angular-validate-report
to a valid XML Testsuite File, so that Jenkins is able to parse it"""

reload(sys)
sys.setdefaultencoding('utf8')

with open('html-angular-validate-report.json') as data_file:
    data = json.load(data_file)

root = ET.Element("testsuite", {'name': 'html-angular-validate',
                               'tests': str(data['fileschecked']), 
                               'failures': str(data['filesfailed']),
                               'errors': '0' })

if not data['allpassed']:
    for err in data['failed']:
        case = ET.SubElement(root, "testcase", {'name': str(err['filepath'])})
        failure = ET.SubElement(case, "failure",{'message': 
                                str(len(err['errors'])) + ' Failure(s)' })
        errmsg = []
        
        for fail in err['errors']:
            errmsg.append('At line ' + str(fail['line']) 
                          + ': ' + str(fail['msg']) + '\n')
        
        failure.text = "".join(errmsg)

tree = ET.ElementTree(root)
ET.dump(tree)
Exemplo n.º 36
0
    def _send(self, in_data):
        """Send OMP data to the manager and read the result.

        `in_data` may be either an unicode string, an utf-8 encoded
        string or an etree Element. The result is as an etree Element.

        :param in_data: data to send.
        :type in_data: str | ElementTree

        :return: XML tree element.
        :rtype: `ElementTree`

        :raises: ServerError
        """

        if self.__host == "dummy":
            return etree.fromstring(in_data)

        # Make sure the data is a string.
        if etree.iselement(in_data):
            in_data = etree.dump(in_data)
        if isinstance(in_data, unicode):
            in_data = in_data.encode('utf-8')

        # Synchronize access to the socket.
        with self.__socket_lock:

            # Send the data to the server.
            try:
                self.socket.sendall(in_data)
            except socket.error:
                raise ServerError("Can't connect to the server.")

            # Get the response from the server.
            tree = None
            data = ""
            try:
                while True:
                    chunk = self.socket.recv(1024)
                    if not chunk:
                        break
                    data += chunk

                    # We use this tip for avoid socket blocking:
                    # If xml is correct, we're finished to receive info. Otherwise,
                    # continue receiving
                    try:
                        tree = etree.fromstring(data)
                    except Exception:
                        continue
                    break
            except socket.error, e:
                raise ServerError("Can't receive info from the server: %s" % e)

            # if tree is None:
            if tree is None:
                tree = etree.ElementTree()
                return tree

            # Return the parsed response.
            return tree
Exemplo n.º 37
0
import xml.etree.cElementTree as ET

filename = "/Users/umangagarwal/Desktop/kolkata_india.osm"


"""Contributions by user "FuckOSMFandODbL" are spurious and incorrect"""

osm = iter(ET.iterparse(filename, events=("end",)))
x = 0
for event, elem in osm:
    try:
        if elem.attrib["user"] == "FuckOSMFandODbL":
            x += 1
            ET.dump(elem)
    except KeyError:
        continue
    finally:
        elem.clear()

print x
Exemplo n.º 38
0
 def show_xml_tree(self):
     dump(self.xmltree)
Exemplo n.º 39
0
 def dump(self):
     ET.dump(self.root)
Exemplo n.º 40
0
                            domain="tag").text = str(self._wrap_in_cdata(tag))
            tree.SubElement(item, "category", domain="tag",
                            nicename=tag).text = str(self._wrap_in_cdata(tag))

    def _wrap_in_cdata(self, original_data):
        # prefix = r"<![CDATA["
        # suffix = r"]]>"
        # print(prefix + original_data + suffix)
        # return prefix + original_data + suffix
        return "CDATA_START" + str(original_data) + "CDATA_END"

    def _gen_images(self):
        result = ""
        for photo in self._photos:
            result += "IMG_TAG_START" + str(photo) + "IMG_TAG_ENDBREAK_TAG"
        return result


if __name__ == "__main__":
    post = XMLPost("1", "fake_title", "fake_body_of_text fiasdjoifjaswoijfsdoa", [
        "cool", "post", "bro"
    ], [
        "https://cnet4.cbsistatic.com/img/SPn24bmx9mm7jKE-3iZgRWjurJw=/2018/04/18/b0d2e71b-f600-41b4-9075-af845f1e6531/p-incredible-hero-avengers-58e3c823.jpg",
        "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=2ahUKEwjhqembi4PhAhWWup4KHen1BPsQjRx6BAgBEAU&url=https%3A%2F%2Fwww.polygon.com%2Fspider-man-ps4-guide%2F2018%2F9%2F10%2F17841942%2Fselfie&psig=AOvVaw0seJ_wIIY7Yko4kXH-mCXt&ust=1552702885153545",
        "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=2ahUKEwicjf6ji4PhAhWVvJ4KHSwIB4YQjRx6BAgBEAU&url=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt4154664%2F&psig=AOvVaw1XbDkWMBuVRe4_Ilj2kOFH&ust=1552702923373070"
    ], "1995-12-01 10:13:00")
    result = post.generate_xml()
    indent(result)
    final_result = tree.ElementTree(result)
    tree.dump(final_result)
    final_result.write("output.xml", encoding="utf-8")
Exemplo n.º 41
0
def main( argv = None ):
    if argv is None:
        argv = sys.argv
        
    optList, optArgs = getopt.getopt( argv[ 1: ], "w:d:h", [ '--web', '--dir', '--help' ] )
    webBase = None
    dirBase = None
    for clList, clArgs in optList:
        if clList in [ '-w', '--web' ]:
            webBase = clArgs
        elif clList in [ '-d', '--dir' ]:
            dirBase = clArgs

    if dirBase is None:
        print( 'Base Dir Not Specified!' )
        return 1
                    
    for srcDir in os.listdir( dirBase ):
        if os.path.isfile( os.path.join( dirBase, srcDir ) ):
            continue
                        
        rssRoot = ET.Element( "rss" )
        rssChann = ET.SubElement( rssRoot, 'channel' )
        rssChann.attrib[ 'xmlns:itunes' ] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        rssChann.attrib[ 'version' ] = '2.0'
        
        castTitle = ET.SubElement( rssChann, 'title' )
        castLink = ET.SubElement( rssChann, 'link' )
        castDesc = ET.SubElement( rssChann, 'description' )
        castiTunesDesc = ET.SubElement( rssChann, 'itunes:summary' )
        castiTunesArtist = ET.SubElement( rssChann, 'itunes:author' )
        
        fullPath = os.path.join( dirBase, srcDir )
        for fileName in genFeed( fullPath ):
            relPath = os.path.join( srcDir, fileName ) 
            fullURL = os.path.join( webBase, urllib.quote( relPath ) )
            metaInfo = getMeta( os.path.join( fullPath, fileName ) )
            if metaInfo[ 'Title' ] == '':
                metaInfo[ 'Title' ] = srcDir
             
            castTitle.text = metaInfo[ 'Album' ] 
            castLink.text = webBase
            castDesc.text = metaInfo[ 'Summary' ]
            castiTunesDesc.text = metaInfo[ 'Summary' ]
            castiTunesArtist.text = str( metaInfo[ 'Authors' ] )
            
            castItem = ET.SubElement( rssChann, 'item' )
            
            itemTitle = ET.SubElement( castItem, 'title' )
            itemTitle.text = metaInfo[ 'Title' ]
            
            itemEnc = ET.SubElement( castItem, 'enclosure' )
            itemEnc.attrib[ 'url' ] = str( fullURL )
            itemEnc.attrib[ 'length' ] = str( metaInfo[ 'Size' ] )
            mimeType = mimetypes.guess_type( fullURL )[ 0 ]
            if not mimeType is None:
                itemEnc.attrib[ 'type' ] =  mimetypes.guess_type( fullURL )[ 0 ]
            else:
                if fileName.endswith( 'm4b' ):
                    itemEnc.attrib[ 'type' ] = 'audio/x-m4b'
            
            itemPubDate = ET.SubElement( castItem, 'pubDate' )
            itemPubDate.text = str( metaInfo[ 'PubDate' ] )
            
            itemGUID = ET.SubElement( castItem, 'guid' )
            itemGUID.text = fullURL
            
            itemiTunesAuthor = ET.SubElement( castItem, 'itunes:author' )
            itemiTunesAuthor.text = str( metaInfo[ 'Authors' ] )
            
            itemiTunesSummary = ET.SubElement( castItem, 'itunes:summary' )
            itemiTunesSummary.text = str( metaInfo[ 'Summary' ] )
            
            itemiTunesSubtitle = ET.SubElement( castItem, 'itunes:subtitle' )
            itemiTunesSubtitle.text = str( metaInfo[ 'Summary' ] )

            itemiTunesDuration = ET.SubElement( castItem, 'itunes:duration' )
            stringDuration = str( datetime.timedelta( seconds=int( metaInfo[ 'Duration' ] ) ) )
            itemiTunesDuration.text = stringDuration
            
        fullXML = ET.ElementTree( rssRoot )
        ET.dump( fullXML )
        xmlPath = os.path.join( dirBase, '%s.xml' % srcDir )
        fullXML.write ( xmlPath  )            
Exemplo n.º 42
0
def parse_galaxy_sub_elem(elem):
    mydict = {}
    if elem.tag == "inputs":
        mydict[elem.tag] = {}
        mydict[elem.tag]["input_files"] = []
        mydict[elem.tag]["sequence"] = []
        mydict[elem.tag]["integer"] = []
        mydict[elem.tag]["float"] = []
        mydict[elem.tag]["text"] = []
        mydict[elem.tag]["boolean"] = []
        mydict[elem.tag]["long_args"] = []
        mydict[elem.tag]["integer"] = []
        # inputs in galaxy could be input file or any other input value
        # like input textbox...
        for subelem in elem.iter():
            if subelem.tag == "param":
                if "name" in subelem.attrib:
                    name = subelem.attrib["name"]
                    mydict[elem.tag][name] = {}
                    mydict[elem.tag][name]["long_args"] = name
                else:
                    # Is that possible ?
                    print "An input sub element has no name " + \
                    str(ET.dump(subelem))
                    continue
                if "help" in subelem.attrib:
                    mydict[elem.tag][name]["descrips_args"] = subelem.\
                    attrib["help"]
                if "label" in subelem.attrib:
                    mydict[elem.tag][name]["prompt"] = subelem.\
                    attrib["label"]
                if "value" in subelem.attrib:
                    # value galaxy <=> vdef pise
                    mydict[elem.tag][name]["value"] = subelem.\
                    attrib["value"]
                if subelem.attrib["type"] == "select":
                    mydict[elem.tag][name]["vlist"] = {}
                    mydict[elem.tag][name]["vlist"]["value"] = []
                    mydict[elem.tag][name]["vlist"]["text"] = []
                    for elemval in subelem.findall("option"):
                        if "selected" in elemval.attrib:
                            mydict[elem.tag][name]["value"] = elemval.\
                            attrib["value"]
                        mydict[elem.tag][name]["vlist"]["value"].append(\
                        elemval.attrib["value"])
                        mydict[elem.tag][name]["vlist"]["text"].append(\
                        elemval.text)
                elif subelem.attrib["type"] == "data" or \
                subelem.attrib["type"] == "file" or \
                subelem.attrib["type"] == "ftpfile" :
                    if subelem.attrib["format"] == "fasta":
                        mydict[elem.tag][name]["sequence"] = True
                    else:
                        mydict[elem.tag][name]["input_files"] = True
                elif subelem.attrib["type"] == "integer":
                    mydict[elem.tag][name]["integer"] = True
                elif subelem.attrib["type"] == "float":
                    mydict[elem.tag][name]["float"] = True
                elif subelem.attrib["type"] == "text":
                    mydict[elem.tag][name]["string"] = True
                elif subelem.attrib["type"] == "boolean":
                    mydict[elem.tag][name]["boolean"] = True
            elif subelem.tag == "conditional" or subelem.tag == "when":
                print "A conditional/when tag has been detected! "+\
                "There is no equivalent in Pise!"

    elif elem.tag == "outputs":
        mydict[elem.tag] = {}
        mydict[elem.tag]["long_args"] = []
        for subelem in elem.iter():
            if subelem.tag == "data":
                if "name" in subelem.attrib:
                    name = subelem.attrib["name"]
                    mydict[elem.tag][name] = {}
                    mydict[elem.tag][name]["long_args"] = name
                else:
                    print "An output sub element has no name " + \
                    str(ET.dump(subelem))
                    continue
            if "format" in subelem.attrib:
                # format is text or exotic type from datatypes_conf.xml
                # file (sam, bam, maf, acedb, qual...)
                # Anyway it is often text... Except some binaries :(
                # So I will consider it is text
                mydict[elem.tag][name]["format"] = subelem.\
                attrib["format"]
            if "from_work_dir" in subelem.attrib:
                mydict[elem.tag][name]["from_work_dir"] = subelem.\
                attrib["from_work_dir"]
            if "label" in subelem.attrib:
                mydict[elem.tag][name]["descrips_args"] = subelem.\
                attrib["label"]
            if "metadata_source" in subelem.attrib:
                mydict[elem.tag][name]["metadata_source"] = subelem.\
                attrib["metadata_source"]

    return mydict
Exemplo n.º 43
0
#! /usr/bin/env python

import pprint
import sys
import xml.etree.cElementTree as xmlet
'''
e is an element instance
'''

e = xmlet.Comment('Hello World')
ea = xmlet.Element('sampletag', {'a': 'hello'}, b='world')
es = xmlet.fromstring('<this ought="to" be="parsed" by="this">call</this>')
ex = xmlet.XML('<this ought="to" be="parsed" by="this">call</this>')
ei, ed = xmlet.XMLID('<this ought="to" be="parsed" by="this">call</this>')
if xmlet.iselement(es):
    print "fromstring() successfully created the element"
xmlet.dump(e)
xmlet.dump(ea)
xmlet.dump(es)
xmlet.dump(ex)
xmlet.dump(ei)

ET = xmlet.parse('wav.xml')
et = ET.getroot()

if e:
    xmlet.dump(e)
Exemplo n.º 44
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import xml.etree.cElementTree as XML
new_xml = XML.Element('data')
name = XML.SubElement(new_xml, 'name', attrib={'enrolled': 'yes'})
age = XML.SubElement(name, 'age', attrib={'checked': 'no'})
sex = XML.SubElement(name, 'sex')
name.text = 'Daniel'
sex.text = 'Male'
age.text = '29'

et = XML.ElementTree(new_xml)
et.write('create.xml', encoding='utf-8', xml_declaration=True)

XML.dump(new_xml)
Exemplo n.º 45
0
def categoriesXML():
	tree = et.ElementTree()
	categories=session.query(Category).all()
	return categories(et.dump(tree), mimetype='application/xml')
Exemplo n.º 46
0
def generate_outtext(info, output_format, target_plot, Ctable = False):
    """
    input the database query and generate the formatted text

    :param info:
        generated from database query.
    :param output_format:
        'xml', 'csv'
    :param target_plot:
        'NZE'-- NZE plot ("week_year,day_time,speed,vol,lanedr")
        'TVV'-- Time VS Volume plot ("date_time, volume, lanedir")
    :return:
    """
    if Ctable == True:
        # heading = ['ACISA,' + ','.join([str(i) for i in range(25)])]
        heading = []
        for oneAC in info:
            Volcontent = ['-1' for x in range(25)]
            for i in info[oneAC]:
                Volcontent[int(i)] = info[oneAC][i]
            heading.append(oneAC + ',' + ','.join(Volcontent))
        return '\n'.join(heading)


    if target_plot == 'NZE':  # format for generating NZE plot ("week_year,day_time,speed,vol,lanedr")
        if output_format == 'xml':
            # construct XML
            root = ET.Element("items")
            for k, v in info.items():
                lanedr = ET.SubElement(root, "lanedr")
                lanedr.set('direction', k.strip())
                for v0 in v:
                    item = ET.SubElement(lanedr, "item")
                    item.set("datetime", v0['datetime'].strftime("%Y-%m-%d %H:%M:%S"))
                    item.set("speed", str(v0['speed']))
                    item.set("vol", str(v0['vol']))

            tree = ET.ElementTree(root)
            #    tree.write("test.xml") # write to a temporary file
            return ET.dump(tree) # return an XML string

        elif output_format == 'csv':
            # construct csv
            text = ["week_year,day_time,speed,vol,lanedr"]
            for k, v in info.items():
                kk = k.strip()
                for v0 in v:
                    wday = datetime.datetime(1900, 1, 7, v0['datetime'].hour, v0['datetime'].minute,
                                             v0['datetime'].second) + datetime.timedelta(
                        (v0['datetime'].weekday() + 1) % 7, 0)
                    text.append("%s,%s,%s,%s,%s" % (
                        v0['datetime'].strftime("%Y-%m-%d"), wday.strftime("%Y-%m-%d %H:%M:%S"), str(v0['speed']),
                        str(v0['vol']), kk))
            outtext = '\n'.join(t for t in text)
            return outtext

    elif target_plot == 'TVV': # format for generating Time VS Volume plot ("date_time, volume, lanedir")
        if Ctable is True:
            print 'TODO'
            return 'Something'
        if output_format == 'xml':
            # construct XML
            root = ET.Element("items")
            for k, v in info.items():
                lanedr = ET.SubElement(root, "lanedr")
                lanedr.set('direction', k.strip())
                for v0 in v:
                    item = ET.SubElement(lanedr, "item")
                    item.set("datetime", v0['datetime'].strftime("%Y-%m-%d %H:%M:%S"))
                    item.set("vol", str(v0['vol']))

            tree = ET.ElementTree(root)
            #    tree.write("test.xml") # write to a temporary file
            return ET.dump(tree) # return an XML string

        elif output_format == 'csv':
            # construct csv
            text = ["datetime,vol,lanedr"]
            for k, v in info.items():
                kk = k.strip()
                for v0 in v:
                    if str(v0['vol']) == 'None':
                        text.append("%s,%s,%s" % (v0['datetime'].strftime("%Y-%m-%d %H:%M:%S"), '0', kk))
                    else:
                        text.append("%s,%s,%s" % (v0['datetime'].strftime("%Y-%m-%d %H:%M:%S"), str(v0['vol']), kk))
            outtext = '\n'.join(t for t in text)
            return outtext

    elif target_plot == 'BBL': # format for bubble  (change all 0 to 1)
        if output_format == 'json':
            outdict = traverse_hier_dict_info(info, 0, changeZeroToOne=True)
            #outtext = json.dumps(outdict, sort_keys=True, indent=4)
            return outdict

    elif target_plot == 'TMP': # format for TreeMap
        ## only capable for json
        if output_format == 'json':
            outdict = traverse_hier_dict_info(info, 0)
            #outtext = json.dumps(outdict, sort_keys=True, indent=4)
            return outdict

    elif target_plot == 'SMX': # fromat for Scatter Matrix
        if output_format == 'csv':
            header = "phase,acisa,laneDir,volume,speed,occupancy"
            outlist = list()
            outlist.append(header)

            for i in info:
                hr = i[0] + 1
                if hr >= 6 and hr < 12:
                    hr_cate = "morning"
                elif hr >= 12 and hr < 20:
                    hr_cate = "afternoon"
                else:
                    hr_cate = "night"

                outlist.append(hr_cate + ',' + ','.join(str(xx) for xx in i[1:]))
            outtext = '\n'.join(xx for xx in outlist)
            return outtext
Exemplo n.º 47
0
	def dump(self):
		"""Print element.
		
		:rtype: str
		"""
		return etree.dump(self._elem)
Exemplo n.º 48
0
 def show_xml_tree(self):
     dump(self.xmltree)
Exemplo n.º 49
0
    def saveConfig(self, xml_file="~/.faraday/config/user.xml"):
        """ Saves XML config on new file. """

        ROOT = Element("faraday")
        
        API_CON_INFO_HOST = Element(CONST_API_CON_INFO_HOST)
        API_CON_INFO_HOST.text = self.getApiConInfoHost()
        ROOT.append(API_CON_INFO_HOST)
        
        API_CON_INFO_PORT = Element(CONST_API_CON_INFO_PORT)
        API_CON_INFO_PORT.text = str(self.getApiConInfoPort())
        ROOT.append(API_CON_INFO_PORT)
        
        APPNAME = Element(CONST_APPNAME)
        APPNAME.text = self.getAppname()
        ROOT.append(APPNAME)

        AUTH = Element(CONST_AUTH, encrypted="no", algorithm="OTR")
        AUTH.text = self.getAuth()
        ROOT.append(AUTH)

        AUTO_SHARE_WORKSPACE = Element(CONST_AUTO_SHARE_WORKSPACE)
        AUTO_SHARE_WORKSPACE.text = self.getAutoShareWorkspace()
        ROOT.append(AUTO_SHARE_WORKSPACE)

        CONFIG_PATH = Element(CONST_CONFIG_PATH)
        CONFIG_PATH.text = self.getConfigPath()
        ROOT.append(CONFIG_PATH)

        DATA_PATH = Element(CONST_DATA_PATH)
        DATA_PATH.text = self.getDataPath()
        ROOT.append(DATA_PATH)

        DEBUG_STATUS = Element(CONST_DEBUG_STATUS)
        DEBUG_STATUS.text = str(self.getDebugStatus())
        ROOT.append(DEBUG_STATUS)

        DEFAULT_CATEGORY = Element(CONST_DEFAULT_CATEGORY)
        DEFAULT_CATEGORY.text = self.getDefaultCategory()
        ROOT.append(DEFAULT_CATEGORY)

        DEFAULT_TEMP_PATH = Element(CONST_DEFAULT_TEMP_PATH)
        DEFAULT_TEMP_PATH.text = self.getDefaultTempPath()
        ROOT.append(DEFAULT_TEMP_PATH)

        FONT = Element(CONST_FONT)
        FONT.text = self.getFont()
        ROOT.append(FONT)

        HOME_PATH = Element(CONST_HOME_PATH)
        HOME_PATH.text = self.getHomePath()
        ROOT.append(HOME_PATH)


        HOST_TREE_TOGGLE = Element(CONST_HOST_TREE_TOGGLE)
        HOST_TREE_TOGGLE.text = self.getHostTreeToggle()
        ROOT.append(HOST_TREE_TOGGLE)

        HSTACTIONS_PATH = Element(CONST_HSTACTIONS_PATH)
        HSTACTIONS_PATH.text = self.getHsactionsPath()
        ROOT.append(HSTACTIONS_PATH)

        ICONS_PATH = Element(CONST_ICONS_PATH)
        ICONS_PATH.text = self.getIconsPath()
        ROOT.append(ICONS_PATH)

        IMAGE_PATH = Element(CONST_IMAGE_PATH)
        IMAGE_PATH.text = self.getImagePath()
        ROOT.append(IMAGE_PATH)

        LOG_CONSOLE_TOGGLE = Element(CONST_LOG_CONSOLE_TOGGLE)
        LOG_CONSOLE_TOGGLE.text = self.getLogConsoleToggle()
        ROOT.append(LOG_CONSOLE_TOGGLE)

        NETWORK_LOCATION = Element(CONST_NETWORK_LOCATION)
        NETWORK_LOCATION.text = self.getNetworkLocation()
        ROOT.append(NETWORK_LOCATION)

        PERSISTENCE_PATH = Element(CONST_PERSISTENCE_PATH)
        PERSISTENCE_PATH.text = self.getPersistencePath()
        ROOT.append(PERSISTENCE_PATH)

        PERSPECTIVE_VIEW = Element(CONST_PERSPECTIVE_VIEW)
        PERSPECTIVE_VIEW.text = self.getPerspectiveView()
        ROOT.append(PERSPECTIVE_VIEW)

        REPO_PASSWORD = Element(CONST_REPO_PASSWORD)
        REPO_PASSWORD.text = self.getRepoPassword()
        ROOT.append(REPO_PASSWORD)

        REPO_URL = Element(CONST_REPO_URL, type="SVN")
        REPO_URL.text = self.getRepoUrl()
        ROOT.append(REPO_URL)

        REPO_USER = Element(CONST_REPO_USER)
        REPO_USER.text = self.getRepoUser()
        ROOT.append(REPO_USER)

        REPORT_PATH = Element(CONST_REPORT_PATH)
        REPORT_PATH.text = self.getReportPath()
        ROOT.append(REPORT_PATH)

        SHELL_MAXIMIZED = Element(CONST_SHELL_MAXIMIZED)
        SHELL_MAXIMIZED.text = self.getShellMaximized()
        ROOT.append(SHELL_MAXIMIZED)

        LAST_WORKSPACE = Element(CONST_LAST_WORKSPACE)
        LAST_WORKSPACE.text = self.getLastWorkspace()
        ROOT.append(LAST_WORKSPACE)

        COUCH_URI = Element(CONST_COUCH_URI)
        COUCH_URI.text = self.getCouchURI()
        ROOT.append(COUCH_URI)

        COUCH_IS_REPLICATED = Element(CONST_COUCH_ISREPLICATED)
        COUCH_IS_REPLICATED.text = str(self.getCouchIsReplicated())
        ROOT.append(COUCH_IS_REPLICATED)

        COUCH_REPLICS = Element(CONST_COUCH_REPLICS)
        COUCH_REPLICS.text = self.getCouchReplics()
        ROOT.append(COUCH_REPLICS)

        VERSION = Element(CONST_VERSION)
        VERSION.text = self.getVersion()
        ROOT.append(VERSION)

        PLUGIN_SETTINGS = Element(CONST_PLUGIN_SETTINGS)
        PLUGIN_SETTINGS.text = json.dumps(self.getPluginSettings())
        ROOT.append(PLUGIN_SETTINGS)

        TKT_URI = Element(CONST_TKTURI)
        TKT_URI.text = self.getTktPostUri()
        ROOT.append(TKT_URI)

        TKT_APIPARAMS = Element(CONST_TKTAPIPARAMS)
        TKT_APIPARAMS.text = self.getApiParams()
        ROOT.append(TKT_APIPARAMS)

        TKT_TEMPLATE = Element(CONST_TKTTEMPLATE)
        TKT_TEMPLATE.text = self.getTktTemplate()
        ROOT.append(TKT_TEMPLATE)

        self.indent(ROOT, 0)                         
        dump(ROOT)                                        
        xml_file = os.path.expanduser(xml_file)
        ElementTree(ROOT).write(xml_file)                                      
Exemplo n.º 50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import xml.etree.cElementTree as XML
new_xml = XML.Element('data')
name = XML.SubElement(new_xml,'name',attrib={'enrolled':'yes'})
age = XML.SubElement(name,'age',attrib={'checked':'no'})
sex = XML.SubElement(name,'sex')
name.text = 'Daniel'
sex.text = 'Male'
age.text = '29'

et = XML.ElementTree(new_xml)
et.write('create.xml',encoding='utf-8',xml_declaration=True)

XML.dump(new_xml)

Exemplo n.º 51
0
    def _send(self, in_data):
        """Send OMP data to the manager and read the result.

		`in_data` may be either an unicode string, an utf-8 encoded
		string or an etree Element. The result is as an etree Element.

		:param in_data: data to send.
		:type in_data: str | ElementTree

		:return: XML tree element.
		:rtype: `ElementTree`

		:raises: ServerError
		"""

        if self.__host == "dummy":
            return etree.fromstring(in_data)

        # Make sure the data is a string.
        if etree.iselement(in_data):
            in_data = etree.dump(in_data)

        try:
            in_data = in_data.encode('utf-8')
        except Exception:
            pass

        # Synchronize access to the socket.
        with self.__socket_lock:

            # Send the data to the server.
            try:
                self.socket.sendall(in_data)
            except socket.error:
                raise ServerError("Can't connect to the server.")

            # Get the response from the server.
            tree = None
            data = []
            try:
                while True:
                    chunk = self.socket.recv(1024)
                    if not chunk:
                        break
                    data.append(chunk)

                    # We use this tip for avoid socket blocking:
                    # If xml is correct, we're finished to receive info. Otherwise,
                    # continue receiving
                    try:
                        tree = etree.fromstring(b"".join(data))
                    except Exception:
                        continue
                    break
            except socket.error as e:
                raise ServerError("Can't receive info from the server: %s" % e)

            # if tree is None:
            if tree is None:
                tree = etree.ElementTree()
                return tree

            # Return the parsed response.
            return tree
Exemplo n.º 52
0
 def dump(self):
     ET.dump(self.document)
# Build kml with eTree

# https://github.com/GeospatialPython/Learning/raw/master/broken_data.gpx

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
root = ET.Element("kml")
root.attrib["xmlns"] = "http://www.opengis.net/kml/2.2"
placemark = ET.SubElement(root, "Placemark")
office = ET.SubElement(placemark, "name")
office.text = "Office"
point = ET.SubElement(placemark, "Point")
coordinates = ET.SubElement(point, "coordinates")
coordinates.text = "-89.3462521, 30.396190"
tree = ET.ElementTree(root)
tree.write("placemark.kml", xml_declaration=True,
           encoding='utf-8', method="xml")
ET.dump(tree.getroot())
Exemplo n.º 54
0
 def DumpXML (self):
     return ET.dump(self.XML_DATA)