def _ConvertModelPerformance(perf, modelPerf): if len(modelPerf) > 3: confMat = modelPerf[3] accum = 0 for row in confMat: for entry in row: accum += entry accum = str(accum) else: confMat = None accum = 'N/A' if len(modelPerf) > 4: elem = SubElement(perf, "ScreenThreshold") elem.text = str(modelPerf[4]) elem = SubElement(perf, "NumScreened") elem.text = accum if len(modelPerf) > 4: elem = SubElement(perf, "NumSkipped") elem.text = str(modelPerf[6]) elem = SubElement(perf, "Accuracy") elem.text = str(modelPerf[0]) elem = SubElement(perf, "AvgCorrectConf") elem.text = str(modelPerf[1]) elem = SubElement(perf, "AvgIncorrectConf") elem.text = str(modelPerf[2]) if len(modelPerf) > 4: elem = SubElement(perf, "AvgSkipConf") elem.text = str(modelPerf[5]) if confMat: elem = SubElement(perf, "ConfusionMatrix") elem.text = str(confMat)
def _ConvertModelPerformance(perf,modelPerf): if len(modelPerf)>3: confMat = modelPerf[3] accum = 0 for row in confMat: for entry in row: accum += entry accum = str(accum) else: confMat = None accum = 'N/A' if len(modelPerf)>4: elem = SubElement(perf,"ScreenThreshold") elem.text=str(modelPerf[4]) elem = SubElement(perf,"NumScreened") elem.text=accum if len(modelPerf)>4: elem = SubElement(perf,"NumSkipped") elem.text=str(modelPerf[6]) elem = SubElement(perf,"Accuracy") elem.text=str(modelPerf[0]) elem = SubElement(perf,"AvgCorrectConf") elem.text=str(modelPerf[1]) elem = SubElement(perf,"AvgIncorrectConf") elem.text=str(modelPerf[2]) if len(modelPerf)>4: elem = SubElement(perf,"AvgSkipConf") elem.text=str(modelPerf[5]) if confMat: elem = SubElement(perf,"ConfusionMatrix") elem.text = str(confMat)
def createFilePodcast(mediaFilePath, title, description=''): """ create the xml file using utf """ mediaItem = Element("media") mediaItem.attrib["version"] = VERSION titleNode = SubElement(mediaItem, "title") titleNode.text = title descrNode = SubElement(mediaItem, "description") descrNode.text = description createXmlFile(mediaFilePath + '.xml', mediaItem) mediaItem.clear()
def TextElement(root, name, detail_value): if detail_value: te = SubElement(root, name) if detail_value.type == "text/html": detail_value.type = "html" if detail_value.type == "text/plain": detail_value.type = "text" te.attrib["type"] = detail_value.type te.text = detail_value.value
def toElementTree(self, details): """ Return an Element node with the XML rappresentation of this module """ c = Element('module') n = SubElement(c, 'name') n.text = self._alias if details: # version v = SubElement(c, 'version') v.text = str(self._version) # type t = SubElement(c, 'type') t.text = self._type # lock u = SubElement(c, 'upgradable') u.text = repr(self._upgradable).lower() return c
def addRing(self, objRing, strType): if strType == 'Inner': elemBnd = Element('innerBoundaryIs') else: elemBnd = Element('outerBoundaryIs') elemRing = SubElement(elemBnd, 'LinearRing') elemCoords = SubElement(elemRing, "coordinates") elemCoords.text = self.addCoordinates(objRing[1]) return elemBnd
def addGraphonesToLexicon(xml, graphones): lexicon = xml.getroot() for letters, phonemes in graphones: lemma = SubElement(lexicon, "lemma") lemma.text = "\n " orth = SubElement(lemma, "orth") orth.text = "_" + "".join(letters) + "_" orth.tail = "\n " phon = SubElement(lemma, "phon") phon.text = " ".join(phonemes) phon.tail = "\n " synt = SubElement(lemma, "synt") SubElement(synt, "tok").text = lmToken(letters, phonemes) synt.tail = "\n" # synt.tail = '\n ' # eval = SubElement(lemma, 'eval') # SubElement(eval, 'tok').text = '[UNKNOWN]' # eval.tail = '\n' lemma.tail = "\n"
def addGraphonesToLexicon(xml, graphones): lexicon = xml.getroot() for letters, phonemes in graphones: lemma = SubElement(lexicon, 'lemma') lemma.text = '\n ' orth = SubElement(lemma, 'orth') orth.text = '_' + ''.join(letters) + '_' orth.tail = '\n ' phon = SubElement(lemma, 'phon') phon.text = ' '.join(phonemes) phon.tail = '\n ' synt = SubElement(lemma, 'synt') SubElement(synt, 'tok').text = lmToken(letters, phonemes) synt.tail = '\n' # synt.tail = '\n ' # eval = SubElement(lemma, 'eval') # SubElement(eval, 'tok').text = '[UNKNOWN]' # eval.tail = '\n' lemma.tail = '\n'
def GetFeedElement(feed): """Create an atom:feed element for the provided feed. The provided feed must be in the format described at http://feedparser.org. """ rss = Element("rss") rss.attrib["version"] = "2.0" root = SubElement(rss, "channel") TextElement(root, "title", feed.feed.get("title_detail")) if feed.feed.has_key("links"): for link in feed.feed.links: if link.rel != "self": continue SubElementIf(root, "link", link.href) TextElement(root, "description", feed.feed.get("subtitle_detail")) TextElement(root, "copyright", feed.feed.get("rights_detail")) SubElement(root, "generator").text = "feedarchive" if feed.feed.has_key("image"): im = feed.feed.image ie = SubElement(root, "image") SubElementIf(ie, "url", im.get("href")) SubElementIf(ie, "title", im.get("title")) SubElementIf(ie, "link", im.get("link")) if feed.feed.has_key("tags"): for tag in feed.feed.tags: te = SubElement(root, "category") if (tag.has_key("scheme")): te.attrib["domain"] = tag.scheme te.text = tag.term for entry in feed.entries: ee = SubElement(root, "item") TextElement(ee, "title", entry.get("title_detail")) SubElementIf(ee, "link", entry.get("link")) TextElement(ee, "description", entry.get("summary_detail")) SubElementIf(ee, "guid", entry.get("id")) DateTimeElement(ee, "pubDate", entry, "published") PersonElement(ee, "author", entry.get("author_detail")) if entry.has_key("links"): for link in entry.links: if link.rel != "enclosure": continue ence = SubElement(ee, "enclosure") AttribIf(ence, "url", link.get("url")) AttribIf(ence, "length", link.get("length")) AttribIf(ence, "type", link.get("type")) return rss
def __init__(self, lstData, GeoType, strPath, strFilename, strLayername): dctWriteKML = {'Point': self.writePoint, 'Polyline': self.writeLine, 'Polygon': self.writePolygon} #Create new element tree with a root of KML... objRoot = Element("{http://earth.google.com/kml/2.1}kml") objTree = ElementTree(element=objRoot) elemDoc = SubElement(objRoot, 'Document') elemDocName = SubElement(elemDoc, 'name') #According the KML spec, default Polystyle stuff goes here... elemDocName.text = strLayername #Add a document name element here...populate from supplied parameters for objRow in lstData: elemPlace = SubElement(elemDoc, 'Placemark') elemName =SubElement(elemPlace,'name') elemName.text = objRow['Name'] #Add support for the description tag... elemDesc = SubElement(elemPlace, 'description') elemDesc.text = objRow['Description'] elemGeo = dctWriteKML.get(GeoType, self.errHandler)(objRow['Geometry'], elemPlace) elemPlace.append(elemGeo) self.Write(objTree, strPath, strFilename)
def ToElement(self): """ Gets an ElementTree.Element representation. """ peer = self.peer elt = Element("entity", id=peer.id_) SubElement(elt, "address").text = peer.address.ToString() SubElement(elt, "version").text = str(peer.protocol_version) hist = SubElement(elt, "history") keys = self.intervals.keys() keys.sort() for k in keys: c = SubElement(hist, "connected") i = self.intervals[k] c.text = "%s-%s" % (i.start, i.end) return elt
def add_work_unit_to_task(tree_root, task_name_or_id): """Adds a work unit to the specified task. If the task is not active, the operation throws Active_error.""" # Obtain the task id. node = find_task(tree_root, task_name_or_id) task_id = node.find("id").text # If the task is killed, report it. if node.get("killed") == "yes": raise Active_error("Task %s is dead, aborting " "operation." % task_name_or_id) # Create a work-unit for the found task. work_units = tree_root.find("work-unit-list") work_unit = SubElement(work_units, "work-unit") work_unit.set("id", task_id) work_unit.text = get_today()
def recurse_for_children(current_node, parent_node, active_cat, show_empty=True): child_count = current_node.child.count() if show_empty or child_count > 0 or current_node.product_set.count() > 0: temp_parent = SubElement(parent_node, 'li') attrs = {'href': current_node.get_absolute_url()} if current_node == active_cat: attrs["class"] = "current" if current_node.parent: link = SubElement(temp_parent, 'a', attrs) else: link = SubElement(temp_parent, 'span', {}) link.text = current_node.name if child_count > 0: new_parent = SubElement(temp_parent, 'ul') children = current_node.child.all() for child in children: recurse_for_children(child, new_parent, active_cat)
def add_task(tree_root, task_name): """Adds (stripped) task_name to the tree_root.""" assert task_name == task_name.strip() assert len(task_name) > 1 # Get a new task id, higher than all previous ones. id_num = highest_task_id(tree_root) + 1 assert id_num >= 0 # Create the task. tasklist = tree_root.find("task-list") task = SubElement(tasklist, "task") SubElement(task, "id").text = "%d" % id_num SubElement(task, "name").text = task_name.strip() date_today = get_today() SubElement(task, "starting-day").text = date_today SubElement(task, "note").text = "" last_unit = SubElement(task, "last-unit", attrib = {"amount": "0"}) last_unit.text = date_today
def create_empty_configuration_file(file_name): """Creates a default empty file with today's date as starting day.""" root = Element("frequent-task-reminder") # Create the configuration element. config = SubElement(root, "configuration") # Set the first day to track as today. start = SubElement(config, "starting-day") start.text = time.asctime() # Create a default empty task. tasklist = SubElement(root, "tasklist") task = SubElement(tasklist, "task") SubElement(task, "id").text = 0 SubElement(task, "name").text = "Default name" SubElement(task, "notes").text = "Some random notes you can modify." # Finally write the xml file. ElementTree(root).write(file_name, encoding="latin1") print "Created empty configuration file '%s'." % file_name
import sys import re from elementtree.ElementTree import ElementTree, Element, SubElement, dump, parse if len(sys.argv) < 3: print sys.argv[0] + " inputfile outputfile" sys.exit(1) data = open(sys.argv[1],'r') kml_root = Element("kml") kml_root.set("xmlns","http://earth.google.com/kml/2.0") kml_doc = SubElement(kml_root,"Document") kml_docname = SubElement(kml_doc,"name") kml_docname.text = raw_input("Inserire il nome da dare al documento KML: ") kml_folder = SubElement(kml_doc,"Folder") kml_foldername = SubElement(kml_folder,"name") kml_foldername.text = raw_input("Inserire il nome dell'insieme di punti rilevati: ") coordinates = str() for txtline in data.readlines(): trackopen = re.search('type="track" name="(?P<name>[^"]+)"', txtline) trackpoint = re.search('type="trackpoint"\s+altitude="(?P<alt>[^"]+)"\s+latitude="(?P<lat>[^"]+)"\s+longitude="(?P<lon>[^"]+)"', txtline) trackend = re.search('type="trackend"', txtline) if trackopen: kml_placemark = SubElement(kml_folder,"Placemark") kml_placemark_desc = SubElement(kml_placemark, "description") kml_placemark_desc.text = raw_input("Inserire descrizione per il percorso di nome '"+trackopen.group('name')+"': ") kml_placemark_name = SubElement(kml_placemark,"name")
print "Transforming Components..." for comp_fname in os.listdir(comp_path): fpath = os.path.join(comp_path, comp_fname) et.parse(fpath) version = et.getroot().get("version") if not version: print "\tTransforming %s..." % comp_fname category = "" if et.find("category"): category = et.find("category").text.strip() root = Element("component", {"version": "1.0", "name": et.find("name").text.strip(), "description": et.find("description").text.strip(), "category": category}) tpcl_req = SubElement(root, "tpcl_requirements") tpcl_req.text = et.find("tpcl_requirements").text.strip() root.append(Comment("propertylist")) for prop in et.findall("property"): propelem = SubElement(root, "property", {"name": prop.find("name").text.strip()}) tpcl_cost = SubElement(propelem, "tpcl_cost") tpcl_cost.text = prop.find("tpcl_cost").text.strip() et = ElementTree(root) et.write(fpath, indent=True) elif version == "1.0": print "\tTransforming %s..." % comp_fname old_root = et.getroot() category = old_root.get("category") root = Element("component", {"version": "1.1", "name": old_root.get("name"),
BASE = "http://localhost:3000/" client = httplib2.Http(".cache") def showNotes(): headers, xml = client.request(BASE + "notes.xml") doc = ElementTree.fromstring(xml) for note in doc.findall('note'): print "%s: %s" % (note.find('date').text, note.find('body').text) newNote = Element("note") date = SubElement(newNote, "date") date.attrib['type'] = "date" date.text = time.strftime("%Y-%m-%d", time.localtime()) body = SubElement(newNote, "body") body.text = "A test note" headers, ignore = client.request(BASE + "notes.xml", "POST", body=tostring(newNote), headers={'content-type': 'application/xml'}) newURI = headers['location'] modifiedBody = Element("note") body = SubElement(modifiedBody, "body") body.text = "This note has been modified" client.request(newURI, "PUT",
def createXML(self, order, payment): """Create the xml to be sent to Virtual Merchant""" merchantid = IVirtualMerchantOptions(self.context).merchant_id if merchantid == '': log.error('No Merchant ID has been set in GetPaid, please set one.') merchantpin = IVirtualMerchantOptions(self.context).merchant_pin if merchantpin == '': log.error('No Merchant PIN has been set in GetPaid, please set one.') userid = IVirtualMerchantOptions(self.context).merchant_user_id if userid == '': userid = merchantid billing = order.billing_address amount = order.getTotalPrice() contact = order.contact_information order_id = order.getOrderId() names = payment.name_on_card.split() firstname = names[0] if len(names) > 1: lastname = names[-1] else: lastname = '' expiration_date = '' if hasattr(payment.cc_expiration, 'strftime'): expiration_date = payment.cc_expiration.strftime('%m%y') else: # If cc_expiration is not of type date, then it should be # a string like this: '2011-08-03 00:00' # This is a bug in getpaid.formgen's single page checkout # and the correct fix is to swap out it's expiration date # widget with one that returns a date. yearMonthDay = payment.cc_expiration.split(' ')[0].split('-') _date = date(int(yearMonthDay[0]), int(yearMonthDay[1]), int(yearMonthDay[2])) expiration_date = _date.strftime('%m%y') getpaidoptions = IGetPaidManagementPaymentOptions(self.context) if getpaidoptions.store_name: storename = getpaidoptions.store_name else: storename = '' options = dict( ssl_merchant_id = merchantid, ssl_user_id = userid, ssl_pin = merchantpin, ssl_transaction_type = 'ccsale', ssl_card_number = payment.credit_card, ssl_exp_date = expiration_date, ssl_amount = str(amount), ssl_sales_tax = '0.00', ssl_cvv2cvc2_indicator = '1', ssl_cvv2cvc2 = payment.cc_cvc, ssl_invoice_number = order_id, credit = 'Credit to '+storename, ssl_credit_card_type = payment.credit_card_type, ssl_first_name = firstname, ssl_last_name = lastname, ssl_avs_address = billing.bill_first_line, ssl_city = billing.bill_city, ssl_state = billing.bill_state, ssl_avs_zip = billing.bill_postal_code, ssl_phone = payment.bill_phone_number, ssl_email = contact.email ) if billing.bill_second_line: options['ssl_address2'] = billing.bill_second_line # This ensures test credit card numbers return APPROVED if config.TESTING: options['ssl_test_mode'] = 'TRUE' xml = Element('txn') for key, value in options.items(): subelement = SubElement(xml, key) subelement.text = value return xml
pl = app["afpy"] catalog = getToolByName(pl, "portal_catalog") jobs = catalog.searchResults( portal_type='AFPYJob', sort_on='creation_date', sort_order='reverse', ) afpyjobs = Element("jobs") for j in jobs: jobobj = j.getObject() job = SubElement(afpyjobs, 'job') id = SubElement(job, 'id') id.text = j.id creator = SubElement(job, 'creator') creator.text = jobobj.listCreators()[0] creation_date = SubElement(job, 'creation_date') creation_date.text = str(j.created) review_state = SubElement(job, 'review_state') review_state.text = j.review_state url = SubElement(job, 'url') url.text = j.getPath() textdetails = SubElement(job, 'text') textdetails.text = jobobj.getText().decode("utf-8") title = SubElement(job, 'title') title.text = j.Title.decode("utf-8") company = SubElement(job, 'company') company.text = jobobj.company.encode("utf-8").decode("utf-8") desc = SubElement(job, 'description')
def writeLine(self, objGeo, elemPlace): elemGeo = Element('LineString') elemCoords = SubElement(elemGeo, "coordinates") elemCoords.text = self.addCoordinates(objGeo) return elemGeo
def main(argv): scale = 1.0 pathToCSV = "" forceHRM = False removePauses = False sport = "Running" lat = 0.0 longt = 0.0 ylat = 37.337766 ylong = -121.920347 try: opts, args = getopt.getopt(argv, "hbpYs:i:t:l:",["scale=", "ifile=", "sport=", "location="]) except getopt.GetoptError: usage() sys.exit(1) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-s", "--scale"): scale = float(arg) elif opt in ("-i", "--ifile"): pathToCSV = arg elif opt in ("-t", "--sport"): sport = arg elif opt in ("-l", "--location"): lat, longt = arg.split(",") lat = float(lat) longt = float(longt) elif opt == '-Y': lat = ylat longt = ylong elif opt == '-b': forceHRM = True elif opt == '-p': removePauses = True if pathToCSV == "": usage() sys.exit(1) f = open(pathToCSV) dataDict = csv.DictReader(f) intensity = "Resting" triggerMethod = "Distance" tcxTrackpoints = {} earliestEpochMS = earliestTimeInDict(dataDict) earliestEpoch = math.floor(int(earliestEpochMS) / 1000) root = Element("TrainingCenterDatabase") root.set("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd") root.set("xmlns:ns2", "http://www.garmin.com/xmlschemas/UserProfile/v2") root.set("xmlns:ns3", "http://www.garmin.com/xmlschemas/ActivityExtension/v2") root.set("xmlns:ns4", "http://www.garmin.com/xmlschemas/ProfileExtension/v1") root.set("xmlns:ns5", "http://www.garmin.com/xmlschemas/ActivityGoals/v1") root.set("xmlns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2") root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") actsElement = SubElement(root, "Activities") actElement = SubElement(actsElement, "Activity", Sport=sport) idElement = SubElement(actElement, "Id") idElement.text = stringGMTimeFromEpoch(earliestEpoch) lastTimeEpoch = 0 lapElement = SubElement(actElement, "Lap", StartTime=stringGMTimeFromEpoch(earliestEpoch)) totalDistanceMeters = 0 maxSpeed = 0 calories = 0.0 maxBPM = 0 maxSpeed = 0.0 numRows = 0 totalBPM = 0 epochStart = 0 diff = 0 trackpoints = list() for row in dataDict: speed = scale * float(row['SPEED']) stepRate = int(row['STEP_RATE']) mCadence = int(row['CADENCE']) if speed > maxSpeed: maxSpeed = speed if not removePauses or (speed > 0 and stepRate > 0): if epochStart != 0: diff += int(row['timestamp_epoch']) - epochStart epochStart = 0 trackpointElement = Element("Trackpoint") trackpoints.append(trackpointElement) # TIME epochMS = row['timestamp_epoch'] epoch = math.floor((int(epochMS) - diff) / 1000) timeElement = SubElement(trackpointElement, "Time") timeElement.text = stringGMTimeFromEpoch(epoch) # POSITION if (lat == 0.0 and longt == 0.0): latValue = row['LATITUDE'] longValue = row['LONGITUDE'] else: latValue = str(lat) longValue = str(longt) if (abs(float(latValue)) <= 180 and abs(float(longValue)) <= 180 and abs(float(latValue)) > 0.1 and abs(float(longValue)) > 0.1): posElement = SubElement(trackpointElement, "Position") latElement = SubElement(posElement, "LatitudeDegrees") latElement.text = latValue longElement = SubElement(posElement, "LongitudeDegrees") longElement.text = longValue # Altitude alt = row['ELEVATION'] altElement = SubElement(trackpointElement, "AltitudeMeters") altElement.text = alt # DISTANCE distanceMeters = str(scale * float(row['DISTANCE'])) distElement = SubElement(trackpointElement, "DistanceMeters") distElement.text = distanceMeters # BPM heartRate = math.trunc(float(row['HEARTRATE'])) if forceHRM or heartRate > 0: bpmElement = SubElement(trackpointElement, 'HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\"') bpmValElement = SubElement(bpmElement, "Value") bpmValElement.text = str(heartRate) extElement = SubElement(trackpointElement, 'Extensions') # SPEED speed *= MPS_TO_MPH ns3Element = SubElement(extElement, 'ns3:TPX') speedElement = SubElement(ns3Element, 'ns3:Speed') speedElement.text = str(speed) if lastTimeEpoch == 0 or epoch > lastTimeEpoch: lastTimeEpoch = epoch if totalDistanceMeters == 0 or float(distanceMeters) > float(totalDistanceMeters): totalDistanceMeters = distanceMeters rowCalories = row['CALORIEBURN'] calories = rowCalories if maxBPM == 0 or heartRate > maxBPM: maxBPM = heartRate numRows += 1 totalBPM += heartRate # CADENCE cadenceElement = SubElement(trackpointElement, "Cadence") if mCadence == 0: cadenceElement.text = str(stepRate / 2) else: cadenceElement.text = str(mCadence) elif epochStart == 0: epochStart = int(row['timestamp_epoch']) # TIME totalTimeSeconds = lastTimeEpoch - earliestEpoch avgBPM = totalBPM / numRows totalTimeElement = SubElement(lapElement, "TotalTimeSeconds") totalTimeElement.text = str(int(totalTimeSeconds)) # DISTANCE totalDistanceElement = SubElement(lapElement, "DistanceMeters") totalDistanceElement.text = totalDistanceMeters # MAX SPEED if maxSpeed > 0.0: maxSpeedElement = SubElement(lapElement, "MaximumSpeed") maxSpeedElement.text = str(maxSpeed) # CALORIES totalCalsElement = SubElement(lapElement, "Calories") totalCalsElement.text = str(int(float(calories))) # BPM if forceHRM or avgBPM > 0: avgBPMElement = SubElement(lapElement, 'AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') avgBPMValElement = SubElement(avgBPMElement, "Value") avgBPMValElement.text = str(int(avgBPM)) if forceHRM or maxBPM > 0: maxBPMElement = SubElement(lapElement, 'MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') maxBPMValElement = SubElement(maxBPMElement, "Value") maxBPMValElement.text = str(int(maxBPM)) # INTENSITY intensityElement = SubElement(lapElement, "Intensity") intensityElement.text = "Active" #TRIGGER triggerElement = SubElement(lapElement, "TriggerMethod") triggerElement.text = "Distance" # Append trackpoints trackElement = SubElement(lapElement, "Track") for trackpoint in trackpoints: trackElement.append(trackpoint) print XMLHeader() + tostring(Comment("Scale: "+str(scale))) + tostring(root)
def textChild(parent, name, text): n = SubElement(parent, name) n.text = text return n
import sys import re from elementtree.ElementTree import ElementTree, Element, SubElement, dump, parse if len(sys.argv) < 3: print sys.argv[0] + " inputfile outputfile" sys.exit(1) data = open(sys.argv[1],'r') kml_root = Element("kml") kml_root.set("xmlns","http://earth.google.com/kml/2.0") kml_doc = SubElement(kml_root,"Document") kml_docname = SubElement(kml_doc,"name") kml_docname.text = raw_input("Inserire il nome da dare al documento KML: ") for txtline in data.readlines(): openlist = re.search('type="waypointlist"', txtline) waypoint = re.search('.*name="(?P<name>[^"]+)"\s+altitude="(?P<alt>[^"]+)"\s+latitude="(?P<lat>[^"]+)"\s+longitude="(?P<lon>[^"]+)"', txtline) if openlist: kml_folder = SubElement(kml_doc,"Folder") kml_foldername = SubElement(kml_folder,"name") kml_foldername.text = raw_input("Inserire il nome dell'insieme di punti rilevati: ") if waypoint: kml_placemark = SubElement(kml_folder,"Placemark") kml_placemark_desc = SubElement(kml_placemark, "description") kml_placemark_desc.text = raw_input("Inserire descrizione per il punto di nome '"+waypoint.group('name')+"': ") kml_placemark_name = SubElement(kml_placemark,"name")
def rec2format (context, recs, output_format='mods'): try: config = context.config source_catalog = context.get_source_catalog() ctm = source_catalog.get_complete_mapping() root = Element('modsCollection') root.set('xmlns', 'http://www.loc.gov/mods/v3') root.set('xmlns:xlink', 'http://www.w3.org/1999/xlink') root.set('version', '3.0') root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') root.set('xsi:schemaLocation', 'http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd') for rec in recs: try: mods = SubElement(root, 'mods') mm = rec.get_mapped_metadata(ctm) if mm.get('title', ''): titleInfo = SubElement(mods, 'titleInfo') title = SubElement(titleInfo, 'title') title.text = mm['title'] if mm.get('author', []): for au in mm['author']: name = SubElement(mods, 'name') name.set('type', 'personal') # Note: bibutils looks for family/given split if ' ' in au: family, given = au.split(' ') namePart = SubElement(name, 'namePart') namePart.set('type', 'given') namePart.text = given namePart = SubElement(name, 'namePart') namePart.set('type', 'family') namePart.text = family else: namePart = SubElement(name, 'namePart') namePart.set('type', 'family') namePart.text = au role = SubElement(name, 'role') roleTerm = SubElement(role, 'roleTerm') roleTerm.set('type', 'text') roleTerm.text = 'author' typeOfResource = SubElement(mods, 'typeOfResource') typeOfResource.text = 'text' # The following block is about the "host" journal in which this # article appeared relatedItem = SubElement(mods, 'relatedItem') relatedItem.set('type', 'host') titleInfo = SubElement(relatedItem, 'titleInfo') title = SubElement(titleInfo, 'title') title.text = mm['journal'] if mm.get('issn', ''): identifier = SubElement(relatedItem, 'identifier') identifier.set('type', 'issn') identifier.text = mm['issn'] originInfo = SubElement(relatedItem, 'originInfo') issuance = SubElement(originInfo, 'issuance') issuance.text = 'continuing' part = SubElement(relatedItem, 'part') if mm.get('volume', ''): detail = SubElement(part, 'detail') detail.set('type', 'volume') number = SubElement(detail, 'number') number.text = mm['volume'] if mm.get('issue', ''): detail = SubElement(part, 'detail') detail.set('type', 'issue') number = SubElement(detail, 'number') number.text = mm['issue'] if mm.get('pages', ''): extent = SubElement(part, 'extent') extent.set('unit', 'page') if '-' in mm['pages']: start, end = mm['pages'].split('-') st = SubElement(extent, 'start') st.text = start en = SubElement(extent, 'end') en.text = end else: st = SubElement(extent, 'start') st.text = mm['pages'] if mm.get('pubdate', ''): date = SubElement(part, 'date') date.text = mm['pubdate'][:4] for subtype in ['subject', 'keyword']: for sub in mm.get(subtype, []): subject = SubElement(mods, 'subject') if subtype == 'subject': subject.set('authority', 'mesh') topic = SubElement(subject, 'topic') topic.text = sub except: print traceback.print_exc() mods_out = etree.tostring(root) if output_format == 'mods': return mods_out elif output_format in FORMATS.keys(): bibutils_format_name = FORMATS[output_format] filename = '%s/records-%s.mods' % (config.temp_image_dir, time.time()) fp = open(filename, 'w') fp.write(mods_out) fp.close() bibutils_call = '/usr/local/bin/xml2%s %s > %s.%s' % (bibutils_format_name, filename, filename, output_format) os.system(bibutils_call) time.sleep(3) return open('%s.%s' % (filename, output_format)).read() except: print traceback.print_exc()
import httplib2 import time BASE = "http:??localhost:3000/" client = httplib2.Http(".cache") def showNotes(): headers, xml = client.request(BASE + "notes.xml") doc = ElementTree.fromstring(xml) for note in doc.findall('note'): print "%s: %s" % (note.find('date').text, note.find('body').text) newNote = Element("note") date = SubElement(newNote, "date") date.attrib['type'] = "date" date.text = time.strftime("%Y-%m-%d", time.localtime()) body = SubElement(newNote, "body") body.text = "A test note" headers, ignore = client.request(BASE + "notes.xml", "POST", body = tostring(newNote), headers={'content-type': 'application/xml'}) newURI = headers['location'] modifiedBody = Element("note") body = SubElement(modifiedBody, "body") body.text = "This note has been modified" client.request(newURI, "PUT", body=tostring(modifiedBody), headers={'content-type': 'application/xml'})
def main(): if len(sys.argv) != 2: print 'Usage: ' + sys.argv[0] + ' <CSV file>' sys.exit(1) pathToCSV = sys.argv[1] f = open(pathToCSV) dataDict = csv.DictReader(f) intensity = "Resting" triggerMethod = "Distance" tcxTrackpoints = {} earliestEpochMS = earliestTimeInDict(dataDict) earliestEpoch = math.floor(int(earliestEpochMS) / 1000) root = Element("TrainingCenterDatabase") root.set("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd") root.set("xmlns:ns2", "http://www.garmin.com/xmlschemas/UserProfile/v2") root.set("xmlns:ns3", "http://www.garmin.com/xmlschemas/ActivityExtension/v2") root.set("xmlns:ns4", "http://www.garmin.com/xmlschemas/ProfileExtension/v1") root.set("xmlns:ns5", "http://www.garmin.com/xmlschemas/ActivityGoals/v1") root.set("xmlns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2") root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") actsElement = SubElement(root, "Activities") actElement = SubElement(actsElement, "Activity", Sport="Running") idElement = SubElement(actElement, "Id") idElement.text = stringGMTimeFromEpoch(earliestEpoch) lastTimeEpoch = 0 lapElement = SubElement(actElement, "Lap", StartTime=stringGMTimeFromEpoch(earliestEpoch)) totalDistanceMeters = 0 maxSpeed = 0 calories = 0.0 maxBPM = 0 numRows = 0 totalBPM = 0 trackpoints = list() for row in dataDict: trackpointElement = Element("Trackpoint") trackpoints.append(trackpointElement) # TIME epochMS = row['timestamp_epoch'] epoch = math.floor(int(epochMS) / 1000) timeElement = SubElement(trackpointElement, "Time") timeElement.text = stringGMTimeFromEpoch(epoch) # POSITION latValue = row['LATITUDE'] longValue = row['LONGITUDE'] if (abs(float(latValue)) <= 180 and abs(float(longValue)) <= 180 and abs(float(latValue)) > 0.1 and abs(float(longValue)) > 0.1): posElement = SubElement(trackpointElement, "Position") latElement = SubElement(posElement, "LatitudeDegrees") latElement.text = latValue longElement = SubElement(posElement, "LongitudeDegrees") longElement.text = longValue # Altitude alt = row['ELEVATION'] altElement = SubElement(trackpointElement, "AltitudeMeters") altElement.text = alt # DISTANCE distanceMeters = row['DISTANCE'] distElement = SubElement(trackpointElement, "DistanceMeters") distElement.text = distanceMeters # BPM heartRate = math.trunc(float(row['HEARTRATE'])) # if heartRate > 0: bpmElement = SubElement(trackpointElement, 'HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\"') bpmValElement = SubElement(bpmElement, "Value") bpmValElement.text = str(heartRate) extElement = SubElement(trackpointElement, 'Extensions') # SPEED speed = float(row['SPEED']) speed *= MPS_TO_MPH ns3Element = SubElement(extElement, 'ns3:TPX') speedElement = SubElement(ns3Element, 'ns3:Speed') speedElement.text = str(speed) if lastTimeEpoch == 0 or epoch > lastTimeEpoch: lastTimeEpoch = epoch if totalDistanceMeters == 0 or float(distanceMeters) > float(totalDistanceMeters): totalDistanceMeters = distanceMeters rowCalories = row['CALORIEBURN'] calories = rowCalories if maxBPM == 0 or heartRate > maxBPM: maxBPM = heartRate numRows += 1 totalBPM += heartRate # TIME totalTimeSeconds = lastTimeEpoch - earliestEpoch avgBPM = totalBPM / numRows totalTimeElement = SubElement(lapElement, "TotalTimeSeconds") totalTimeElement.text = str(int(totalTimeSeconds)) # DISTANCE totalDistanceElement = SubElement(lapElement, "DistanceMeters") totalDistanceElement.text = totalDistanceMeters # CALORIES totalCalsElement = SubElement(lapElement, "Calories") totalCalsElement.text = str(int(float(calories))) # BPM # if avgBPM > 0: avgBPMElement = SubElement(lapElement, 'AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') avgBPMValElement = SubElement(avgBPMElement, "Value") avgBPMValElement.text = str(int(avgBPM)) # if maxBPM > 0: maxBPMElement = SubElement(lapElement, 'MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') maxBPMValElement = SubElement(maxBPMElement, "Value") maxBPMValElement.text = str(int(maxBPM)) # INTENSITY intensityElement = SubElement(lapElement, "Intensity") intensityElement.text = "Active" #TRIGGER triggerElement = SubElement(lapElement, "TriggerMethod") triggerElement.text = "Distance" # Append trackpoints trackElement = SubElement(lapElement, "Track") for trackpoint in trackpoints: trackElement.append(trackpoint) print XMLHeader() + tostring(root)
def _make_mods(self, qdc, PID): """Create a mods xml string for use with bibutils.""" mods = Element("mods") # Metadata from the Journal try: ISSN = getattr(self, 'ISSN') except: ISSN = self.portal_properties.dipp_properties.ISSN.strip() if ISSN == "": fedora = getToolByName(self, "fedora") jqdc = fedora.getQualifiedDCMetadata(fedora.PID) ISSN = jqdc['identifierISSN'] # Metadata stored only in Plone try: startpage = self.startpage except: startpage = None try: endpage = self.endpage except: endpage = None # Qualified Dublin Core Metadata (qdc) stored in Fedora # title qTitles = qdc['title'] titleInfo = SubElement(mods, "titleInfo") title = SubElement(titleInfo, "title") title.text = qTitles[0]['value'] # authors for author in qdc['creatorPerson']: name = SubElement(mods, "name", type="personal") namePart = SubElement(name, "namePart", type="family") namePart.text = author['lastName'] namePart = SubElement(name, "namePart", type="given") namePart.text = author['firstName'] # abstract qAbstracts = qdc['DCTermsAbstract'] abstract = SubElement(mods, "abstract") abstract.text = qAbstracts[0]['value'] # subjects subject = SubElement(mods, "subject") for qSubject in qdc['subject']: topic = SubElement(subject, "topic") topic.text = qSubject # ddc for qDDC in qdc['DDC']: ddc = SubElement(mods, "classification", authority="ddc") ddc.text = qDDC # genre relatedItem = SubElement(mods, "relatedItem", type="host") genre = SubElement(relatedItem, "genre", authority="marcgt") genre.text = "periodical" genre = SubElement(relatedItem, "genre") genre.text = "academic journal" # Bibliographic Data bc = qdc['bibliographicCitation'][0] # Journaltitle titleInfo = SubElement(relatedItem, "titleInfo") title = SubElement(titleInfo, "title") title.text = bc['journalTitle'] # Volume/Issue/Pagenumbers part = SubElement(relatedItem, "part") volume = SubElement(part, "detail", type="volume") number = SubElement(volume, "number") number.text = bc["journalVolume"] issue = SubElement(part, "detail", type="issue") number = SubElement(issue, "number") number.text = bc["journalIssueNumber"] date = SubElement(part, "date") try: year = DateTime(bc["journalIssueDate"]).strftime('%Y') except: year = "????" date.text = year if startpage: extent = SubElement(part, "extent", unit="page") start = SubElement(extent, "start") start.text = str(startpage) end = SubElement(extent, "end") end.text = str(endpage) # identifier id = qdc['creatorPerson'][0]["lastName"].lower() + str(year) if ISSN: issn = SubElement(mods, "identifier", type="issn") issn.text = ISSN urn = SubElement(mods, "identifier", type="urn") urn.text = qdc['identifierURN'] if qdc['identifierDOI']: doi = SubElement(mods, "identifier", type="doi") doi.text = qdc['identifierDOI'] uri = SubElement(mods, "identifier", type="uri") uri.text = "http://nbn-resolving.de/" + qdc['identifierURN'] citekey = SubElement(mods, "identifier", type="citekey") citekey.text = id return mods
def PackageToXml(pkg,summary="N/A",trainingDataId='N/A', dataPerformance=[], recommendedThreshold=None, classDescriptions=[], modelType=None, modelOrganism=None): """ generates XML for a package that follows the RD_Model.dtd If provided, dataPerformance should be a sequence of 2-tuples: ( note, performance ) where performance is of the form: ( accuracy, avgCorrectConf, avgIncorrectConf, confusionMatrix, thresh, avgSkipConf, nSkipped ) the last four elements are optional """ head = Element("RDModelInfo") name = SubElement(head,"ModelName") notes = pkg.GetNotes() if not notes: notes = "Unnamed model" name.text = notes summ = SubElement(head,"ModelSummary") summ.text = summary calc = pkg.GetCalculator() descrs = SubElement(head,"ModelDescriptors") for name,summary,func in zip(calc.GetDescriptorNames(),calc.GetDescriptorSummaries(),calc.GetDescriptorFuncs()): descr = SubElement(descrs,"Descriptor") elem = SubElement(descr,"DescriptorName") elem.text = name elem = SubElement(descr,"DescriptorDetail") elem.text = summary if hasattr(func,'version'): vers = SubElement(descr,"DescriptorVersion") major,minor,patch = func.version.split('.') elem = SubElement(vers,"VersionMajor") elem.text = major elem = SubElement(vers,"VersionMinor") elem.text = minor elem = SubElement(vers,"VersionPatch") elem.text = patch elem = SubElement(head,"TrainingDataId") elem.text = trainingDataId for description,perfData in dataPerformance: dataNode = SubElement(head,"ValidationData") note = SubElement(dataNode,'ScreenNote') note.text = description perf = SubElement(dataNode,"PerformanceData") _ConvertModelPerformance(perf,perfData) if recommendedThreshold: elem = SubElement(head,"RecommendedThreshold") elem.text=str(recommendedThreshold) if classDescriptions: elem = SubElement(head,"ClassDescriptions") for val,text in classDescriptions: descr = SubElement(elem,'ClassDescription') valElem = SubElement(descr,'ClassVal') valElem.text = str(val) valText = SubElement(descr,'ClassText') valText.text = str(text) if modelType: elem = SubElement(head,"ModelType") elem.text=modelType if modelOrganism: elem = SubElement(head,"ModelOrganism") elem.text=modelOrganism hist = SubElement(head,"ModelHistory") revision = SubElement(hist,"Revision") tm = time.localtime() date = SubElement(revision,"RevisionDate") elem = SubElement(date,"Year") elem.text=str(tm[0]) elem = SubElement(date,"Month") elem.text=str(tm[1]) elem = SubElement(date,"Day") elem.text=str(tm[2]) note = SubElement(revision,"RevisionNote") note.text = "Created" return ElementTree(head)
def TextElement(root, name, detail_value): if detail_value: te = SubElement(root, name) te.text = detail_value.value
fpath = os.path.join(comp_path, comp_fname) et.parse(fpath) version = et.getroot().get("version") if not version: print "\tTransforming %s..." % comp_fname category = "" if et.find("category"): category = et.find("category").text.strip() root = Element( "component", { "version": "1.0", "name": et.find("name").text.strip(), "description": et.find("description").text.strip(), "category": category }) tpcl_req = SubElement(root, "tpcl_requirements") tpcl_req.text = et.find("tpcl_requirements").text.strip() root.append(Comment("propertylist")) for prop in et.findall("property"): propelem = SubElement(root, "property", {"name": prop.find("name").text.strip()}) tpcl_cost = SubElement(propelem, "tpcl_cost") tpcl_cost.text = prop.find("tpcl_cost").text.strip() et = ElementTree(root) et.write(fpath, indent=True) elif version == "1.0": print "\tTransforming %s..." % comp_fname old_root = et.getroot() category = old_root.get("category") root = Element( "component", { "version": "1.1",
def writePoint(self, objGeo, elemPlace): elemGeo = Element('Point') elemCoords = SubElement(elemGeo, "coordinates") strCoord = self.addCoordinates(objGeo) elemCoords.text = self.addCoordinates(objGeo) return elemGeo
def PackageToXml(pkg, summary="N/A", trainingDataId='N/A', dataPerformance=[], recommendedThreshold=None, classDescriptions=[], modelType=None, modelOrganism=None): """ generates XML for a package that follows the RD_Model.dtd If provided, dataPerformance should be a sequence of 2-tuples: ( note, performance ) where performance is of the form: ( accuracy, avgCorrectConf, avgIncorrectConf, confusionMatrix, thresh, avgSkipConf, nSkipped ) the last four elements are optional """ head = Element("RDModelInfo") name = SubElement(head, "ModelName") notes = pkg.GetNotes() if not notes: notes = "Unnamed model" name.text = notes summ = SubElement(head, "ModelSummary") summ.text = summary calc = pkg.GetCalculator() descrs = SubElement(head, "ModelDescriptors") for name, summary, func in zip(calc.GetDescriptorNames(), calc.GetDescriptorSummaries(), calc.GetDescriptorFuncs()): descr = SubElement(descrs, "Descriptor") elem = SubElement(descr, "DescriptorName") elem.text = name elem = SubElement(descr, "DescriptorDetail") elem.text = summary if hasattr(func, 'version'): vers = SubElement(descr, "DescriptorVersion") major, minor, patch = func.version.split('.') elem = SubElement(vers, "VersionMajor") elem.text = major elem = SubElement(vers, "VersionMinor") elem.text = minor elem = SubElement(vers, "VersionPatch") elem.text = patch elem = SubElement(head, "TrainingDataId") elem.text = trainingDataId for description, perfData in dataPerformance: dataNode = SubElement(head, "ValidationData") note = SubElement(dataNode, 'ScreenNote') note.text = description perf = SubElement(dataNode, "PerformanceData") _ConvertModelPerformance(perf, perfData) if recommendedThreshold: elem = SubElement(head, "RecommendedThreshold") elem.text = str(recommendedThreshold) if classDescriptions: elem = SubElement(head, "ClassDescriptions") for val, text in classDescriptions: descr = SubElement(elem, 'ClassDescription') valElem = SubElement(descr, 'ClassVal') valElem.text = str(val) valText = SubElement(descr, 'ClassText') valText.text = str(text) if modelType: elem = SubElement(head, "ModelType") elem.text = modelType if modelOrganism: elem = SubElement(head, "ModelOrganism") elem.text = modelOrganism hist = SubElement(head, "ModelHistory") revision = SubElement(hist, "Revision") tm = time.localtime() date = SubElement(revision, "RevisionDate") elem = SubElement(date, "Year") elem.text = str(tm[0]) elem = SubElement(date, "Month") elem.text = str(tm[1]) elem = SubElement(date, "Day") elem.text = str(tm[2]) note = SubElement(revision, "RevisionNote") note.text = "Created" return ElementTree(head)
_end_time = None if _t.find("end_time") is None \ else datetime.strptime( _t.findtext("end_time"), "%Y-%m-%d %H:%M:%S") # compute duration time _dur = None if _start_time is None or _end_time is None \ else str(_end_time - _start_time) # insert start time _start = SubElement(_talk, "start") if _start_time is None: pass else: # ensure valid time format 09:15 _start_time = ":".join( map(lambda _t: "%02d" % int(_t), _start_time.strftime("%H:%M").split(":"))) _start.text = str(_start_time) # insert duration _duration = SubElement(_talk, "duration") if _dur is None: pass else: # ensure valid duration format 00:15 _dur = ":".join( map(lambda _d: "%02d" % int(_d), _dur.split(":")[:-1])) _duration.text = str(_dur) # set room name SubElement(_talk, "room_name").text = _r # empty tag _tag = SubElement(_talk, "tag") # set title SubElement(_talk, "title").text = None \