Using DOMCategory to parse namespace xml's? - dom

My input.xml
<z1:BookNames name="Groovy" dataType="INTEGER" xmlns:z0="messages" xmlns:z2="base" xmlns:z3="number" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:z1="bookcat">
<z3:BookCost>
<z3:IntegerValue>1106</z3:IntegerValue>
</z3:BookCost>
</z1:BookNames>
My Code-
document = parse(new FileReader('input.xml'))
rootElement = document.documentElement
println rootElement
use(groovy.xml.dom.DOMCategory)
{
println rootElement.'#dataType'
cf = rootElement.'z3:BookCost'
}
I'm trying to fetch book cost but unsuccessful so far. Can you throw ideas here. I can't declare prefix z3 as 'z3:BookCost' z3 can be anything in input xml. But namespace value can be hard-coded in code.

Here's a way using XmlSlurper:
new File( 'input.xml' ).withReader { x ->
new XmlSlurper().parse( x ).with { root ->
println root.#dataType
println root.BookCost.IntegerValue
}
}
DOMCategory isn't namespace aware (afaik)

Related

How to provide the output result of a function as a PUT request in scala?

i have a scala code that converts a layer to a Geotiff file. Now i want this Geotiff file to be passed in a PUT request as a REST service. How can i do that?
Here is a section of code:
val labeled_layerstack =
{
//Labeled Layerstack
//val layers_input = Array(layer_dop) ++ layers_sat
val layers_labeled_input = Array(layer_label) ++ Array(output_layerstack) //++ layers_input
ManyLayersToMultibandLayer(layers_labeled_input, output_labeled_layerstack)
output_labeled_layerstack
}
if (useCleanup) {
DeleteLayer(layer_label)
if(useDOP)
DeleteLayer(layer_dop)
for( layer_x <- layers_sat)
DeleteLayer(layer_x)
}
labeled_layerstack
}
else output_labeled_layerstack //if reusing existing layerstack ( processing steps w/o "layerstack")
if(processingSteps.isEmpty || processingSteps.get.steps.exists(step => step == "classification")) {
if (useRandomForest) {
ClusterTestRandomForest(labeled_layerstack, fileNameClassifier, layerResult, Some(output_layerstack))
if (useExportResult) {
LayerToGeotiff(layerResult, fileNameResult, useStitching = useExportStitching)
}
}
else if (useSVM) {
ClusterTestSVM(labeled_layerstack, fileNameClassifier, layerResult, Some(output_layerstack))
if (useExportResult) {
LayerToGeotiff(layerResult, fileNameResult, useStitching = useExportStitching)
}
}
}
The original code is quite long and is not shareable so i am sharing this which is relevant to the problem. The output of LayertoGeotiff should be passed as an PUT request. How can i create such a request?
I suggest to you the Play framework to send a PUT request

Casper require() with CoffeeScript not importing external files

I followed CasperJS's documentation about including .coffee files from the main Casper test file. My code looks like this:
home/tests/my_test_file.coffee:
parameters = require('../parameters')
casper.test.begin "Test ", (test) ->
home_page = parameters.root_path
page_to_test = home_page + "my_page_to_test"
casper.start page_to_test, ->
test.assertEquals #getCurrentUrl(), page_to_test
casper.run ->
test.done()
home/parameters.coffee:
require = patchRequire global.require
root_path = "http://localhost:1080/"
my_page = "foo"
other_param = "bar"
exports = ->
{
'root_path': root_path,
'my_page': my_page,
'other_param': other_param
}
However, Casper keeps telling me that page_to_test is undefined in my_test_file.coffee.
That's not a proper use of exports. First you don't need a function here, because you directly access the properties of the returned object. And second you cannot assign something directly to exports. That's what module.exports is for.
module.exports = {
'root_path': root_path,
'my_page': my_page,
'other_param': other_param
}
or
exports.root_path = root_path
exports.my_page = my_page
exports.other_param = other_param
By assigning an object to exports (exports = obj), you overwrite the object that does the actual exporting and nothing is exported.

Apache-Spark: method in foreach doesn't work

I read file from HDFS, which contains x1,x2,y1,y2 representing a envelope in JTS.
I would like to use those data to build STRtree in foreach.
val inputData = sc.textFile(inputDataPath).cache()
val strtree = new STRtree
inputData.foreach(line => {val array = line.split(",").map(_.toDouble);val e = new Envelope(array(0),array(1),array(2),array(3)) ;
println("envelope is " + e);
strtree.insert(e,
new Rectangle(array(0),array(1),array(2),array(3)))})
As you can see, I also print the e object.
To my surprise, when I log the size of strtree, it is zero! It seems that insert method make no senses here.
By the way, if I write hard code some test data line by line, the strtree can be built well.
One more thing, those project is packed into jar and submitted in the spark-shell.
So, why does the method in foreach not work ?
You will have to collect() to do this:
inputData.collect().foreach(line => {
... // your code
})
You can do this (for avoiding collecting all data):
val pairs = inputData.map(line => {
val array = line.split(",").map(_.toDouble);
val e = new Envelope(array(0),array(1),array(2),array(3)) ;
println("envelope is " + e);
(e, new Rectangle(array(0),array(1),array(2),array(3)))
}
pairs.collect().foreach(pair => {
strtree.insert(pair._1, pair._2)
}
Use .map() instead of .foreach() and reassign the outcome.
Foreach does not return the outcome of applyied function. It can be used for sending data somewhere, storing to db, printing, and so on.

Calling class function within a constructor isn't being recognised

Answer:
It turns out I had neglected to use the new keyword when creating the class instance. The code in the question itself is fine.
Question:
I have a fairly simple class where the constructor calls another method on the class (editor_for_node). The call happens inside a jQuery each() loop, but I've also tried moving it outside.
define ['jquery'], ($) ->
class Editor
constructor: (#node, #data, #template) ->
#node.widgets().each (i, elem) =>
data = if #data then #data[i] else null
node = $(elem)
#editor_for_node node, data
editor_for_node: (node, data) ->
console.log 'hello!'
return {
'Editor': Editor,
}
When the line #editor_for_node node, data gets called, I get an error (in Firebug) saying this.editor_for_node is not a function.
I really can't see why this isn't working properly, the only possible source of weirdness that I can see is my use of require.js's define function at the start.
Edit: Generated output
(function() {
define(['jquery'], function($) {
var Editor;
Editor = (function() {
Editor.name = 'Editor';
function Editor(node, data, template) {
var _this = this;
this.node = node;
this.data = data;
this.template = template;
this.node.widgets().each(function(i, elem) {
data = _this.data ? _this.data[i] : null;
node = $(elem);
return _this.editor_for_node(node, data);
});
}
Editor.prototype.editor_for_node = function(node, data) {
return console.log('hello!');
};
return Editor;
})();
return {
'Editor': Editor
};
});
}).call(this);
First: Which version of CoffeeScript are you using? The fat arrow has been a source of bugs in certain previous releases.
If you're using the latest (1.3.1), then I'm going to go ahead and say that this is an indentation issue. When I copy and paste your code, it works fine. Are you mixing tabs and spaces? Verify that the compiled output contains the line
Editor.prototype.editor_for_node = ...
Update: See the comments on this answer. Turns out the problem was that the new keyword wasn't being used when invoking the constructor.

Is there a tool to merge NUnit result files?

For unclear reasons my Nunit test fixture cannot be executed in a single run, so I'm forced to execute a few tests in separate runs. However this means that the test results are splitted over multiple output files.
Is there a tool available which can merge NUnit result XML files into a single XML file?
I've tried using the existing Nunit-summary tool, but this simply sequentially parses the XML files with the given XSL file and concatenates the result as one big file.
Instead I would like it to merge/group the results for the test cases into the right namespaces/testfixtures first and then feed it to the XSLT processor. This way all test results should be displayed by fixture even though they're not gathered in a single run.
This is probably too late to help you, but we recently encountered a similar issue and wrote a small open source tool to help out: https://github.com/15below/NUnitMerger
From the readme:
Using in MSBuild
Load the task:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0"
DefaultTargets="Build">
<UsingTask AssemblyFile="$(MSBuildProjectDirectory)\..\Tools\MSBuild\15below.NUnitMerger.dll" TaskName="FifteenBelow.NUnitMerger.MSBuild.NUnitMergeTask" />
...
Feed it an array of files with in a target:
<Target Name="UnitTest" DependsOnTargets="OtherThings">
... Generate the individual files here in $(TestResultsDir) ...
<ItemGroup>
<ResultsFiles Include="$(TestResultsDir)\*.xml" />
</ItemGroup>
<NUnitMergeTask FilesToBeMerged="#(ResultsFiles)" OutputPath="$(MSBuildProjectDirectory)\TestResult.xml" />
</Target>
Find the resulting combined results at OutputPath.
Using in F#
Create an F# console app and add 15below.NUnitMerger.dll, System.Xml and System.Xml.Linq as references.
open FifteenBelow.NUnitMerger.Core
open System.IO
open System.Xml.Linq
// All my files are in one directory
WriteMergedNunitResults (#"..\testdir", "*.xml", "myMergedResults.xml")
// I want files from all over the place
let myFiles = ... some filenames as a Seq
myFiles
|> Seq.map (fun fileName -> XDocument.Parse(File.ReadAllText(fileName)))
|> FoldDocs
|> CreateMerged
|> fun x -> File.WriteAllText("myOtherMergedResults.xml", x.ToString())
I was using the 15below NUnitMerger above for a while, but wanted to extend it and since my F# skills are not good enough to do it there, I inspected their mechanism and implemented the following class in C# to achieve the same thing. Here is my starting code which might help anyone who also want to do this kind of manipulation in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
namespace RunNUnitTests
{
public static class NUnitMerger
{
public static bool MergeFiles(IEnumerable<string> files, string output)
{
XElement environment = null;
XElement culture = null;
var suites = new List<XElement>();
bool finalSuccess = true;
string finalResult = "";
double totalTime = 0;
int total = 0, errors = 0, failures = 0, notrun = 0, inconclusive = 0, ignored = 0, skipped = 0, invalid = 0;
foreach (var file in files)
{
var doc = XDocument.Load(file);
var tr = doc.Element("test-results");
if (environment == null)
environment = tr.Element("environment");
if (culture == null)
culture = tr.Element("culture-info");
total += Convert.ToInt32(tr.Attribute("total").Value);
errors += Convert.ToInt32(tr.Attribute("errors").Value);
failures += Convert.ToInt32(tr.Attribute("failures").Value);
notrun += Convert.ToInt32(tr.Attribute("not-run").Value);
inconclusive += Convert.ToInt32(tr.Attribute("inconclusive").Value);
ignored += Convert.ToInt32(tr.Attribute("ignored").Value);
skipped += Convert.ToInt32(tr.Attribute("skipped").Value);
invalid += Convert.ToInt32(tr.Attribute("invalid").Value);
var ts = tr.Element("test-suite");
string result = ts.Attribute("result").Value;
if (!Convert.ToBoolean(ts.Attribute("success").Value))
finalSuccess = false;
totalTime += Convert.ToDouble(ts.Attribute("time").Value);
if (finalResult != "Failure" && (String.IsNullOrEmpty(finalResult) || result == "Failure" || finalResult == "Success"))
finalResult = result;
suites.Add(ts);
}
if (String.IsNullOrEmpty(finalResult))
{
finalSuccess = false;
finalResult = "Inconclusive";
}
var project = XElement.Parse(String.Format("<test-suite type=\"Test Project\" name=\"\" executed=\"True\" result=\"{0}\" success=\"{1}\" time=\"{2}\" asserts=\"0\" />", finalResult, finalSuccess ? "True" : "False", totalTime));
var results = XElement.Parse("<results/>");
results.Add(suites.ToArray());
project.Add(results);
var now = DateTime.Now;
var trfinal = XElement.Parse(String.Format("<test-results name=\"Merged results\" total=\"{0}\" errors=\"{1}\" failures=\"{2}\" not-run=\"{3}\" inconclusive=\"{4}\" ignored=\"{5}\" skipped=\"{6}\" invalid=\"{7}\" date=\"{8}\" time=\"{9}\" />", total, errors, failures, notrun, inconclusive, ignored, skipped, invalid, now.ToString("yyyy-MM-dd"), now.ToString("HH:mm:ss")));
trfinal.Add(new[] { environment, culture, project });
trfinal.Save(output);
return finalSuccess;
}
}
}
I read on the web that Nunit result files are XML so i guess you can merge the file with an ordinary merge software as WinMerge