Beispiel #1
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
Beispiel #2
0
	def write(self, node, data):
		dt = SubElement(node, 'dt')
		dt.text = str(data.dt)

		meta_event = SubElement(node, 'MetaEvent')

		event = MetaEventFactory.get(data.event.type)
		event.write(meta_event, data.event)
Beispiel #3
0
	def write(self, node, data):
		dt = SubElement(node, 'dt')
		dt.text = str(data.dt)

		sysex_event = SubElement(node, 'SysExEvent')

		event = SysExEventFactory.get(data.event.value)
		event.write(sysex_event, data.event)
Beispiel #4
0
  def __init__(self):
    self.data = Element("data")

    entityRendererElement = SubElement(self.data, "mtg:EntityRenderer")

    entityRendererElement.attrib['xmlns:mtg'] = 'http://maltego.paterva.com/xml/mtgx'

    self.position = SubElement(entityRendererElement, "mtg:Position")
Beispiel #5
0
	def write(self, node, data):
		dt = SubElement(node, 'dt')
		dt.text = str(data.dt)

		midi_event = SubElement(node, 'MidiEvent')

		event = MidiEventFactory.get(data.event.value)
		event.write(midi_event, data.event)
Beispiel #6
0
  def add_entity_property(self, parent, prop, value):
    propertyElement = SubElement(parent, "mtg:Property")

    propertyElement.attrib = {
      'name': prop.get('name'),
      'type': prop.get('dataType', 'string')
    }

    SubElement(propertyElement, "mtg:Value").text = value
Beispiel #7
0
 def __build(self, node, builder):
     for child in node.children:
         if child.namespace != child.rootNamespace:
             if child.nsMapper.get(child.namespace):
                 child.tag = child.nsMapper[child.namespace] + ":" + child.tag
         _sub = SubElement(builder, child.tag, child.attrib)
         if child.hasText:
             _sub.text = child.text
         self.__build(child, _sub)
Beispiel #8
0
 def _update_xml_item(self, xml_item, item):
     if item.image:
         image_el = SubElement(xml_item, 'image')
         image_el.text = item.image
     addons_el = SubElement(xml_item, 'addons')
     for addon_id in item:
         addon_id_el = SubElement(addons_el, 'addon_id')
         addon_id_el.text = addon_id
     return xml_item
Beispiel #9
0
    def _create_actions(self, actions):
        for action_name, action in actions.iteritems():
            action_element = SubElement(self.action_list_element, "action")

            element = SubElement(action_element, "name")
            element.text = action.name
            
            # <argumentList>
            argument_list_element = SubElement(action_element, "argumentList")
            if action.arguments:
                self._create_arguments(argument_list_element, action.arguments)
	def rebuildElement (self, parentElement, node):
		newElement = SubElement(parentElement, node['name'])
		newElement.text = node['text'].strip()

		if node['name'] in {'gml:pos', 'gml:posList'}:
			# convert the lat/lon -> lon/lat.
			contentlist = newElement.text.split("\n")
			newElement.text = ' '.join( [ x[1] + "," + x[0] for x in [x.split() for x in contentlist if x != ""]] )

		for n in node['node']:
			self.rebuildElement(newElement, n)
    def save_project(project):
        root = Element("project")
        root.set("name", project.get_name())
        files_node = SubElement(root, "files")
        for filename in project.get_files():
            f_node = SubElement(files_node, "file")
            f_node.set("path", filename)

        with open(project.get_file(), "w") as f:
            f.write(utils.get_pretty_xml(root))
            f.flush()
Beispiel #12
0
def xmlnode(root, name, text="", **attrs):
    "Simple way to attach an ElementTree node."

    elem = SubElement(root, name) if root is not None else Element(name)
    if text:
        elem.text = text

    for k, v in attrs.iteritems():
        elem.set(k, v)

    return elem
Beispiel #13
0
def _dict_xml_node(data, parent):
    """Traverse the dict data under the root key"""
    if isinstance(data, dict):
        for elem, value in six.iteritems(data):
            sub = SubElement(parent, elem)
            sub.text = _dict_xml_node(value, sub)
    elif isinstance(data, list):
        for entry in data:
            _dict_xml_node(entry, parent)
    else:
        return data
 def save_edge(edge, parent_node_el):
     edge_el = SubElement(parent_node_el, "arc")
     edge_el.set("node-id", edge.get_target().get_id())
     edge_el.set("label", edge.get_label())
     edge_el.set("events-count", str(edge.get_events_count()))
     edge_el.set("time", str(edge.get_time()))
     edge_el.set("pids", str(edge.get_pids()))
     return edge_el
Beispiel #15
0
    def _create_embedded_devices(self):
        if self.device.is_root_device():
            embedded_devices = self.device.devices

            if len(embedded_devices) > 0:
                device_list_element = SubElement(self.device_element,
                                                 "deviceList")
                for embedded_device in embedded_devices.values():
                    embedded_device_description = DeviceXMLGenerator(
                                                            embedded_device)
                    device_list_element.append(embedded_device_description.
                                               generate())
Beispiel #16
0
 def set_comment(self, text):
     meta_data_elem = self._graph_pair.get_meta_data()
     comment_elem = meta_data_elem.find("comment")
     
     if text.strip():
         if comment_elem is None:
             comment_elem = SubElement(meta_data_elem, "comment")
         comment_elem.text = text
     elif comment_elem:
         meta_data_elem.remove(comment_elem)
         
     self._changed = True
Beispiel #17
0
  def __init__(self, entityType, entity, value):
    self.data = Element("data")
    entityElement = SubElement(self.data, "mtg:MaltegoEntity")

    entityElement.attrib = {
      'xmlns:mtg': 'http://maltego.paterva.com/xml/mtgx',
      'type': entityType
    }

    propertiesElement = SubElement(entityElement, "mtg:Properties")

    self.add_entity_property(propertiesElement, entity, value)
Beispiel #18
0
    def to_xml(self, filename, id2name):
        results_tag = Element("Results")
        dataset_tag = SubElement(results_tag, "Dataset")
        dataset_tag.text = "Test"
        stories_tag = SubElement(results_tag, "Stories")

        for story in self:
            story_elem = SubElement(stories_tag, "Story", {"StoryId": str(story["story_id"])})
            tags = SubElement(story_elem, "Tags")
            for tag in story["tags"]:
                SubElement(tags, "Tag", {"OrgID": str(tag), "Company": id2name[tag], "Relevance": "H"})
        ET.ElementTree(results_tag).write(filename)
    def edx(self, out_dir):
        chapter_dir = os.path.join(out_dir, 'chapter')
        if not os.path.exists(chapter_dir):
            os.makedirs(chapter_dir)
        chapter = Element('chapter', {'display_name':escape(self.project)});
        for group in self.groups:
            e = SubElement(chapter, 'sequential')
            e.set('url_name', group.url_name())
        tree = ElementTree(chapter)
        tree.write(os.path.join(chapter_dir, "{0}.xml".format(self.url_name())) )

        for group in self.groups:
            group.edx(out_dir)
Beispiel #20
0
  def __init__(self, label):
    self.data = Element("data")

    linkElement = SubElement(self.data, "mtg:MaltegoLink")

    linkElement.attrib = {
      'xmlns:mtg': 'http://maltego.paterva.com/xml/mtgx',
      'type': 'maltego.link.manual-link'
    }

    propertiesElement = SubElement(linkElement, "mtg:Properties")

    self.add_entity_property(propertiesElement, {'name': 'maltego.link.manual.type'}, label)
 def build(root, channels):
     if channels:
         for reference, namealternatives in channels.iteritems():
             name, alternatives = namealternatives[:]
             if alternatives:
                 # Add channel
                 web = alternatives[0]
                 element = SubElement(root, "channel", name=stringToXML(name), id=stringToXML(web))
                 element.text = stringToXML(reference)
                 del alternatives[0]
                 if alternatives:
                     for web in alternatives:
                         SubElement(element, "web").text = stringToXML(web)
     return root
Beispiel #22
0
 def generateWay (self, attr):
     featureMember = Element("gml:featureMember")
     feature = SubElement(featureMember, "way")
     FID = SubElement(feature, "osm_id")
     FID.text = str(attr["id"])
     geometryProperty = SubElement(feature, "gml:geometryProperty")
     lineString = SubElement(geometryProperty, "gml:LineString")
     coordinates = SubElement(lineString, "gml:coordinates")
     coordinates.text = " ".join(map(lambda x: "%s,%s" % x, attr['nodes']))
     for k, v in attr.iteritems():
         if (k != "nodes") and (k!="") and ((k in exportTags) or exportAll):
             SubElement(feature, "" + k).text = v
     ElementTree(featureMember).write(self.fh, "utf-8")
     self.fh.write("\n")
	def generateFeature (self):
		featureMember = Element('gml:featureMember')
		feature = SubElement(featureMember, 'ogr:' + self.featuretag)
		# set the fid.
		for node in self.nodes:
			if node['name'] == 'fid':
				feature.attrib['fid'] = node['text'].strip()

		# generate the id node.
		SubElement(feature, "ogr:id").text = self.featureid

		# generate the child nodes.
		for node in self.nodes:
			newElement = SubElement(feature, 'ogr:' + node['name'])
			newElement.text = node['text'].strip()

			if node['type'] in {'gml:CurvePropertyType', 'gml:DiscreteCoverageType',
                                            'gml:PointPropertyType', 'gml:SurfacePropertyType'}:
				geomElement = SubElement(newElement, 'ogr:geometryProperty')
				geomElement.text = node['text'].strip()
				for n in node['node']:
					self.rebuildElement(geomElement, n)

				# set the 'srsName' in child node.
				iter = geomElement.iter("*")
				gmlElement = next(islice(iter, 1, None), None)
				gmlElement.attrib['srsName'] = 'EPSG:4612'

			elif node['type'] == 'gml:TimeInstantType':
				lastElement = deque(node['node'], maxlen=1).pop()
				newElement.text = lastElement['text'].strip()

		ElementTree(featureMember).write(self.fh, 'utf-8')
		self.fh.write("\n")
Beispiel #24
0
 def generateNode (self, attr):
     featureMember = Element("gml:featureMember")
     feature = SubElement(featureMember, "node")
     FID = SubElement(feature, "osm_id")
     FID.text = str(attr["id"])
     geometryProperty = SubElement(feature, "gml:geometryProperty")
     lineString = SubElement(geometryProperty, "gml:Point")
     coordinates = SubElement(lineString, "gml:coordinates")
     coordinates.text = ("%s,%s" % self.node[attr["id"]])
     for k, v in attr.iteritems():
         if (k!="") and ((k in exportTags) or exportAll):
             SubElement(feature, "" + k).text = v
     ElementTree(featureMember).write(self.fh, "utf-8")
     self.fh.write("\n")
Beispiel #25
0
 def gpx(self,gpx):
   "Construct an ElementTree for the given GPX file"
   root = Element("gpx",xmlns=NS,version="1.1",creator=self.creator)
   for wpt in gpx.waypoints:
     root.append(self.wpt(wpt,"wpt"))
   for route in gpx.routes:
     el = self.path(route,"rte","rtept")
     xmlutil.write(el,route,Route._scheme)
     root.append(el) 
   for track in gpx.tracks:
     el = SubElement(root,"trk")
     xmlutil.write(el,track,Track._scheme)
     for seg in track:
       el.append(self.path(seg,"trkseg","trkpt"))
   return root
    def add_agents_to_xml(config_xml, asl_list):
        tree = ElementTree()
        tree.parse(config_xml)

        root = tree.getroot()
        nodes = root.findall('asl-list')
        for node in nodes:
            root.remove(node)
        node = SubElement(root, 'asl-list')
        for entry in asl_list:
            agentNode = SubElement(node, 'asl')
            for key, value in entry.iteritems():
                agentNode.attrib[key] = value

        return tree
Beispiel #27
0
    def _insert_node(self, root, k, v, key_attr=None):
        element = SubElement(root, k)
        if v is None:
            element.attrib[u'xsi:nil'] = u'true'
        elif not isinstance(v, (list, dict)):
            element.text = text_type(v)
        else:
            if isinstance(v, list):
                it = enumerate(v)
            else:
                it = v.items()
            for key, value in it:
                self._insert_node(element, self._value_tag, value, key)

        if key_attr is not None:
            element.attrib[self._key_attr] = text_type(key_attr)
Beispiel #28
0
    def get_element(self):
        # <root>
        elt = Element('scpd', xmlns = 'urn:schemas-upnp-org:' +
                           UPnPDefaults.SERVICE_SCHEMA_VERSION)
        # <specVersion>
        spec_version_element = SubElement(elt, 'specVersion')
        element = SubElement(spec_version_element, 'major')
        element.text = UPnPDefaults.SCHEMA_VERSION_MAJOR
        element = SubElement(spec_version_element, 'minor')
        element.text = UPnPDefaults.SCHEMA_VERSION_MINOR

        # <actionList> and <serviceStateTable>
        action_list_element, service_state_table_element = ServiceXMLGenerator(self.service).generate()
        elt.append(action_list_element)
        elt.append(service_state_table_element)
        return elt
Beispiel #29
0
    def get_element(self):
        # <root>
        elt = Element('root',
                      xmlns='urn:schemas-upnp-org:' +
                      UPnPDefaults.SCHEMA_VERSION)
        # <specVersion>
        spec_version_element = SubElement(elt, 'specVersion')
        element = SubElement(spec_version_element, 'major')
        element.text = UPnPDefaults.SCHEMA_VERSION_MAJOR
        element = SubElement(spec_version_element, 'minor')
        element.text = UPnPDefaults.SCHEMA_VERSION_MINOR

        # <urlBase>
        if self.url_base != None:
            element = SubElement(elt, 'URLBase')
            element.text = self.url_base

        # <device>
        elt.append(DeviceXMLGenerator(self.device, self.extra_elts).generate())
        return elt
Beispiel #30
0
    def add_record_type(self, ctype):
        """Add explicit record to bind, unless it is already mentioned
           explictly in the <record> nodes.
        """

        if self.node:
            for rec in self.node.findall("record"):
                if rec.get("ctype") == ctype:
                    return

            SubElement(self.node, "record", {"ctype": ctype})
Beispiel #31
0
def container_to_xml(listing, base_name):
    doc = Element('container', name=base_name.decode('utf-8'))
    for record in listing:
        if 'subdir' in record:
            name = record.pop('subdir')
            sub = SubElement(doc, 'subdir', name=name)
            SubElement(sub, 'name').text = name
        else:
            sub = SubElement(doc, 'object')
            for field in ('name', 'hash', 'bytes', 'content_type',
                          'last_modified'):
                SubElement(sub, field).text = six.text_type(record.pop(field))

            if 'symlink_path' in record:
                SubElement(sub, 'symlink_path').text = six.text_type(
                    record.pop('symlink_path'))

    return tostring(doc, encoding='UTF-8').replace(
        "<?xml version='1.0' encoding='UTF-8'?>",
        '<?xml version="1.0" encoding="UTF-8"?>', 1)
Beispiel #32
0
 def build(root, channels):
     if channels:
         for reference, namealternatives in channels.iteritems(
         ):
             name, alternatives = namealternatives[:]
             if alternatives:
                 # Add channel
                 web = alternatives[0]
                 element = SubElement(root,
                                      "channel",
                                      name=stringToXML(name),
                                      id=stringToXML(web))
                 element.text = stringToXML(reference)
                 del alternatives[0]
                 if alternatives:
                     for web in alternatives:
                         SubElement(
                             element,
                             "web").text = stringToXML(web)
     return root
Beispiel #33
0
    def set_zero_orone(self, programme, element, p):
        """
        set_zero_ormore(programme, element, p) -> None

        Add nodes under p for the element 'element', which occurs zero
        times or once with PCDATA and a 'lang' attribute
        """
        if DEBUG >= 0: print "in set_zero_orone(self, programme, element, p)"
        if programme.has_key(element):
            e = SubElement(p, element)
            self.settext(e, programme[element])
Beispiel #34
0
    def set_zero_ormore(self, programme, element, p):
        """
        set_zero_ormore(programme, element, p) -> None

        Add nodes under p for the element 'element', which occurs zero
        or more times with PCDATA and a 'lang' attribute
        """
        if programme.has_key(element):
            for item in programme[element]:
                e = SubElement(p, element)
                self.settext(e, item)
Beispiel #35
0
    def _insert_node(self,
                     root: Any,
                     k: str,
                     v: Any,
                     key_attr: Optional[Any] = None):
        element = SubElement(root, k)
        if v is None:
            element.attrib[u'xsi:nil'] = u'true'
        elif not isinstance(v, (list, dict)):
            element.text = str(v)
        else:
            if isinstance(v, list):
                it = enumerate(v)
            else:
                it = v.items()
            for key, value in it:
                self._insert_node(element, self._value_tag, value, key)

        if key_attr is not None:
            element.attrib[self._key_attr] = str(key_attr)
    async def send_xml(self, xml_dict):
        data_root = Element('msg')
        data_root.set('t', 'sys')

        sub_element_parent = data_root
        for sub_element, sub_element_attribute in xml_dict.items():
            sub_element_object = SubElement(sub_element_parent, sub_element)

            if type(xml_dict[sub_element]) is dict:
                for sub_element_attribute_key, sub_element_attribute_value in xml_dict[
                        sub_element].items():
                    sub_element_object.set(sub_element_attribute_key,
                                           sub_element_attribute_value)
            else:
                sub_element_object.text = xml_dict[sub_element]

            sub_element_parent = sub_element_object

        xml_data = tostring(data_root)
        await self.send_line(xml_data.decode('utf-8'))
Beispiel #37
0
 def create_listing(self, req, out_content_type, info, resp_headers,
                    metadata, container_list, container):
     for key, (value, timestamp) in metadata.items():
         if value and (key.lower() in self.save_headers
                       or is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req,
                    headers=resp_headers,
                    content_type=out_content_type,
                    charset='utf-8')
     if out_content_type == 'application/json':
         ret.body = json.dumps(
             [self.update_data_record(record) for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in [
                         "name", "hash", "bytes", "content_type",
                         "last_modified"
                 ]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     SubElement(obj_element, field).text = str(
                         record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     ret.last_modified = math.ceil(float(resp_headers['X-PUT-Timestamp']))
     return ret
Beispiel #38
0
 def __init__(self, *args, **kwargs):
     """Initialize the XmlMenuElement class.  This takes all regular
     arguments for ElementTree.Element, as well as the menu_name keyword
     argument, used for setting the Menu Name property."""
     if 'menu_name' in list(kwargs.keys()):
         menu_name = kwargs['menu_name']
         kwargs.pop("menu_name", None)
     else:
         menu_name = None
     super(XmlMenuElement, self).__init__(*args, **kwargs)
     if menu_name:
         SubElement(self, "Name").text = menu_name
Beispiel #39
0
    def set_zero_orone(self, programme, element, p):
        """
        set_zero_ormore(programme, element, p) -> None

        Add nodes under p for the element 'element', which occurs zero
        times or once with PCDATA and a 'lang' attribute
        """
        logger.log(9, 'set_zero_orone(programme=%r, element=%r, p=%r)',
                   programme, element, p)
        if programme.has_key(element):
            e = SubElement(p, element)
            self.settext(e, programme[element])
Beispiel #40
0
 def _addElements(self,
                  element,
                  atts,
                  mappings={},
                  timeFields=[],
                  skipFields=[]):
     if atts is not None:
         keys = atts.keys()
         for key in keys:
             if key in skipFields:
                 continue  #don't want this in the output XML
             value = atts[key]
             if value is not None:
                 elementMappings = mappings.get(key, key)
                 if type(elementMappings) in [tuple, list]:
                     elementName = elementMappings[0]
                     subElementName = elementMappings[1]
                 else:
                     elementName = elementMappings
                     subElementName = "item"
                 subE = SubElement(element, elementName)
                 if type(value) in [tuple, list]:
                     for indValue in value:
                         indE = SubElement(subE, subElementName)
                         if key in timeFields:
                             self._encodeTimeField(indE, value)
                         else:
                             indE.text = str(indValue)
                 else:
                     if key in timeFields:
                         self._encodeTimeField(subE, value)
                     else:
                         subE.text = str(value)
Beispiel #41
0
 def to_juniper(self, dev, commands=None, extra=None):
     if commands is None:
         commands = []
     cmds = [Element('lock-configuration')]
     files = self.files
     action = self.action
     if action == 'overwrite':
         action = 'override'
     for fname in files:
         #log.msg("fname: %s" % fname)
         filecontents = ''
         if not os.path.isfile(fname):
             fname = tftp_dir + fname
         try:
             filecontents = file(fname).read()
         except IOError as e:
             log.msg("Unable to open file: %s" % fname)
         if filecontents == '':
             continue
         lc = Element('load-configuration', action=action, format='text')
         body = SubElement(lc, 'configuration-text')
         body.text = filecontents
         cmds.append(lc)
     if len(commands) > 0:
         lc = Element('load-configuration', action=action, format='text')
         body = SubElement(lc, 'configuration-text')
         body.text = "\n".join(commands)
         cmds.append(lc)
     cmds.append(Element('commit-configuration'))
     return cmds
Beispiel #42
0
	def writeXMLTVConfig(self):

		if int(self.epgimportversion[0]) >= 5 and int(self.xmltvimportversion[0]) >= 5:
			return

		if self.epgimport is None and self.xmltvimport is None:
			return

		if config.plugins.seriesplugin.epgimport.value == False and config.plugins.seriesplugin.xmltvimport.value == False:
			return

		# Build Header
		from .plugin import NAME, VERSION
		root = Element("sources")
		root.set('version', VERSION)
		root.set('created_by', NAME)
		root.append(Comment(_("Don't edit this manually unless you really know what you are doing")))

		element = SubElement(root, "source", type="gen_xmltv", channels="wunschliste.channels.xml")

		SubElement(element, "description").text = "Wunschliste XMLTV"
		SubElement(element, "url").text = config.plugins.seriesplugin.xmltv_url.value

		etree = ElementTree(root)

		indent(etree.getroot())

		if config.plugins.seriesplugin.epgimport.value:
			log.debug("Write: xml channels for epgimport")
			try:
				self.epgimport.writeXML(etree)
			except Exception as e:
				log.exception("Exception in write XML: " + str(e))

		if config.plugins.seriesplugin.xmltvimport.value:
			log.debug("Write: xml channels for xmltvimport")
			try:
				self.xmltvimport.writeXML(etree)
			except Exception as e:
				log.exception("Exception in write XML: " + str(e))
Beispiel #43
0
    def binning_op(self, source_product_list, aggregator_list, output_file, variable_list=[],
                   region=None, start_date_time=None, period_duration=None,
                   time_filter_method="NONE", min_data_hour=None, spatial_resolution=9.28,
                   super_sampling=1, max_distance_on_earth=-1, mask_expr="True",
                   output_type="Product", output_format="GeoTIFF", output_binned_data=False,
                   output_mapped_product=True, metadata_properties_file="./metadata.properties",
                   metadata_template_dir=".", metadata_aggregator_name="NAME"):
        node_id, node, parameters = self._set_node_boilerplate("Binning", source_product_list)
        aggregators = SubElement(parameters, "aggregators")
        for agg in aggregator_list:
            aggregator = SubElement(aggregators, "aggregator")
            self._set_parameter(aggregator, "type", agg["type"])
            self._set_parameter(aggregator, "varName", agg["varName"])
            self._set_parameter(aggregator, "targetName", agg["targetName"])
        variables = SubElement(parameters, "variables")
        for var in variable_list:
            variable = SubElement(variables, "variable")
            self._set_parameter(variable, "name", var["name"])
            self._set_parameter(variable, "expr", var["expr"])
            self._set_parameter(variable, "validExpr", var["validExpr"])
        self._set_parameter(parameters, "region", region)
        self._set_parameter(parameters, "startDateTime", start_date_time)
        self._set_parameter(parameters, "periodDuration", period_duration)
        self._set_parameter(parameters, "timeFilterMethod", time_filter_method)
        self._set_parameter(parameters, "minDataHour", min_data_hour)
        self._set_parameter(parameters, "numRows", int(round(20037.5336/spatial_resolution/2.)*2.))
        self._set_parameter(parameters, "superSampling", super_sampling)
        self._set_parameter(parameters, "maxDistanceOnEarth", max_distance_on_earth)
        self._set_parameter(parameters, "maskExpr", mask_expr)
        self._set_parameter(parameters, "outputType", output_type)
        self._set_parameter(parameters, "outputFile", output_file)
        self._set_parameter(parameters, "outputFormat", output_format)
        self._set_parameter(parameters, "outputBinnedData", output_binned_data)
        self._set_parameter(parameters, "outputMappedProduct", output_mapped_product)
        self._set_parameter(parameters, "metadataPropertiesFile", metadata_properties_file)
        self._set_parameter(parameters, "metadataTemplateDir", metadata_template_dir)
        self._set_parameter(parameters, "metadataAggregatorName", metadata_aggregator_name)

        self.graph.append(node)
        return node_id
Beispiel #44
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
Beispiel #45
0
	def write(self, root, track):
		node = SubElement(root, 'TrackChunk')
		node.set("id", track.id)
		node.set("size", str(track.size))

		i = 0
		for data in track.data:
			type_event = TypeEventFactory.get(data.name)
			event_node = SubElement(node, '_'+str(i))
			type_event.write(event_node, data)
			i += 1
Beispiel #46
0
    def create_listing(self, req, out_content_type, resp_headers,
                       result, container, **kwargs):
        container_list = result['objects']
        for p in result.get('prefixes', []):
            record = {'name': p,
                      'subdir': True}
            container_list.append(record)
        ret = Response(request=req, headers=resp_headers,
                       content_type=out_content_type, charset='utf-8')
        versions = kwargs.get('versions', False)
        if out_content_type == 'application/json':
            ret.body = json.dumps(
                [self.update_data_record(r, versions) for r in container_list])
        elif out_content_type.endswith('/xml'):
            doc = Element('container', name=container.decode('utf-8'))
            for obj in container_list:
                record = self.update_data_record(obj, versions)
                if 'subdir' in record:
                    name = record['subdir'].decode('utf-8')
                    sub = SubElement(doc, 'subdir', name=name)
                    SubElement(sub, 'name').text = name
                else:
                    obj_element = SubElement(doc, 'object')
                    for field in ["name", "hash", "bytes", "content_type",
                                  "last_modified"]:
                        SubElement(obj_element, field).text = str(
                            record.pop(field)).decode('utf-8')
                    for field in sorted(record):
                        SubElement(obj_element, field).text = str(
                            record[field]).decode('utf-8')
            ret.body = tostring(doc, encoding='UTF-8').replace(
                "<?xml version='1.0' encoding='UTF-8'?>",
                '<?xml version="1.0" encoding="UTF-8"?>', 1)
        else:
            if not container_list:
                return HTTPNoContent(request=req, headers=resp_headers)
            ret.body = '\n'.join(rec['name'] for rec in container_list) + '\n'

        return ret
Beispiel #47
0
    def seticons(self, node, icons):
        """
        seticon(node, icons) -> None

        Create 'icons' under 'node'
        """
        for icon in icons:
            if 'src' not in icon:
                raise ValueError("'icon' element requires 'src' attribute")
            i = SubElement(node, 'icon')
            for attr in ('src', 'width', 'height'):
                if attr in icon:
                    self.setattr(i, attr, icon[attr])
Beispiel #48
0
def _add_dataset_to_element(dataset, element):
    """Adds a dataset object to an element, which is the parent in
    the ElementTree."""
    dataset_el = SubElement(element, 'dataset')
    for key in parameters.keys_required:
        sub_el = SubElement(dataset_el, key)
        sub_el.text = str(getattr(dataset, key))
    for key in parameters.keys_optional:
        if getattr(dataset, key) is not None:
            sub_el = SubElement(dataset_el, key)
            sub_el.text = str(getattr(dataset, key))
Beispiel #49
0
 def returnStatus(self, status, messageString=None):
     root = Element('ihis')
     ele = SubElement(root, "status")
     ele.text = str(status)
     if messageString is not None:
         msgE = SubElement(ele, "message")
         msgE.text = str(messageString)
     return ElementTree.tostring(root)
Beispiel #50
0
def add_senses(entry, x, to_lang, is_suffix):
    groups = groupby(x["senses"], lambda s: (s["trans_list"]))
    for trans_list, subsenses in groups:
        sense = SubElement(entry, "sense")
        # translation
        cit = SubElement(sense, "cit", {"type": "trans", "xml:lang": to_lang})
        for trans in trans_list:
            assert trans, "empty translation for %r" % x
            quote = SubElement(cit, "quote")
            if is_suffix:
                trans = trans[1:]
            quote.text = trans

        # subsenses
        for s in subsenses:
            if s["gloss"]:
                subsense = SubElement(sense, "sense")
                sense_def = SubElement(subsense, "def")
                sense_def.text = s["gloss"]
Beispiel #51
0
def _convert_matrix_row(row: list, parent: Element, alignment: Optional[str],
                        single_mtd: bool):
    mtr = SubElement(parent, "mtr")
    iterable: Iterator[int] = iter(range(len(row)))
    if single_mtd:
        mtd = SubElement(mtr, "mtd")
    for i in iterable:
        element = row[i]
        if alignment:
            column_align: str = {
                "r": "right",
                "l": "left",
                "c": "center"
            }.get(alignment, "")
            mtd = SubElement(mtr, "mtd", columnalign=column_align)
        elif not single_mtd:
            mtd = SubElement(mtr, "mtd")
        if isinstance(element, list):
            _classify_subgroup(element, mtd)
        elif element in COMMANDS:
            _convert_command(element, row, i, iterable, mtd)
        else:
            _classify(element, mtd)
Beispiel #52
0
def generate_sitemap(links):
    urlset = Element(nstag('urlset')) #, **nsmap_keyargs) # lxml
    urlset.text = '\n'
    for link in links:
        if isinstance(link, basestring):
            loc = link
            lastmod = changefreq = priority = None
        else: loc, lastmod, changefreq, priority = (tuple(link) + (None, None, None))[:4]
        url = SubElement(urlset, nstag('url'))
        url.text = url.tail = '\n'
        SubElement(url, nstag('loc')).text = loc
        if lastmod:
            if not isinstance(lastmod, basestring):
                if getattr(lastmod, 'tzinfo', None) is not None:
                    lastmod = lastmod.replace(tzinfo=None) - lastmod.utcoffset()
                lastmod = lastmod.strftime('%Y-%m-%dT%H:%M:%SZ')
            SubElement(url, nstag('lastmod')).text = lastmod
        if changefreq:
            SubElement(url, nstag('changefreq')).text = changefreq
        if priority is not None:
            SubElement(url, nstag('priority')).text = str(priority)
        for child in url: child.tail = '\n'
    return urlset
Beispiel #53
0
    def seticons(self, node, icons):
        """
        seticon(node, icons) -> None

        Create 'icons' under 'node'
        """
        logger.log(9, 'seticons(node=%r, icons=%r)', node, icons)
        for icon in icons:
            if not icon.has_key('src'):
                raise ValueError("'icon' element requires 'src' attribute")
            i = SubElement(node, 'icon')
            for attr in ('src', 'width', 'height'):
                if icon.has_key(attr):
                    self.setattr(i, attr, icon[attr])
Beispiel #54
0
    def asXml(self, parentnode, authed=False):
        from xml.etree.cElementTree import SubElement
        me = SubElement(parentnode, "user")
        xmlpopulate(me, self.player_obj)

        if authed:
            me.set("x_addrstring", self.ipaddress)
        else:
            me.set("address", "")

        if self.channel.server.hasUserTexture(self.userid):
            from views import showTexture
            from django.core.urlresolvers import reverse
            textureurl = reverse(showTexture,
                                 kwargs={
                                     'server': self.channel.server.id,
                                     'userid': self.userid
                                 })
            me.set('x_texture',
                   "http://" + Site.objects.get_current().domain + textureurl)

        if self.mumbleuser and self.mumbleuser.gravatar:
            me.set('x_gravatar', self.mumbleuser.gravatar)
Beispiel #55
0
 def check_for_missing(self):
     """Set all missing sensors to fault."""
     for (vmdb_id, data_time), indexlist in self.index.items():
         for index in self.datex2index[vmdb_id]:
             if index not in indexlist:
                 metdata = SubElement(self.resultOf[(vmdb_id, data_time)], "metData", index=str(index))
                 metdata.attrib['xsi:type'] = self.datex2index[vmdb_id][index].xsitype
                 innertag = SubElement(metdata, "fault")
                 innertag.text = "true"
Beispiel #56
0
 def write_xml(self, xml_doc=None, option=None, element_name=None):
     """ Method writes the xml representation of the managed object. """
     if option == WriteXmlOption.DIRTY and not self.is_dirty():
         return
     if xml_doc is None:
         xml_obj = Element(self.prop_mo_meta.xml_attribute)
     else:
         if element_name == None:
             xml_obj = SubElement(xml_doc, self.prop_mo_meta.xml_attribute)
         else:
             xml_obj = SubElement(xml_doc, element_name)
     if CoreUtils.find_class_id_in_mo_meta_ignore_case(
             self._class_id) != None:
         for prop in CoreUtils.get_property_list(self._class_id):
             prop_meta = CoreUtils.get_mo_property_meta(
                 self._class_id, prop)
             #if (at_meta.access == MoPropertyMeta.Internal):
             #        continue
             #elif ((option != WriteXmlOption.DIRTY) or ((at_meta.mask != None) and (self._dirty_mask & at_meta.mask) != 0)):
             if option != WriteXmlOption.DIRTY or (
                     prop_meta.mask != None and
                 (self._dirty_mask & prop_meta.mask) != 0):
                 if self.get_attr(prop) != None:
                     #xml_obj.setAttribute(prop_meta.xml_attribute, self.get_attr(prop))
                     xml_obj.set(prop_meta.xml_attribute,
                                 self.get_attr(prop))
     #Adding xtraProperties from object into Xml query document
     for xtra_prop in self.__xtra_property:
         #xml_obj.setAttribute(ImcUtils.word_l(xtra_prop), self.__xtra_property[xtra_prop])
         xml_obj.set(ImcUtils.word_l(xtra_prop),
                     self.__xtra_property[xtra_prop])
     self.child_write_xml(xml_obj, option)
     #        x_child = self.child_write_xml(xml_obj, option)
     #        for xchild in x_child:
     #            if xchild != None:
     #                xml_obj.append(xchild)
     return xml_obj
Beispiel #57
0
def _write_kodi_nfo(information, path):
    """Write the provided information to movie.nfo."""
    click.echo("Writing movie.nfo...")
    root = Element("movie")
    SubElement(root, "title").text = information.get("title")
    SubElement(root, "originaltitle").text = information.get("title")
    SubElement(root, "sorttitle").text = information.get("title")
    SubElement(root, "set").text = information.get("set")
    SubElement(root, "year").text = information.get("release_date")[:4]
    SubElement(root, "plot").text = information.get("plot")
    SubElement(root, "studio").text = information.get("studio")
    tree = ElementTree(root)
    tree.write(os.path.join(path, "movie.nfo"), encoding="UTF-8")
Beispiel #58
0
def add_senses(entry, x, to_lang, is_suffix):
    groups = groupby(x['senses'], lambda s: (s['trans_list']))
    for trans_list, subsenses in groups:
        sense = SubElement(entry, 'sense')
        # translation
        cit = SubElement(sense, 'cit',
                         {'type': 'trans', 'xml:lang': to_lang})
        for trans in trans_list:
            assert trans, 'empty translation for %r' % x
            quote = SubElement(cit, 'quote')
            if is_suffix:
                trans = trans[1:]
            quote.text = trans

        # subsenses
        for s in subsenses:
            if s['gloss']:
                subsense = SubElement(sense, 'sense')
                sense_def = SubElement(subsense, 'def')
                sense_def.text = s['gloss']