Parse a Cobertura xml report and create measures accordingly
548774
public void parseReport(File xmlFile) {
    try {
      parseSources(xmlFile);
      parsePackages(xmlFile);
    } catch (XMLStreamException e) {
      throw MessageException.of("Unable to parse Cobertura report.", e);
    }
  }
358194
def _parse_report_item(self, prop):
        

        item_type = None

        if prop == 'attribute_accuracy':
            item_type = 'DQQuanAttAcc'
        elif prop == 'dataset_completeness':
            item_type = 'DQCompOm'

        xroot = self._get_xroot_for(prop)

        parsed = (element_to_dict(e) for e in get_elements(self._xml_tree, xroot))
        parsed = flatten_items(e['children'] for e in parsed if e['attributes'].get('type') == item_type)

        return reduce_value([p['text'] for p in parsed if p['name'] == 'measDesc'])
209788
function buildXml()
    {
        $this->checkConnector();
        $this->checkRequest();

        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

        if (!isset($_GET["fileName"])) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
        }

        $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_GET["fileName"]);

        if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName) || $resourceTypeInfo->checkIsHiddenFile($fileName)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if (!$resourceTypeInfo->checkExtension($fileName, false)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $fileName);

        if (!file_exists($filePath) || !is_file($filePath)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
        }

        list($width, $height) = getimagesize($filePath);
        $oNode = new Ckfinder_Connector_Utils_XmlNode("ImageInfo");
        $oNode->addAttribute("width", $width);
        $oNode->addAttribute("height", $height);
        $this->_connectorNode->addChild($oNode);
    }
806256
public function xml()
    {
        foreach ($this->_result as $quota) {
            $quotaChild = $this->xml->addChild("Quota");
            $quotaChild->addAttribute("User", $quota['user']);
            $quotaChild->addAttribute("ByteUsed", $quota['byte_used']);
            $quotaChild->addAttribute("ByteSoft", $quota['byte_soft']);
            $quotaChild->addAttribute("ByteHard", $quota['byte_hard']);
            $quotaChild->addAttribute("BytePercentUsed", $quota['byte_percent_used']);
            $quotaChild->addAttribute("FileUsed", $quota['file_used']);
            $quotaChild->addAttribute("FileSoft", $quota['file_soft']);
            $quotaChild->addAttribute("FileHard", $quota['file_hard']);
            $quotaChild->addAttribute("FilePercentUsed", $quota['file_percent_used']);
        }

        return $this->xml->getSimpleXmlElement();
    }
1247875
def _to_DOM(self):
        
        root_node = ET.Element("station_history")
        station_id_node = ET.SubElement(root_node, "station_id")
        station_id_node.text = str(self._station_ID)
        interval_node = ET.SubElement(root_node, "interval")
        interval_node.text = self._interval
        reception_time_node = ET.SubElement(root_node, "reception_time")
        reception_time_node.text = str(self._reception_time)
        measurements_node = ET.SubElement(root_node, "measurements")
        for m in self._measurements:
            d = self._measurements[m].copy()
            d['reference_time'] = m
            xmlutils.create_DOM_node_from_dict(d, "measurement",
                                               measurements_node)
        return root_node
222189
private void  parseAttributesCore(SvgElementBase obj, Attributes attributes) throws SVGParseException
   {
      for (int i=0; i<attributes.getLength(); i++)
      {
         String  qname = attributes.getQName(i);
         if (qname.equals("id") || qname.equals("xml:id"))
         {
            obj.id = attributes.getValue(i).trim();
            break;
         }
         else if (qname.equals("xml:space")) {
            String  val = attributes.getValue(i).trim();
            if ("default".equals(val)) {
               obj.spacePreserve = Boolean.FALSE;
            } else if ("preserve".equals(val)) {
               obj.spacePreserve = Boolean.TRUE;
            } else {
               throw new SVGParseException("Invalid value for \"xml:space\" attribute: "+val);
            }
            break;
         }
      }
   }
8756
public function xml()
    {
        foreach ($this->_result as $bat_item) {
            $xmlbat = $this->xml->addChild("Bat");
            if (isset($bat_item['name'])) {
                $xmlbat->addAttribute("Name", $bat_item['name']);
            }
            if (isset($bat_item['model']) && ($bat_item['model'] !== "1")) {
                $xmlbat->addAttribute("Model", $bat_item['model']);
            }
            if (defined('PSI_PLUGIN_BAT_SHOW_SERIAL') && PSI_PLUGIN_BAT_SHOW_SERIAL
               && isset($bat_item['serialnumber'])
               && ($bat_item['serialnumber'] !== "")
               && ($bat_item['serialnumber'] !== "0")
               && ($bat_item['serialnumber'] !== "0000")) {
                $xmlbat->addAttribute("SerialNumber", $bat_item['serialnumber']);
            }
            if (isset($bat_item['manufacturer'])) {
                $xmlbat->addAttribute("Manufacturer", $bat_item['manufacturer']);
            }
            if ((!isset($bat_item['remaining_capacity']) || (isset($bat_item['full_capacity']) && ($bat_item['full_capacity'] == 0))) &&
                isset($bat_item['capacity']) && ($bat_item['capacity']>=0)) {
                if (isset($bat_item['capacity_unit']) && ($bat_item['capacity_unit'] !== "???")
                   && (isset($bat_item['full_capacity']) && ($bat_item['full_capacity'] > 0))) {
                    $xmlbat->addAttribute("CapacityUnit", $bat_item['capacity_unit']);
                    $xmlbat->addAttribute("RemainingCapacity", round($bat_item['capacity']*$bat_item['full_capacity']/100));
                    $xmlbat->addAttribute("FullCapacity", $bat_item['full_capacity']);
                    if (isset($bat_item['design_capacity'])) {
                        $xmlbat->addAttribute("DesignCapacity", $bat_item['design_capacity']);
                    }
                } else {
                    $xmlbat->addAttribute("FullCapacity", 100);
                    $xmlbat->addAttribute("RemainingCapacity", $bat_item['capacity']);
                    $xmlbat->addAttribute("CapacityUnit", "%");
                }
            } else {
                if (isset($bat_item['full_capacity'])) {
                    if (isset($bat_item['design_capacity'])) {
                        $xmlbat->addAttribute("DesignCapacity", $bat_item['design_capacity']);
                    }
                    $xmlbat->addAttribute("FullCapacity", $bat_item['full_capacity']);
                } elseif (isset($bat_item['design_capacity'])) {
                    $xmlbat->addAttribute("FullCapacity", $bat_item['design_capacity']);
                }
                if (isset($bat_item['remaining_capacity'])) {
                    $xmlbat->addAttribute("RemainingCapacity", $bat_item['remaining_capacity']);
                }
                if (isset($bat_item['capacity_unit'])) {
                    $xmlbat->addAttribute("CapacityUnit", $bat_item['capacity_unit']);
                }
            }
            if (isset($bat_item['design_voltage']) && ($bat_item['design_voltage']>0)) {
                $xmlbat->addAttribute("DesignVoltage", $bat_item['design_voltage']);
                if (isset($bat_item['design_voltage_max']) && ($bat_item['design_voltage_max']>0) && ($bat_item['design_voltage_max'] != $bat_item['design_voltage'])) {
                    $xmlbat->addAttribute("DesignVoltageMax", $bat_item['design_voltage_max']);
                }
            } elseif (isset($bat_item['design_voltage_max']) && ($bat_item['design_voltage_max']>0)) {
                $xmlbat->addAttribute("DesignVoltage", $bat_item['design_voltage_max']);
            }
            if (isset($bat_item['present_voltage'])) {
                $xmlbat->addAttribute("PresentVoltage", $bat_item['present_voltage']);
            }
            if (isset($bat_item['charging_state'])) {
                $xmlbat->addAttribute("ChargingState", $bat_item['charging_state']);
            } else {
                if (isset($bat_item['charging_state_i'])) {
                    $xmlbat->addAttribute("ChargingState", 'Charging');
                } elseif (!isset($bat_item['charging_state_e'])) {
                    $xmlbat->addAttribute("ChargingState", 'Discharging');
                } elseif (isset($bat_item['charging_state_f'])) {
                    $xmlbat->addAttribute("ChargingState", 'Fully Charged');
                } else {
                    $xmlbat->addAttribute("ChargingState", 'Unknown state');
                }
            }
            if (isset($bat_item['battery_type'])) {
                $xmlbat->addAttribute("BatteryType", $bat_item['battery_type']);
            }
            if (isset($bat_item['battery_temperature'])) {
                $xmlbat->addAttribute("BatteryTemperature", $bat_item['battery_temperature']);
            }
            if (isset($bat_item['battery_condition'])) {
                $xmlbat->addAttribute("BatteryCondition", $bat_item['battery_condition']);
            }
            if (isset($bat_item['cycle_count'])) {
                $xmlbat->addAttribute("CycleCount", $bat_item['cycle_count']);
            }
        }

        return $this->xml->getSimpleXmlElement();
    }
944027
public function xml()
    {
        foreach ($this->_result as $disk_items) {
            if (isset($disk_items['Name']) && (trim($disk_items['Name']) !== '')) {
                $xmlstablebit_disk = $this->xml->addChild("Disk");
                foreach ($this->stablebit_items as $item) {
                    if (isset($disk_items[$item]) && (($itemvalue=$disk_items[$item]) !== '') &&
                    (($item !== 'SerialNumber') || (defined('PSI_PLUGIN_STABLEBIT_SHOW_SERIAL') && (PSI_PLUGIN_STABLEBIT_SHOW_SERIAL === true)))) {
                        $xmlstablebit_disk ->addAttribute($item, $itemvalue);
                    }
                }
            }
        }

        return $this->xml->getSimpleXmlElement();
    }
20513
public function buildXml()
  {
    if (!extension_loaded('zip')) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_COMMAND);
    }

    $this->checkConnector();
    $this->checkRequest();

    if ( !$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_UPLOAD)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }

    $this->_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
    $currentResourceTypeConfig = $this->_currentFolder->getResourceTypeConfig();
    $_sServerDir = $this->_currentFolder->getServerPath();

    $files = array();

    $_zipFilesSize = 0;
    $config = $this->getConfig();
    $zipMaxSize = $config['zipMaxSize'];
    if ( !empty($zipMaxSize) && $zipMaxSize == 'default' ){
      $zipMaxSize = $currentResourceTypeConfig->getMaxSize();
    }

    $_isBasket = ( isset($_POST['basket']) && $_POST['basket'] == 'true' )? true : false;

    if ( !empty($_POST['files']))
    {

      $_aclConfig = $this->_config->getAccessControlConfig();
      $aclMasks = array();
      $_resourceTypeConfig = array();

      foreach ( $_POST['files'] as $arr ){
        if ( empty($arr['name']) || empty($arr['type']) || empty($arr['folder']) ) {
          continue;
        }
        // file name
        $name = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($arr['name']);
        // resource type
        $type = $arr['type'];
        // client path
        $path = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($arr['folder']);

        // check #1 (path)
        if (!CKFinder_Connector_Utils_FileSystem::checkFileName($name) || preg_match(CKFINDER_REGEX_INVALID_PATH, $path)) {
          continue;
        }

        // get resource type config for current file
        if (!isset($_resourceTypeConfig[$type])) {
          $_resourceTypeConfig[$type] = $this->_config->getResourceTypeConfig($type);
        }

        // check #2 (resource type)
        if (is_null($_resourceTypeConfig[$type])) {
          continue;
        }

        // check #3 (extension)
        if (!$_resourceTypeConfig[$type]->checkExtension($name, false)) {
          continue;
        }

        // check #4 (extension) - when moving to another resource type, double check extension
        if ($currentResourceTypeConfig->getName() != $type && !$currentResourceTypeConfig->checkExtension($name, false)) {
          continue;
        }

        // check #5 (hidden folders)
        // cache results
        if (empty($checkedPaths[$path])) {
          $checkedPaths[$path] = true;

          if ($_resourceTypeConfig[$type]->checkIsHiddenPath($path)) {
            continue;
          }
        }

        // check #6 (hidden file name)
        if ($currentResourceTypeConfig->checkIsHiddenFile($name)) {
          continue;
        }

        // check #7 (Access Control, need file view permission to source files)
        if (!isset($aclMasks[$type."@".$path])) {
          $aclMasks[$type."@".$path] = $_aclConfig->getComputedMask($type, $path);
        }

        $isAuthorized = (($aclMasks[$type."@".$path] & CKFINDER_CONNECTOR_ACL_FILE_VIEW) == CKFINDER_CONNECTOR_ACL_FILE_VIEW);
        if (!$isAuthorized) {
          continue;
        }

        $sourceFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($_resourceTypeConfig[$type]->getDirectory().$path,$name);
        // check #8 (invalid file name)
        if (!file_exists($sourceFilePath) || !is_file($sourceFilePath)) {
          continue;
        }

        // check #9 - max file size
        if ( !empty($zipMaxSize) ){
          clearstatcache();
          $_zipFilesSize += filesize($sourceFilePath);
          if ( $_zipFilesSize > $zipMaxSize ) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_CREATED_FILE_TOO_BIG);
          }
        }

        $zipPathPart = ( $_isBasket ) ? CKFinder_Connector_Utils_FileSystem::combinePaths($type,$path) : '';

        $files[$sourceFilePath] = $zipPathPart.pathinfo($sourceFilePath,PATHINFO_BASENAME);
      }
    }
    else
    {
      if (!is_dir($_sServerDir)) {
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND);
      }
      $files = $this->getFilesRecursively($_sServerDir,$zipMaxSize);
    }
    if ( sizeof($files)<1) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }
    // default destination dir - temp
    $dest_dir = CKFinder_Connector_Utils_FileSystem::getTmpDir();
    $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

    // default file name - hash
    $zip_filename = substr(md5(serialize($files)), 0, 16).$resourceTypeInfo->getHash().'.zip';

    // compress files - do not download them
    // change destination and name
    if ( isset($_POST['download']) && $_POST['download'] == 'false'){
      $dest_dir = $_sServerDir;
      if ( isset($_POST['zipName']) && !empty($_POST['zipName'])){
        $zip_filename = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_POST['zipName']);
        if (!$resourceTypeInfo->checkExtension($zip_filename)) {
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
        }
      }
    }
    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($zip_filename) || $resourceTypeInfo->checkIsHiddenFile($zip_filename)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
    }
    if ($this->_config->forceAscii()) {
      $zip_filename = CKFinder_Connector_Utils_FileSystem::convertToAscii($zip_filename);
    }

    $zipFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($dest_dir, $zip_filename);

    if (!is_writable(dirname($zipFilePath))) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
    }

    // usually we would need to create zip?
    $createZip = true;

    // only if file already exists and we want download it
    // do not create new one - because hash of previously created is the same - existing archive is ok
    if ( file_exists($zipFilePath) && isset($_POST['download']) && $_POST['download'] == 'true' ){
      $createZip = false;
    }
    // if we only want to create archive
    else
    {
      if ( file_exists($zipFilePath) && ( !isset($_POST['fileExistsAction']) || !in_array($_POST['fileExistsAction'], array('autorename','overwrite')) ) ){
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ALREADY_EXIST);
      }

      if ( !$this->_currentFolder->checkAcl( CKFINDER_CONNECTOR_ACL_FILE_UPLOAD )) {
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
      }
      // check how to deal with existing file
      if ( isset($_POST['fileExistsAction']) && $_POST['fileExistsAction'] == 'autorename' )
      {
        if ( !$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_RENAME )) {
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }
        $zip_filename = CKFinder_Connector_Utils_FileSystem::autoRename($dest_dir, $zip_filename);
        $zipFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($dest_dir, $zip_filename);
      }
      elseif ( isset($_POST['fileExistsAction']) && $_POST['fileExistsAction'] == 'overwrite' )
      {
        if ( !$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_RENAME | CKFINDER_CONNECTOR_ACL_FILE_DELETE)) {
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }
        if (!CKFinder_Connector_Utils_FileSystem::unlink($zipFilePath)){
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }
      }
    }

    if ( $createZip ){
      $zip = new ZipArchive();
      $result = $zip->open( $zipFilePath, ZIPARCHIVE::CREATE);
      if ( $result !== TRUE ) {
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNKNOWN);
      }
      foreach ( $files as $pathname => $filename ){
        if ( !empty($filename) ){
          if ( file_exists($pathname) && is_readable($pathname) ){
            $zip->addFile( $pathname, $filename );
          }
        } else {
          $zip->addEmptyDir( $pathname );
        }
      }
      $zip->close();
    }

    $file = new CKFinder_Connector_Utils_XmlNode("ZipFile");
    $file->addAttribute("name", $zip_filename);
    $this->_connectorNode->addChild($file);
  }
409249
public function parse()
    {
        if ($this->getProtocol()==='RSS') {
            // channel
            $parser                 = new Parser($this->xml->channel, $this, 'channel');
            $channel                = $parser->getData();
            $channel->protocol      = strtolower($this->getProtocol());
            $this->setData($channel);

            // items
            $this->items            = new XMLObjectsCollection($this->xml->channel);
            foreach ($this->items as $i=>$item) {
                $parser             = new Parser($item, $this, 'item');
                $item               = $parser->getData();
                $item->protocol     = strtolower($this->getProtocol());
                $item->id           = $this->id.'_'.Helper::encodeStringToId($item->title->content);
                $this->items->addData($i, $item);
            }
        } elseif ($this->getProtocol()==='ATOM') {
            // entry
            $parser             = new Parser($this->xml, $this, 'feed');
            $channel            = $parser->getData();
            $channel->protocol  = strtolower($this->getProtocol());
            $this->setData($channel);

            // entry
            $this->items            = new XMLObjectsCollection($this->xml);
            foreach ($this->items as $i=>$item) {
                $parser             = new Parser($item, $this, 'feed');
                $item               = $parser->getData();
                $item->protocol     = strtolower($this->getProtocol());
                $item->id           = $this->id.'_'.Helper::encodeStringToId($item->title->content);
                $this->items->addData($i, $item);
            }
        }
    }
311172
private void readXmlDeclaration() throws IOException, KriptonRuntimeException {
		if (bufferStartLine != 0 || bufferStartColumn != 0 || position != 0) {
			checkRelaxed("processing instructions must not start with xml");
		}

		read(START_PROCESSING_INSTRUCTION);
		parseStartTag(true, true);

		if (attributeCount < 1 || !"version".equals(attributes[2])) {
			checkRelaxed("version expected");
		}

		version = attributes[3];

		int pos = 1;

		if (pos < attributeCount && "encoding".equals(attributes[2 + 4])) {
			encoding = attributes[3 + 4];
			pos++;
		}

		if (pos < attributeCount && "standalone".equals(attributes[4 * pos + 2])) {
			String st = attributes[3 + 4 * pos];
			if ("yes".equals(st)) {
				standalone = Boolean.TRUE;
			} else if ("no".equals(st)) {
				standalone = Boolean.FALSE;
			} else {
				checkRelaxed("illegal standalone value: " + st);
			}
			pos++;
		}

		if (pos != attributeCount) {
			checkRelaxed("unexpected attributes in XML declaration");
		}

		isWhitespace = true;
		text = null;
	}
723957
def measurements_from_xml(filename,
                          collect_histograms=True,
                          cd_parent=False,
                          silence=False):
    
    if not os.path.isfile(filename):
        raise OSError("the file {0} does not exist".format(filename))
    silence_context = silence_sout_serr if silence else do_nothing

    filename = os.path.abspath(os.path.normpath(filename))

    if cd_parent:
        xml_directory = os.path.dirname(filename)
        parent = os.path.abspath(os.path.join(xml_directory, os.pardir))
        cd_context = working_directory
    else:
        parent = None
        cd_context = do_nothing

    log.info("parsing XML in {0} ...".format(filename))
    with cd_context(parent):
        parser = ROOT.RooStats.HistFactory.ConfigParser()
        with silence_context():
            measurements_vect = parser.GetMeasurementsFromXML(filename)
        # prevent measurements_vect from being garbage collected
        ROOT.SetOwnership(measurements_vect, False)
        measurements = []
        for m in measurements_vect:
            if collect_histograms:
                with silence_context():
                    m.CollectHistograms()
            measurements.append(asrootpy(m))
    return measurements
24382
private function _xmlbody()
    {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $root = $dom->createElement("tns:phpsysinfo");
        $root->setAttribute('xmlns:tns', 'http://phpsysinfo.sourceforge.net/');
        $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $root->setAttribute('xsi:schemaLocation', 'http://phpsysinfo.sourceforge.net/ phpsysinfo3.xsd');
        $dom->appendChild($root);
        $this->_xml = new SimpleXMLExtended(simplexml_import_dom($dom), $this->_sysinfo->getEncoding());

        $generation = $this->_xml->addChild('Generation');
        $generation->addAttribute('version', PSI_VERSION_STRING);
        $generation->addAttribute('timestamp', time());
        $options = $this->_xml->addChild('Options');
        $options->addAttribute('tempFormat', defined('PSI_TEMP_FORMAT') ? strtolower(PSI_TEMP_FORMAT) : 'c');
        $options->addAttribute('byteFormat', defined('PSI_BYTE_FORMAT') ? strtolower(PSI_BYTE_FORMAT) : 'auto_binary');
        $options->addAttribute('datetimeFormat', defined('PSI_DATETIME_FORMAT') ? strtolower(PSI_DATETIME_FORMAT) : 'utc');
        if (defined('PSI_REFRESH')) {
            $options->addAttribute('refresh',  max(intval(PSI_REFRESH), 0));
        } else {
            $options->addAttribute('refresh', 60000);
        }
        if (defined('PSI_FS_USAGE_THRESHOLD')) {
            if ((($fsut = intval(PSI_FS_USAGE_THRESHOLD)) >= 1) && ($fsut <= 99)) {
                $options->addAttribute('threshold', $fsut);
            }
        } else {
            $options->addAttribute('threshold', 90);
        }
        if (count($this->_plugins) > 0) {
            if ($this->_plugin_request) {
                $plug = $this->_xml->addChild('UsedPlugins');
                $plug->addChild('Plugin')->addAttribute('name', $this->_plugin);
            } elseif ($this->_complete_request) {
                $plug = $this->_xml->addChild('UsedPlugins');
                foreach ($this->_plugins as $plugin) {
                    $plug->addChild('Plugin')->addAttribute('name', $plugin);
                }
/*
            } else {
                $plug = $this->_xml->addChild('UnusedPlugins');
                foreach ($this->_plugins as $plugin) {
                    $plug->addChild('Plugin')->addAttribute('name', $plugin);
                }
*/
            }
        }
    }
389815
public function processData()
    {
        while ( $this->processedCount < $this->xmlTextContentObjectAttributeCount() )
        {
            $limit = array( 'offset' => $this->offset,
                            'length' => $this->fetchLimit );

            $xmlAttributeChunk = eZContentObjectAttribute::fetchListByClassID( $this->xmlClassAttributeIds(), false, $limit, true, false );

            foreach ( $xmlAttributeChunk as $xmlAttr )
            {
                $result = true;
                // If the current entry has been logged, we don't increment the running number
                // so that the entries can be displayed together on output.
                $currentEntryLogged = false;

                $currentId = $xmlAttr->attribute( 'id' );
                $objectId = $xmlAttr->attribute( 'contentobject_id' );
                $version = $xmlAttr->attribute( 'version' );
                $languageCode = $xmlAttr->attribute( 'language_code' );

                $label = "Attribute [id:{$currentId}] - [Object-id:{$objectId}] - [Version:{$version}] - [Language:{$languageCode}]";

                $xmlText = eZXMLTextType::rawXMLText( $xmlAttr );
                if ( empty( $xmlText ) )
                {
                    if ( $this->verboseLevel > 0 )
                    {
                        $this->outputString( "Empty XML-data", $label, $currentEntryLogged );
                        $currentEntryLogged = true;
                    }
                    $result = false;
                    continue;
                }

                $dom = new DOMDocument( '1.0', 'utf-8' );
                $success = $dom->loadXML( $xmlText );
                if ( !$success )
                {
                    if ( $this->verboseLevel > 0 )
                    {
                        $this->outputString( "XML not loaded correctly for attribute", $label, $currentEntryLogged );
                        $currentEntryLogged = true;
                    }
                    $result = false;
                    continue;
                }

                $linkNodes = $dom->getElementsByTagName( 'link' );
                $urlIdArray = array();

                foreach ( $linkNodes as $link )
                {
                    // We are looking for external 'http://'-style links, not the internal
                    // object or node links.
                    if ( $link->hasAttribute( 'url_id' ) )
                    {
                        $urlIdArray[] = $link->getAttribute( 'url_id' );
                    }
                }
                $urlIdArray = array_unique( $urlIdArray );

                if ( count( $urlIdArray ) > 0 )
                {
                    if ( $this->verboseLevel > 0 )
                    {
                        $this->outputString( "Found http-link elements in xml-block", $label, $currentEntryLogged );
                        $currentEntryLogged = true;
                    }

                    if ( $this->doFix)
                    {
                        $db = eZDB::instance();
                        $db->begin();
                        eZSimplifiedXMLInput::updateUrlObjectLinks( $xmlAttr, $urlIdArray );
                        $db->commit();
                    }
                }

                $this->script->iterate( $this->cli, $result );
                $label = null;
            }

            $this->processedCount += count( $xmlAttributeChunk );
            $this->offset += $this->fetchLimit;
            unset( $xmlAttributeChunk );
        }
    }
1277545
protected function parseXML($xml){
        if (!$xml){
            return false;
        }
        
        $this->response = array();
        $this->response['ReportRequestId'] = (string)$xml->ReportRequestId;
        $this->response['ReportType'] = (string)$xml->ReportType;
        $this->response['StartDate'] = (string)$xml->StartDate;
        $this->response['EndDate'] = (string)$xml->EndDate;
        $this->response['Scheduled'] = (string)$xml->Scheduled;
        $this->response['SubmittedDate'] = (string)$xml->SubmittedDate;
        $this->response['ReportProcessingStatus'] = (string)$xml->ReportProcessingStatus;
        
    }
1258175
def parse_reports(self):
    

    # Set up vars
    self.picard_alignment_metrics = dict()

    # Go through logs and find Metrics
    for f in self.find_log_files('picard/alignment_metrics', filehandles=True):
        parsed_data = dict()
        s_name = None
        keys = None
        for l in f['f']:
            # New log starting
            if 'AlignmentSummaryMetrics' in l and 'INPUT' in l:
                s_name = None
                keys = None
                # Pull sample name from input
                fn_search = re.search(r"INPUT(?:=|\s+)(\[?[^\s]+\]?)", l, flags=re.IGNORECASE)
                if fn_search:
                    s_name = os.path.basename(fn_search.group(1).strip('[]'))
                    s_name = self.clean_s_name(s_name, f['root'])
                    parsed_data[s_name] = dict()

            if s_name is not None:
                if 'AlignmentSummaryMetrics' in l and '## METRICS CLASS' in l:
                    keys = f['f'].readline().strip("\n").split("\t")
                elif keys:
                    vals = l.strip("\n").split("\t")
                    if len(vals) == len(keys):
                        # Ignore the FIRST_OF_PAIR / SECOND_OF_PAIR data to simplify things
                        if vals[0] == 'PAIR' or vals[0] == 'UNPAIRED':
                            for i, k in enumerate(keys):
                                try:
                                    parsed_data[s_name][k] = float(vals[i])
                                except ValueError:
                                    parsed_data[s_name][k] = vals[i]
                    else:
                        s_name = None
                        keys = None

        # Remove empty dictionaries
        for s_name in list(parsed_data.keys()):
            if len(parsed_data[s_name]) == 0:
                parsed_data.pop(s_name, None)

        # Manipulate sample names if multiple baits found
        for s_name in parsed_data.keys():
            if s_name in self.picard_alignment_metrics:
                log.debug("Duplicate sample name found in {}! Overwriting: {}".format(f['fn'], s_name))
            self.add_data_source(f, s_name, section='AlignmentSummaryMetrics')
            self.picard_alignment_metrics[s_name] = parsed_data[s_name]

    # Filter to strip out ignored sample names
    self.picard_alignment_metrics = self.ignore_samples(self.picard_alignment_metrics)

    if len(self.picard_alignment_metrics) > 0:

        # Write parsed data to a file
        self.write_data_file(self.picard_alignment_metrics, 'multiqc_picard_AlignmentSummaryMetrics')

        # Add to general stats table
        self.general_stats_headers['PCT_PF_READS_ALIGNED'] = {
            'title': '% Aligned',
            'description': 'Percent of aligned reads',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'format': '{:,.0f}',
            'scale': 'RdYlGn',
            'modify': lambda x: self.multiply_hundred(x)
        }
        for s_name in self.picard_alignment_metrics:
            if s_name not in self.general_stats_data:
                self.general_stats_data[s_name] = dict()
            self.general_stats_data[s_name].update( self.picard_alignment_metrics[s_name] )



        # Make the bar plot of alignment read count
        pdata = dict()
        for s_name in self.picard_alignment_metrics.keys():
            pdata[s_name] = dict()
            # Picard reports both reads for PE data. Divide it by two as most people will expect # clusters
            if self.picard_alignment_metrics[s_name]['CATEGORY'] == 'PAIR':
                pdata[s_name]['total_reads'] = self.picard_alignment_metrics[s_name]['TOTAL_READS'] / 2
                pdata[s_name]['aligned_reads'] = self.picard_alignment_metrics[s_name]['PF_READS_ALIGNED'] / 2
            else:
                pdata[s_name]['total_reads'] = self.picard_alignment_metrics[s_name]['TOTAL_READS']
                pdata[s_name]['aligned_reads'] = self.picard_alignment_metrics[s_name]['PF_READS_ALIGNED']
            pdata[s_name]['unaligned_reads'] = pdata[s_name]['total_reads'] - pdata[s_name]['aligned_reads']

        keys = OrderedDict()
        keys['aligned_reads'] = {'name': 'Aligned Reads'}
        keys['unaligned_reads'] = {'name': 'Unaligned Reads'}

        # Config for the plot
        pconfig = {
            'id': 'picard_aligned_reads',
            'title': 'Picard: Aligned Reads',
            'ylab': '# Reads',
            'cpswitch_counts_label': 'Number of Reads',
        }

        self.add_section (
            name = 'Alignment Summary',
            anchor = 'picard-alignmentsummary',
            description = "Plase note that Picard's read counts are divided by two for paired-end data.",
            plot = bargraph.plot(pdata, keys, pconfig)
        )

    # Return the number of detected samples to the parent module
    return len(self.picard_alignment_metrics)
568359
protected static function _exportMetrics($xmlDocument, $metrics)
    {
        $data = $metrics->data();
        $xmlMetrics = $xmlDocument->createElement('metrics');
        $xmlMetrics->setAttribute('loc', $data['loc']);
        $xmlMetrics->setAttribute('ncloc', $data['nlloc']);
        $xmlMetrics->setAttribute('statements', $data['lloc']);
        $xmlMetrics->setAttribute('coveredstatements', $data['cloc']);
        return $xmlMetrics;
    }