Song-specific temperament

Question: So equal temperament is a compromise to allow songs to be played without without having to retune them on the fly, to match the more consonant sounding just intonation intervals.
However, in a world where MIDI-based soft synthesizers with customizable tuning exist, it could be practical to optimise the tuning system to the played song, as the instrument can be tuned on a note-by-note basis.
I was thinking this could be algorithmically computed by shifting tuning towards just intonation based on if the note is used in multiple intervals or not. If it is not used in another context it would be completely tuned to its just intonation interval. e.g. the intro to Scar Tissue
An example of how it would work:

MIDI file read into program to analyse things like song key, most frequent intervals, most played chords, etc.
Program algorithmically computes tuning
Program outputs tuning
Tuning and song played back by synthesizer

Is there a known way to do this? Is just intonation the right 'ideal' to aim for? How do I ensure that the pitch does not drift?
Comment: This kind of thing has been explored, but mostly in the form of changing the tuning dynamically to make each chord as consonant as possible (dynamic/adaptive tuning/intonation) - would that be of interest to you too, or are you only interested in coming up with the fixed best compromise on a note-by-note basis for a given song? If the latter, why would the tuning drift?
Comment: matero: *every* temperament is a way of not having to retune "on the fly," since it is as you note not practical to do that with a keyboard instrument.  The main distinguishing feature of equal temperament is that it sounds equally good (or equally bad) in every key.  Meantone temperaments sound decidedly better in certain keys and decidedly worse in others, but they all allow you to play in the good keys without retuning, and that's something that you can't do with just intonation, unless you only use a *subset* of the chords of certain keys.
Comment: Slightly off subject, but on a couple of my keyboards, they can be recalibrated to play in other tunings - just being one. But I have to tell them which key I'm going to play the piece in. Modulate and there's a problem. So 12tet, whilst being a compromise, seems the best solution, albeit not *exactly* in tune. But it's been working for many decades now.
Comment: Might be of interest: https://music.stackexchange.com/questions/53218/would-an-instrument-that-tuned-itself-harmonically-on-the-fly-sound-in-tune/109732#109732
Comment: Why keep each note at the same pitch for the whole song?  You could adjust notes as needed during the song, as musicians playing variable-pitch instruments do.
Comment: @Tim Are all of the diatonic perfect fifths in tune in so-called just intonation?  If they are, it's some temperament, not "pure" just intonation.
Answer:
So equal temperament is a compromise to allow songs to be played without without having to retune them on the fly, to match the more consonant sounding just intonation intervals.

It's not only that - it also makes a given song sound more in tune when chords from different keys are used within the same song (whether due to modulation, chord borrowing, or whatever), and it makes all chords of the same type sound equally in tune. It might be that for many individual pieces of music, equal temperament (or something close to it) would still be judged to be the best tuning!

An example of how it would work:
MIDI file read into program to analyse things like song key, most frequent intervals, most played chords, etc.
Program algorithmically computes tuning
Program outputs tuning Tuning and song played back by
synthesizer
Is there a known way to do this?

If you are thinking of writing that program, then yes - you could come up with your desired tuning and then use MIDI tuning standard to convey that tuning to an instrument that supports MTS. I'm not aware of a program that calculates the 'best' tuning for a piece - that might be a matter of opinion, depending on which chords you want to sound most in tune.

Is just intonation the right 'ideal' to aim for?

Not necessarily - Just intonation has its compromises too. As well as not working well for pieces that move between keys, It doesn't even make all the chords in a given key 'in tune' - So it doesn't necessarily represent 'pure' or 'perfect' tuning. This is one reason why adaptive/dynamic tuning has attracted more interest than just trying to 'statically' find the best tuning for a given piece.
Comment: Agreed.  I'd just add, as a just intonation junkie, that there are kinds of music that don't aspire to making "all the chords in a given key 'in tune'".  That doesn't mean that they are second-class citizens.

Song-specific temperament


Java.lang.NoSuchMethodError: org.json.JSONObject.put

Question: I'm developing an Android library, i add my lib in my Test project, now i have a error that can't allow to finish my test:
Could not find method org.json.JSONObject.put, referenced from method com.ldm.JsonBuilder.jsonbuilder

Process: , PID: 31181
java.lang.NoSuchMethodError: org.json.JSONObject.put
at com.ldm.JsonBuilder.jsonbuilder(JsonBuilder.java:70)
at com.ldm.TestConnection.TestNow(TestConnection.java:79)
at ldm.eisworld.it.test.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5442)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)

This is my gradle:
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/httpcore-4.4.4.jar')
    compile files('libs/json.jar')
    compile 'org.json:json:20141113'
}

And this is a part of my code:
   /* Parsing of hash map */
    for (Map.Entry<String, ArrayList<String>> tr : rh.entrySet()) {

        try {
            /* Object that contains URL */
            JSONObject TraceUrl = new JSONObject();
            /* Object that contains nodes for each URL */
            JSONObject TraceNodes = new JSONObject();

            TraceUrl.put("url", tr.getKey());
            TraceUrl.put("nodes", tr.getValue());
            trace.put(TraceUrl);
        } catch (JSONException e) {
            System.out.println("Exception: " + e.toString());
        }

How i can resolve it ?
Comment: post your tr object where you set the values please
Comment: Looks like incompatible classes
Answer: You appear to be importing some kind of external json library that doesn't have a put() method.
JSONObject that has put() is "built in" to android, you don't need any additional libraries for it.
import org.json.JSONObject;

JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");

This will work.
Comment: I have imported a external library because in the process of exportation of my jar I have a problem with JSON function (cannot resolve Json...)
Comment: @Max, well, the library you use does not support `put()` method on the json object. You can either use the builtin json library like I showed, or find a corresponding method for put() in your external library
Comment: Ok, how i can resove this problem ?
Comment: I don't undestard, if i wrote a class in Android app all my code work perfectlym but If i create a java lib does't work because "JSON* cannot resolve  symbol"
Answer: KOTLIN
Late but, i think it might help someone.
i had this error
No virtual method put(Ljava/lang/String;F)Lorg/json/JSONObject; in class Lorg/json/JSONObject

i was importing the correct class and not importing any other related 3rd party libs.  even added progaurd rules but nothing helped.
then i replaced
                val orderRequest = JSONObject()
                orderRequest.put("amount", amount)
                orderRequest.put("currency", "INR")
                orderRequest.put("receipt", "order_rcptid_11")

with
         val reqStr = """
                    {
                    "amount" : "$amount",
                    "currency" : "INR",
                    "receipt" : "order_rcptid_11"
                    }
                    """.trimIndent()

         val orderRequest = JSONObject(reqStr)

Answer: Per the documentation, the Object value passed to JSONObject.put must be:

...a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities.

tr.getValue() is of type ArrayList<String>. Since this is not one of the listed types, the attempt fails at runtime.


Draw route map between two locations via another location

Question: I don't know about Google maps API much and I am just learning now. With the example explained here, I am able to draw map between two locations. But I am just curious to know whether it is possible to include via location or not.. Any help on this..?
Answer: I have solved it by using waypoints like below
 var request = {
   origin: "Mumbai, India",
   destination: "Pune, India",
   waypoints: [{ location: "Via point address", stopover: true}],
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

Thanks


MongoDB - Storing date without timezone

Question: We have a simple application in which we have all user in same timezone & therefore we are not interested to store timezone information in mongo date object.
Reason for such extreme step is we have multiple micro service using common database managed by different developers. Each of them requires to explicitly set timezone related stuff in query & forgetting same results in invalid dataset.
Since currently MongoDB folks Mongo Data Types
doesn't support storing dates without timezone.
Just eager to know that is their any alternative approach to represent date without timezone in mongo by which we can still able to take advantage of mongo database queries date based syntax like date ranges, date etc.
At the same time it would be convenient for DBA's to read and manage records.
Answer: Look at this answer: https://stackoverflow.com/a/6776273/6105830
You can use two types of long representation (milliseconds or format yyyyMMddHHmmss). These are the only ways to not store timezone and still be able to make range queries.
Unfortunately you lost some aggregation properties. But you can do something like keeping two representations and use them at opportune times.
UPDATE:
Do not store date as I said before. You will lost many and many features of MongoDB and also will be hard to perform major operators on date fields.
Newer versions of MongoDB has operators to deal with timezone, and it should be enough to work with ISOTime formats. My application was using my own suggestion to store date. Now I have to let my users select their TimeZone (company has grown and we need to expand to other countries). We are struggling to change all models to use timestamp instead of a normalized date format.
For further more explore the link: https://docs.mongodb.com/manual/reference/method/Date/
and you can also use MongoDB official community channel for questioning
Here is the link: https://developer.mongodb.com/community/forums/
Comment: hmmm  I did checked this post before posting problem. Issue with this approach is that both of them makes date unreadable by humans. So any DBA operation which can be previously performed directly on console will need to use some conversion wrapper to convert human readable to int values and vice versa. Thus leading to a different problem.
Comment: I don't think the format yyyyMMddHHmmss is unreadable haha

But for your problem, I think the other way (maybe only one) you can do is to storing the timezone and subtract/add timezone offset in queries, just like this aggregation (in java):

{
  "$project": {
    "date": {
      "$add": [
        "$date",
        TimeZone.getDefault().getOffset(System.currentTimeMillis())
      ]
    }
  }
}
Comment: oopss may be my understanding is wrong about yyyyMMddHHmmss, I was assuming to store same as a int/long only with extracted values.  Yes I think it should work perfectly for even for ranges query as well though we need to write some custom regex where we need to ignore year. Also I would also try your second suggested solution.
Answer: You could consider storing all the dates in UTC and presenting to the users in UTC, so you don't have the problem of silent conversion by either client JavaScript, server or MongoDB and therefore confusion.
You can do it like this: new Date(Date.UTC(2000, 01, 28))
Here's MDN link on the subject.
Answer: create a separate date.js module and export it
function formatDate(dateString) {
  const date = new Date(dateString);
  const day = String(date.getDate()).padStart(2, "0"); // Add leading zero if single digit
  const monthIndex = date.getMonth();
  const year = date.getFullYear().toString().slice(0); // Get the last two digits of the year
  const formattedDate = `${year}-${String(monthIndex + 1).padStart(
    2,
    "0"
  )}-${day}`; // Add leading zero if single digit
  return formattedDate;
}

module.exports = formatDate;

then in the import it in your main app const formatDate = require("./date");
then change your schema to something like this in the date field mine looks like this
const clientSchema = new mongoose.Schema({
  name: String,
  phone: String,
  acc: Number,
  radio: String,
  date: { type: String, default: formatDate(new Date().toISOString()) },
  amount: String,
  due: String,
});

change the date type to STRING

MongoDB - Storing date without timezone


How to display prices on the site in different currencies?

Question: The site has 5 currencies. The sales price of goods and delivery is set in euros. But the customer can choose the preferred currency to display prices.
A better solution would be to keep prices in all currencies in the table "prices" or convert dynamically?
Structure of table "prices":

id
currency
variant_id
value
original_value
Comment: Conversion rates change often, so keep track of the conversion rate from your default currency and work it out dynamically. If you wanted to, you could cache these converted prices in a way you can regularly refresh them.
Comment: @Jonnix, currency rates will be updated on schedule at midnight and cached in redis. I can use these coefficients to convert dynamically, and I can also update prices at midnight in the "prices" table based on these coefficients. What solution will be more productive and correct from the point of view of architecture?
Comment: My default position would be to do it dynamically (so entirely personal opinion). The calculation is simple so not much processing, also immediate effect when the conversion rate has changed without relying on a second job. But there are arguments for pre-calculated ones.
Answer: Dynamically.  It would be a simple JOIN plus a calculation.
However, ... It would be tempting to ROUND(..,2) when displaying.  This works for many Western currencies but does not work well for some of the Gulf states, which need 3 decimal places, or Korea, which does not really use Jeons any more.
If you need to round to a different number of places, use a Stored Function.  And/or perhaps the JOIN also gives the number of decimal places.
Answer: The answer depend on the business rule. If a price can be calculated by a simple conversion then store only price in some reference currency and convert it dynamically. However, you need a date to store rate history. When a price cannot be calculated dynamically you should store it. The combined approach may be used, too.


Calculate CNF and DNF without truth tables

Question: $$
\begin{array}{l}{\varphi_{1}=(\neg a \wedge b) \rightarrow \neg c} \\ {\varphi_{2}=((c \rightarrow \neg a) \wedge(\neg b \rightarrow \neg c)) \rightarrow(a \vee b \vee c)} \\ {\varphi_{3}=(a \vee \neg b) \leftrightarrow(a \wedge c)} \\ {\varphi_{4}=(\neg a \wedge c) \vee(a \rightarrow b)} \\ {\varphi_{5}=((a \wedge b) \vee(b \wedge \neg c)) \rightarrow(b \vee c)} \\ {\varphi_{6}=((a \uparrow b) \oplus(a \downarrow c))}\end{array}
$$
I have to calculate the cnf and dnf for all. I have problems doing that without the truth table. Have to do find the dnf for $4-6$ without truth table and cnf for $1-3$ without truth table. Can somebody help me doing that? Please.
Problems with $5$ my truth table tells me it's a tautology.
Calculating the DNF leads me to : $$
((\neg a \vee b) \wedge(c \vee \neg b)) \vee(b \vee c)
$$
Comment: Welcome to mathematics SE. People here like to see your work.  What have you tried? Please edit your post to include some of your thoughts on the problem.
Answer: Here's how you can proceed (I hope that this exercise intends to teach you that using the truth tables is a better method):

Convert all operators so that only the operators $\neg,\, \vee, \, \wedge$ remain(eg $\phi \to \psi$ becomes $\neg \phi \vee \psi$).
Use either distributivity  until you're in conjonctive (resp. disjunctive) form. Favor distributivity of $\vee$ over $\wedge$ if you want CNF and vice-versa.
Don't forget to simplify using associativity and idempotency after each step.

As an example, let's compute the CNF of $\varphi_4$ :
$$\begin{eqnarray} \varphi_4  & = &(\neg A \wedge C)\vee (A \to B)\\   &\equiv &  (\neg A \wedge C)\vee (\neg A \vee B)\\ &\equiv& \big(\neg A \vee (\neg A \vee B)\big)\wedge \big( C\vee (\neg A \vee B) \big) \\ &\equiv& (\neg A \vee B)\wedge ( C\vee \neg A \vee B)\end{eqnarray}$$
$(\neg A \vee B)\wedge ( C\vee \neg A \vee B)$ is in conjonctive form, it is hence the CNF of $\varphi_4$.
Comment: @rapiz Can you edit your original post and show us how you get the DNF of $\varphi_4$?
Comment: Done it correct?
Comment: @rapiz No, the last equality doesn't hold. I suggest that you start with CNF and use distributivity of $\wedge$ over $\vee$.
Comment: Don't get it. Yeah i negated the second term my bad. Want to understand rewrite these equations. What do you mean?
Comment: is this calculation right?
Comment: No. Introducing double negations will leed you to nowhere, since they will eventually undo each other. Just try to apply distributivity of $\wedge$ over $\vee$ in the CNF.
Comment: Sorry but i don't know how with 4 literals
Comment: Set $\psi := (C \vee \neg A \vee B)$ and use distributivity in $(\neg A \vee B)\wedge \psi$.
Comment: How did you get that psi??
Comment: In my case i would set $(\neg a \wedge c)$ as $\psi$
Comment: $\psi := (\neg a \wedge c)$ So $\psi \vee (\neg a \vee b)$ Now i get $(\psi \vee \neg a) \wedge ( \psi \vee b)$
Answer: Update: (Use Logical equivalence)

$$p⊕q\equiv (p\land\neg q)\lor (\neg p\land q)\equiv(p\lor q)\land(\neg p\lor\neg q)\tag*{aka Xor}$$
$$p ↓ q\equiv \neg p \land \neg q\tag*{aka Nor}$$
$$p ↑ q\equiv \neg p\lor\neg q\tag*{aka Nand}$$

\begin{align}
\varphi_6&\equiv((a↑b)⊕(a↓c))\\
&\equiv(\neg a\lor\neg b)⊕(\neg a \land \neg c)\\
&\equiv((\neg a\lor\neg b)\lor(\neg a \land \neg c))\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv (((\neg b\lor\neg a)\lor \neg a)\land((\neg a\lor\neg b)\lor\neg c)\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv ((\neg b\lor(\neg a\lor \neg a))\land((\neg a\lor\neg b)\lor\neg c)\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv ((\neg b\lor \neg a)\land((\neg a\lor\neg b)\lor\neg c))\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv ((\neg a\lor \neg b)\land((\neg a\lor\neg b)\lor\neg c))\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv (\neg a\lor \neg b)\land(\neg(\neg a\lor\neg b)\lor\neg(\neg a \land \neg c))\\
&\equiv (\neg a\lor \neg b)\land((a\land b)\lor(a \lor c))\\
&\equiv ((\neg a\lor \neg b)\land (a\land b))\lor ((\neg a\lor \neg b)\land(a \lor c))\\
&\equiv (\neg( a\land b)\land (a\land b))\lor ((\neg a\lor \neg b)\land(a \lor c))\\
&\equiv \bot\lor ((\neg a\lor \neg b)\land(a \lor c))\\
&\equiv (\neg a\lor \neg b)\land(a \lor c)\tag*{CNF}\\
&\equiv (\neg a\land(a \lor c))\lor (\neg b\land(a \lor c))\\
&\equiv ((\neg a\land a) \lor (\neg a\land c)))\lor ((\neg b\land a) \lor (\neg b\land c)))\\
&\equiv (\bot \lor (\neg a\land c)))\lor ((\neg b\land a) \lor (\neg b\land c)))\\
&\equiv (\neg a\land c)\lor ((\neg b\land a) \lor (\neg b\land c)))\\
\end{align}
And since $(\neg a\land c)\lor (\neg b\land a)$ implies $(\neg b\land c)$ we can prove its DNF form is $(\neg a\land c)\lor (\neg b\land a)$.

Hints for $1-3$:
\begin{align}
\varphi_1&\equiv(\neg a\land b)\to c\\
&\equiv a\lor \neg b\lor c\tag*{CNF&DNF}\\
\varphi_2&\equiv\neg((\neg c\lor¬a)∧(b\lor¬c))\lor(a∨b∨c)\\
&\equiv(c\land a)\lor(\neg b\land c)\lor(a\lor b \lor c)\\
&\equiv a\lor b\lor c\tag*{CNF&DNF}\\
\varphi_3&\equiv (a∨¬b)↔(a∧c)\\
&\equiv (a∨¬b)\to(a∧c)\land(a\land c)\to(a\lor\neg b)\\
&\equiv ((\neg a\land b)\lor(a\land c))\land((\neg a\lor \neg c)\lor(a\lor \neg b))\\
&\equiv ((\neg a\land b)\lor(a\land c))\land\top\\
&\equiv (\neg a\land b)\lor(a\land c)\tag*{DNF}\\
&\equiv ((\neg a\land b)\lor a) \land ((\neg a\land b)\lor c)\\
&\equiv (\neg a\lor a)\land(a \lor b)\land(\neg a\lor c)\land(b\lor c)\\
&\equiv \top\land(a \lor b)\land(\neg a\lor c)\land(b\lor c)\\
&\equiv (a \lor b)\land(\neg a\lor c)\land(b\lor c)\\
\end{align}
And since $(a \lor b)\land(\neg a\lor c)\equiv(\neg a \to b)\land(a\to c)$ which will imply $(b\lor c)$, that will make it true in the statement, so we can prove its CNF is $(a \lor b)\land(\neg a\lor c)$.
(my suggestion is, for relatively detailed answers, ask one question a time.)
Comment: How did you get the tautology in line 3 for Number 3?
Comment: @rapiz notice there are both $\neg a \lor a$ in it, first apply Associative law to make ($\neg a \lor a$) together, then Negation law it become $\top$, that part will be $\top \lor (\neg c\lor \neg b)$, then by Domination law we have $\top$
Comment: Okey got it could you help me with 5 and 6 ? Have to finish it within 2 hours to pass a weekly test that leads to dropping or not and i don't quite get it i will try the dnf for 5 furhter ..
Comment: okay, i'll take a look
Comment: What i actually have $ (( \neg a \wedge \neg b ) \vee (\neg a \wedge \neg c) \vee (\neg b \wedge \neg b)) \vee (b \vee b)$
Comment: My truth table tells me it's a tautology
Comment: yep, $5$ is a tautology
Comment: By De Morgan's law $(\neg b\land \neg b)\equiv\neg(b\lor b)$, then by Negation law we have $\neg(b\lor b)\lor (b\lor b)\equiv\top$, then keep applying Domination law we can prove $\varphi_5\equiv\top$
Comment: Is my formula wrong? I guess i did something wrong i'm actually calculating again and get $ ((\neg a \wedge \neg b) \vee (\neg a \wedge c) \vee (\neg b \wedge \neg b) \vee (\neg b \vee c)) \vee (b \vee c)$
Comment: you mean $\varphi_5 ?$ your formula is a tautology which is equivalent to it
Comment: yeah, ok well than i will proceed to get to the tautology with this formula
Comment: @rapiz updated, as a proof for minimal DNF form, it's not yet finished, but that's the idea.
Comment: and $\varphi_4$ you can simplify it to $\neg a\lor b$, as it's DNF&CNF form
Comment: Since with Identity law $(\neg a\lor b)\land((\neg a\lor b)\lor c)\equiv((\neg a\lor b)\lor\bot)\land((\neg a\lor b)\lor c)$, by distributive law that $(\neg a\lor b)\lor (\bot\land c)$, apply domination law we have $\neg a\lor b$


vue vue-resource $http.get não reconhece json com [

Question: Tenho um php que entrega o seguinte conteúdo
[{"Id":"50630","Operador":"","Id_cadastro":"61693"}]

O vue-resource só reconhece se eu remover o []
meu código vue é
this.$http.get('data.json').then(function(response) {
     this.cervejarias = response.data.Id_cadastro;
}

No PHP estou fazendo assim:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $data[] = $row;
}
print json_encode($data);

Estou esquecendo algo?
Este mesmo json, consigo ler pelo Angular.
Comment: Algo que você pode fazer também é trocar o seu código PHP por
`print json_encode($smtm->fetchAll());`
Comment: E para debugar códigos assim você pode usar `console.log(response)` e ver no seu console como os dados estão chegando.
Comment: Só vais queres mostrar um registo desse JSON? Não seria algo assim: http://jsfiddle.net/a312sa5a/ ?
Answer: A propriedade correta de response é body e não data.
// supondo que o retorno seja [{"Id":"50630","Operador":"","Id_cadastro":"61693"}]
this.$http.get('data.json').then(function(response) {
  this.cervejarias = response.body[0].Id_cadastro;
}

Comment: Funcionou!!!
agora eu quero jogar isso tudo em um v-for
seria somente response.body;?
Comment: this.cervejarias = response.body
Comment: Testei aqui e funcionou,  tudo belezinha agora.  Obrigado Amigos
Answer: O ideal é evitar a escrita de Promises dessa forma, não só da margem para errar chaves como também tem uma leitura ruim.
Tente assim na próxima:
this.$http.get('data.json')
    .then(res => res.json())
    .then(res => this.cervejarias = res.Id_cadastro)

Repare que você tem o retorno chamando diretamente a chave da sua API. Caso precise trabalhar o retorno antes de fazer algo basta usar chaves na arrow function.
this.$http.get('data.json')
    .then(res => res.json())
    .then(res => {

        // múltiplas linhas
        this.cervejarias = res.Id_cadastro)

    })


Is there a C header parser tool for wrapper generation like gccxml?

Question: I need to write a few c header wrappers for a new programming language and would like something like gccxml but without the full dependency on gcc and the problems it gives on a windows system.
Just needs to read C not C++. Output in any format is okay as long it is fully documented.
Need it for Curl, SQLite, GTK2, SDL, OpenGL, Win32 API and C posix API's on Linux/Solaris/FreeBSD/MacOSX.
Comment: Try to use [ABI Compliance Checker](http://ispras.linuxbase.org/index.php/ABI_compliance_checker#Usage_as_a_Parser_of_API) tool as a parser of C header files. See [this answer](http://stackoverflow.com/a/12546962/241776) for instructions on how to do this.
Answer: VivaCore is very cool. Have you tried SWIG the wikipedia page on ffi has some good links too.  I think there is a MSVC codedom example that does C also.
Answer: See our SD C Front End for DMS.  Full C parsing, symbol table construction, post parsing dump of any information you like.  Can dump code and symbol tables in XML format.
Comment: Wow, haven't seen this answer I gave since I wrote it 4 years ago.  Added standard SO indication of self-interest, *our*, that was not a requirement when I first gave this answer.
Answer: You may like pycparser in Python. Used in CFFI and other awesome projects.


Laravel 4: pass array to filter

Question: From my understanding, we can pass argument to filter via this:
Route::filter('age', function($route, $request, $value)
{
    //
});

Route::get('user', array('before' => 'owner|age:200', function()
{
    return 'Hello World';
}));

But, how can I pass array to the filter? For example, I want to pass "cars, speed boat, condominium" to the owner filter. The number of items in the array is dynamic, depending on the route. How is it possible to do that?
Thank you.
Answer: I do this tricks:
Route::filter('filtername', function($route, $request, $value)
{
    $array = explode('-',$value); // use - for delimiter
    // do whatever here
});

And on the routes, use like this
Route::get('user', array('before' => 'filtername:item1-item2-item3', function()
{
    return 'Hello World';
}));

Hope this helped.
Answer: You can not pass array (might possible in Laravel 4.1) in Laravel 4.0. However, you can pass more than one parameters in a filter and ensure they are separated by a comma (,).
For example:
Route::filter('age', function($route, $request, $age, $gender, $name)
{
    if ($age < 200 && $gender == 'male' && $name = 'anam' ) {
        return "Welcome to Laravel. Enjoy the awesome!";
    }
});

Route::get('user', array('before' => 'owner|age:200,male,anam', function()
{
    return 'Hello World';
}));

Answer: Like Anam said, you can give multiple parameters separated by a comma.
You can give multiple parameters and turn them back into an array with func_get_args().
array_except is a laravel function to delete certain keys from an array.
Route::filter('age', function($route, $request, $value)
{
    $params = array_except(func_get_args(), array(0, 1));
    if(count($params) > 3) {
        // do something
    }
});

Laravel 4: pass array to filter


NGINX routes to the wrong virtual host when Host header contains colon character

Question: My nginx.conf has several "server" sections, and a catch-all server section. Here is an example nginx.conf to give you an idea:
user www-data;
worker_processes auto;
worker_cpu_affinity auto;
pid /run/nginx.pid;

events {
    worker_connections 4000;
    use epoll;
    accept_mutex off;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    error_log /var/log/nginx/error.log;

    server {
        listen 80;

        server_name foo.com;

        location / {
            default_type text/plain;
            return 200 "hello from foo.com";
        }

        error_page 500 502 503 504 /500.html;
    }

    server {
        listen 80 default_server;
        server_name _;

        location / {
            return 403 "sorry";
        }
    }

}

I'm expecting the server to return 403 if the "Host" header is anything but "foo.com".
Somebody's apparently running Burp Suite on my server, and I noticed and interesting behavior when they send a "Host: foo.com:more-stuff-here" header: NGINX routes the request to the first "server" section. It looks as if it ignores the colon and everything after it in the header value.
I can reproduce it locally with the above nginx.conf:
$ curl -H "Host: foo.com" http://127.0.0.1
hello from foo.com

$ curl -H "Host: foo.com:unexpected-content" http://127.0.0.1
hello from foo.com

$ curl -H "Host: bar.com" http://127.0.0.1
sorry

Why does NGINX do this? Is this an expected behavior? What should I change in nginx.conf to ensure requests with "Host: foo.com:more-stuff-here" header go to the default block?
Update: For anybody researching the same issue, I also created a ticket in NGINX issue tracker.
Comment: underscore invalidate the host name and makes it to the default
Comment: @djdomi – nginx docs say underscore has no special meaning, it's just an invalid hostname. The important bit is "default_server" in the listen directive. I'm confused why nginx treats the Host value "foo.com:unexpected-content" as a direct match for the server name "foo.com".
Answer: The definition for the host header in the HTTP RFC indicates that the Host header should have the form host:port, with the :port being optional.
nginx sees everything after the colon as the port for the host, but it is irrelevant in your context since you have not specified a server block that way. So it uses the closest match it can find, the host without the "port".
Comment: Thought so much. Well, then I don't think there is anything you can do on the nginx side. This should be fixed in the application that makes the invalid requests.
Comment: The only option I can think of would be to try to add `foo.com:*` as an server_alias to the default host and hope that nginx is intelligent enough to distinguish it.
Comment: Ah, I see. What can I do to fix this? Is it possible to make nginx ignore requests with invalid port values?
Comment: Is it your problem that an application which sends invalid requests doesn't work properly? If yes I'd fix the application, if no I'd just ignore it.
Comment: My application generates a warning about an invalid Host header. I can silence the warning, but I would prefer if NGINX could catch the invalid requests before they make to the application.
Comment: I tested `foo.com:*`, NGINX doesn't start and prints an error: `invalid server name or wildcard "foo.com:*"`
Answer: The following might work for default_server:
server {
    listen 80 default_server;

    server_name _ ~example\.com:;

    location / {
        return 403 "sorry";
    }
}

The important part is the tilde ~, which indicates a regular expression match.
Comment: Good idea, but doesn't seem to work for me – the request still gets routed to the other server section.
Answer: The only alternative thought I could think of would be to code something in at the server side application level to check the host value and return the 403 response in code.
This however is not really the right way to do it, because the issue is a client issue to fix and not for your application.
for example, taking from this SO answer given a PHP application you could easily amend this logic to achieve the desired effect, note specifically the check for the SERVER_PORT as per Gerald's answer
$allowed_hosts = array('foo.example.com', 'bar.example.com');
$allowed_ports = array(80,443);
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts) || !in_array($_SERVER['SERVER_PORT'], $allowed_ports )) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

Comment: Thanks for the answer. That's how it's working currently for me here (the backend application uses Django web framework, which checks the host header against an allowlist. This is fine, but I was hoping to get NGINX to act as a "shield" in front of the backend app, making sure only valid, well-formed requests go through to the backend app)


Is it possible to keep track of whois requests of a domain?

Question: I'm interested in a domain, and want to buy it cheap.
Is it possible that I worsen my position in the discussion in the deal if I check it regularly with whois requests ?
Is it possible to show how many times somebody checked a domain whois records ?
What are the technical details needed to be able to do this ?
Answer: For the domain holder, it's normally impossible to see at all that someone checked a whois record for this domain.
Comment: Think i hit 2 secs earlier :)
Answer: As far i know the only guys who can monitor this are the sysadmins of the whois server which your client using. So the answer is no.
Please ellaborate what do you mean under technical requirements
Comment: So, if the person who wons the domain owns the whois server too, they can see ?
Who owns these whois servers usually ?
Comment: The domain registrar will typically run the relevant whois server.


highchart/highstock tooltip does not adjust after zoom

Question: I'm using highstocks to plot a serie. When using tooltip pointformat showing point.y the tooltip doesn`t readjust when zooming, so if you zoom in the middle of the graph the graph should always start at 0, but the tooltip is showing yaxis value from when the graph wasn´t zoomed.
If I choose to show point.change it will readjust when zoom, but the total shows wrong. For example should the last point (2017-12-28) show 320.59%, and when using point.change its showing 318.78% (which is wrong).
How can I fix so the tooltip pointformat readjusts when zooming? I'm using compare: 'value' in plotOptions {} so the graph starts at 0 when zooming.
Please see fiddle:
http://jsfiddle.net/cabvvpze/2/
Comment: `point.change` seems to have the incorrect value because the compare function does not like the first value `0`. This shifts all values by the difference of the first and second point, i.e. `1.8`. I tried setting the first point to 0.00001 and that does seem to give `point.change` the correct value. Not posting this as an answer since it not really a solution. See http://jsfiddle.net/ewolden/cabvvpze/3/ for my example.
Comment: Well it might be an work around worth trying, and then keep looking for a better solution. Thanks!
Answer: The point.change is calculated using the first non-null and non-zero value (https://api.highcharts.com/highstock/series.line.compare). When the chart is not zoomed the first value that satisfies this condition is ~1.81 (second point) - everything is done using this value as baseline.
Series hold the information about this specific value in compareValue property - it can be used in tooltip.pointFormatter to achieve the desired result.
If the chart is not zoomed (it can be determined by checking whether chart.resetZoomButton is initialized or not) print series.compareValue + point.change in the tooltip. Otherwise use point.change.
  pointFormatter: function() {
    var series = this.series,
      chart = series.chart;

    return '' + ((!chart.resetZoomButton ? series.compareValue : 0) + this.change) + '%
';

  }

Live demo: http://jsfiddle.net/kkulig/32kuokhb/
API reference: https://api.highcharts.com/highstock/tooltip.pointFormatter
Comment: Is that the desired final result?: http://jsfiddle.net/kkulig/32kuokhb/
Comment: Yes! That is correct! Thanks! Update your answer and I will accept it


Display images as a form element in a webform

Question: The goal is quite simple – I'm looking for a way to display an image in a webform.
By that I mean the image would part of the webform as a complement to a question (example: "what color is the car in this picture").
If possible it'd be great if the user could to upload the images when administrating the webform elements, and also if they were their own element that would be awesome (but even adding them to the descriptions of the question-elements themselves could work as well).
So basically, how can I setup a "display custom image in the webform"-element?
I've tried searching for a solution but all my results are about how to add an image upload field, which is quite the opposite of what I'm looking for.
Grateful for any help I could get on this.
Answer: If you install the IMCE module and set up the right permissions, users can upload and insert images into a webform.
Another option is to change the Webform module's default HTML Editor to use a Text format which supports inline images. You would do this by going to Webform > Configuration > Elements ( (/admin/structure/webform/config/elements)
Comment: Brilliant – I didn't know that Media Library could be [added to CKEditor](https://drudesk.com/blog/media-library-drupal-8-embed-button) as well, so after adding that to the text format I have all the functionality I need without any additional modules, thank you for the help!


Grouping flat xml using xslt (muenchian grouping), can't get it to group

Question: I spent quite some time trying to get muenchian grouping of the below xml to work but I can't get it to work. I tried a number of different ways so posting the most recent attempt probably just confuses anyone trying to help me. :-)
Xslt needs to be 1.0
Input file is invoice lines where "invoice header info" is duplicated for each line belonging to a particular invoice.
Grouping should be made in field _id, i e value in RESULTSET/ROW"/COL[12]/DATA (e. g. 'C82F1B47-9758-4D18-ABD7-80386385F6AD')
COL[21] through COL[27] are the different invoice lines for the invoice and as such should be listed line by line and under the respective invoice.
Input xml (it is from Filemaker):
<?xml version="1.0" encoding="UTF-8" ?>
<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">
    <ERRORCODE>0</ERRORCODE>
    <PRODUCT BUILD="01-22-2016" NAME="FileMaker" VERSION="ProAdvanced 14.0.5"/>
    <DATABASE DATEFORMAT="Yyyy-m-d" LAYOUT="" NAME="fmStaben.fmp12" RECORDS="113" TIMEFORMAT="k:mm:ss "/>
    <METADATA>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_MEMBER" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_MEDLEM_KSIFFER" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_FIRST_NAME" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_LAST_NAME" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_FIRST_PNAME" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_LAST_PNAME" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_ADDRESS1" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_ADDRESS2" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_ZIP" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_CITY" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_STATE" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::_id" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_ORDERNR" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_POSTAGE" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_ORDER_TOTAL" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_DISCOUNT" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_MVA_AMOUNT" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_AMOUNT_TO_PAY" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_KID" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OrderHeader::OH_AMOUNT_MODUS" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_LINE" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_LTYPE" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_ART_NR" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_ART_TEXT" TYPE="TEXT"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_QUANTITY" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_PRICE" TYPE="NUMBER"/>
        <FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="OL_TOTAL" TYPE="NUMBER"/>
    </METADATA>
    <RESULTSET FOUND="6">
        <ROW MODID="0" RECORDID="601">
            <COL>
                <DATA>109948</DATA>
            </COL>
            <COL>
                <DATA>45</DATA>
            </COL>
            <COL>
                <DATA>JOHN</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>JAMES</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>2323 MAIN STREET</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>C82F1B47-9758-4D18-ABD7-80386385F6AD</DATA>
            </COL>
            <COL>
                <DATA>409949</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>3534534534517</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>010</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-131015DM</DATA>
            </COL>
            <COL>
                <DATA>WORLD CUP KIT 1</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
        <ROW MODID="0" RECORDID="602">
            <COL>
                <DATA>109948</DATA>
            </COL>
            <COL>
                <DATA>45</DATA>
            </COL>
            <COL>
                <DATA>JOHN</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>JAMES</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>2323 MAIN STREET</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>C82F1B47-9758-4D18-ABD7-80386385F6AD</DATA>
            </COL>
            <COL>
                <DATA>409949</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>3534534534517</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>020</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-140312DM</DATA>
            </COL>
            <COL>
                <DATA>WORLD CUP KIT 2</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
        <ROW MODID="0" RECORDID="603">
            <COL>
                <DATA>049985</DATA>
            </COL>
            <COL>
                <DATA>77</DATA>
            </COL>
            <COL>
                <DATA>TEST</DATA>
            </COL>
            <COL>
                <DATA>VON TEST</DATA>
            </COL>
            <COL>
                <DATA>TESTPARENT</DATA>
            </COL>
            <COL>
                <DATA>VON TEST</DATA>
            </COL>
            <COL>
                <DATA>789 LEFT STREET</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>5A2D83C6-ECEB-4636-968E-97DC6E5B1C8A</DATA>
            </COL>
            <COL>
                <DATA>409950</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>92350429953250</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>010</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-140312DM</DATA>
            </COL>
            <COL>
                <DATA>WORLD CUP KIT 3</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
        <ROW MODID="0" RECORDID="605">
            <COL>
                <DATA>129984</DATA>
            </COL>
            <COL>
                <DATA>15</DATA>
            </COL>
            <COL>
                <DATA>CARL</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>JANE</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>4525 GREAT ROAD</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>478E8CF0-7C93-4BE4-B314-FBCBDB5184F0</DATA>
            </COL>
            <COL>
                <DATA>409951</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>92359999843251</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>020</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-1407156</DATA>
            </COL>
            <COL>
                <DATA>150 FOOTBALL LEGENDS</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
        <ROW MODID="0" RECORDID="606">
            <COL>
                <DATA>129984</DATA>
            </COL>
            <COL>
                <DATA>15</DATA>
            </COL>
            <COL>
                <DATA>CARL</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>JANE</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>4525 GREAT ROAD</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>478E8CF0-7C93-4BE4-B314-FBCBDB5184F0</DATA>
            </COL>
            <COL>
                <DATA>409951</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>92359999843251</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>030</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-140312DM</DATA>
            </COL>
            <COL>
                <DATA>WORLD CUP KIT 3</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
        <ROW MODID="0" RECORDID="607">
            <COL>
                <DATA>129984</DATA>
            </COL>
            <COL>
                <DATA>15</DATA>
            </COL>
            <COL>
                <DATA>CARL</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>JANE</DATA>
            </COL>
            <COL>
                <DATA>DOE</DATA>
            </COL>
            <COL>
                <DATA>4525 GREAT ROAD</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>999 99</DATA>
            </COL>
            <COL>
                <DATA>MAGIC KINGDOM</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>478E8CF0-7C93-4BE4-B314-FBCBDB5184F0</DATA>
            </COL>
            <COL>
                <DATA>409951</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA/>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>49,00</DATA>
            </COL>
            <COL>
                <DATA>92359999843251</DATA>
            </COL>
            <COL>
                <DATA>7</DATA>
            </COL>
            <COL>
                <DATA>040</DATA>
            </COL>
            <COL>
                <DATA>A</DATA>
            </COL>
            <COL>
                <DATA>99-1402175</DATA>
            </COL>
            <COL>
                <DATA>WORLD CUP KIT 2</DATA>
            </COL>
            <COL>
                <DATA>1</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
            <COL>
                <DATA>0,00</DATA>
            </COL>
        </ROW>
    </RESULTSET>
</FMPXMLRESULT>

Needed output xml:
<?xml version="1.0" encoding="UTF-8" ?>
<Invoices>
    <Invoice>
        <Recipient>
            <MemberNo>109948</MemberNo>
            <CheckDigit>99</CheckDigit>
            <FirstName>JOHN</FirstName>
            <LastName>DOE</LastName>
            <GuardianFirstName>JAMES</GuardianFirstName>
            <GuardianLastName>DOE</GuardianLastName>
            <Address1>2323 MAIN STREET</Address1>
            <Address2/>
            <PostalCode>999 99</PostalCode>
            <City>MAGIC KINGDOM</City>
            <State/>
        </Recipient>
        <InvoiceHeader>
            <OrderNo>409949</OrderNo>
            <Postage>49,00</Postage>
            <OrderTotal>49,00</OrderTotal>
            <Discount/>
            <VATAmount>0,00</VATAmount>
            <AmountToPay>49,00</AmountToPay>
            <PaymentReferenceNo>3534534534517</PaymentReferenceNo>
            <AmountModus>7</AmountModus>
        </InvoiceHeader>
        <InvoiceLines>
            <InvoiceLine>
                <LineNo>010</LineNo>
                <LineType>A</LineType>
                <ItemNo>99-131015DM</ItemNo>
                <ItemDescription>WORLD CUP KIT 1</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
            <InvoiceLine>
                <LineNo>020</LineNo>
                <LineType>A</LineType>
                <ItemNo>99-140312DM</ItemNo>
                <ItemDescription>WORLD CUP KIT 2</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
        </InvoiceLines>
    </Invoice>
    <Invoice>
        <Recipient>
            <MemberNo>049985</MemberNo>
            <CheckDigit>77</CheckDigit>
            <FirstName>TEST</FirstName>
            <LastName>VON TEST</LastName>
            <GuardianFirstName>TESTPARENT</GuardianFirstName>
            <GuardianLastName>VON TEST</GuardianLastName>
            <Address1>789 LEFT STREET</Address1>
            <Address2/>
            <PostalCode>999 99</PostalCode>
            <City>MAGIC KINGDOM</City>
            <State/>
        </Recipient>
        <InvoiceHeader>
            <OrderNo>409950</OrderNo>
            <Postage>49,00</Postage>
            <OrderTotal>49,00</OrderTotal>
            <Discount/>
            <VATAmount>0,00</VATAmount>
            <AmountToPay>49,00</AmountToPay>
            <PaymentReferenceNo>92350429953250</PaymentReferenceNo>
            <AmountModus>7</AmountModus>
        </InvoiceHeader>
        <InvoiceLines>
            <InvoiceLine>
                <LineNo>010</LineNo>
                <LineType/>
                <ItemNo>99-140312DM</ItemNo>
                <ItemDescription>WORLD CUP KIT 3</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
        </InvoiceLines>
    </Invoice>
    <Invoice>
        <Recipient>
            <MemberNo>129984</MemberNo>
            <CheckDigit>15</CheckDigit>
            <FirstName>CARL</FirstName>
            <LastName>DOE</LastName>
            <GuardianFirstName>JANE</GuardianFirstName>
            <GuardianLastName>DOE</GuardianLastName>
            <Address1>4525 GREAT ROAD</Address1>
            <Address2/>
            <PostalCode>999 99</PostalCode>
            <City>MAGIC KINGDOM</City>
            <State/>
        </Recipient>
        <InvoiceHeader>
            <OrderNo>409951</OrderNo>
            <Postage>49,00</Postage>
            <OrderTotal>49,00</OrderTotal>
            <Discount/>
            <VATAmount>0,00</VATAmount>
            <AmountToPay>49,00</AmountToPay>
            <PaymentReferenceNo>92359999843251</PaymentReferenceNo>
            <AmountModus>7</AmountModus>
        </InvoiceHeader>
        <InvoiceLines>
            <InvoiceLine>
                <LineNo>020</LineNo>
                <LineType>A</LineType>
                <ItemNo>99-1407156</ItemNo>
                <ItemDescription>150 FOOTBALL LEGENDS</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
            <InvoiceLine>
                <LineNo>030</LineNo>
                <LineType>A</LineType>
                <ItemNo>99-140312DM</ItemNo>
                <ItemDescription>WORLD CUP KIT 3</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
            <InvoiceLine>
                <LineNo>040</LineNo>
                <LineType>A</LineType>
                <ItemNo>99-1402175</ItemNo>
                <ItemDescription>WORLD CUP KIT 2</ItemDescription>
                <Quantity>1</Quantity>
                <UnitPrice>0,00</UnitPrice>
                <LineAmount>0,00</LineAmount>
            </InvoiceLine>
        </InvoiceLines>
    </Invoice>
</Invoices>

Xlst that I usually use as a base to get the values from the input xml. I used it on several other occasions when I didn't need to group the data (and formating of output was a bit different):
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fmp="http://www.filemaker.com/fmpxmlresult"
exclude-result-prefixes="fmp"
>

    <xsl:output method="xml" indent="yes" />

  <xsl:template match="/fmp:FMPXMLRESULT">
    <Invoices>
        <xsl:apply-templates select="fmp:RESULTSET/fmp:ROW" />
    </Invoices>
  </xsl:template>

    <xsl:template match="fmp:RESULTSET/fmp:ROW">
        <Invoice>
            <Recipient>
                <MemberNo>
                    <xsl:apply-templates select="fmp:COL[1]" />
                </MemberNo>
                <CheckDigit>
                    <xsl:apply-templates select="fmp:COL[2]" />
                </CheckDigit>
                <FirstName>
                    <xsl:apply-templates select="fmp:COL[3]" />
                </FirstName>
                <LastName>
                    <xsl:apply-templates select="fmp:COL[4]" />
                </LastName>
                <GuardianFirstName>
                    <xsl:apply-templates select="fmp:COL[5]" />
                </GuardianFirstName>
                <GuardianLastName>
                    <xsl:apply-templates select="fmp:COL[6]" />
                </GuardianLastName>
                <Address1>
                    <xsl:apply-templates select="fmp:COL[7]" />
                </Address1>
                <Address2>
                    <xsl:apply-templates select="fmp:COL[8]" />
                </Address2>
                <PostalCode>
                    <xsl:apply-templates select="fmp:COL[9]" />
                </PostalCode>
                <City>
                    <xsl:apply-templates select="fmp:COL[10]" />
                </City>
                <State>
                    <xsl:apply-templates select="fmp:COL[11]" />
                </State>
            </Recipient>
            <InvoiceHeader>
                <OrderNo>
                    <xsl:apply-templates select="fmp:COL[12]" />
                </OrderNo>
                <Postage>
                    <xsl:apply-templates select="fmp:COL[13]" />
                </Postage>
                <OrderTotal>
                    <xsl:apply-templates select="fmp:COL[14]" />
                </OrderTotal>
                <Discount>
                    <xsl:apply-templates select="fmp:COL[15]" />
                </Discount>
                <VATAmount>
                    <xsl:apply-templates select="fmp:COL[16]" />
                </VATAmount>
                <AmountToPay>
                    <xsl:apply-templates select="fmp:COL[17]" />
                </AmountToPay>
                <PaymentReferenceNo>
                    <xsl:apply-templates select="fmp:COL[18]" />
                </PaymentReferenceNo>
                <AmountModus>
                    <xsl:apply-templates select="fmp:COL[19]" />
                </AmountModus>
            </InvoiceHeader>
            <InvoiceLines>
                <InvoiceLine>
                    <LineNo>
                        <xsl:apply-templates select="fmp:COL[20]" />
                    </LineNo>
                    <LineType>
                        <xsl:apply-templates select="fmp:COL[21]" />
                    </LineType>
                    <ItemNo>
                        <xsl:apply-templates select="fmp:COL[22]" />
                    </ItemNo>
                    <ItemDescription>
                        <xsl:apply-templates select="fmp:COL[23]" />
                    </ItemDescription>
                    <Quantity>
                        <xsl:apply-templates select="fmp:COL[24]" />
                    </Quantity>
                    <UnitPrice>
                        <xsl:apply-templates select="fmp:COL[25]" />
                    </UnitPrice>
                    <LineAmount>
                        <xsl:apply-templates select="fmp:COL[26]" />
                    </LineAmount>
                </InvoiceLine>
            </InvoiceLines>
        </Invoice>
    </xsl:template>

    <xsl:key
name="kMetaData"
match="fmp:METADATA/fmp:FIELD"
use="count(preceding-sibling::fmp:FIELD) + 1"
/>

    <xsl:template match="fmp:COL[1]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[2]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[3]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[4]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[5]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[6]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[7]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[8]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[9]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[10]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[11]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[12]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[13]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[14]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[15]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[16]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[17]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[18]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[19]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[20]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[21]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[22]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[23]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[24]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[25]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[26]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

    <xsl:template match="fmp:COL[27]">
        <xsl:value-of select="fmp:DATA" />
    </xsl:template>

</xsl:stylesheet>

Thanks you in advance to anyone beeing so kind as to take time to help me. :-)
//Freppan
Answer: You don't need to use Muenchian grouping if you're doing the XSL transformation while exporting from FileMaker. You can take advantage of the EXSLT set:distinct() extension function that FileMaker's XSLT engine supports:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fmp="http://www.filemaker.com/fmpxmlresult"
xmlns:set="http://exslt.org/sets"
exclude-result-prefixes="fmp set">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="group" match="fmp:ROW" use="fmp:COL[12]/fmp:DATA" />

<xsl:template match="/fmp:FMPXMLRESULT">
    <Invoices>
        <xsl:for-each select="set:distinct(fmp:RESULTSET/fmp:ROW/fmp:COL[12]/fmp:DATA)">
            <Invoice>
                <Recipient>
                    <MemberNo>
                        <xsl:value-of select="../../fmp:COL[1]/fmp:DATA" />
                    </MemberNo>
                    <CheckDigit>
                        <xsl:value-of select="../../fmp:COL[2]/fmp:DATA" />
                    </CheckDigit>
                    <FirstName>
                        <xsl:value-of select="../../fmp:COL[3]/fmp:DATA" />
                    </FirstName>
                    <LastName>
                        <xsl:value-of select="../../fmp:COL[4]/fmp:DATA" />
                    </LastName>
                    <GuardianFirstName>
                        <xsl:value-of select="../../fmp:COL[5]/fmp:DATA" />
                    </GuardianFirstName>
                    <GuardianLastName>
                        <xsl:value-of select="../../fmp:COL[6]/fmp:DATA" />
                    </GuardianLastName>
                    <Address1>
                        <xsl:value-of select="../../fmp:COL[7]/fmp:DATA" />
                    </Address1>
                    <Address2>
                        <xsl:value-of select="../../fmp:COL[8]/fmp:DATA" />
                    </Address2>
                    <PostalCode>
                        <xsl:value-of select="../../fmp:COL[9]/fmp:DATA" />
                    </PostalCode>
                    <City>
                        <xsl:value-of select="../../fmp:COL[10]/fmp:DATA" />
                    </City>
                    <State>
                        <xsl:value-of select="../../fmp:COL[11]/fmp:DATA" />
                    </State>
                </Recipient>
               <InvoiceHeader>
                    <OrderNo>
                        <xsl:value-of select="../../fmp:COL[12]/fmp:DATA" />
                    </OrderNo>
                    <Postage>
                        <xsl:value-of select="../../fmp:COL[13]/fmp:DATA" />
                    </Postage>
                    <OrderTotal>
                        <xsl:value-of select="../../fmp:COL[14]/fmp:DATA" />
                    </OrderTotal>
                    <Discount>
                        <xsl:value-of select="../../fmp:COL[15]/fmp:DATA" />
                    </Discount>
                    <VATAmount>
                        <xsl:value-of select="../../fmp:COL[16]/fmp:DATA" />
                    </VATAmount>
                    <AmountToPay>
                        <xsl:value-of select="../../fmp:COL[17]/fmp:DATA" />
                    </AmountToPay>
                    <PaymentReferenceNo>
                        <xsl:value-of select="../../fmp:COL[18]/fmp:DATA" />
                    </PaymentReferenceNo>
                    <AmountModus>
                        <xsl:value-of select="../../fmp:COL[19]/fmp:DATA" />
                    </AmountModus>
                </InvoiceHeader>
                <InvoiceLines>
                    <xsl:for-each select="key('group', .)" >
                       <InvoiceLine>
                            <LineNo>
                                <xsl:value-of select="fmp:COL[20]/fmp:DATA" />
                            </LineNo>
                            <LineType>
                                <xsl:value-of select="fmp:COL[21]/fmp:DATA" />
                            </LineType>
                            <ItemNo>
                                <xsl:value-of select="fmp:COL[22]/fmp:DATA" />
                            </ItemNo>
                            <ItemDescription>
                                <xsl:value-of select="fmp:COL[23]/fmp:DATA" />
                            </ItemDescription>
                            <Quantity>
                                <xsl:value-of select="fmp:COL[24]/fmp:DATA" />
                            </Quantity>
                            <UnitPrice>
                                <xsl:value-of select="fmp:COL[25]/fmp:DATA" />
                            </UnitPrice>
                            <LineAmount>
                                <xsl:value-of select="fmp:COL[26]/fmp:DATA" />
                            </LineAmount>
                        </InvoiceLine>
                    </xsl:for-each>
                </InvoiceLines>
            </Invoice>
        </xsl:for-each>
    </Invoices>
</xsl:template>

</xsl:stylesheet>

Comment: This solution works just as well as the first one. Thanks. Filemakers support for EXSLT is very good to know and may come in handy in the future.
Comment: @Freppan Just keep in mind that only *some* EXSLT functions are supported.
Comment: @michael.hor257k Is there a list of EXSLT functions supported by Filemaker?
Comment: @NicolaiKant I have such list, but I cannot post it in a comment. Start a new question.
Comment: @michael.hor257k Thanks. Will do
Answer: Well, given that you know the item you want to group by it should not be that difficult to define your key <xsl:key name="group" match="fmp:ROW" use="fmp:COL[12]/fmp:DATA"/> and use it:

<xsl:key name="group" match="fmp:ROW" use="fmp:COL[12]/fmp:DATA"/>

<xsl:output method="xml" indent="yes"/>

<xsl:template match="/fmp:FMPXMLRESULT">
    <Invoices>
        <xsl:apply-templates
            select="fmp:RESULTSET/fmp:ROW[generate-id() = generate-id(key('group', fmp:COL[12]/fmp:DATA)[1])]"
        />
    </Invoices>
</xsl:template>

<xsl:template match="fmp:RESULTSET/fmp:ROW">
    <Invoice>
        <Recipient>
            <MemberNo>
                <xsl:apply-templates select="fmp:COL[1]"/>
            </MemberNo>
            <CheckDigit>
                <xsl:apply-templates select="fmp:COL[2]"/>
            </CheckDigit>
            <FirstName>
                <xsl:apply-templates select="fmp:COL[3]"/>
            </FirstName>
            <LastName>
                <xsl:apply-templates select="fmp:COL[4]"/>
            </LastName>
            <GuardianFirstName>
                <xsl:apply-templates select="fmp:COL[5]"/>
            </GuardianFirstName>
            <GuardianLastName>
                <xsl:apply-templates select="fmp:COL[6]"/>
            </GuardianLastName>
            <Address1>
                <xsl:apply-templates select="fmp:COL[7]"/>
            </Address1>
            <Address2>
                <xsl:apply-templates select="fmp:COL[8]"/>
            </Address2>
            <PostalCode>
                <xsl:apply-templates select="fmp:COL[9]"/>
            </PostalCode>
            <City>
                <xsl:apply-templates select="fmp:COL[10]"/>
            </City>
            <State>
                <xsl:apply-templates select="fmp:COL[11]"/>
            </State>
        </Recipient>
        <InvoiceHeader>
            <OrderNo>
                <xsl:apply-templates select="fmp:COL[13]"/>
            </OrderNo>
            <Postage>
                <xsl:apply-templates select="fmp:COL[14]"/>
            </Postage>
            <OrderTotal>
                <xsl:apply-templates select="fmp:COL[15]"/>
            </OrderTotal>
            <Discount>
                <xsl:apply-templates select="fmp:COL[16]"/>
            </Discount>
            <VATAmount>
                <xsl:apply-templates select="fmp:COL[17]"/>
            </VATAmount>
            <AmountToPay>
                <xsl:apply-templates select="fmp:COL[18]"/>
            </AmountToPay>
            <PaymentReferenceNo>
                <xsl:apply-templates select="fmp:COL[19]"/>
            </PaymentReferenceNo>
            <AmountModus>
                <xsl:apply-templates select="fmp:COL[20]"/>
            </AmountModus>
        </InvoiceHeader>
        <InvoiceLines>
            <xsl:for-each select="key('group', fmp:COL[12]/fmp:DATA)">
                <InvoiceLine>
                    <LineNo>
                        <xsl:apply-templates select="fmp:COL[21]"/>
                    </LineNo>
                    <LineType>
                        <xsl:apply-templates select="fmp:COL[22]"/>
                    </LineType>
                    <ItemNo>
                        <xsl:apply-templates select="fmp:COL[23]"/>
                    </ItemNo>
                    <ItemDescription>
                        <xsl:apply-templates select="fmp:COL[24]"/>
                    </ItemDescription>
                    <Quantity>
                        <xsl:apply-templates select="fmp:COL[25]"/>
                    </Quantity>
                    <UnitPrice>
                        <xsl:apply-templates select="fmp:COL[26]"/>
                    </UnitPrice>
                    <LineAmount>
                        <xsl:apply-templates select="fmp:COL[27]"/>
                    </LineAmount>
                </InvoiceLine>
            </xsl:for-each>
        </InvoiceLines>
    </Invoice>
</xsl:template>

<xsl:template match="fmp:COL">
    <xsl:value-of select="fmp:DATA"/>
</xsl:template>

I reused your code (had to increment some positional predicates), I would consider cleaning up all those <xsl:apply-templates select="fmp:COL[N]"/> to simply use <xsl:value-of select="fmp:COL[N]/fmp:DATA"/> however, as in this case the pushing the processing to a template does not really achieve some transformation.
Comment: Thanks, work perfectly. I really appreciate the help. I also took your advice on cleaning up the code.
Comment: @Freppan, This solution is superior to any solution that uses extension functions. Always go for 100% portable XSLT code. When using extension functions one is bound to a particular vendor, programming language, or even version of both the vendor's XSLT processor, and the function library. And, if you are using extension functions when there is a pure XSLT solution, you'd probably be better off not using XSLT at all. Don't believe "specialists", who advocate extension functions when pure and efficient XSLT solutions exist.
Comment: If I could downvote a comment I would; that's a ridiculous argument and based on nothing but a personal vendetta against @michael.hor257k. If an environment hosting XSLT has extension functions readily available, use whatever suits your needs best, they're available for a reason.


Do I need to sanitize a user input textfield used in a mail body?

Question: I have a feature on my site where a user is allowed to edit a textfield is a Drupal form (built using the D7 Form API) and then send the contents of that textfield as (part of) the body of an email to another user.  I use drupal_mail to send the mail.
The textfield is saved in the database, and I rely on the Form API to protect against SQL injection.  The textfield is never rendered on the screen outside the textfield widget, so "dangerous" HTML tags and PHP/JavaScript injection is not a concern (I hope).
I use DefaultMailSystem as mail backend.
Given that the user can type anything in this textfield, is there any need to sanitize this user input before it is included in the email body and sent?
Comment: Answer corrected. Sorry.
Answer: There are two reasons to use Drupal's text filtering system: security and proper formatting of the information for the context.
In reverse order:

For formatting: if you use something like the markdown filter or limit with html tags can be used for simple sanity (i.e. no h1) then you want to use a filter that removes that.
For security: you want to remove malicious code if it is being displayed in an environment where that matters. In the case of email, the relevant DOM is the email client which can sometimes be a domain. However, if it is a security weakness to that email user to get javascript...that is a problem with their client. Since anyone can send any email to any address with any (malformed) contents it is not a major consideration of e-mail processing to ensure the body is "safe" (without scripts). See this discussion on g.d.o/security about sanitizing text in email bodies

That said, you don't want your system to be useful for spam.

Consider using the flood_control system.
Consider adding an introduction and closure to your email message to make it less useful for a spammer. For example "This email was sent from example.com. Your friend said: _stuff_here_. If you have questions contact your friend and not example.com"

There is more to e-mail than the body, of course. E-mail headers can be a vector for attacks, since someone can use a newline as part of the "to" address and then append new headers to send as many mails as they want to whomever they want, pretending to be from whoever they want, hurting your domain's reputation in the process.
One other side-note:

The textfield is saved in the database, and I rely on the Form API to
  protect against SQL injection.

SQL Injection protection should come from proper use of methods and arguments in your db_insert or db_query function. It does not come from the Form API.
Answer: It depends on the mail backend you are using. DefaultMailSystem perform basic sanitization on send, but it cares only about mail specification and ignores the fact that body might be HTML - that's on you. So you are guaranteed what you send will be formally valid e-mail, but not that it will be valid HTML. Exact part about body sanitization is:
// Note: e-mail uses CRLF for line-endings. PHP's API requires LF
// on Unix and CRLF on Windows. Drupal automatically guesses the
// line-ending format appropriate for your system. If you need to
// override this, adjust $conf['mail_line_endings'] in settings.php.
$mail_body = preg_replace('@\r?\n@', $line_endings, $message['body']);

And that's it, as mail is pretty accepting format and sets stricter requirements on other fields - NOT on body.
Using drupal_mail() is safer than using backend directly, as it calls format method:
// Format the message body.
$message = $system->format($message);

And default's format method strips the HTML:
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);

The big question is - how much do you trust drupal_html_to_text()? It is there to made text valid, but it never claims it is a safeguard against malicious misuse. As far as I understand it's code, it should be reasonably safe in most cases, but as far as I remember there was some link related holes in mail readers that could be abused anyway.
TL;DR Basic sanitisation is done but there still might be some attacks possible.


Session hibernate, como obter instancia

Question: Em toda a documentação do hibernate, e exemplos pela web tem esse exemplo de código, ou um muito parecido, para usar o hibernate.
List<Object> list = session.createCriteria(Object.class);

Sendo que o session e uma implementação da Interface Session do hibernate, mas como eu consigo essa instacia, já tentei o inject com @Autowired do spring(Fremework MVC que estou usando), mas da java.lang.NullPointerException.
A pergunta é, como consigo a instancia certa de hibernate.Session?
EDIT 1
Oque costumava ser feito era como no trecho de código abaixo:
Session session = (Session) this.entityManager.unwrap(Object.class);

ou
Session session = this.entityManager.unwrap(Object.class);

Mas, ao que me parece, isso foi tirado do Hibernate 4.2 ou 5.*, não sei com certeza, oque acontece é que não estou conseguindo mais essa instancia de session, sempre dá null pointer.
EDIT 2
Tentei oque o @Javeson Yehudi me sugeriu, que é o seguinte :
private static final SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
session = sessionFactory.openSession();

Porem, ainda não funciona, o próprio eclipse não deixou eu usa-lo, pois a classe AnnotationConfiguration(), não esta presente nas minhas bibliotecas, porem, como indicado no comentário, apenas Configuration() funcionou, só que mudou o erro, agora ele diz que eu não tenho o hibernate.cfg.xml, porque eu estou fazendo essa configuração via código, com o Spring... segue o erro.
GRAVE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dashboardController': Unsatisfied dependency expressed through field 'iService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'infoService' defined in file [H:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Administrator\WEB-INF\classes\br\com\finger\service\InfoService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4725)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'infoService' defined in file [H:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Administrator\WEB-INF\classes\br\com\finger\service\InfoService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1110)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1055)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1056)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
    ... 24 more
Caused by: java.lang.ExceptionInInitializerError
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1103)
    ... 35 more
Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:245)
    at br.com.finger.service.InfoService.<clinit>(InfoService.java:40)
    ... 42 more

"Solução"
Após ler a documentação do hibernate, percebi que a abordagem que estava errada, e que na verdade, não é possível injetar mais essa dependencia Hibernate.SessionFactory, ela foi deprecated para incentivar o uso da especificação do JPA, o que torna as coisas mais facies de dar manutenção mais tarde, apesar de acrescentar um pouco de complexidade, porem como boa pratica é melhor optar pela especifição. Segue o trexo e o link que fala sobre isso.

Hibernate offers an older, legacy org.hibernate.Criteria API which should be considered deprecated. No feature development will target those APIs. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery. For details on the org.hibernate.Criteria API, see Legacy Hibernate Criteria Queries.

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#criteria
Comment: Eu escrevi sobre isso anos atrás, talvez o post lhe seja útil: http://www.simpledev.com.br/spring-hibernate.html
Comment: Bem legal seu post... e exatamente o que eu estou fazendo, só que programáticamente, pois não gosto de xml
Comment: Esse post foi escrito a quase 4 anos atrás :)
De qualquer forma, o principio é o mesmo independente da configuração, você não tem que instanciar a session, simplesmente deixe o Spring fazer isso pra você
Comment: Sim... é oque estou implementando agora.
Answer: Se eu estou entendendo o que você quer, então você precisa do SessionFactory para obter uma Session
private static final SessionFactory sessionFactory =        new AnnotationConfiguration().configure().buildSessionFactory();
session = sessionFactory.openSession();

http://www.devmedia.com.br/entendendo-hibernate-session/29215
Agora se você quer com injeção de dependência, você pode encontrar coisas legais aqui
Comment: Essa classe AnnotationConfiguration(), veio de onde? acho que não tenho essa dependencia nas minha bibliotecas...
Comment: Depende das sua versão, tente Configuration no lugar de AnnotationConfiguration
Comment: Editei ai... da uma olhadinha no erro, por favor.
Comment: De fato, pra você usar o Configuration você precisa ter um hibernate.cfg.xml é de lá que ele configura tudo. Como você está usando Spring acho que você tem que usar o autowired, tentar ver esse site http://www.baeldung.com/hibernate-4-spring
Comment: Oque aconteceu na verdade @JavesonYehudi é que, de acordo com a documentação do hibernate o SessionFactory foi deixado de lado na versão 5.2, para tornar mais usada a especificação do JPA, que é o EntityManager.getCriteriaBuilder(), por isso, eu que estou usando as últimas versões do spring e do hibernate, não consigo injetar.
Comment: @RenatoVieiraDantas de fato eu sei que eles estão tentando dar mais atenção ao JPA. Mas ainda não deixaram de lado a API do hibernate.
Você poderia me dar um exemplo de como você está montando sua classe de configuração? Por que, se você quer usar o EntityManager do JPA o correto era fazer:

`@PersistenceContext(unitName = "myPersistenceUnit")
private EntityManager entityManager;

ou

@PersistenceUnit(unitName = "myPersistenceUnit")
private EntityManagerManager entityManagerManager;`

E pra isso você teria que ter o persistence.xml.
Comment: A classe de configuração é programática, o spring permite que façamos as configurações sem xml... É exatamente isso, com o @PersistenceContext mesmo, estava funcionando perfeitamente assim, até que resolvi mudar, mais agora creio que não sera tão grande a mudança. E vou corrigir o que eu havia dito, de fato, eles não a deixaram de lado, mais foi considerada deprecated.
Comment: Bom, só pra deixar claro: Está correto que o hibernate quer dar mais atenção ao JPA, porém o Session não vai ficar deprecated (eu havia entendido isso). Agora ele irá extender do EntityManager. https://github.com/hibernate/hibernate-orm/wiki/Migration-Guide---5.2
Comment: Hmmmmmmm, então oque vai acontecer e que vamos continuar usando session só que pela especificação e não pela implementação? É isso?
Answer: Em vez de utilizar o @Autowired tente o @PersistenceContext.
Comment: Infelizmente, não funcionou...

Session hibernate, como obter instancia


Why is my exception still being thrown after being caught?

Question: I have the following code where a variable is being initialized with the result of a function call. This function throws so I set up a try-catch to catch the exception. For some reason the exception is still showing up on the screen even after the catch clause runs.
#include <iostream>
#include <stdexcept>

int f() { throw std::invalid_argument("threw"); return 50; }

struct S
{
    S()
        try : r(f())
    {
        std::cout << "works";
    }
    catch(const std::invalid_argument&)
    {
        std::cout << "fails";
    }

    int r;
};

int main()
{
    S s;
}

This code prints "fails" after showing the exception:

terminate called after throwing an instance of 'std::invalid_argument'
what():  threw

Why is the exception still thrown? I have the same code set up in main and it works without fail:
int main()
{
    try { throw std::invalid_argument("blah"); }
    catch(const std::invalid_argument&) { }
}

So why does it fail when being used in an initializer list?
Comment: This is really worth reading: http://www.gotw.ca/gotw/066.htm  and so is this: http://stackoverflow.com/questions/7110636/need-for-try-catch-within-a-constructor
Comment: this is defined in standard somewhere... `{S s; cout<<s;}` what do you expect if `s` failed to construct?
Comment: I think the factor you are throwing in the constructor initialization list is possibly related. You dont get to ctr body if lists throw, so maybe the compiler thinks that catch is part of a body it hasnt yet enabled. I expect is you assign r inside the ctr body and it will behave much more as expected.
Comment: Note that the `catch` handler is being entered in your code; if you flush the stream `fails` will be printed. The exception will be rethrown when control reaches the end of the function try block, that's just how they work.
Comment: And this looks useful: http://www.drdobbs.com/introduction-to-function-try-blocks/184401297
Comment: http://www.csci.csusb.edu/dick/c++std/cd2/except.html

15.3  Handling an exception
15.3.16 The  exception being handled is rethrown if control reaches the end of a handler of the function-try-block of a  constructor  or  destructor.  Otherwise,  a  function returns when control reaches the end of a handler for the function-try-block.
Answer: Constructors with function try blocks (like what you have for S) automatically rethrow any exceptions caught by the catch block. Consequently, after the catch catches the exception, it rethrows it. This behavior is different from normal catch handlers, which don't do this. I think the rationale is that if construction of a data member or base class fails, the object has failed to construct. The purpose of the catch handler is just to do any extra cleanup before the exception propagates outward.
Hope this helps!
Answer: From the C++11 Standard, 15.3/15:

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block
  of a constructor or destructor.

The reasons are well explained in the GOTW Jerry links under your question, but summarily: imagine if it hadn't rethrown, then the next lines after S s; will presumably attempt to use s despite it never having completed construction, and when s leaves scope the constructor will have arranged a call to the destructor for s - potentially freeing never-initialised pointers, releasing never-taken locks etc..
By way of contrast, if you let the data member be default initialised then assign to it from a try/catch block in the constructor body, the state of the object including bases and data members can potentially be kept in some coherent state: it's up to you as the programmer to decide whether that state's ok - i.e. whether you'll use the try/catch block inside the constructor body, and have later member functions handle a potentially default-constructed data member.


Rails - console message about associations

Question: Everytime I do something in my terminal of my rails 4 app, I now get a message that has this warning:
gems/activerecord-4.2.4/lib/active_record/associations.rb:1694: warning: already initialized constant User::HABTM_Roles
/Users/ffd/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/associations.rb:1694: warning: previous definition of HABTM_Roles was here

Does anyone know what it means?
In my role.rb, I have:
class Role < ActiveRecord::Base

  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify

end

In my user.rb, I have:
has_and_belongs_to_many :roles, :join_table => :users_roles

Comment: paste your user.rb & give more clarification about the error
Comment: You might have defined twice a `has_and_belongs_to_many` for the `User::HABTM_Roles` association (or `Roles` association in your user model).
Comment: @МалъСкрылевъ - what does that mean? how do i provide  a full path?
Comment: Hi - i don't know what that is.
Answer: I encountered this same problem and found a simple solution.
I was using in my code previously :
module MyModule
  RESET = 'reset'
end

I just change this to
module MyModule
   RESET ||= 'reset'
end

And I got the solution.
So see if you do same in you code somewhere.
This took care of the warning and is a lot simpler than checking if each constant is defined. Let me know if you find a better solution.