What is the practical importance of grasping the concept of tonality? More specially for piano players?

Question: Let me explain the context of this question: my 12 year old niece is learning to play the  piano and has to study musical theory; she recently encountered the notion of tonality and can't manage to find this topic interesting; the reason she gives is that knowing about tonality can only be useful to those who compose musical pieces, while for those who play all the necessary informations are given on the music sheet.
I suppose that the concept of tonality has more than a purely theoretical interest, unless it would not be taught in music courses.
But I could not give her a better argument than : " the notion must be important, for  enlightened music amateurs commonly give the tonality of a musical piece when they refer to this piece".
Hence my question : for which  reasons is it important for those who practice music to know about tonality? in which way ignoring this notion could prevent or slow down one's progress in music practice?
Comment: The word 'tonality' has [many different meanings](https://en.wikipedia.org/wiki/Tonality#Characteristics_and_features) in different contexts. Which 'tonality' do you mean?
Comment: Your niece should be glad and grateful that she has got a piano teacher who shows her the musical background. She will take lot of profit when playing with other instrumentalists or singers, when learning a new piece or playing in performance or accompanying songs by ear.
Comment: @topoReinstateMonica.- By tonality I meant , for example "B flat minor". I meant the kind of expression added to the name of a musical peice : " Mozart's piano sonata B flat major" for instance.
Comment: The way most people learn about tonality at the start is to learn scales. What level is she at - beginner? Has she been taught scales? Once you know scales, knowing the names of keys isn't really much of a "topic" - just a simple bit of terminology.
Comment: And... What other things is she being taught to do, other than play from a score?
Comment: My guess is that she's being taught only to read music - like so many when learning piano - and that's the only way her teacher uses. Change of method, or change of teacher?
Answer: I think this question is terribly opinion-based. At least my answer is.
First of all, it might be very difficult to motivate a 12-year old! She might be opposing the idea just because she wants to oppose things and/or people. Maybe if she saw someone that she looks up to, someone who fluently uses the concepts of tonality to do something that's cool and ossom, she might get interested. Music theory is not very cool! No street credibility is on offer on those lessons. No immediate gratification either - unless you like to tinker with meaningless puzzles.
How do you influence and motivate people? Bribery, extortion, ... and what have you. ;) But that sort of extrinsic motivation isn't very good. I've heard that intrinsic motivation is the most effective kind: challenge, excitement, enjoyment, fun, fascination. And if the person already has a potential for intrinsic motivation, adding extrinsic motivation might actually counteract the positive things! If she happened to enjoy music theory, if you say that she must do it to be a good girl or otherwise there's a punishment or something, or if there's a reward which makes it more like a chore, chances are that she stops enjoying it! But there's one more type, provocation, which might be able to turn into intrinsic motivation ... I'm not sure. Ask a psychologist or something. :)
Make it enjoyable
IMO, the most effective ways to get someone to start learning is to: (1) make it feel possible by providing them simple, doable examples that they succeed in, (2) show a good example person to look up to, and (3) to offer a time, place and means to practice the thing and excel in it.
How do you do this with music theory, if it's taught theory-first? I have no idea! IMO it has to be practice first. The things, in this case concepts of tonality, have to have an immediate practical use that feels good. And that is: playing songs by ear! (And then, making modifications to them by ear - though I'm not sure if everyone enjoys that sort of messing around with songs which are almost sacred things. Many people have a weird preconception that songs should be played correctly, which is, exactly like it's on the famous recording everyone knows.)
For example, why I learned tonality as a kid - I loved to play songs by ear, as chords and melody. It felt much better than listening to radio or something. A good song was even better if I could play it myself. First it was 3-4 chord songs in simple keys like C/Am, F/Dm and G/Em. Then it got more and more complicated and I expanded to all keys one by one. Add borrowed chords, modulations, modes, altered chords, ambiguous harmony like dim7 chords, tritone substitutions ... for most of that stuff I didn't even know the proper names. Like "dorian mode" - it felt weird that there was such a pompous fancy name for such a simple thing. There was always some song that had a trick I didn't know yet, so there was (and is) no maximum level to achieve. I also had a place and practical situations to actually perform, in school, in church, at home, family get-togethers ... accompanying songs and playing small solos. Every time I played anything, I imagined an audience or band or other "real" situation together with other people. I knew it was pop and not fancy classical music, but I didn't care, it all just somehow felt like the right and proper thing to do. And I think it hasn't changed, I think nobody opposes singing songs?
Provocation (probably a bad idea)
This is probably a bad idea, but just to explain the idea through a "warning example":
If you don't understand tonality at all, what kind of a musician are you? A robot that cannot play even a single note without someone else writing the note for you. In my very subjective opinion, being mentally tied and handicapped like that is simply pathetic. An "artist" who cannot express herself. Ok, if your thing is to spend your musical life repeating what is written for you and do exactly as you're told, then ... "fine". Though I don't think that's really fine at all. Wouldn't it be kind of nice to even know a little bit of how the things work? Isn't there something wrong, if you don't know what you're doing, if you don't understand the sentences you're being told to repeat?
Maybe that's too negative. It probably won't help saying things like that, unless you can provide a readily available way to try something better. Probably not even then. You don't have to motivate a dog to give up the bone he's chewing, if you give him a steak instead. (Imaginary example, I know nothing about dogs)
Final Words
Remember that trying to add extrinsic motivation may have the exact opposite effect of what it tries to achieve. If the student isn't shown, if she doesn't experience first-hand, in practice, how the concepts of tonality are used to achieve something "cool", in a way that she can replicate, then there's not much you can do. (And I also think that if the concepts are taught top-down, theory-first, to people who don't practice playing songs by ear, then it's taught wrong.)
Comment: I think provocation might be harmful, but the connection between music theory and expression / self-improvement is a good point to make.
Comment: I object to your statement that "If you don't understand tonality at all, what kind of a musician are you? A robot that cannot play even a single note without someone else writing the note for you." You can play entire pieces by ear without knowing whether any of the pieces are atonal or have keys. I personally haven't figured out all the key signatures of some of the pieces I want to transcribe myself (mainly ones with fleeting key changes).
Comment: @piiperiReinstateMonica - I understand tonality, and my understanding of a tonal piece is that it has a focal note and a key of some sort (I personally put modal pieces in keys). But I've also listened to and sung (or attempted to sing) enough atonal music that I strongly believe that people can simply match what they play to what they hear in their head and therefore play music by ear without ever figuring out whether the music they play is tonal.
Comment: @piiperiReinstateMonica - Yes, that's the belief I've developed based on my experience singing atonal music without sheet music. I still heavily depend on the recording in my head to sing atonal music, as I pitch-match my singing to the recording as closely as possible (including tempo), and I can only transpose those pieces extremely slowly - or else very inaccurately - on the fly. I do not believe I am the only person to learn music by ear this way. (I can figure out the key of an excerpt of music on first listen, so I can skip pure pitch-matching for them.)
Comment: @Dekkadeci I deleted my comments/questions about the atonal stuff, I can't really see the relevance, because atonal music feels like an edge case in the context of this question. But thanks for the insight, I had never thought about the possibility that a person could at least in theory approach music like that.
Answer: As noted by other answers and comments, "tonality" can have a lot of meanings.  But I assume in the context of the question that what we're getting at is something more like "musical structure."  Why is it important to know about musical structure?
And the best answer I can give to someone who is a relative beginner in music is to compare it to something else that might be more familiar.
For example, consider reading a poem.  To make the analogy a bit better, consider that you are learning to read poems aloud, to perform them (as you might perform a piece on a piano).
But suppose that you didn't know what any of the words meant.  Imagine it was a poem in another language, and you were trying to read it aloud in a convincing fashion.  It would be quite difficult, no?  But it could be done perhaps by teaching the phonetics of the language, so all you understood were the raw sounds and were able to transmit those letters on the page into sound.  But you made no connections between those letters, no sense out of the words that connected them.
There would be a lot that you would miss.  It would be more difficult to speak expressively if you didn't know the meaning of the words.  It would be more difficult to see patterns in one poem and how they might connect to other poems.  You might feel the rhythm and sense something about the rhyme scheme, but anything deeper would be a mystery.  Why is there a comma there instead of a period?  Why does this poem use a lot of short words, compared to average -- is it expressing something with those quick monosyllabic word choices?  Why does this other poem seem to have lots of long words. fewer pauses, and long meandering stanzas?  Why does this sort of word keep showing up, except with variations in its form (but since you know nothing about meaning or even grammar, it's unclear what's going on)?  And how does one know which words are more important, which words might be surprising or confusing?  How would your reading change if you understood these elements of meaning?
I truly think looking at a piece of music with no understanding of the underlying theory is similar to this idea of reading a poem without comprehending the words.  Instrumental music may not have a particular meaning (as a poem does), but it has a structure.  Tonal music is often organized into motives and gestures, which are organized into phrases, which get organized into "sentences" and "periods," which form larger sections.  There's a logic and reason behind how many of these elements relate to each other, why they come in the order that they do, when they create a "surprise" by doing something against expectations, etc.
One can pick up on many musical patterns intuitively with a lot of experience, but an understanding of tonal structure can be a shortcut to seeing many of these patterns.
I'll just conclude with a reaction to one particular quote from the question:

the reason she gives is that knowing about tonality can only be useful
  to those who compose musical pieces, while for those who play all the
  necessary informations are given on the music sheet.

Again, I think saying the "necessary information" is all on the music sheet is like saying, "I can sound out the words of the poem, so therefore I can read it."  Music comes with a broader set of expressive marks than poetry does, so there is a lot more information to help you perform the music, even if you don't understand what it's doing or why it's doing it.  Still, it's harder to be a strong performer if you don't get the meaning of the music, which is aided by understanding various elements of its structure.
Because while music has expressive marks, there's also a lot of implicit understanding for things that are obvious in, say, a poem.  For example, a poem tells you where the end of a thought is or where a question occurs through use of punctuation.  But there's often no equivalent signal in musical notation about the end of a musical thought (phrase) or the signal of an incomplete musical thought (half cadence).  To recognize those basic elements, equivalent to the punctuation of a poem, one needs to have some recognition of things like chords and tonality.
But I'd also react strongly against the first part of that quoted statement: all good piano students should learn to make their own music at some point.  Improvisation, for most of history of keyboard instruments, was a common skill.  One doesn't have to be a composer to appreciate how to put music together on a basic level.  Furthermore, I'd make the comparison here to learning a foreign language too.  Some people try to learn a language only by reading it -- by staring at the words on the page and translating what others have done.  But it's widely recognized in language pedagogy that one learns best by creating and imitating, by trying to create your own sentences and talking to other people.  It's a lot harder (if not impossible) to become fluent by merely reading what other people have created.  Instead, you learn a lot faster and come to a much greater understanding of a language by trying to do it yourself.
The goal, however, is not to become a poet or an orator in the foreign language.  It's just to casually understand it and be able to make up your own utterances that make sense.  Similarly, the goal in music study isn't to become a composer (for most people), but being able to understand what it's doing at a glance and to be able to make up your own casual improvisations is an incredibly useful exercise for learning.
Answer: I could tell you many reasons why the concept of tonality and theory is important and helpful for musicians and especially for pianists.
It is actually possible to push down the keys following the notes of a sheet without having an idea of tonality, but this is not the purpose of a musician.
The question - not only in music - is: do you want to know what you are doing and understand what you do or do you just want to follow blind the rules and orders of others like a slave?
Tonality and the key are the most important basic concepts of the theory of traditional western classic and also pop music. Theory is nothing else than reflection about practice.

If you understand the scales, keys, chords and chord progressions you will have a great advantage in reading and playing music, and playing by heart, memorizing a piece and also when performing or for improvisation.
Pianists seldom play just for them selves, they play with others, accompanying a singer  or instrumentalist. It will be necessary to be able to transpose a song or an accompaniment in a different key.
Transposing and reduction of harmony are my daily bread when learning a new piece. Knowledge of keys, chords, functions and understanding the tonality are prerequisites to do so.

Probably you've heard someone saying: this child is very gifted, he is playing  very musically: Tonality is just another aspect for saying "he plays with feeling" ...
Edit:
When I reread this part of your question

Aber ich könnte ihr kein besseres Argument geben als: "Der Begriff muss wichtig sein, denn erleuchtete Musikamateure geben gewöhnlich die Tonalität eines Musikstücks an, wenn sie sich auf dieses Stück beziehen."

I have to assume that the point is just to learn and understand in which key a piece is written, as most titles contain the key tonality. So the piano teacher asks the students that they have to know the key assignments when he speaks about tonality. Knowing the sharps and flats, their function and relationship to the tonality, understanding their role when playing chords or scale passages will help a beginner to avoid mistakes when reading sheetmusic, failures you will hear when she is playing. Next step will be the circle of fifths!
Answer: You could use a foreign language metaphor.
A person can phonetically read some words in a foreign language, but have no idea the meaning of what they are saying. Importantly, accent and articulation can be handled poorly when "reading" a language you don't understand.
Tonality is like the grammar and vocabulary in the language of music. To understand tonality is to understand the musical meaning of the chords and scales in a piece of music. Understanding tonality let's you play with musical understanding.
On the practical side understanding tonality will aid with pattern recognition and understanding musical structure which aid memorization. Basically you can "chunk" parts of music into memory along tonal lines.


How do I call a JavaScript function from my code behind, the function being on a separate .js file?

Question: Code behind:
protected void Page_Load(object sender, EventArgs e)
{
      Page.ClientScript.RegisterClientScriptBlock(GetType(), "MyKey", "CreateNotificationTree(" + UserId + ")", true);
}

.js file:
function CreateNotificationTree(UserId)
{
    var data = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: "../api/notifications/byuserid/" + UserId,
                contentType: "application/json"
            }
        },
        schema: {
            model: {
                children: "notifications"
            }
        }
    });

    $("#treeview").kendoTreeView({
        dataSource: data,
        loadOnDemand: true,
        checkboxes: {
            checkChildren: true
        },
        dataTextField: ["notificationType", "NotificationDesc"]
    });
}

Markup (do I need this?):

This is not working. The treeview does not get loaded on the page.
Comment: http://stackoverflow.com/search?q=call+javascript+code+behind
Comment: The duplicate mentioned here doesnt help me 1 bit.
Comment: Try removing your function call from aspx page.Because from your code-behind you are already calling the function on page_load event.
Answer: In your script block you are not assigning CreateNotificationTree to be called on $(document).ready, but call it right there. The correct way is:

Then you don't need RegisterClientScriptBlock in Page_Load.
The second option is not to use $(document).ready, but call RegisterStartupScript (which writes script at the bottom of the page, when all DOM elements are available) instead of RegisterClientScriptBlock in Page_Load.
Answer: Use
ClientScriptManager.RegisterStartupScript


Constrain null space basis to make its components absolute values equals

Question: Let:
\begin{equation}
\mathbf{A} = \begin{bmatrix}
0.8 & 0.4 & 0.4 & 0.8\\
0.4 & 0.8 & -0.4 & -0.8
\end{bmatrix}
\end{equation}
We can find a null space basis of $\mathbf{A}$ whose vector's components absolute values are (at best) equals by combining its columns and trying to produce zero. If it is not possible that all components are equals, a maximum number of them should be.
\begin{equation}
\mathbf{x} = \begin{bmatrix}
1 & 1 \\
-1 & -1 \\
1 & -1 \\
-1 & 0 \\
\end{bmatrix}
\end{equation}
This is done by hand on a simple matrix. Is there a way to calculate (if it exists) in a systematic way a null space basis for which the absolute values of the vector's components are equals, for an arbitraty matrix?
Comment: I don't understand what you mean by "whose vector's components are equals".  When we are asked for the null space of a  matrix we are given only the matrix, not a vector.  The vectors in the null space may or may not have "all components equal".
Comment: I edited my question (the absolute values of the components should be equal). I mean that the components of the vectors of the basis have equal absolute values. Whether it is possible to find it or not is the entire question, but if not, the maximum number of components  of each vector should be.
Answer: The null space of $\begin{bmatrix}0.8 & 0.4 & 0.4 & 0.80  \\ 0.4 & -0.4 & 0.8 & -0.8 \end{bmatrix}$ is the space of all vectors $\begin{bmatrix} a \\ b \\ c \\ d \end{bmatrix}$ such that
$\begin{bmatrix}0.8 & 0.4 & 0.4 & 0.8 \\ 0.4 & -0.4 & 0.8 & -0.8 \end{bmatrix}\begin{bmatrix} a \\ b \\ c \\ d \end{bmatrix}= \begin{bmatrix}0.8a+ 0.4b+ 0.4c+ 0.8d \\ 0.4a- 0.4b+ 0.8c- 0.8d\end{bmatrix}= \begin{bmatrix}0 \\ 0\end{bmatrix}$.
So we have 0.8a+ 0.4b+ 0.4c+ 0.8d= 0 and 0.4a- 0.4b+ 0.8c- 0.8d= 0. if we add the two equations we get 1.2a+ 1.2c= 0 so c= -a. If we subtract the second equation from the first we get 0.4a+ 0.8b- 0.4c+ 1.6d= 0.8a+ 0.8b+ 1.6d= 0 so b= -2d- a.  We can write $\begin{bmatrix} a \\ b \\ c \\ d \end{bmatrix}= \begin{bmatrix}a \\ -2d- a \\ -a \\ d \end{bmatrix}= a\begin{bmatrix} 1 \\ -1 \\ -1 \\ 0 \end{bmatrix}+ d\begin{bmatrix}0 \\ -2 \\ 0 \\ 1 \end{bmatrix}$.
The null space is the two dimensional space with basis $\begin{bmatrix} 1 \\ -1 \\ -1 \\ 0 \end{bmatrix}$ and $\begin{bmatrix}0 \\ -2 \\ 0 \\ 1 \end{bmatrix}$.
Comment: Thank you for your answer. This does not answer the question though, as I'm asking for a generic method that would constrain the null space basis in a certain way: equal absolute values of all the components of the basis's vectors, and if not possible, a maximum number of component's absolute values should be equal, as in the basis found in the question formulation


Writing field $F$ as a disjoint composition of subfields

Question: Let $K/F$ be a field extension with $char(F)=0$ and degree $n>1$ - a composite number.
Can we always write $K = F_1 F_2$ when $F_1 \cap F_2 = F$ ?
Comment: Can you do this for $\mathbb Q(\sqrt[4]2)$? No intermediate  field of degree 2 other than $\mathbb Q(\sqrt 2)$ comes to my mind.
Answer: Well, a trivial solution would be taking $F_1 = F$ and $F_2 = K$. But there are examples where this is really the only possibility. For example, if $K/F$ is a Galois extension with Galois group $\mathbb Z/p^m \mathbb Z$ for a prime $p$, then the intermediate fields are linearly ordered by inclusion. If $F_1,F_2$ are two intermediate fields, w.l.o.g. $F_1 \subseteq F_2$, then $F_1 \cap F_2 = F_1$ and $F_1F_2 = F_2$. Therefore, the only possibility to have $F_1 F_2 = K$ and $F_1 \cap F_2 = F$ is choosing $F_1 = F$ and $F_2 = K$.


How to run AnnotationProcessor in IntelliJ IDEA?

Question: I created simple Annotation processor in  IntelliJ IDEA, added annotation profile, but I'm not understand how to run it.
I know that annotation processor works in compile time, but I didn't see any messages from Annotation processor messenger in output.
<code>public class SimpleAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {

    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,"hello");
    for (final Element element : roundEnv.getElementsAnnotatedWith(Immutable.class)) {
        if (element instanceof TypeElement) {
            final TypeElement typeElement = (TypeElement) element;

            for (final Element eclosedElement: typeElement.getEnclosedElements()) {
                if (eclosedElement instanceof VariableElement) {
                    final VariableElement variableElement = (VariableElement) eclosedElement;

                    if (!variableElement.getModifiers().contains(Modifier.FINAL)) {
                        **processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                                String.format("Class '%s' is annotated as @Immutable," +
                                                "but filed '%s' is not declared as final",
                                        typeElement.getSimpleName(), variableElement.getSimpleName()));**

                    }
                }
            }
        }
    }

    return true;
}
</code>
}
Answer: Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors -> Enable Annotation Processing.


Dados repetidos com GROUP_CONCAT

Question: Estou com um problema quando eu faço um SELECT no meu BD, estou usando GROUP_CONCAT para concatenar a coluna de telefones e email mas estou pegando dados repetidos.
Aqui está o SELECT:
SELECT contatos.cont_id
     , contatos.cont_firstname
     , contatos.cont_lastname
     , contatos.data_nasc
     , contatos.anotacoes
     , GROUP_CONCAT(contatos_email.email)
     , contatos_telefone.telefone
     , contato_endereco.rua
     , contato_endereco.numero
     , contato_endereco.bairro
     , contato_endereco.cidade
     , contato_endereco.estado
     , contato_endereco.pais
FROM contatos
JOIN contatos_email ON contatos.cont_id = contatos_email.contato_id
JOIN contatos_telefone ON contatos.cont_id = contatos_email.contato_id
JOIN contato_endereco ON contatos.cont_id = contato_endereco.contato_id

na coluna em que esta sendo exibido os emails era para aparecer apenas 3 emails e não ficar repetindo como esta agora...
Comment: Amigo, adicione um exemplo de como os dados estão sendo retornados atualmente e como você deseja que seja o resultado final.Facilitará o entendimento de sua questão.
Comment: Você está usando `GROUP_CONCAT` sem fazer `GROUP` ou qualquer função de agregação. O que pretende que aconteça?
Comment: @Bacco deu certo fiz como você disse coloquei o GROUP_CONCAT( DISTINCT contatos_email.email) e funcionou Vlw :)
Comment: pronto editei a pergunta... Agora acho que da pra entender melhor :)
Comment: Tentou `GROUP_CONCAT( DISTINCT contatos_email.email )`? Qual é o servidor de DB que está usando?
Comment: estou usando o maria db no phpmyadmin
Comment: Bom que resolveu. Como vc já postou a solução, marque como resolvida no V verdinho do lado da sua resposta, para a postagem ficar completa.
Answer: A solução foi essa
SELECT contatos.cont_id,
contatos.cont_firstname,
contatos.cont_lastname,
contatos.data_nasc,
contatos.anotacoes,
GROUP_CONCAT(distinct contatos_email.email),
GROUP_CONCAT(DISTINCT contatos_telefone.telefone),
contato_endereco.rua, contato_endereco.numero,
contato_endereco.bairro, contato_endereco.cidade,
contato_endereco.estado, contato_endereco.pais
FROM contatos
LEFT JOIN contatos_email ON contatos.cont_id = contatos_email.contato_id
LEFT JOIN contatos_telefone ON contatos.cont_id =  contatos_email.contato_id
LEFT JOIN contato_endereco ON contatos.cont_id = contato_endereco.contato_id
group by contatos.cont_id

Dados repetidos com GROUP_CONCAT


Numbering the content list in drupal (as simple as it sound) - possible via the UI?

Question: Went through the conf and the Drupalsite > Content page but couldn't find any where to number the list (or at least to get a nubmer of all contents of all entities and types - including Views, Panels, Webforms, ETC).
Would thank you for showing a simple way for numbering this list \ get a content-total number.
Here is the picture of my natural display of the content page... Thanks, Ben.
Comment: What would the numbers represent exactly (bearing in mind you can filter that list)? One option would probably be [Admin Views](https://www.drupal.org/project/admin_views), it'll convert that page to a View which you can manipulate to provide totals/numbering etc
Comment: The number of items in relation to the filtering... Can you think of a lighter option than a module (Does the module makes everything automatic?).
Answer: Looks like you might be looking for number of nodes by content type (among other things). If that's the case then you may want to consider the Charts module. It comes with a sample view that gives you both a tabular overview and a chart of these numbers.
The (accepted) answer to the question Views and node count for taxonomy terms contains another (views) based example.
The question Count of nodes by type contains some code snippets that may help to write your custom module to calculate these counts.
If you don't want to install/enable the Charts module permanently, you may want to temporarely enable it to (eg) look at the view for the tabular format display, and then create a clone of that view to perfectly fit your needs (and then uninstall the Charts module again). Of course the "Views" module is yet another module. But it's rare to find a site that does not use the views module, so that's maybe an acceptable compromise to consider (you might have Views available already)?
Comment: Is there any non-modular way (maybe even adding something in the PHP template of a relevant core module?
Comment: I do have views installed and use it for several purposes... Is there maybe a simpler way even than views-based modules? Even a simple content pieces counter (with an option to filter entities\publish mode) could do the trick, I just don't want to counter manually.


How do you keep convex string instruments from slipping?

Question: I have been playing the guitar for many years and I recently got myself a traditional Greek instrument to play with (image source):

Pictured above is a μπαγλαμάς (baglamas) and though mine is unfortunately nowhere near as pretty, the shape is the same. The problem is that because of the convex sound box, when placing it on my lap to play, it gradually slides away from me. I am guessing I have some habits that come from my guitar and that these don't translate well to the convex instruments.
So, what tricks do people use to keep convex instruments stable?
Comment: You may want to seek out someone who plays the instrument and study.  Alternatively, it would also be not a bad idea to use the power of the internet to see how native players hold the instrument.
Answer: I know a balalaika and domra orchestra where almost everybody holds their instruments in place using cut pieces of a common type of non-adhesive non-slip rubberized shelf-liner material, like that in this photograph.

You can buy a roll of this for a few dollars in any grocery or hardware store.
I have used this material myself when I was learning how to hold my new bass viola da gamba in the proper position between my thighs and calves. (the viola da gamba's body is similar to the cello but it has no end-pin to rest on the ground.) But after some practice, I can hold the instrument in the proper position without needing the grippy rubber material.
By the way, I would hesitate to leave this material in contact with a musical instrument for a long period, such as while storing the instrument in a case. I worry that, long-term, the rubbery material might decompose and adhere to or damage a wooden instrument's lacquer finish. But all indications are that this material is perfectly safe for use while the instrument is on your lap.
Update
I remember now that some of my acoustic instrument-playing friends use a loose piece of rough-milled suede leather, which might provide some "traction" due to the rough texture. Suede seems to be most popular with violinists or violists who want some extra cushioning between their instrument and the chin or collarbone, but I think other musicians also use it to help position an instruments on the lap as well.
I went looking for examples of this in photos on the Net but couldn't find anything suitable.
Comment: Heh, this is a good workaround, +1. I suppose once you've used this for a while you get used to it and get the right posture.


Razor function to get image path from action

Question: I'm developing a method to display the photo of logged user in a layout page.
It looks like the method is fine, and returns for me the image path, but I don't know to make it works on , or I can do it with some razor function?
If I call my method from url like http://localhost:29469/User/LoadPhoto, it returns the correct path.
The layout is not typed, so I can not display it like Model.Attribute
public ActionResult LoadPhoto()
{
    if (User.Identity.IsAuthenticated)
    {
        var userStore = new UserStore<User>(new ERPIdentityDbContext());
        var userManager = new UserManager<User>(userStore);

        var xUser = userManager.FindById(User.Identity.GetUserId());

        string xPhotoPath = HttpContext.Server.MapPath(@"~/Images/Users/") + xUser.FotoPath ;
        return Content(xPhotoPath);
    }

    return View();
}

I want to use return for LoadPhoto method in
Answer: If your photos are JPGs, return a File ActionResult with the image/jpeg content type:
string xPhotoPath = HttpContext.Server.MapPath(@"~/Images/Users/") + xUser.FotoPath ;
return File(xPhotoPath,"image/jpeg");

Comment: @LeandroLemos no problem, you can mark this as the answer if you'd like.


c#, wpf, Dynamically naming controls

Question: How do i create a new Button/Canvas with a dynamic name?
Button {buttonname read from text file} = new Button;

I have googled this for a while now but i can't find the solution.
Thank you!
Comment: Are you have list name?
Comment: What list name do you mean? if i create a list<> it will solve my problem?
Comment: you want setting name of control, same that : var button = new Button(); button.Name = "test".  Right?
Answer: I'm not sure if I understood correctly, but that name in your example is not the button name, it's just the reference name used in code to access the button. The button name would be set like this:
buttonRefName.Name = "ButtonName1";

So you can set the name to whatever you want: dynamically generated names inside a loop, names read from a file, etc...
You can use the same reference name for multiple buttons, just be sure to add it to List or to WPF Window, Panel, etc... before creating the new one:
var buttonList = new List<Button>();
var buttonRef = new Button { Name = "YourButtonName" };
buttonList.Add(buttonRef);
buttonRef = new Button { Name = "YourButtonName2" };
buttonList.Add(buttonRef);

Comment: The problem is, i dont know how many buttons there might be, so i can't (?) point to them later on.
Like click event get cant point to "YourbuttonName" + i (where i is usual counter), can it?
Comment: Not sure I understand what you mean, but you can point to them later. You can search the list using the button name to get a reference to the Button you want. Or you can attach the same click event to the button before creating the new one, and in the method you'll get the sender of the event. You can cast it to a Button and verify the name.
Answer: It not possible the way you want to do it. If you are reading from a text file better use a List or better a Dictionary... an example use is as follows:
var buttons = new Dictionary<string, Button>();
buttons["yourName"] = new Button();
// logic goes here

Comment: How can i reach that button later on?

c#, wpf, Dynamically naming controls


Confidence interval for difference of means for TukeyHSD vs two-sample t-test?

Question: I have some data with categorical predictors and I'm wondering about comparing the confidence intervals of difference in means of one pairwise comparison in my TukeyHSD analysis vs that of a two-sample t-test. Which one will have a wider confidence interval and will it always be that way for every pairwise comparison?
I just don't understand what's happening, doesn't a lower p-value mean a wider CI? And if so, then why would we be able to expect TukeyHSD to have a wider/skinnier CI if the p-value for each pairwise comparison in TukeyHSD seems to be either high or low? TukeyHSD adjusts for the probability of making type 1 errors. Bonferroni requires a lower P-value for each individual comparison to lower the family-wise error rate which I assume Tukey does as well, so if the p-value goes down, shouldn't the CI go up?
My CI's for the pairwise comparison $D-C$ for example were:
TukeyHSD: $(-16.8, -4.93)$ and
Two-sample t-test: $(-14.91,  -6.82)$
So the CI for the TukeyHSD was wider. Why and will it always be like this?
Comment: The phrase "higher CI" is not standard and can be interpreted in various ways.
Comment: It would help to show an example with values and calculated confidence intervals so it is clear what you are asking.
Comment: @HarveyMotulsky How about wider?
Comment: But the Tukey confidence intervals apply the 95% (or whatever) confidence level to an entire family of comparisons, not to a single comparison. So the two intervals are not really comparable.
Answer: Looks like in your example t-test interval is not adjusted for multiplicity. The quote in bold implies that Bonferroni-adjusted t-test interval would be wider that TukeyHSD's - it's because Bonferroni's procedure is more crude. But indeed, without any adjustment at all t-test interval would be narrower than with smart adjustment by HSD. So raw t-test interval size < TukeyHSD's < Bonferroni-adjusted t-test interval.


How do I pass XML data as a PAYLOAD on the stream?

Question: I'm new to XML, and usually use JSON to pass data. I am working with a new system, and this was part of their instructions to me about passing data:

The XML content then can be sent as either PAYLOAD on the stream or as an additional parameter.  If the latter is done, the parameter name is RequestXML

I'm not sure what this means? I'm afraid if I pass it as a parameter, but I have a lot of text, it will make the URL too long, so I'd like to do the PAYLOAD option. I'm using PHP and Jquery to generate the array. I can create an XML file using PHP and have it properly formatted as XML, but sending it across is confusing me.
What do I need to do to get it sent as a PAYLOAD?
Comment: what is the **system** ??
Comment: It's a system written in Java I believe. Warehouse Management System.
Answer: You'll likely just want to send a POST HTTP request.  Here's an example using the curl library:
<code><?php
$url = "https://example.com/service";
$xml = "<foo />";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
?>
</code>
Comment: Had to test it, sorry for the late reply. This worked just fine.


Issues with Term Reference and Multilingual Taxonomy

Question: The issue:

We have a multilingual Drupal 7 website which allows users access to a content type e.g. Blog - where they can use /node/add/blog and node/*/edit in their chosen language
A taxonomy has been created called category which has been set to 'Localize' under MULTILINGUAL OPTIONS >> Translation mode
Terms listed under category have been translated to FR, DE, NL etc.
On the content_type Blog - a term reference has been set up to reference the category taxonomy, with a select list widget being used.
When visiting e.g. www.multilingual-site.com/node/add/blog (default site language is EN) - the dropdown list shows all the terms.
When visiting e.g. www.multilingual-site.com/fr/node/add/blog or any other language e.g. /de/ or /nl/ etc the dropdown list is blank - the translated terms do not appear.

In an attempt to create the option list ourselves - using hook_form_alter() with taxonomy_get_tree($vid) as suggested here https://drupal.stackexchange.com/a/64666/5253 - when trying to dpm the output
the array is empty for every language other than the default EN.
Can anyone offer any direction? Thanks
Answer: Turns out we needed to unselect 'Select taxonomy terms by language' - found admin/config/regional/i18n/select - hope this helps someone. More reading at: https://drupal.org/node/1868418 #2


Calculating fluxes in local Lax-Friedrichs FVM for shallow water problem

Question: so I have a more programming and some applied maths background, but absolutely none in FVM or Fluid dynamics. I have to implement a solver using the local Lax-Friedrichs method, and so far kinda-so-good. But I got stuck in calculating the fluxes (F and G) in the following Finite Volume solver equation:
$$U_{i,j}^{n+1} - U_{i,j}^{n} = \frac{\Delta t}{\Delta x}[F(u(x_{i+\frac{1}{2}},y,t))-F(u(x_{i-\frac{1}{2}},y,t))] + \frac{\Delta t}{\Delta y}[G(u(x,y_{i+\frac{1}{2}},t))-G((x,y_{i-\frac{1}{2}},t))]$$
The original differential Equation(which neglects a lot of forces) is as follows:
$$\frac{\partial}{\partial t}\begin{bmatrix}h \\ hu \\ hv \end{bmatrix}+ \frac{\partial}{\partial x}\begin{bmatrix}hu \\ hu^2 + 0.5gh^2 \\ huv \end{bmatrix}+ \frac{\partial}{\partial y}\begin{bmatrix}hv \\ huv \\ hv^2 + 0.5gh^2\end{bmatrix} = \begin{bmatrix} 0 \\ -\frac{\partial (ghb)}{\partial x}\\ -\frac{\partial (ghb)}{\partial y}\end{bmatrix}$$
Where:
b is the depth at a point
h is the distance from the bottom of the body of water till the lowest point of a "wave"
hu is one wavelength of a propagating wave\
I hope I explained it thoroughly, to sum up, I sort off understand what needs to be done, but I am having troubles on how to calculate the values of the fluxes to be used in the FV formula.
Answer: Rewrite the PDE as follows:
$$\frac{\partial}{\partial t}U+ \frac{\partial}{\partial x}F(U)+ \frac{\partial}{\partial y}G(U) = 0$$
where
$$
U = \begin{bmatrix}h \\ hu \\ hv \end{bmatrix},\quad
F(U) = \begin{bmatrix}hu \\ hu^2 + 0.5gh^2 + ghb \\ huv \end{bmatrix}, \quad
G(U) = \begin{bmatrix}hv \\ huv \\ hv^2 + 0.5gh^2 + ghb\end{bmatrix} .
$$
The 2D local Lax-Friedrichs (LLF) method can be derived from these expressions, see this document. The scheme reads
$$
U_{i,j}^{n+1} = U_{i,j}^n - \frac{\Delta t}{\Delta x}\left(F_{i+\frac12,j}^n - F_{i-\frac12,j}^n\right) - \frac{\Delta t}{\Delta y}\left(G_{i,j+\frac12}^n - G_{i,j-\frac12}^n\right)
$$
where the LLF numerical fluxes are given in the linked document p. 33.
Comment: Thanks, Very helpful, Follow up question: If the flux is a scalar value(which I think it is), how to we calculate it given that the F(U) and G(U) functions have 3 components to it? Using the formulae in the referenced document on page 33.
Comment: @Ian Answer edited! I believe that unknowns $U$ and fluxes $F$ are also assumed vectors, since they introduce the signal speed $\lambda^x_{i+1/2, j}$ in $x$-direction as *the maximum Eigenvalues of the flux Jacobian* $\partial F/\partial U$. Differentiating the flux vector $F$ w.r.t. to the vector $U$ gives a Jacobian matrix, of which we can compute the eigenvalues.
Comment: Thanks, It is starting to fall into place! If I suddenly develop an extra question to this, should i edit my original question,or post new?
But a short question otherwise, if the fluxes F and G are vectors, then the 1st component is used to update h, the second to update hu, and the last to update hv?


Difference between python2 and python3 in the decode function

Question: Recently, I watched a video about writing a code to decode the title and contents of the file from decimal numbers into strings. However, it is written in python2 so I decided to rewrite the code in python3. Unfortunately, I am having trouble in decoding the contents of the picture.
This is the original code in python2:
#!/usr/bin/env python

import os

directory = '1262404985085867488371'

def decrypt(number):
    return hex(int(number))[2:].replace("L","").decode("hex")

os.chdir(directory)
for i in os.listdir('.'):
    try:
        print(decrypt(i))
        c = open(i).read()
        open(decrypt(i),'w').write(decrypt(c))
        #o.write(decrypt(c))

    except:
        print("FAILED WITH",i)

And this is the code written in python3:
#!/usr/bin/env python3

import os

directory = '1262404985085867488371'

def decrypt(number):
    hex_num = hex(int(number))[2:].replace("L","")
    return  bytes.fromhex(hex_num).decode("ascii")

os.chdir(directory)
for i in os.listdir('.'):
    try:
        print(decrypt(i))
        c = open(i).read()
        open(decrypt(i),'w').write(decrypt(c))
        #o.write(decrypt(c))

    except:
        print("FAILED WITH",i)

Can anyone help me to have a look how can I solve this problem? This is the problem about:

My computer got infected with ransomware and now none of my documents are accessible anymore! If you help me out, I'll reward you a flag!
  https://static.tjctf.org/7459b0c272ba30c9fea94391c7d7051d78e1732c871c3a6f27070fcb34f9e734_encrypted.tar.gz

Basically, I have tried by changing the ascii into utf-8 and open the file with the mode in "wb" or "rb" but neither of them works...
Comment: no worries, thanks. but that link is protected by username and password, so we cannot see what you see, the picture, or the problem description or contents.
Comment: do you get any errors? if so, please include them.
Comment: If you can include any other information so we can reproduce the problem would be helpful, for example [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: the edit to your code capitalizing `directory` variable does *not* improve code formatting. python syntax encourages lower-case variables.
Comment: @davedwards Alright. Thanks. This is my first time using stack overflow so I am not too familiar on the syntax yet. Btw, I have reedited to provide the source of my problem.
Comment: Alright. Let me try to post the questions and the link over here!!
Comment: ok, just be sure not to post any private or secure information. thanks.
Comment: Ok. This is just a computer security challenge competition held by a high school that is opened to public through online.
Comment: I don't know much about the problem you are facing, but when I extracted that `tar.gz` file you linked to, there is a file `HAHAHA.txt` which includes `"All your files have been encrypted with a uncrackable algorithm.
You are now screwed forever."`. Do you really think this is a safe challenge? I would be very careful. especially since your question includes `"My computer got infected with ransomware "`
Comment: Yeaa definitely. Basically the title of the files and the contents of the files have been encrypted into decimal numbers. And my code is aimed to decode it to strings.
Comment: Ok cool, just making sure.
Comment: There is 1 video writeup for the challenge. https://www.youtube.com/watch?v=m9FuGso8BE8
Comment: Hm, interesting. It doesn't produce any errors for me, so far I only get empty files. It seems like it's related to [Decode Hex String in Python 3](https://stackoverflow.com/questions/3283984/decode-hex-string-in-python-3), or [Convert(decode) hex string to ASCII or any other understandable format](https://stackoverflow.com/questions/29547104/convertdecode-hex-string-to-ascii-or-any-other-understandable-format), but I can't solve it yet, will keep trying and update with any success.
Comment: Yeaa, it does not produce any error for me also. Basically, I got empty files when I compiled using the python3 code but I got the image files when I compiled using the python2 code. I am thinking maybe the problem is on the writing the byte object or whatever into a file because the decrypt function actually works fine with the name of the file. It only fails during writing the conversion into the contents of the file.I have tried to debug my code and I found out the problem is on this line when the decrypt function is called with the c as the argument.
open(decrypt(i),'w').write(decrypt(c))
Comment: Maybe it is because of the newline or what from the read() function and I tried to replace newline with empty string but it still doesnt work loll...
Answer: I'm going to jump the gun here and since you did not include any examples and\or errors I will guess you got this kind of error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)

This is caused by a file\directory with a unicode name, which in turn triggers this exception when you try to decode with ascii as in decode("ascii").
Instead, try decoding with "utf-8".
Comment: That's great so if you tried something already, include it in the question so we can focus our help instead of taking wild guesses :P
Comment: Actually I have tried with that before but it still doesn't work. I am thinking maybe it has something to do with the byte object.


JQuery - Minha queue não funciona mais de uma vez nessa animação. O que pode ser?

Question: Criei uma função a qual quando o mouse passasse por cima da DIV, ela faria uma animação inserindo e removendo classes. Mas o que eu não entendo é que a animação que está dentro da queue,  só funciona a primeira vez.
Quando passo o mouse novamente, ela não funciona. Tentei até o usar o console.log() pra ver o que era, e realmente, depois da segunda vez, ele nem entrava na Queue.
divTarget2.hover(function(){

       console.log(stats);
       $(this).find('img').addClass('anima-doenca-hover').delay(1000).
           queue(function(){
               console.log('entrou na queue');

               $(this).parent().addClass('anima-caixa-hover');

               console.log(stats);
            });
            soundEffect.play();

}).mouseleave(function(){

        $(this).find('img').removeClass('anima-doenca-hover');

        $(this).removeClass('anima-caixa-hover');

        soundEffect.pause();
        soundEffect.currentTime = 0;
        console.log(stats);

        });

Comment: Quando você tira o mouse, ele retorna ao estado original ?
Comment: Sim, quando eu tiro o mouse ele remove a class e volta o original certinho. O problema é quando eu vou tentar passar o mouse novamente, ele só executa uma das animações, mas a que está dentro da Queue não executa mais.Mas o que eu não entendo, é que de primeira vez que eu passo o mouse ela funciona certinho.
Answer: Uma solução funcional pra isso, seria você adicionar a própria div, eventos do mouse para disparar sua função.

Outra forma seria você transformar seu código em duas partes diferentes apenas com mouseover e mouseout
var time; // Variável para armazenar o temporizador (Necessário apenas para interrompe-lo)

$("#idMinhaDiv").on("mouseover",function(){
    $(this).toggleClass("anima-caixa-hover");
    $(this).toggleClass("qualquer-classe");
    this.time = setTimeout(() => {executaComDelay();},2000); // Executa com delay
    // E suas outras instruções e funções.
});

$("#idMinhaDiv").on("mouseout",function(){
    clearTimeout(this.time); // Para ele executar mesmo com o mouse já saído de cima, remova essa linha
    $(this).removeClass("anima-caixa-hover");
    $(this).removeClass("qualquer-classe");
    // E suas outras instruções e funções.
});

function executaComDelay(){
  // função executada com delay
}

Veja o exemplo -> aqui <-
Comment: Tentei fazer mas ta com o mesmo problema. Porque a parte de chamada do evento ta funcionando certinho, o que está dando errado é na minha primeira função de Hover. Que eu quero que ele execute uma instrução JQuery e logo em seguida outra com Delay, por isso utilizei o Delay e a Queue. Mas o problema, é que quando é passado o mouse pela primeira vez funcionam as duas instruções certinho. Mas, quando o mouse é tirado e é passado pela segunda vez, ele simplesmente executa a primeira instrução, mas a segunda que está dentro da Queue após Delay não.
Comment: Eu mudei o exemplo, dá uma olhada novamente. Pelo que eu entendi, ele não está passando no queue na segunda vez. Tenta mudar a abordagem deste delay. Olha o exemplo que eu fiz.
Comment: Seu console não indica nenhum erro?
Comment: nenhum, creio que seja erro semântico. Mas já resolvi já, troquei o delay do jquery pelo setTimeout do Javascript, e funcionou muito bem.
Comment: Show! Boa sorte em seus projetos! ;)
Comment: vlw cara, te desejo o mesmo!


TreeTable Design

Question: I've got a problem with the sap.ui.table.TreeTable which also occurs for some colleagues.
I had a look at the Fiori Guidelines for the table and I like the style with the arrows which fits the normal SAPUI5 style.
After including the TreeTable in my application, it has a really inapplicable style.
Now my question: How do I achieve the desired look? Am I doing anything wrong or am I missing any additional styles or options?
Infos:

using SAPUI5 1.38.7
used Table: sap.ui.table.Treetable
Controller:
var testModel = new sap.ui.model.json.JSONModel();
    var testData = {
        data:{
            subItems:[
                {
                    name:"NAME 1",
                    subItems:[
                        {
                            name:"NAME 1-1",
                            subItems:[
                                {
                                    name:"NAME 1-1-1"
                                },
                                {
                                    name:"NAME 1-1-2",
                                    subItems:[
                                        {
                                            name:"NAME 1-1-2-1"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            name:"NAME 1-2",
                            subItems:[
                                {
                                    name:"NAME 1-2-1"
                                },
                                {
                                    name:"NAME 1-2-2",
                                    subItems:[
                                        {
                                            name:"NAME 1-2-2-1"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    name:"NAME 2",
                    subItems:[
                        {
                            name:"NAME 2-1",
                            subItems:[
                                {
                                    name:"NAME 2-1-1"
                                },
                                {
                                    name:"NAME 2-1-2",
                                    subItems:[
                                        {
                                            name:"NAME 2-1-2-1"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            name:"NAME 2-2",
                            subItems:[
                                {
                                    name:"NAME 2-2-1"
                                },
                                {
                                    name:"NAME 1-2-2",
                                    subItems:[
                                        {
                                            name:"NAME 1-2-2-1"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    name:"NAME 3"
                },
                {
                    name:"NAME 4"
                },
                {
                    name:"NAME 5",
                    subItems:[
                        {
                            name:"NAME 5-1"
                        },
                        {
                            name:"NAME 5-2",
                            subItems:[
                                {
                                    name:"NAME 5-2-1"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    };
    testModel.setData(testData);
    this.getView().byId("sapEquipmentTree").setModel(testModel,"testModel");

View
<t:TreeTable
    id="sapEquipmentTree"
    rows="{path:'/data', parameters: {arrayNames:['subItems']}}"
    selectionMode="MultiToggle"
    enableSelectAll="false"
    ariaLabelledBy="titleSAPTree">
        <t:toolbar>
            <Toolbar>
                <content>
                    <Title id="titleSAPTree" text="HEADER" />
                </content>
            </Toolbar>
        </t:toolbar>
    <t:columns>
        <t:Column width="13rem">

            <t:template>
                <Text text="{name}"/>
            </t:template>
        </t:Column>
    </t:columns>
 </t:TreeTable>

Thank you for your help.
Answer: With version 1.38, an explicit form factor CSS class has to be set (e.g. sapUiSizeCozy) in order to get the arrow style.
Please see Content Density
Without the form factor CSS, the table Legacy Mode generates the +/- Images only.
As of version 1.40, this should no longer be required and +/- Icons should be replaced.

TreeTable Design


How to update a single value in a Laravel Session Array?

Question: I have a Session array like this:
[
    {
        "itemId": "1",
        "itemQuantity": "3",
        "itemName": "Item_name1"
    },
    {
        "itemId": "2",
        "itemQuantity": "2",
        "itemName": "Item_name2"
    }
]

How can I update the quantity of a single item if I know the itemId?
I know that one way of doing this would be to fetch the whole array, loop through the array, make the updates and 'put' the entire array back into the session.
Is this the only way?
I'm a beginner. Please help out.
Thanks.
Comment: In case you're using the array session driver, that I'm afraid that's the only option.
Comment: What other driver can I use? Thanks!
Comment: Hey there. Out of curiosity, is your `itemId` auto-incrementing? If it is, how did you achieve it?
Answer: Objects are passed by reference so you can simply do this.
foreach(Session::get('cart') as $item) {
    if ($item->itemId == '2') { // say we  want to double the quantity for itemId 2
        $item->itemQuantity = $item->itemQuantity * 2;
        break;
    }
}
dd(Session::get('cart'));

Output:
array:2 [▼
  0 => {#162 ▼
    +"itemId": "1"
    +"itemQuantity": "3"
    +"itemName": "Item_name1"
  }
  1 => {#163 ▼
    +"itemId": "2"
    +"itemQuantity": 4  <<--- the quantity has been doubled
    +"itemName": "Item_name2"
  }
]

Comment: @peterm I'm trying something similar but I'm getting "Trying to get property of non-object" error on line
` $item->itemQuantity = $item->itemQuantity * 2; `
Comment: @peterm yes, I'm just not sure why it happens since my code is based on yours:

`foreach(Session::get('cart.program') as $item){
    if ($item->id == '1xxx') {
        $item->segment_weekday = '9';
        break;
    }
}`
Comment: @peterm var_dump(Session::get('cart.program')):

`array (size=2)
  0 =>
    array (size=1)
      'id' => string '1' (length=1)
  1 =>
    array (size=1)
      'id' => string '1xxx' (length=4)`
Comment: @peterm Thanks for your help. I can access array members, just can't figure out how to pass `$item` by reference `&$item` to save back to session.
Comment: @peterm Created a new question at http://stackoverflow.com/questions/31887608/save-new-value-to-laravel-session-array/31887705#31887705


Is cross-staff beaming helpful or confusing?

Question: I'm writing a fairly simple piano piece which has a repeated pattern which crosses staves/hands. I think it looks clearer musically to write it with cross-staff beaming as in the first bar below, but I suspect that others, particularly those less confident reading music, might prefer the staves to be written separately as in the second bar.

Are there any rules/guidelines for the use of cross-staff beaming? I guess it's partly a matter of opinion, but I do want it to be as clear as possible for a wide range of readers, and as it's a fairly easy piece I don't want to put off less experienced players. If anyone can point me to any hard and fast rules, or something from a grade syllabus, that'd be great. I don't recall being taught about cross-staff beaming myself, but I think it might have confused me as a beginner.
Answer: The notation helps you to see to which voices the notes belong to.
The first measure clearly suggest there are two voices, the top one moving in half-notes and the bottom one playing eight-note arpeggios.
In the second measure you have dotted rhythm melody in right hand and arpeggios consisting of three notes in the left hand. Notice that even the note lengths are different (is the first G in the violin clef supposed to be a half note, or dotted quarter-note?) That's quite different music, isn't it?
See also:

Sheet Music query, a note printed in a bar as half note and quarter note on the same beat
Rest above a note in a piano piece
Why does this note have a stem pointing up and another pointing down?
Comment: @BobsaysreinstateMonica: Even if the upper note is changed to a dotted-quarter in both versions, still a good player would play the two slightly differently, using the articulation and dynamics to make the E sound either like part of the figuration voice with the arpeggio below, or else part of a melody with the G above.
Comment: @Bob Musescore is actually giving you the answer.
Comment: I had to make it a half note for the example to stop musescore showing the rest (you can hide rests for export but it still shows as greyed-out on screen). It should be dotted-quarter really.
Comment: @AndrewLeach how do you mean?
Comment: @Bob Musescore wouldn't allow you to do what you wanted to do. Therefore what you wanted to do was at best unconventional.
Comment: what does "voices" refer to in the context of a piano?
Comment: @srcs voices are independent musical lines. This applies to any instrument or ensemble. This is quite fundamental concept, and if this short explanation is insufficient, I would suggest you to ask a separate question about that.
Answer: I think the two alternatives to consider are...

...cross staff versus ledger lines.
I think using ledger lines is the modern way to do it.
It seems to me that cross staff beaming is found in older scores. This beaming...

...also seems to be an old practice.
Personally, I like those old methods, but it's probably better to follow the modern practice.

EDIT
It seems unclear in the posts on this question how to regard the hands in cross staff beaming. My understanding is the same as this quote from Berklee Contemporary Music Notation, although I didn't learn it from that particular book...

...cross staff beaming is used to make clear phrasing and using a single hand.
Also, it seem worth noting that textbook example uses cross beam to avoid three ledger lines. The OP would avoid only two ledger lines.
Comment: That's interesting. I've often seen cross-staff beaming used to indicate the precise oppostie: that a single voice is split between hands. This was my intention, so maybe I need to rethink.
Comment: Edit: just googled "cross-staff beaming" to see if I could find anyone agreeing/disagreeing with Berklee and this question was the top result! The rest is just a sea of how-tos for finale/sibelius/etc. so not very helpful.
Comment: yes, I was frustrated by the same searching, and felt a bit of confirmation bias in the Berklee book! _Behind Bars_ seems to be one of the most important reference books about notation. Personally, I don't own a copy, but it seems like it's the kind of thing you need.
Answer: These two do not sound the same. The E in the left hand (first example) sounds against the RH G; in the second example, the E stands alone (like a piece of cheese).
Whether one uses cross-staff beaming as in the first example or just writ it with two ledger notes doesn't much matter I slightly prefer the ledger lines above the bass clef as it keeps the RH voicing pattern visually separate. The second example places the E as part of the RH pattern.
Comment: Your first version will naturally lead a pianist to play the E with the RH. If you put the E on a ledger line in the bass clef as suggested some people will expect to play it with the LH. This may be a useful teaching point. Neither is wrong; it depends what you want.
Answer: On keyboard instruments, the upper staff is, in the absence of markings to the contrary, used to indicate notes played by the right hand and the lower staff for notes to be played by the left hand.  The normal purpose of cross-staff beaming would be to show that a rhythmic figure includes some notes which are played by each hand.  The first measure in the original question would suggest that the E should be played by the right hand.  If the E had instead been written as a ledger line on the bass clef, that would suggest that it should be played by the left hand.
An alternative way of notating the music to show that the right hand should play the E without using cross-staff beaming would be to place the E on a cleff ledger line, but include an L-shaped bracket with the notation "R.H." to the left of the note, with the horizontal part of the bracket just below it.
Some people may find the music easier to read using ledger lines and an explicit R.H. notation, while others may find it easier to read if all right-hand notes were placed on the upper staff.  Which approach is better would likely depend upon factors like the relative skill of the person who will be reading the music, whether it would likely be performed by someone who was sight reading, etc.  People should be familiar with the different ways of notating such constructs, but that doesn't mean they would be equally adept at reading all of them.
Answer: Some standard ways to write the same thing: (The "OR"s are just alternative beamings.)

I agree with you, Bob: the first bar, which was your original, looks clearest.
It's odd how, without any expression marks or slurs, bars one and four look the most legato and bar two the least. In fact it looks choppy. Bar three seems to emphasize four beats to the bar, while the other bars sound as if they could be in 2/2.
Comment: I think you are missing an important alternative which is putting the E4 in the bass using two ledger lines.
Comment: @Michael Curtis It wouldn't be played by the left hand without a reason. It could be an exercise (as someone has suggested). Or it could be that the right hand is about to play higher up the keyboard or the left hand is changing its position in preparation for what comes next. BUT as the right hand **doesn't** move higher, and the left hand **doesn't** change position - they simply repeat the figure - there is no reason to put that E on a ledger line.
Comment: I'm confused by your point about the hands. The cross staff beaming seems to me to mean the figure is played all left hand. The other three look like one voice LH and two voices RH.
Comment: e' in lower stave on ledger lines would have been my answer too.


If $\nu_n \ll \mu$ and $|\nu_n - \nu|(X) \rightarrow 0$ for finite measures $\mu, \nu_n, \nu$ on space $X$, then does $\nu \ll \mu$?

Question: This is a question from here:

Let $\mu, \nu, \nu_n$ be finite measures on $(X, \mathcal{F})$, and suppose that $\nu_n \ll \mu$ for all $n \in \mathbb{N}$. Is the following true or false?
If $|\nu_n - \nu|(X) \rightarrow 0$, then $\nu \ll \mu$.

I have a few scattered thoughts about it, if decompose $\nu$ into $\nu = \nu_{ac} + \nu_s$, such that $\nu_{ac} \ll \mu$, and $\nu_s \perp \mu$. Then it suffices to show that $\nu_s = 0$ to prove the statement to be true. Assume that there is some $E \in \mathcal{F}$ such that $\nu_s(E) > 0$, that is, there is some $X_s \in \mathcal{F}$ such that $\nu_s(E) = \nu_s(E \cap X_s)$ and $\mu(X_s) = 0$. So by absolute continuity of the $\nu_n$'s, $\nu_n(X_s) = 0$. So clearly $\nu$ cannot be the limit of the $\nu_n$'s.
Here's where I'm stuck. I feel like in general this statement is false, because I should be able to construct a $\nu$ that agrees with the limit of $\nu_n(X)$, but I want it to disagree with the limit of the $\nu_n(E)$ for some $E$ such that $\mu(E) = 0$. Does the fact that everything here is a finite measures here give me anything more to go off? What properties is relevant here?
Answer: The basic inequality $$\nu(E) \leq |\nu-\nu_n|(E)+\nu_n(E) $$
implies that if $\mu(E) = 0$, then $\nu(E) = 0$.
For completeness, if $\mu$ and $\nu$ are finite signed measures, then $$|\mu+\nu|(A)\leq |\mu|(A)+|\nu|(A)$$
Comment: Is this using the assumption that $|\nu -\nu_n| \ll \mu$, or $|\nu - \nu_n|(E) \rightarrow 0$ for arbitrary $E$? In this question I'm only given $|\nu - \nu_n|(X) \rightarrow 0$.
Comment: Oh! It's monotonicity, since $|\nu -\nu_n|$ is positive.
Comment: Yes, and the finiteness of the measures is only needed to make sense of the (a priori) formal sum $\mu+\nu$


Magento2 - Setup Compile Error - Class Not_Existing_Class does not exist

Question: I installed magento 2 Community version successfully. Now when i try to upgrade the setup i get the error Please re-run Magento compile command.
So i ran the compile command
magento setup:di:compile

but i am getting this error
Area configuration aggregation... 5/7 [====================>-------]  71% 35 min
s 736.2 MiB

  [ReflectionException]
  Class Not_Existing_Class does not exist

  [ReflectionException]
  Class Not_Existing_Class does not exist

Any ideas as to how this can be resolved ?!
Thanks in advance.
Answer: As a temporary fix, i was able to resolve this problem by commenting following line:
 \Not_Existing_Class $notExistingClass

in << Magento2 Root Folder >>\vendor\magento\framework\Code\Test\Unit\Generator\TestAsset\TestGenerationClass.php
I have also reported the issue on GitHub here and awaiting the community's response: https://github.com/magento/magento2/issues/2404


define custom jquery event to use in ajax form

Question: How can I create custom jquery event to use in event:
$form['submitted']['subject']['#ajax'] = array(
  'callback' => 'suggest_ajax_callback',
  'effect' => 'fade',
  'event' => 'change',
);

for example I want execute suggest_ajax_callback each time user enter Space while filling text-field. so "How Can I Pay?" will cause 3 time execution...
Answer: The solution for your question is not handled compelety by back-end of drupal.
By default drupal ajax not support customized event
You can acheive your means by jquery and ajax(non-drupal ajax)
Something like this
For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.
function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'acess callback' => TURE, //you can set it with your permission
      );
  return $items;
   }

and in yourhalderjust need pass a block
function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);

}

and in your clientside get it with something like this
  $('#yourelement').change(function() {
    if( checkfor your means) {
         $.ajax({
                       type: "POST",
                       url: 'youruniqepath',
                       //data: {}, you can also pass block name and act more dynamicly
                      success: function (data){
                          $('#yourplace').html(data);
                      },});
         }

});


Is this a reasonable start to my string quartet?

Question:
This is what I have of my string quartet so far. I am using Musescore for composing this, so I put in 100 measures because I didn't know how long the first movement of the string quartet would be. If there are no dynamics in the piece, Musescore defaults to playing it mezzo-forte. I exported it as an image and then added the arrows and text to it.
I don't know if I have the cello going too fast with the Alberti bass in the tutti and the eighth notes in the solo. I have my Allegro at 120 BPM. I have been binge-listening to Mozart's string quartets and you can probably see that I am doing a Neo-Mozart, if you will, with this string quartet.
But is what I have a reasonable start to a string quartet? And importantly, is the cello going too fast there with the Alberti bass and the eighths?
Answer: You're doubling the 3rd of both the tonic and dominant chords a lot.  Actually, the whole harmonic scheme is a bit suspect.  I suggest you consolidate the broken chords into longer notes, so it looks more like a hymn tune, and see if you really like how it sounds.  Particularly around bar 4.
(Actually, just set the tempo slow, maybe q=40, and PLAY bar 4.  Is that really what was in your 'inner ear?')
What does 'Tutti' and 'solo' mean in relation to the cello part of a string quartet?
You don't have to prepare the 'empty manuscript paper' in MuseScore.  It will expand as you enter notes.
Cello can manage 16th note broken chords at q=120.
Comment: What I mean by the Tutti and solo is that the second group of 5 bars, I planned to have as a cello solo and then a transition back to a full Tutti.


How to manually know the RSA2 key finger print?

Question: When I grep in the etc folder, I get this message:
grep: ssh_host_rsa_key: Permission denied.

Since I am on cygwin, I can't use sudo or something else.
Please let me know how to find it out.
Answer: ssh-keygen -l -f /etc/ssh_host_rsa_key.pub

This command will output just the fingerprint like this:
2048 9e:1a:5e:27:16:4d:2a:13:90:2c:64:41:bd:25:fd:35 /etc/ssh/ssh_host_rsa_key.pub

-f is for filename
-l is to output the fingerprint of the public key file.
Output consists of three parts

bit length of the key: 2048
finger print of the key: 9e:1a:5e:27:16:4d:2a:13:90:2c:64:41:bd:25:fd:35
name of the key file: /etc/ssh/ssh_host_rsa_key.pub

I would like to request experts on this matter to point any shortcomings in this method.
Comment: For new version of openssh, use
    ssh-keygen -E md5 -lf /etc/ssh/ssh_host_rsa_key.pub
to get the fingerprint with md5 hash format. The default is the sha256 format.
Comment: You left out a file folder in the command line. The file is under /etc/ssh/'filename'
You put /etc/'filename' Cheers!
Answer: Sudo is aditional package, which has to be installed during Cygwin installation. Have you tried su to become superuser?
Anyway, you can always view content of the Cygwin files from Windows...
Comment: I have tried su, but it did not work. I am guessing we have a vanilla Cygwin installation. Also I do not have the install permissions on the server. I will get this installed and try. I was not able to open these files from text editor as well.
Comment: Fortunately I have hit upon a solution from ssh documentation. I have posted it below as an answer. Thanks for your insight!


How do you implement a program to find the shortest path in a 2d plane?

Question: If on a 2d plane there are a no. of obstacles of all possible 2d shapes(circles, quadrilaterals, triangles, irregular shapes...) then how do you implement a mechanism to find the shortest path around the obstacles? I'm considering visual c++, as it provides many graphical classes to draw such figures.
I have come quite far
1) Firstly i'll be using A* search(A-star) to find the path with least cost
2) The path with the least displacement from the straight path will be considered for best path. (not really sure though)
3) The shortest path to get around a figure, for eg from the start, is a line from that point to :
<code>a) the farthest vertex in case of a polygon/quadrilateral
b) a point on the circumference such that the line drawn would be tangential to the circle, in case of a circle or arc
c) (not sure about irregular figures)
</code>

Now coming back to the 2) point- least displacement between 2 or more paths can be determined by comparing perpendiculars from those lines to the farthest points of an object on their respective sides. (hope i've made myself understood) .
So then- how do we draw perpendiculars to the straight path?
x1,x2,y1,y2,k and l are known. We just have to find a,b.
Slope of the straight path * slope of it's perpendicular = -1
<code>=> (y2-y1)/(x2-x1) * (b-l)/(1-k) = -1
hence, b = [(x1-x2)/(y2-y1) * (a-k)] + l
</code>
I've imagined that by using pythagoras theorem we can find the other equation in terms of the co-ordinates. The lengths of each line can be found by this way:
    dx = x1-x2
    dy = y1-y2
    dist = sqrt(dxdx + dydy)
And then by solving these 2 eqns we can find the correct values of a,b.

I can't think of anything further- any ideas or suggestions?
Comment: Have you had a look at the references here? It seems quite an established problem, you can likely find good info, http://cs.smith.edu/~orourke/TOPP/P21.html
Answer: Is it possible that you use polygonal (i.e. straight line segment) approximations for all shapes?
This would simplify the implementation of the algorithm a lot.
Assuming that this is indeed possible: If you want to use A* then you'll need a graph representation
of the possible paths that you can take. The nodes of this graph are the combination of:

all the vertices of all shapes[1], and
the start and end points
all intersection points between {the straight line segment between the start and end point} and all shapes.

The edges in this graph, then, are between each pair of nodes only if

there exists a straight line between their corresponding two vertices
that doesn't intersect any of the shapes[2].

The length of each edge in the graph is then simply the (euclidean) distance between the two vertices it represents, and the shortest path is always a subset of these edges (I think), which you can find by applying A* to this graph.
[1] - To reduce the number of vertices, you can make all concave shapes convex (unless this causes the start
or end point to lie inside such a shape, then it should be kept concave).
[2] - You can use a variety of data structures to speed up these queries, such as kD or quad trees, or maybe use a sweep line algorithm (such as http://en.wikipedia.org/wiki/Bentley%E2%80%93Ottmann_algorithm) in combination with a doubly-connected edge list.
Answer: For the second point if have the points (l,k). Consider two points located on the line(x1,y1),(x2,y2) which are equidistant from(l,k). So the perpendicular will be the combination of all points which are equidistant from (x1,y1)and (x2,y2).
Answer: Well i am not pretty sure if this might help but anyways every irregular object can be split into a combination of regular objects like a circle just that the radius of the curve keeps changing.So you can consider it to be a combination of arcs corresponding to different radii.


Ao adicionar função sistema não compila

Question: Tenho a seguinte classe:
package br.com.xti.ouvidoria.helper;

import java.util.Collection;

/**
 * @author Samuel Correia Guimarães
 */
public class ValidacaoHelper {

    /**
     * @param obj
     *            objeto a ser validado
     * @return TRUE se o objeto passado por parâmetro for NULL, VAZIO
     *         (Collections, Arrays, Strings) ou menor/igual a zero para tipos
     *         númericos
     */
    public static boolean isEmpty(Object obj) {
        boolean vazio = false;

        if (obj == null) {
            vazio = true;
        } else {
            if (obj instanceof String) {
                vazio = ((String) obj).replaceAll("\\s+", " ").trim().isEmpty();
            } else if (obj instanceof Number) {
                if (((Number) obj).longValue() == 0)
                    vazio = true;
            } else if (obj instanceof Collection<?>) {
                Collection<?> col = (Collection<?>) obj;
                vazio = (col == null || col.isEmpty());
            } else if (obj instanceof Object[]) {
                vazio = (((Object[]) obj).length == 0);
            }

        }
        return vazio;
    }

    /**
     * @param objs
     *            objetos a serem validados
     * @return TRUE se algum dos objetos passados por parâmetro for NULL ou
     *         VAZIO
     */
    public static boolean isEmpty(Object... objs) {
        boolean isEmpty = false;
        for (Object obj : objs) {
            isEmpty = isEmpty(obj);
            if (isEmpty) {
                break;
            }
        }
        return isEmpty;
    }

    /**
     * @param obj
     *            objeto a ser validado
     * @return TRUE se o objeto passado por parâmetro for diferente de NULL,
     *         VAZIO (Collections, Arrays, Strings) e maior que zero para tipos
     *         númericos
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

Queria adicionar a ela a seguinte função:
public static boolean saoIguais(Integer obj, Integer obj2) {
    boolean iguais = false;

    if (obj == obj2) {
        iguais = true;
    }
    return iguais;
}

Porém com está o sistema nem compila!
Se eu colocar como Object no lugar de Integer ele compila:
public static boolean saoIguais(Object obj, Object obj2) {
    boolean iguais = false;

    if (obj == obj2) {
        iguais = true;
    }
    return iguais;
}

Porém nesse caso a comparação nunca retorna como true.
Comment: Que erro e compilação ele produz?
Comment: Porque você não utiliza o método [`Object.equals(Object, Object)`](https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#equals-java.lang.Object-java.lang.Object-) que já está pronto, já está na biblioteca padrão e já faz o que você quer?
Comment: E qual é o erro de compilação nesse caso?
Comment: @VictorStafusa Estava equivocado na minha entrada de dados por isso achei que algo estava errado
Comment: Mas o principal da minha pergunta ainda não entendi que é o pq utilizando o `(Integer obj, Integer obj2)` o sistema nem compila
Answer: O operador == em tipos não primários compara apenas a referência do objeto, não sua igualdade. Quando você faz obj1 == obj2, você esta comparando apenas se o ponteiro do obj1 aponta para o mesmo endereço de memória do obj2, independente do valor de cada um dos objetos. Para comparar igualdade, use o método equals:
    boolean saoIguais = obj1.equals(obj2);

Comment: Erro meu, o retorno de um dos objetos estava diferente dq esperava por isso do erro, com o equals comparou certo
Comment: Cuidado com os `null`s sendo passados também. É necessário verificar por eles, pois por exemplo se o 1º objeto for `null`, terá uma `NullPointerException`
Answer: O erro da comparação é isso mesmo que o Orlando respondeu, quando você compara um variável de de tipos complexos como os objetos você compara as suas referencias de memória. Para comparar se os valores são iguais o correto é você sobrescrever o método equals. Mas no seu caso como esta comparando um Integer ele já sobrescreve o equals e compara o conteúdo do objeto.
Peguei o seu método e fiz uma implementação com a sugestão dada e validando a nulidade do objeto:
    public static boolean saoIguais(Integer obj, Integer obj2) {
    //Se quiser considerar que os dois valores nulos são iguais então use o if abaixo
    if(obj == null && obj2 == null )
        return true;
    //Este if é obrigatório para validar se o objeto é nulo
    if(obj == null || obj2 == null )
        return false;
    //Compara os valores usando a implementação equal da classe Integer
    return obj.equals(obj2);
}

Ao adicionar função sistema não compila


New Content type is not listing in Add Content in Drupal 7

Question: When create custom content type through UI or programmatically in Drupal 7, there is no link is listed in the Content > Add content.
I was creating the content types without any trouble, but now it is created(succes message is showing) when I check them in the node_type table but not lising in the admin/structure/types.
But no content type is listing(not any links showing) in the Content > Add content, or Structure > Content type administration menu.
Here is the code that allows users to access node pages:
<code>/*
 * Allow users to view the contents
 */
function mymodule_node_access_records($node){
    $grants = array();
    $grants[] = array(
        'realm' => 'example_realm',
        'gid' => 123,
        'grant_view' => 1,

  'grant_update' => 0,
    'grant_delete' => 0,
    'priority' => 0,
);
return $grants;
}

/**
 * Implements hook_node_grants().
 */
function mymodule_node_grants($account, $op){
    $grants = array();
    if ($op == 'view') {
        $grants['example_realm'] = array(
            123,
        );
    }
    return $grants;
}
</code>
Then I rebuild permissions using Content Access module.
Comment: Iv'e only had this issue right after I create one and a page refresh fixes it. Could it be perms perhaps?
Comment: have you emptied the cache ?
Comment: I am hanging with this for 5hrs(min). It would not be that easy to count the cache operations. @rtome: Thank you for your comment anyway.
Comment: are you using any cache other than default core cache? Say [Authcache](http://drupal.org/project/authcache) or [Memcache](http://drupal.org/project/memcache).
Comment: also manually check this path, is it a 404? 403? 500? yourdomain.com/node/add/MACHINE_NAME where MACHINE_NAME is the machine name (doh!) of the node type you created.
Answer:
Check the permission for node creation of that type in admin/people/permissions
Clear all caches and retry and it should be OK
Comment: May be you are getting to the point. But how is it possible to -"check the permission for node creation of that type", when I am going to create a new type?
Comment: @usermesam0023 check the permission of the one you already created but has disappeared. It's listed in the permissions list as 'create new node of type XYZ'.
Comment: Also, try to access directly this link **node/add/your-new-type**
Comment: @nabil: I have posted this question after I tried all these possibilities. When I go this path: I get the same 'Add Content' form.
Comment: Now I am running the site with the single 'Administrator'(allowed all permissions) and other users(anonymous). I have allowed these anonymous users to access all my node contents. Now I am going to add this code to my question.
Comment: You didn't mention before that you are using the **content access** module.
Ok, try disabling this module, and rebuild permissions in this page : **admin/reports/status/rebuild**, then try accessing the **node/add/content-type**


Find the Range of the function $f(x) = |x-6|+x^2-1$

Question:
find the Range of $f(x) = |x-6|+x^2-1$

$$ f(x) = |x-6|+x^2-1 =\left\{
\begin{array}{c}
x^2+x-7,& x>0 .....(b) \\
5,& x=0 .....(a) \\
x^2-x+5,& x<0 ......(c)
\end{array}
\right.
$$
from eq (b) i got $$f(x)= \left(x+\frac12\right)^2-\frac{29}4 \ge-\frac{29}4$$
and from eq (c) i got $$f(x)= \left(x-\frac12\right)^2+\frac{19}4 \ge\frac{19}4$$
and eq(b) tells me that it also passes through 5 and so generalize all this and found its range is $\left[-\frac{29}4 , \infty\right)$
but the graph says its range is $(5, \infty)$
Comment: When you have something like $|x-k|$ in the equation, try to expand it for the two cases of $x \geq k$ and $x \lt k$ instead of expanding around $x \geq 0$ and $x \lt 0$.
Answer: No derivatives are necessary. For $x\ge6$ the function is
$$
f(x)=x^2+x-7
$$
The graph is an arc of a parabola with its axis at $x=-1/2$, so in this interval the function is increasing, with its minimum at $6$: $f(6)=35$.
For $x<6$ the function is
$$
f(x)=x^2-x+5
$$
whose graph is an arc of a parabola with its axis at $x=1/2$. Since $1/2<6$ the minimum of $f$ is reached at $1/2$: $f(1/2)=19/4$.
Thus the range is $(19/4,\infty)$ because, clearly, $\lim_{x\to\infty}f(x)=\infty$.
Answer: $$f'(x)=\frac{x-6}{|x-6|}+2x$$
$f'(x)=0\iff x=\frac{1}{2}$ and $f'(x)<0$ if $x<\frac{1}{2}$ and $f'(x)>0$ if $x>\frac{1}{2}$, therefore the range is $[f(\frac{1}{2}),+\infty  [$.
Answer: You should have $x-6<0$, $x-6=0$ and $x-6>0$ respectively. Always look to the entire expression within the absolute value.
Oh, and another thing: While finding such minimum, you need to check whether it is in the domain. For example, you have $x>0$ (should be $x>6$) for (b), but the minimum is given at $x=-\frac{1}{2}$.


Using AWS Blue/Green deployment, how do I modify the staging database?

Question: AWS has rolled out a Blue/Green Deployment feature for RDS, allow you to create a staging (green) database that's in parallel with your production (blue) database. Their documentation specifically says you can make changes and test them out, however:

It's readonly by default
It's got replication, syncing the green to the blue
I can't create a SUPER user to disable readonly mode or disable replication.

I understand why they'd default to those, changes could mess up replication, and without replication you'd lose data unless you manually copy data over in a way that's compatible with whatever changes you make to the green. I'm willing to manage that, but can't actually figure out how to modify the database! With no SUPER user I can't run:
STOP REPLICA;
set GLOBAL read_only = false;

And apparently AWS RDS doesn't allow SUPER users, and there's no way in the console to disable either of these.
What am I missing? Does green/blue only allow you to upgrade MySQL versions? Seems like a big limitation, not really spelled out anywhere.
Comment: I am wondering the same exact thing. Their documentation clearly states that making schema modifications to the green staging instance should be doable. Did you ever find a solution for this?
Answer: I can confirm that the Green Deployment primary endpoint is read-only by default.
If your use case requires you to make write operations or schema changes you will need to apply a new DB parameter group to the primary instance with read_only parameter set to 0.
(The read_only parameter is a dynamic parameter, and therefore no reboot is required when applied.)
Here are some general steps to apply the new parameter group:

Create a new Parameter Group or clone your existing Parameter Group.
Once the Parameter group is created, modify the parameter read_only and set the value from the default {TrueIfReplica} to 0.
Select the Green Deployment primary instance and modify the DB parameter group to the new group from the drop-down via the Additional Configuration section.
Once the DB parameter group is updated, select "Apply immediately" in the schedule modification and click on Modify DB Instance.

Verification:
MySQL [(none)]> CREATE DATABASE menagerie;
Query OK, 1 row affected (0.148 sec)

MySQL [(none)]> show variables where variable_name='innodb_read_only';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| innodb_read_only | OFF   |
+------------------+-------+


Java: Dynamically size Columns in 2D Array

Question: How can I size my columns dynamically to support a possible ragged array?
int[][] x;
x = new int[3][] //makes 3 rows
col = 1;
for( int i = 0; i < x.length; i++){
  x = new int[i][col]
  col++;  }

Would the above code assign each col length?
Thank you in advance for any help.
Answer: since you are re-assigning x, what you are doing is creating the entire 2D array each loop, which is wrong.
You need to do inside your loop:
x[i] = new int[col];

Comment: that is exactly what I mean to do!! Thank you so much for the Syntax!!
Answer: // create the single reference
int[][] x;

// create the array of references
x = new int[3][] //makes 3 rows

int col = 1;
for( int i = 0; i < x.length; i++){
    // this create the second level of arrays // answer
    x[i] = new int[col];
    col++;
}

More on 2D Arrays.
- https://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm


Using querySelector() to obtain last td element

Question: I have a variable which is a node from the dom. I've managed to get all the way down to close to where I want to be:
myvar.querySelector('.tblItinPriceSummary tr')

Gives me this:

    Subtotal
    $189.00

What I want is the textContent of the second td $189.
Is there anything I can add inside of querySelector so that I can append it with .textContent to get this piece of data?
Comment: linked - https://stackoverflow.com/q/5684811/104380
Answer: You could either use :last-child or :last-of-type to access the last td element within the parent.
document.querySelector('.tblItinPriceSummary tr td:last-child').textContent;


How to implement rank structure

Question: What is the best way to implement a rank system:
here is the code i will use
public class MyRank
{
    private int LevelOneMaxPoints = 100;
    private int LevelTwoMinPoints = 200;
    private int LevelTwoMaxPoints = 299;
    private int LevelThreeMinPoints = 300;
    private int LevelThreeMaxPoints = 399;
    private int LevelFourMinPoints = 400;
    private int LevelFourMaxPoints = 599;
    private int LevelFourPlusMinPoints = 600;
    private int LevelFourPlusMaxPoints = 999;
    private int LevelFiveMinPoints = 1000;
    private int LevelFiveMaxPoints = 1299;
    private int LevelSixMinPoints = 1300;
    private int LevelSixMaxPoints = 2699;
    private int LevelSevenMinPoints = 2700;
    private int LevelSevenMaxPoints = 3999;
    private int LevelEightMinPoints = 4000;
    private int LevelEightMaxPoints = 5499;
    private int LevelEightPlusMinPoints = 5500;
    private int LevelEightPlusMaxPoints = 7499;
    private int LevelNineMinPoints = 7500;
    private int LevelNineMaxPoints = 9999;
    private int LevelTenMinPoints = 10000;

    private string LevelOneName = "Private";
    private string LevelTwoName = "PV2";
    private string LevelThreeName = "Private Fist Class";
    private string LevelFourName = "Specialist";
    private string LevelFourPlusName = "Corporal";
    private string LevelFiveName = "Sergeant";
    //private string LevelSixName = "Staff Sergeant";
    private string LevelSevenName = "Sergeant First Class";
    private string LevelEightName = "Master Sergeant";
    private string LevelEightPlusName = "First Sergeant";
    private string LevelNineName = "Sergeant Major";
    //private string LevelTenName = "Sergeant Major of the Answers";
    private int points = 0;

    public string RankName { get; private set; }
    public MyRank(int points)
    {
        this.points = points;
        RankName = GetRankName();
    }

    private string GetRankName()
    {
        if (points >= Int32.MinValue && points <= LevelOneMaxPoints)
            return LevelOneName;
        else if (points >= LevelTwoMinPoints && points <= LevelTwoMaxPoints)
            return LevelTwoName;
        else if (points >= LevelThreeMinPoints && points <= LevelThreeMaxPoints)
            return LevelThreeName;
        else if (points >= LevelFourMinPoints && points <= LevelFourMaxPoints)
            return LevelFourName;
        else if (points >= LevelFourPlusMinPoints && points <= LevelFourPlusMaxPoints)
            return LevelFourPlusName;
        else if (points >= LevelFiveMinPoints && points <= LevelFiveMaxPoints)
            return LevelFiveName;
        else if (points >= LevelSixMinPoints && points <= LevelSixMaxPoints)
            return LevelFiveName;
        else if (points >= LevelSevenMinPoints && points <= LevelSevenMaxPoints)
            return LevelSevenName;
        else if (points >= LevelEightMinPoints && points <= LevelEightMaxPoints)
            return LevelEightName;
        else if (points >= LevelEightPlusMinPoints && points <= LevelEightPlusMaxPoints)
            return LevelEightPlusName;
        else if (points >= LevelNineMinPoints && points <= LevelNineMaxPoints)
            return LevelNineName;
        else if (points >= LevelNineMinPoints && points <= LevelNineMaxPoints)
            return LevelNineName;
        else if (points >= LevelTenMinPoints)
            return LevelFourName;
        else
            return "No Rank";
    }
}

Do you think this is the most efficient way to do this?
Answer: I would start by converting your Levels to a single enum. The value of each Enum can be the minimum value, there's no need to keep track of maximum as you'll see below.
public enum Level
{
    [Description("Private")]
    One = 0,
    [Description("PV2")]
    Two = 200,
    [Description("Private Fist Class")]
    Three = 300,
    ...
    ...
    [Description("Sergeant Major of the Answers")]
    Ten = 10000
}

Then you can write this to get the name:
string GetRankName(Level level)
{
    FieldInfo fieldInfo = level.GetType().GetField(level.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
    return (attributes.Length > 0) ? attributes[0].Description : level.ToString();
}

and this to get the Level
Level GetLevel(int points)
{
    Level level = Level.One;
    foreach(int i in Enum.GetValues(typeof(Level)))
    {
        if (points < i) break;
        level = (Level)i;
    }
    return level;
}

then your object members would be:
public Level Level { get; set; }
public string RankName { get; set; }
public MyRank(int points)
{
    Level = GetLevel(points);
    RankName = GetRankName(Level);
}

Comment: I get a syntax error - the type or namespace "description" could not be found. Am I doing something wrong with the attributes?
Comment: Yes it does..I have it working now. it is much more manageable. Thanks alot for your help
Answer: You can use an array:
private int[] levelPoints = new int[]{
    99, 299, 399, 599, 999, 1299, 2699, 3999, 5499, 7499, 9999
};

private string[] levelNames = new string[]{
    "Private", "PV2", "Private First Class", "Specialist", "Corporal",
    "Sergeant", "Staff Sergeant", "Sergeant First Class", "Master Sergeant",
    "First Sergeant", "Sergeant Major", "Sergeant Major of the Answers"
};

private int GetMinPointsOfLevel( int level ) {
    // I think, the levels starts from 1

    if ( level <= 1 ) { return 0; }
    else if ( level >= levelPoints.Lengtht ) { return levelPoints.Last(); }
    else { return levelPoints[level - 2] + 1; }
}
private int GetMaxPointsOfLevel( int level ) {
    if ( level <= 1 ) { return levelPoints[level - 1]; }
    else if ( level >= levelPoints ) { return int.MaxValue; }
    else { return levelPoints[level - 1]; }
}
private inte GetNameOfLevel( int level ) {
    if ( level < 1 ) { return levelNames[0]; }
    else if ( level >= levelPoints - 1 ) { return levelNames.Last(); }
    else { return levelNames[level - 1]; }
}

How to implement rank structure