How to intuitively understand the reconstruction of the original data after dimension reduction

Question: So I have been trying to understand PCA for the past day, and the part that I don't understand is when the original data is reconstructed after dimension reduction. Below is the code that I was follow from here. I what the code is doing for the most part, but the one line that I don't understand is this line:

Xt_reconstructed <- Xt_projected %*% t(res$rotation[,1:pc.use])

 # Generate data

m=50 # columns or features
n=100 # rows or observations
frac.gaps <- 0.5 # the fraction of data with NaNs
N.S.ratio <- 0.25 # the Noise to Signal ratio for adding noise to data

x <- (seq(m)*2*pi)/m
t <- (seq(n)*2*pi)/n

#True field
Xt <-
 outer(sin(x), sin(t)) +
 outer(sin(2.1*x), sin(2.1*t)) +
 outer(sin(3.1*x), sin(3.1*t)) +
 outer(tanh(x), cos(t)) +
 outer(tanh(2*x), cos(2.1*t)) +
 outer(tanh(4*x), cos(0.1*t)) +
 outer(tanh(2.4*x), cos(1.1*t)) +
 tanh(outer(x, t, FUN="+")) +
 tanh(outer(x, 2*t, FUN="+"))

Xt <- t(Xt) # data matrix nxm
# PCA
res <- prcomp(Xt, center = TRUE, scale = FALSE)
names(res)

#plot(cumsum(res$sdev^2/sum(res$sdev^2)))
#cumulative explained variance

########################################
# reconstruction of original data from lower number of features
######################################
pc.use <- 3 # num of principal components to use
Xt_projected <- res$x[,1:pc.use] # projection of original data onto PCs
Xt_reconstructed <- Xt_projected %*% t(res$rotation[,1:pc.use])

# add the center (and re-scale) back to original data
if(res$scale != FALSE){
 Xt_reconstructed <- scale(Xt_reconstructed, center = FALSE , scale=1/res$scale)
 }
if(res$center != FALSE){
 Xt_reconstructed <- scale(Xt_reconstructed, center = -1 * res$center, scale=FALSE)
 }
 dim(Xt_reconstructed); dim(Xt)

So if my understanding is correct Xt_projected is the Xt projected onto 3 dimension space, where each axis of the space is defined by the eigenvectors. Now to reconstruct the data to the original m = 50 dimensions, why are we multiplying Xt_projected by the transpose of the eigenvectors used to map the Xt to the 3 dimension space, am I missing something here?
I'm guessing that when Xt_projected is multiplied by the transpose of the the eigenvectors that projected Xt to Xt_projected it is effectively "reconstructing" the original data. But this is just a guess and even if it is correct I still don't intuitively understand what is happening when the projected data is multiplied by the transpose of the eigenvectors that projected them there.
Sorry if this is unclear, please tell me so that I can edit it accordingly.
Answer: So the advantage of coding directly is that you can "see that it works", the disadvantage is that if you haven't done the maths on the side you might get confused (as you apparently are now) so allow me to do some maths:
You have an initial data matrix which we will call $M$ (the notations in the code are particularly unhelpful). This is your Xt which is of size $100\times 50$. Now $M$ can be written as:
$ M = U\Lambda V^T$
this is the SVD decomposition (such a decomposition always exists), $U$ is of size $100\times 50$, $\Lambda$ is a diagonal matrix of size $50\times 50$ and $V$ a squared, orthonormal ($V^TV =I)$, matrix of size $50\times 50$.
To connect with the R code, res contains the results from the decomposition with res$x being $U\Lambda $ and res$rotation being $V$.
You can check this in your code by doing
res <- prcomp(Xt,center=FALSE,scale=FALSE)
norm(Xt -  res$x %*% t(res$rotation))

which should give you something extremely small.
Now PCA essentially amounts to truncating a bunch of singular values (just ignoring them). That is, you write a reconstruction
$\hat M = U \hat \Lambda V^T$
where $\hat \Lambda$ is the same $\Lambda$ but with a zero diagonal apart from the first few largest singular values (corresponding to the number of components you're considering). So in your case, keeping only three elements
$\hat\Lambda = \left(\begin{array}{ccccc}
a & & & &\\
& b& & &\\
& & c & &\\
& & & 0 &\\
& & & & \ddots\end{array}\right)$
but multiplying this matrix to $V^T$, means really you should only care about the first three lines of $V^T$ in the reconstruction (the rest will be multiplied by zero), and similarly, the first three columns of $U$
the PCA uses slightly different notations but the principle is exactly the same, the res$x is, as said before, $U\Lambda$ so taking res$x[,1:pc.use] exactly amounts to $U\hat\Lambda$. And similarly, the first three rows of $V^T$ are the transpose of the first three columns of $V$ whence the t(res$rotation[,1:pc.use])
the $\hat M$ from above is then just your Xt_reconstructed:
Xt_reconstructed <- res$[,1:pc.use] %*% t(res$rotation[,1:pc.use])

I'm hoping by now all the operations make sense.
What I'd stress given your question is that you're not reconstructing the original data ($M\neq \hat M$, obviously, unless you're taking all the components which is silly). There may be confusion due to this. What you're doing is reconstructing in the original space. That's it. But effectively all you care about is that you can now store a "pretty good" approximation to $M$ by just storing the first three columns of $U\Lambda$ (your res$x[,1:pc.use]) and the first three columns of $V$ (your res$rotation[,1:pc.use]), then whenever you actually need to consider what it looks like (in order, for example, to visualize it) then you compute the product and you end up with a representation which has the same dimension than the original object (and therefore is comparable to it) but has effectively less information in it.
More info about the SVD: https://en.wikipedia.org/wiki/Singular_value_decomposition
More info about PCA versus SVD: Relationship between SVD and PCA. How to use SVD to perform PCA?
Comment: I think the M^{hat} really cleared it up for me, and also your last paragraph! Thanks for you answer!


Fusion Charts: How to hide values of Pie Chart

Question: Referring the URL, how can I hide values around Pie chart? I need to do it to consume the space. I am unable to find the way to do it.
I am using Free version of Fusion Charts
Answer: Try
<chart [..........] showLabels='0' showValues='0' [...........]  >

Comment: @All: showNames='0' needs to be used to hide the labels, whereas showValues='0' will hide the values associated with the labels.
Answer: Try using showNames='0' showValues='0' in the <chart> element.
Answer: You can use these configuration to hide values for pie
 "showlabels": "0",
 "showvalues": "0"

Reference code -
    FusionCharts.ready(function() {
  var revenueChart = new FusionCharts({
    type: 'pie2d',
    renderAt: 'chart-container',
    width: '550',
    height: '350',
    dataFormat: 'json',
    dataSource: {
      "chart": {
        "caption": "Split of revenue by product categories",
        "subCaption": "Last year",
        "numberPrefix": "$",
        "showPercentInTooltip": "0",
        "decimals": "1",
        //Theme
        "theme": "fusion",
        "tooltipBorderRadius": "20",

        // hide lables & values
        "showlabels": "0",
            "showvalues": "0"
      },
      "data": [{
          "label": "Food",
          "value": "285040"
        },
        {
          "label": "Apparels",
          "value": "146330"
        },
        {
          "label": "Electronics",
          "value": "105070"
        },
        {
          "label": "Household",
          "value": "49100"
        }
      ]
    }
  }).render();

});

Reference JsFiddle


Is "J41" a known Sousaphone model? Of which brand?

Question: The sousaphone I'm speaking of in another question has "J 41" embossed near the screws that hold the bell. I'm wondering if this could be a model name. Does anyone know the brand ? Or the place where I can find the answer to that questions ?
I tried to google the answer but without success. The "J" made me think of Jupiter but their current model numbers to not look like J + 2 digit number.
I also found a serial number, which is 85937.
Per request, here are some photos. Please add a comment if you need a specific area.
Comment: I can't think of a case where the brand isn't easy to find. Are you sure you can't find one? It might be around the bell, on the valve cluster, or (in one case I can recall) on a support strut. Any recognizable logos?
Comment: What key is it in? E.g. BBb, EEb, Eb, F, etc.
Comment: it's an old battered instrument, painted with a rather thick layer of white paint.  I'll try and remove the paint, starting with the areas you mention.
Comment: Do you know about how old it is? Where did you get it?
Comment: @Luke no, I brought it on a garage sale and the seller had no information on this. All I could find is this J41 emboss and a serial number.
Comment: Can you post a picture of it? I have a hunch of what it is. /if it is correct, there should be a 0 after the 1. Perhaps it is hidden under the paint?
Comment: @luke unfortunately, there is very little chance that I missed a letter. The embossing is very clear...
Answer: This site gives lists of various serial numbers for Conn wind instruments.
If it was made in 1987 or later:

From 1987 on, the two-digit prefix number plus 50 will give you the year of manufacture on all Conn products... Data for the years 1967 to March 1974 is rather sketchy, for it was around that period of time that the Conn Brasswinds were being manufactured in Abilene, TX. Instruments made during that period are not likely to be their best examples, as the workers were still relatively new at the manufacturing process.

<code>41+50=1991
</code>
This theory, unfortunately, does not account for the J.
If it was made between March 1974 and 1986:

In March of 1974 an alpha-numeric system was established, where the first character (letter) of a serial number indicated the decade; "G" for the 1970's, "H" for the 1980's, etc. The second character, also a letter, indicates the month of the year; "A" for January, "B" for February, "C" for March, "D" for April, "E" for May, "F" for June, "G" for July, "H" for August, "I" for September, "J" for October, "K" for November, and "L" for December.The third character (a number) indicates the number of year within the decade (indicated earlier by the first letter). The fourth character (number) indicates the specific type of instrument: "1" = Cornet, "2" = Trumpet, "3" = Alto Horn, "4" = French Horn, "5" = Mellophone, "6" = Valve Trombone, "7" = Slide Trombone, "8" = Baritone Horn & Euphonium, "9" = Tuba, and "10" = Sousaphone. The remaining four numbers of the serial number indicate the production number of the instrument on a monthly basis.

x -- either G for the 1970s or H for the 1980s.
J -- made in October
4 -- made in 1974 or 1984
1 -- first digit of "10" for sousaphone
x -- should be 0. second digit of "10" for sousaphone
x -- production number digit one
x -- production number digit two
x -- production number digit three
x -- production number digit four
This theory requires that there be six more letters, hidden under the paint.

This page about Jupiter instruments also gives serial numbers:

... The age of Jupiter instruments may be determined by adding one to the first digit of the serial number. The resulting number then would represent the year after 1984 that the instrument was manufactured. For example, if the serial number began with a number "4" you would then add "1" to this number and know that the instrument was manufactured in 1985. If the first number was a "0", would indicate that the instrument was manufactured in 1991.

The page also states all instruments made 1990 and later have a suffix of J.
Thus, if it is a Jupiter sousaphone, it would be a from 1995.
However, here there are also problems. This theory does not account for what the "1" means.

These are the only possible manufacturers that I have found. Conn is an American company, Jupiter is Taiwanese. It is likely your sousaphone was French (your profile says you're from France). Three characters isn't much to go on. If you find anything else on it, update me.
I hope it helps...
Comment: Hi, Thanks for the research. I've added the photos on the site (sorry for doing this so late). J41 is likely the model number, not the serial number. See question for the value of the serial no.
Comment: It seems from looking at serial numbers of various companies, it is from the fifties or early sixties. (My guess is 1952)
Answer: It comes from the former East Germany (GDR). The brand is Weltklang (and it does not have a good reputation).


When KL and Reverse KL divergence become same

Question: I'm curious if there are any two probability distributions whose kl divergence and reverse kl divergence value are the same. For obvious case, It'll be satisfied if two distribution are the same. So I want to exclude this.
Thank you
Answer: Fix a probability measure $\mu$ and let $\nu=f\;d\mu$ for some density $f$. The condition for the KL divergence and reverse KL divergence of $\mu$ and $\nu$ being equal is equivalent to
\begin{equation}
\label{eqn:Condition}
\int (1+f)\log(f)\;d\mu=0.
\end{equation}
(The expression above follows by just writing the condition so I am not writing it.)


Serialization in android?

Question: Hi I am serializing an object using different VM (Oracle hotspot,jse) and deserializing it with android VM(dalvik). will there be any problem?
Answer: Assuming that by "serialization" you mean Serializable, then yes. Serialization is not guaranteed to be the same across distinct VMs. Please use something else (e.g., XML, JSON).
UPDATE
Your first comment is so flawed that I cannot fit my response in 500 characters.

ofcourse yes. without implementing Serializable we cannot serialize

Talented programmers can. Talented programmers can serialize data to XML, JSON, Protocol Buffers, Thrift, ASN.l, YAML, and any number of other formats.

what actually i am doing is i am writing an object on to the network using ObjectOutputStream(oracle hotspot) and reading that object on the android using ObjectInputStream

Talented programmers use platform-independent serialization approaches, such as any of the ones I listed above. That is because talented programmers realize that, in the future, there may be need to have clients or servers that are not based in Java.

So you mean to say as of now this is fine but in the future it is not guaranteed.

No. I wrote:

Serialization is not guaranteed to be the same across distinct VMs.

An object serialized using one VM (e.g., Oracle) should be able to be de-serialized using that VM. There is no guarantee that an object serialized with one VM can be de-serialized using another VM. In fact, developers have gotten in trouble trying to do precisely what you are trying to do. This is another example of why talented programmers use platform-independent serialization structures.
Comment: Thank you. Your emphasis about "talented programmers" is good. I liked it.
Comment: ofcourse yes. without implementing Serializable we cannot serialize. what actually i am doing is i am writing an object on to the network using ObjectOutputStream(oracle hotspot) and reading that object on the android using ObjectInputStream. So you mean to say as of now this is fine but in the future it is not guaranteed. is it?
Comment: one last doubt. If i write bytes on to the network using one jvm and reading bytes using another jvm. Is this ok. byte is primitive data and reading the same on different jvm should be the same. is it right?
Comment: @muralidhar: Yes. Plain data is fine. The issue is not the network -- you would run into problems with `Serializable` when writing an object graph to a file and reading it back in with another VM.
Comment: Serialization is completely defined by the Object Serialization Specification. All JVMs must comply. Your statement that it is 'not guaranteed to be the same across JVMs' is not correct. -1
Comment: @EJP: You will notice that the Dalvik VM is not a JVM, and that I never claimed that it is 'not guaranteed to be the same across JVMs'.

Serialization in android?


How to play duplicated note at the same time?

Question: I just start playing Schumann's Traumerei, but I noticed something unusual:

in a 4/4 meter, the F on the bass staff counts for 5 beats in the same bar.
My guess: press down the sustain pedal, play F for one beat, and again for the remaining three beats?
Comment: Does this answer your question? [What is this double-note and how do you play it?](https://music.stackexchange.com/questions/45167/what-is-this-double-note-and-how-do-you-play-it)
Comment: Does this answer your question? [Too many notes in this measure](https://music.stackexchange.com/questions/53041/too-many-notes-in-this-measure)
Comment: An interesting example of what, at first sight, might seem a frequently-asked (and answered)  question, with two instances of 'orchestral' piano writing - the doubled bass note and the interlocked inner parts.  It would be a pity to dismiss it as a mere duplicate.
Answer: When writing for piano, composers very often notate a musical intention rather than precise playing instructions.   We're being told that Schumann feels there are four musical 'voices' here, and had he been scoring for four actual individual instruments he might have done this.

A pianist will actually play this.  Does being made aware of Schumann's concept make any audible difference?  Maybe, just a little!

You'll also notice that Schumann dovetails the inner notes, asking the r and l hands to overlap.   This would be worth doing if there WERE different instruments playing each layer of the music.   Whether it makes a jot of difference on piano is debatable.
But I quite like that Schumann thought orchestrally, even in his piano solo music.

(I see I've misprinted the pickup note.  Should be a C.  Sorry.)
Comment: All good points, Laurence. I would add that there's something to be said for making the performer _think_. Even if all you think is, 'I wonder why he did that?' it affects your attitude to a piece and changes the way you play. It stops you playing on automatic pilot. That 4-note chord, fingered as written, feels fuller, fatter and more stable than it does in your last rewrite. A 5th and a maj6th are more stable than a 4th and a min3rd.And it feels warmer because your hands are touching for a second or two: almost clasped.
Comment: This dovetailing is actually quite typical for Schumanns piano writing!
Comment: Just a nitpick; your treble pick-up note changed from a C to an F in the second and third scorings.
Comment: Did you mean F₁ or F₂ for the contrabass part? Your argument makes more sense when it's F₂, however that would normally be written on the second line, unlike in the cello part. (Double bass clef being really 8vb bass clef, or as many people prefer to say, double bass "transposing" down an octave.)
Answer: I want to add to Laurence Payne's already good answer. Not only are there clearly four voices in this piece, they have clear and distinct characters. The second voice is syncopated, which is why there is a rest in the first bar before it starts. But the third voice is not! Instead, it starts with the tonic note F together with the fourth voice.
Some people have suggested that this makes no difference in playing. This is just wrong. Schumann wants the pianist to play as if there are really four voices. This would mean that the shared F should be louder than if it was only in the fourth voice. Furthermore, precisely because that F in the third voice precedes the C-A chord in the second beat, the C-A chord should be felt and played as if it serves as a 'follow-up' to the F.
How to tell that this F is a shared note? (It does not seem to have been explicitly explained so far.) A note shared by multiple voices is notated either by putting the copies right next to each other with no space in-between, or by having two stems if they both have stems and the note heads are identical. Clearly, the second option is inapplicable for the shared F in Traumerei.
Answer: No. This is notation of two voices in one hand, both of which start on the f. So you have one voice that plays the f and then the c,a, and another voice that just remains on the f. Maybe also put a little emphasis on the f.
Answer: This could have been better written with a rest in the tenor part. There's really no point in writing that F twice - it's confusing to a lot of folk  - hence the question.
It certainly doesn't make 5 beats in the bar, nor get played twice, so is superfluous.
Comment: I do not think so. We need to take into account that this is a particularly bad looking edition, that starts the crescendo at a completely wrong point and and adds a *ben espressivo* in between , which totally messes up the spacing. Needless to say, Schumann did not put a *ben espressivo* there.
Answer: It's sort of a bit of semantic information.  You play the attack of the F to fit nicely with the following C-A, but you don't release the note (either by holding with the finger or employing a suitable pedal for that purpose).
That is hard to convey without writing the quarter note since then the timing suggests the F to be independent from the C-A and more played like a bass harmony note doubling the F in the violin clef rather than forming a melodic attack of its own.


If $T$ is compact such as $T(e_n)=\lambda_n e_n$ then $\lim_n\lambda_n=0$

Question: Let $H$ be a Hilbert separable space. with the orthonormal bais $(e_n)_{n\in \mathbb{N}}$, and $(\lambda_n)_{n\in \mathbb{N}}$ a bounded sequence in $ \mathbb{C}$.
We define the operator $T : H \rightarrow H$, as $T(e_n)=\lambda_n e_n$
We need to prove that $T$ is compact if and only if $\lim_n\lambda_n=0.$
I only did the reverse :
Suppose that $(\lambda_n)_n $ converge to $0$.
We define the finite rank operators $T_k$ defined as : $T_k(x)=(\lambda_1x_1,..,\lambda_kx_k,0,0,...)$.
And now we prove that $||T_k-T||\rightarrow 0.$
We have : $T(x)-T_k(x)=(0,0,...,\lambda_{k+1}x_{k+1},...)$
then : $||T_k-T||\leq sup_{n>k+1}|\lambda_n|\rightarrow0.$
then $T$ is compact as limit of finite rank operators.
[But I'm always stuck with the direct implication]
Answer: Recall that the image of the unit ball under $T$ is relatively (sequentially) compact by definition of compact operator. So begin by assuming to the contrary that there is a subsequence $n(k)$ such that
$$
|\lambda_{n(k)}|\ge \epsilon>0,
$$for some $\epsilon >0$. Then, we have
$$
\|Te_{n(k)}-Te_{n(r)}\|^2 = \|\lambda_{n(k)}e_{n(k)} - \lambda_{n(r)}e_{n(r)} \|^2= |\lambda_{n(k)}|^2 +|\lambda_{n(r)}|^2\geq 2\epsilon^2.
$$ This means $(Te_{n(k)})_{k\ge 1}$ cannot have a Cauchy subsequence. This contradicts relative sequential compactness, hence we get
$$
\lim_{n\to\infty}|\lambda_n| = 0.
$$
Comment: If a sequence in not a Cauchy sequence,then surely it has no subsequence convergent at all ?
Comment: I've just corrected my answer. It was an error.
Comment: Now, the proof is good.
Comment: Actually more is true: if $T$ is compact, then it sends a weakly convergent sequence to a strongly convergent sequence. So, in any case $Te_n$ should converge to $0$ because $e_n$ weakly converges to $0$.
Comment: Yes, I saw that proposition. Do you have/recommand a good book for operators and exercies ?
Comment: I have only a few books on Functional Analysis, so this is just my personal opinion: I felt Royden & Fitzpatrick (4th ed) is providing a comprehensive introduction to topics of FA. And if you want to concentrate on operator theory, perhaps Conway's FA will fit your needs.
Comment: Thnak you for your recommandation.
Answer: By the equivalent characterization of compact operators on a Hilbert space as taking the unit ball to a compact set, we just need to find a sequence in the image with no convergent subsequence. Because the $\lambda_i$ do not converge to $0$, pick a subsequence $\lambda_{n_i}$ with $|\lambda_{n_i}|>\delta$. Then the vectors $\lambda_{n_i}e_{n_i}$ are in the image of the unit  ball, but they are all orthogonal, so the distance between each of them is at least $\sqrt{2}\delta$.


Como ler conteúdo de um site em javascript?

Question: Gostaria de saber como faço para ler conteúdo de outras paginas da web utilizando apenas javascript ou alguma biblioteca.
Por exemplo, de um site de noticias remoto, no caso: www.terra.com.br.
E eu gostaria de criar uma webapp para ler as últimas notícias apresentadas nessa pagina, sendo que a mesma não tem RSS e etc.
Eu sei dos problemas que poderiam ocorrer caso as paginas que eu estou me alimentando mude o layout ou qualquer coisa do tipo.
Teria alguma forma de fazer isso?
Comment: Era essa minha dúvida, se era pra algum específico ou pra todos.
Comment: Para qual SO? Tem que ser webapp mesmo?
Comment: tanto faz o SO né? Posso fazer uma pagina web e rodar em algum webview.
Comment: ahh ok, tudo certo :)
Answer: Pode fazer diretamente uma requisição AJAX para o servidor, assim:
xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var html = xmlhttp.responseText;
        processPage(html);
    }
}

xmlhttp.open("GET", "http://www.terra.com.br/", true);
xmlhttp.send();

Note que dependendo do servidor você pode ter problemas com requisições cross-origin. Uma forma simples de burlar isso é usar um serviço como o whateverorigin.org. Nesse caso fica assim:
xmlhttp.open("GET", "http://whateverorigin.org/get?url=" +
                    encodeURIComponent("http://www.terra.com.br/"), true);

Comment: Outro site que também permite isso é o http://www.corsproxy.com/, a forma de utilizar ele é, inclusive, mais fácil. `xmlhttp.open('GET', 'http://crosproxy.com/www.terra.com.br/'), true);`
Comment: Olhe o exemplo: http://jsfiddle.net/TG8Bm/
Comment: BTW andei pesquisando como que o jQuery lida com strings de HTML sem processar os scripts: [`.parseHTML`](http://james.padolsey.com/jquery/#v=git&fn=jQuery.parseHTML), [`.buildFragment`](http://james.padolsey.com/jquery/#v=git&fn=jQuery.buildFragment). É semelhante ao meu exemplo, só que usando `documentFragment`s e com resolução de bugs.
Comment: ok perfeito... mas como faço para manipular o conteúdo? No caso eu quero copiar conteúdo de alguma DIV e colocar no meu webapp por exemplo, todo conteúdo da Div de notícias.
Comment: @ArilsonCarmo Implemente a sua `processPage()`. Lá você pode usar algum parser de html ou (se for algo muito simples, não recomendo) usar regex mesmo. Depende do que você quer extrair.
Comment: No caso eu queria extrair todos os filmes deste endereço http://www.jcnet.com.br/cinema.php, pegar a imagem e os horarios. Você teria algum JSFiddle de exemplo? Se puder é claro.
Comment: @GuilhermeBernal Estamos falando de Javascript, não de outra linguagem. Extrair HTML de um texto é questão de duas linhas em javascript.
Comment: Note que inserir o html no DOM para fazer o navegador o processar por você vai causar execução de scripts e afins. Não é uma boa solução.
Comment: Sim exatamente! javascript que estamos falando! Quero extrair TODO conteúdo da pagina e manipular. Eu não entendi como eu faço isso... OK.. faço a requisição Ajax consigo ter a html e o resto? Por exemplo como eu pego um determinado conteúdo de uma tag?
Comment: @GuilhermeBernal Ele não executa enquanto não inserir na DOM, mas processa. // Me lembrei agora: primeira versão de um site meu fiz usando isso. Dica: não use, uma mudança no site e seu programa para.
Comment: tá.. mas não vi uma forma de manipular o conteúdo... requisição ajax? ok. Mas como faço para manipular o que eu realmente preciso?
Comment: Nossa tava olhando agora... que coisa horrível é a página...Eu não sei se a parte cinema é um iframe ou o que que é.. mas não consigo extrair o conteudo... da forma que você fez está muito correto... obrigado... mas teria que ser do conteudo cinema.php... e não vai! Bizarro!
Comment: ah entendi o que eles fizeram... cada filme novo é uma table '-'
Comment: vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/13351/discussion-between-arilson-carmo-and-gustavo-rodrigues)


Turborepo React app fails to load Tailwind

Question: I've created a monorepo with Turborepo that for now have 1 React Vite App, and tailwind-config package. And my problem for now is that my App is not loading tailwind at all.
Let me try to explain you my project structure and files.
root
|
|- packages
|   |- tailwind-config
|
`- apps
    |- container

tailwind-config module contains basic package.json, tailwind.config.js and postcss.config.js files.
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
    content: [],
    theme: {
        extend: {},
    },
    plugins: [],
}

postcss.config.js:
module.exports = {
  plugins: {
      tailwindcss: {},
      autoprefixer: {}
  }
}

Inside my container app I added tailwind-config package as the local devDependency, added Tailwind directives to my index.css.
At the end in container I created  tailwind.config.cjs that looks like:
/** @type {import('tailwindcss').Config} */
const sharedConfig = require("tailwind-config/tailwind.config")

module.exports = {
    ...sharedConfig,
    content: ["./src/**/*.{js,ts,jsx,tsx}", "./public/index.html"]
}

And postcss.config.cjs
module.exports = {
  plugins: {
      tailwindcss: {},
      autoprefixer: {},
  }
}

As I mentioned the problem is that container app is not applying any tailwind classes I provide.
Thank you all for help in advance and hope you have nice day :)
Answer: Add the exact location of .jsx/.tsx files in tailwind.config.js file
e.g.:
tailwind.config.js
/** @type {import('tailwindcss').Config} */
const sharedConfig = require("tailwind-config/tailwind.config")

module.exports = {
    ...sharedConfig,
    content: ["./src/**/*.{js,ts,jsx,tsx}", "./public/index.html", "../apps/**/*.{js,ts,jsx,tsx}"]
}

Answer: A better way to share tailwind configs is to use presets.

Create a tailwind-presets.js file in your shared config folder
Add all the configuration options you want to use in all projects

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [require("daisyui"), require("@tailwindcss/typography")],
};

In each project, setup the tailwind.config.js to use the preset

/** @type {import('tailwindcss').Config} */
module.exports = {
  presets: [require("../../packages/config/tailwind-preset.js")],
};

You can override any option individually in each project but this is a fairly straightforward way of sharing the config.


Comparação de ID em elementos XML

Question: Estou fazendo uma verificação entre 2 ids de 2 elementos diferentes em XML, porém quando faço a comparação o resultado é sempre false mesmo que o gettype seja o mesmo resultado e o numero também seja o mesmo resultado.
Para realizar a verificação eu tenho 2 loops, um dentro do outro, o primeiro é o resultado da comparação de igualdade:
var_dump($filme->attributes()['id'] == $m->attributes()['id']);

E o segundo é a comparação dos tipos e dos id's:
echo get_class($filme->attributes()['id']) . ' ' .$filme->attributes()['id']
. ' --> ' .
get_class($m->attributes()['id']) . ' ' . $m->attributes()['id'] . '
';

Abaixo a lista completa:
bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5718

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5764

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5767

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5792

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5794

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 6015

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 6031

bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 6052

Note na quinta linha do resultado a cima que o resultado é o mesmo porém a verificação é false
bool(false)
SimpleXMLElement 5794 --> SimpleXMLElement 5794

Já realizei a verificação dos tipos e dos valores e continuo recebendo false.
Answer: Assim não funciona?
var_dump((string)$filme->attributes()['id'] == (string)$m->attributes()['id']);

Comment: Porque a comparação entre dois objetos (SimpleXMLElement) pode considerar outros aspectos que não somente o valor que é representado... Fazendo o cast pro tipo string, a comparação fica restrito ao valor da tag...
Comment: Pq funcionaria dessa forma? poderia explicar?
Comment: de fato funcionou. eu havia tentado usar `(int)` mas o certo era `(integer)`.

Comparação de ID em elementos XML


How to add a new tab to user profile in administration?

Question: How can I add a new tab to user profile beside View(active tab) and Edit. I want to add for instance New User Tab which will be visible only by administrator (not by the user itself).
I want to add in this tab some informations related to the user and to make some associations with specific nodes related to the user.
Answer: If this is for Drupal 7, you should take a look at the profile2 module. It allows you to create a profile entity where you can add any fields. It also creates tabs on the user page via permissions.
In general to create tabs, you need to create menu local items. Views 3 support this, and it is also possible to create such a tab with hook_menu by setting the type to MENU_LOCAL_TASK. There are some requirements to the path of the url to make this work, but this is all well documented at the drupal API reference, linked to above.


A sequence of four numbers such that the first three are in G.P. and the last three are in A.P. What is wrong in my solution?

Question: I came across a question today

Given a sequence of four numbers such that the first three are in G.P. and the last three are in A.P. with common difference $6$. If the first and the fourth number are equal, then common ratio of the G.P. is?

Now correct way of doing this is given as:
Let the last three numbers be $a, a+6, a+12$, so that the first three numbers are $a+12, a, a+6$. As these are in G.P. $$a^2 = (a+12)(a+6) \Rightarrow a=-4$$
Common ratio is $-2$

But how I did this is
I took first term of G.P. as $a_1$ and the first term of A.P. as $a_2$. So the series is  $$a_1, (a_1r) \text{ or }(a_2), (a_1r^2) \text{ or } (a_2+6), a_2 +12$$
So,  $a_1 = a_2+12$ and $r= \dfrac{a_2+6}{a_2}$ and $a_1r^2 - a_1r=6$
Solving these three equations I get Common ratio (r) = $-0.5$

What is wrong in my solution? I know that my solution is bit more time consuming but why is it wrong?
Answer: The common ratio is indeed $-\frac{1}{2}$. You can check that the answer $a=-4$ of the first solution produces common ratio $-\frac{1}{2}$, and not $-2$.
Answer: Let the four terms be:
$$\begin{align}
&a\\
&ar=&&a-12\\
&ar^2=&&a-6\\
& &&a\end{align}$$
From the above, we have
$$6=a(1-r^2)\\
12=a(1-r)$$
Dividing (allowed as $r\neq 1$) and solving gives
$$r=-\frac12\quad\blacksquare$$

Solving gives $a=8$, hence the four numbers are
$$\lbrace 8,-4,\;2,\;8\rbrace$$
Answer: <>let the last three numbers of the set which are in A.P be b,b+6,b+12 and the first number be a.
→thus ,the four numbers are a,b,b+6,b+12
given,a=b+12-----(1)
also, given a,b,b+6 are in G.P
by equation (1)
→b+12,b,b+6 are in G.P
→b/(b+12)=(b+6)/b
→b²=(b+6)(b+12)
→b²=b²+18b+72
→18b=-72
→b=-4
→a=-4+12=8
hence the four numbers are 8,-4,2,8
I hope this will help u ;)
Comment: Here's a [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for typing math.


Javascript analog Clock Hour Hand Is Not Working while the other hands are

Question: I have an analog clock built with a bit of javascript code. The second hand and the minute hand are working perfectly, however, the hour hand is not functioning. Can anyone see why?
const deg = 6;
const degHR = 30;
const hr = document.querySelector("#hr");
const mn = document.querySelector("#mn");
const sc = document.querySelector("#sc");
setInterval(() => {
        let day = new Date();
        let hh = day.getHours() * degHR;
        let mm = day.getMinutes() * deg;
        let ss = day.getSeconds() * deg;
        hr.style.transform = `rotateZ(${hh+(mm/12)} deg)`;
        mn.style.transform = `rotateZ(${mm}deg)`;
        sc.style.transform = `rotateZ(${ss}deg)`;

Answer: I suspect because it's the only one with a fractional number of degrees. Try changing (mm/12) to Math.round(mm/12).
Comment: I gave it a shot with hr.style.transform = `rotateZ(${hh+Math.round(mm/12)} deg)`; with the same result.
Answer: The getHours() method returns hours in 24h format. Probably you want to adapt the corresponding lines as follows:
    let hh = ((day.getHours() % 12) + day.getMinutes()/60) * degHR;
    let mm = day.getMinutes() * deg;
    let ss = day.getSeconds() * deg;
    hr.style.transform = `rotateZ(${hh}deg)`;
    mn.style.transform = `rotateZ(${mm}deg)`;
    sc.style.transform = `rotateZ(${ss}deg)`;

Especially notice the removed space before deg!
Comment: Thanks... Still no luck with.
Comment: Maybe you can give some more information about what is wrong with the hour hand. Is it moving too slow?
Comment: I haven't had it running for an hour yet, but it is starting at the 12 o'clock position rather than the actual time.
Comment: I think your rotateZ transformation is also off. I edited my answer.
Comment: It probably starts at the 12 o'clock position because the transformation is not correctly applied. You need to remove the space before the deg unit.


Finding angle in isosceles triangle

Question: An isosceles triangle $ABC$ has $AB=AC$. Angle $A$ measures $20^\circ$. On $AC$, point $E$ is such that $AE=BC$. The task is to find the measure of angle $BEC$ without using trigonometry. How can one go about this?
Comment: Point E is on AC. EAC will be 0.
Comment: I can't see how knowing $\;BC=AE\;$ can be helpful *without trigonometry* in this case...
Comment: Investigate Euclid's Elements Book 1 Proposition 5 for an idea of how to proceed.
Comment: Its simple angle chasing...
Answer: Construct an isosceles triangle AEQ with ∠AQE = 20°. Since. AE = BC, the latter is equal to ΔABC. In particular, AQ = AB. Also,
∠BAQ = ∠EAQ - ∠EAB = 80° - 20° = 60°.
Which makes ΔABQ equilateral. In particular, BQ = EQ = AQ.
In ΔBQE, EQ = BQ and ∠BQE = 60° - 20° = 40°. Thus, ∠BEQ = (180° - 40°) / 2 = 70° so that ∠AEC = 80° + 70° = 150°.and from that angle BEC=30.

Finding angle in isosceles triangle


Switch user session programmatically

Question: I'm trying to switch user session thanks to Drupal Switch. I want to do this so that when I have a certain role, I can switch to another user account to check some data from the user i choose to switch.
My routing :
double_vue.page_double_vue:
    path: '/double-vue'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::doubleVue'
        _title: 'Double vue'
    requirements:
        _permission: 'access content'
double_vue.switched_user:
    path: '/double-vue/{userSwitchedID}'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::switchUser'
        _title: 'UserSwitched'
    requirements:
        _permission: 'access content'

My view :
switch

My function :
  public function switchUser($userSwitchedID){
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = \Drupal\user\Entity\User::load($userSwitchedID);
    return $accountSwitcher->switchTo($account);
  }

When I click on my to link to switch to another user, I have this error in my logs :

The controller must return a response
  (Object(Drupal\Core\Session\AccountSwitcher) given)

If I remove the return, I have this :

The controller must return a response (null given)

How can I fix that so that I can switch to another user account ?
Comment: The question you've asked has been answered, you need to ask a new question for next problem. There's no way you'll get a tutorial of how to build the entire functionality of the Masquerade module in a single question, it's not how this site is structured. If you break all of your tasks down and when you get stuck at any point, ask a single, narrowly-scoped question each time, you'll be able to build your own tutorial, while respecting the ethos of the site at the same time
Comment: You _have_ switched to a different user account - but you also need to return a response for the request. Could be a normal page, a redirect, even a binary file download - but you'll need to return a response
Comment: So what should I do ?
Comment: Return whatever response you need to - I couldn't tell you what that is, obviously, it's your requirement :)
Comment: I don't realy know, I have a "super user" who needs to have access to other user account by my view, I understood that I need to use the switch, but I don't what does this should return
Comment: Well what's the user supposed to see? What page are they supposed to be on after they've hit this URL? Return a redirect response to that URL
Comment: He's supposed to have access to other user's informations through view. It's like to have 2 sessions connected at the same time
Comment: That's impossible, at best you'd have to stash the old one and offer a way to switch back (like the Masquerade module does, for example).
Comment: Yes I need exactly something like masquerade, but with a frontend with all my users in a list and next to each user, the button like masquerade
Comment: You'll need to do some development yourself for that. If/when you get a specific question, that's when to ask here
Comment: I tried something, that's why I'm here ^^'
Answer: So first, the account switcher is for a temporary switch in the same request, to execute a specific thing as another user, it can't be used for what you want.
What Masquerade does is a lot more complicated and I don't understand why you don't just use that. Masquerade automatically adds itself to the user operations, so if you build a view that lists your users with the operations field then you will have exactly what you want to do.

The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

Switch user session programmatically


UIAutomation tests are not working on device

Question: I am trying to run few UIAutomation (XCTest) tests on device but as soon as I select my device a target device, all the tests in the test pane goes away and count shows 0. When I select simulator, I see all of them back.
I am using 5th Gen iPod Touch with iOS 8.3 and have enabled UI Automation in Settings --> Developer --> Enable UI Automation.
Anyone has a workaround or a solution to this situation?
PS:

I am using correct provisioning profile and can run the application directly from Xcode to my device but test are going away.
Tried disconnecting and reconnecting device on USB but no luck!
Tried re-booting the device but no luck!
Tried deleting Derived Data but no luck!
Answer: UI tests in Xcode require iOS 9. UIAutomation is the name of UI testing with Instruments:
https://developer.apple.com/library/ios/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/UIAutomation.html
Comment: Thank you @Mats for your response. I am not using profiler for automation testing. I am using XCUITest for scripting and UI automation. Is that also minimum iOS 9 supported? I am using Xcode 7.2.1.


Drupal Commerce: Can I have product list and checkout in the same page?

Question: I have a D7 site and I´m trying to implement Drupal Commerce.
I just need a page where the user can select the product from a list, and give some information about himself (billing information). And at the bottom it should be the "buy" button.
I don´t want a cart, the possibility of "continue shopping" and stuff like that.
How may I do that with Drupal Commerce? I´ve watched all day the videos and read some documentation, but it really seems over complicated when you just want a simple thing (opposed to a big ecommerce site).
Any guidance, tip or help will be very much appreciated. Thanks!
Answer: Try Commerce Express Checkout

The Express Checkout button redirects to the Checkout page directly,
  without going to the Cart first, It also removes the Review page and
  adds the Payment checkout pane to the Checkout page, so the whole
  checkout process is done on one page.

Ckeck

http://www.drupalcommerce.org/discussions/952/all-checkout-steps-one-page
http://atendesigngroup.com/blog/express-checkout-drupal-commerce


Is there any official WCF logo?

Question: It would be great to have a logo to put on a brochure for prospective clients. Silverlight has a logo. WPF has a logo : http://windowsclient.net/wpf/ . Where can I find the logo for WCF (windows communication foundation)?
Answer: As far as I'm aware, their logo is just the .Net one with some text, the same as on the community site:
Answer: Using images.google.com, this was the closest I could find:
Comment: Don't forget `-world -cat -federation -fight -championship -curling -chimpanzee -women` :)

Is there any official WCF logo?


Derive formula for volume element of manifold

Question: In a course regarding analysis of manifolds, I was given the following question:

$M\subseteq\mathbb{R}^n$ is a smooth $(n-1)$-dimensional manifold,
which is described by a graph of a function $f:U\rightarrow\mathbb{R}$
where $U\subseteq\mathbb{R}^{n-1}$ is an open set and $r:U\rightarrow M$ is the parameterization given by $r\left(x_{1},...,x_{n-1}\right)=\left(x_{1},...,x_{n-1},f\left(x_{1},...,x_{n-1}\right)\right)$ . Then the volume of
the manifold is:
$$\intop_{M}1dV=\intop_{U}\sqrt{1+\Vert\nabla f\Vert^{2}}du_{1}du_{2}...du_{n-1}$$

I've tried proving this using induction on the the dimension of the manifold but I get stuck in some real gritty algebra.
I know how to prove this for the case $n=3$, where the volume element is the square root of the Gram matrix made from each partial derivative.
$$\det\left(\mathrm{Gram}\left(\frac{\partial r}{\partial x_{1}},\frac{\partial r}{\partial x_{2}}\right)\right) =\left\langle \frac{\partial r}{\partial x_{1}},\frac{\partial r}{\partial x_{1}}\right\rangle \cdot\left\langle \frac{\partial r}{\partial x_{2}},\frac{\partial r}{\partial x_{2}}\right\rangle -\left\langle \frac{\partial r}{\partial x_{1}},\frac{\partial r}{\partial x_{2}}\right\rangle \cdot\left\langle \frac{\partial r}{\partial x_{2}},\frac{\partial r}{\partial x_{1}}\right\rangle
 =\left(1+\left|\frac{\partial f}{\partial x_{1}}\right|^{2}\right)\cdot\left(1+\left|\frac{\partial f}{\partial x_{2}}\right|^{2}\right)-\left(\left|\frac{\partial f}{\partial x_{1}}\right|\left|\frac{\partial f}{\partial x_{2}}\right|\right)^{2}
 =1+\left|\frac{\partial f}{\partial x_{1}}\right|^{2}+\left|\frac{\partial f}{\partial x_{2}}\right|^{2}=1+\Vert\nabla f\Vert^{2}$$
So the volume element comes out the way I want it.
But the next transition is the one I get stuck on:
$$\det\left(\mathrm{Gram}\left(\frac{\partial r}{\partial x_{1}},...,\frac{\partial r}{\partial x_{n-1}}\right)\right)=1+\Vert\nabla f\Vert^{2}$$
I would appreciate a nudge in the right direction.
Answer: First we notice
$$\mathrm{Gram}\left(\frac{\partial r}{\partial x_{1}},...,\frac{\partial r}{\partial x_{n-1}}\right)= I_{n-1} + \nabla f\cdot(\nabla f)^\mathrm{T}$$
Choose an orthogonal matrix $O$ such that $O(\nabla f) = (\Vert\nabla f\Vert,0,\dots,0)^\mathrm{T}$, then
$$\det\left(\mathrm{Gram}\left(\frac{\partial r}{\partial x_{1}},...,\frac{\partial r}{\partial x_{n-1}}\right)\right) = \det\left(I_{n-1} +\nabla f\cdot(\nabla f)^\mathrm{T}\right) = \det\left(OO^\mathrm{T} +O\nabla f\cdot(\nabla f)^\mathrm{T} O^\mathrm{T}\right) = \det\left(\text{diag}(1+\Vert\nabla f\Vert^2,1,\dots,1)\right) = 1+\Vert\nabla f\Vert^2$$
Comment: $(\nabla f)^\mathrm{T}\cdot\nabla f$ is a scalar, so how would you define the addition in the first row?
Comment: Oh I have misidentified $\nabla f$ with its transpose. Editted.


Nagios SMS notification with gammu smsd does not work

Question: gammu-smsd configuration:
#vi /etc/gammu-smsdrc

 # Configuration file for Gammu SMS Daemon

 # Gammu library configuration, see gammurc(5)
[gammu]
 # Please configure this!
port = /dev/rfcomm0
connection = bluephonet
 # Debugging
logformat = textall

 # SMSD configuration, see gammu-smsdrc(5)
[smsd]
service = files
 #logfile = syslog
logfile = /var/log/gammu-smsd

 # Increase for debugging information
debuglevel = 0

 # Paths where messages are stored
inboxpath = /var/spool/gammu/inbox/
outboxpath = /var/spool/gammu/outbox/
sentsmspath = /var/spool/gammu/sent/

It works and I can send SMS from terminal.
Nagios
#vi /etc/nagios3/conf.d/localhost_nagios2.cfg
define host{
          use                     generic-host            ; Name of host template to use
          host_name               localhost
          alias                   localhost
          address                 x.x.x.187
          check_command           check-host-alive
          max_check_attempts      10
          notification_interval   120
         notification_period     24x7
          notification_options    d,r
          contact_groups  admins
  }

#vi /etc/nagios3/conf.d/timeperiods_nagios2.cfg
 define timeperiod{
         timeperiod_name 24x7
         alias           24 Hours A Day, 7 Days A Week
        sunday          00:00-24:00
         monday          00:00-24:00
         tuesday         00:00-24:00
         wednesday       00:00-24:00
         thursday        00:00-24:00
         friday          00:00-24:00
         saturday        00:00-24:00
 }

#vi /etc/nagios3/conf.d/contacts_nagios2.cfg
 define contact{
         contact_name                    localhost
         alias                           localhost
         service_notification_period     24x7
         host_notification_period        24x7
         service_notification_options    w,u,c,r
         host_notification_options       d,r
         service_notification_commands   notify-service-by-sms
         host_notification_commands      notify-host-by-sms
         pager                           +88xxxxxxxxxxx
 }
 define contactgroup{
         contactgroup_name       admins
         alias                   Nagios Administrators
         members                 localhost
 }

 #vi /etc/nagios3/conf.d/services_nagios2.cfg
 define service{
         use                             generic-service
         host_name                       localhost
         service_description             SSH
         is_volatile                     0
         check_period                    24x7
         max_check_attempts              4
         normal_check_interval           5
         retry_check_interval            1
         contact_groups                  admins
         notification_interval           960
         notification_period             24x7
         check_command                   check_ssh
  }

Command:
define command{
        command_name    notify-host-by-sms
        command_line    /usr/bin/printf "%b" "Alert $HOSTNAME$ is $HOSTSTATE$" | /usr/bin/gammu --sendsms TEXT $CONTACTPAGER$

        }

define command{
        command_name    notify-service-by-sms
        command_line    /usr/bin/printf "%b" "Alert service $SERVICEDESC$ on $HOSTNAME$" is $SERVICESTATE$ | /usr/bin/gammu --sendsms TEXT $CONTACTPAGER$

        }

Edit:
log

Sun 2012/08/12 23:14:03 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:14:41 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:15:17 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:15:55 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:16:32 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:17:09 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:17:46 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:18:25 gammu-smsd[5712]: Read 0 messages
Sun 2012/08/12 23:19:04 gammu-smsd[5712]: Read 0 messages

Additional info
Nagios.log

[1344792542] SERVICE ALERT: localhost;SSH;CRITICAL;SOFT;1;Connection refused
[1344792602] SERVICE ALERT: localhost;SSH;CRITICAL;SOFT;2;Connection refused

#grep notify-service-by-sms /var/log/nagios3/nagios.log

[1344760748] SERVICE NOTIFICATION: localhost;localhost;SSH;CRITICAL;notify-service-by-sms;Connection refused
[1344762800] SERVICE NOTIFICATION: localhost;localhost;SSH;OK;notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0)
[1344780228] SERVICE NOTIFICATION: localhost;localhost;SSH;CRITICAL;notify-service-by-sms;Connection refused
[1344784378] SERVICE NOTIFICATION: localhost;localhost;SSH;OK;notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0)
[1344785462] SERVICE NOTIFICATION: localhost;localhost;SSH;CRITICAL;notify-service-by-sms;Connection refused
[1344785762] SERVICE NOTIFICATION: localhost;localhost;SSH;OK;notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0)
[1344786242] SERVICE NOTIFICATION: localhost;localhost;SSH;CRITICAL;notify-service-by-sms;Connection refused
[1344786842] SERVICE NOTIFICATION: localhost;localhost;SSH;OK;notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0)
[1344788117] SERVICE NOTIFICATION: localhost;localhost;SSH;CUSTOM (OK);notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0);nagiosadmin;test
[1344792289] SERVICE NOTIFICATION: localhost;localhost;SSH;CUSTOM (OK);notify-service-by-sms;SSH OK - OpenSSH_5.9p1 Debian-5ubuntu1 (protocol 2.0);nagiosadmin;sdd
[1344792722] SERVICE NOTIFICATION: localhost;localhost;SSH;CRITICAL;notify-service-by-sms;Connection refused

Nagios.debug
[1344830776.241243] [256.1] [pid=2978] Running command '/usr/bin/printf "%b" "Alert service SSH on localhost" is CRITICAL | /usr/bin/gammu --sendsms TEXT +880xxxxxxxxxx'...
[1344830776.258139] [256.1] [pid=2978] Execution time=0.016 sec, early timeout=0, result=3, output=Error opening device, it doesn't exist.

Sending SMS from nagios user
root@khalid-Dell-System-Inspiron-N4110:/home/khalid# sudo su - nagios -s /bin/bash
nagios@khalid-Dell-System-Inspiron-N4110:~$ echo "Test SMS" | gammu-smsd-inject TEXT   88xxxxxxxxxxx

gammu-smsd-inject[3438]: Warning: No PIN code in /etc/gammu-smsdrc file
Failed to inject message: Can not open specified file.
nagios@khalid-Dell-System-Inspiron-N4110:~$

Comment: Once you get the problem, you should take a look at the logs to see what happens. If it doesn't help, increase the debug level.
Comment: How about `nagios.log`?
Comment: I looked at but could not get any help by google
Comment: I haven't looked at nagios.log. Thank you....Now I am trying to fix it....
Comment: i have added the output of `grep notify-service-by-sms /path/to/nagios.log` above.
Comment: set `debug_level` to 256, try again and post the `nagios.debug` here.
Answer:
It works and I can send SMS from terminal.

Have you tested as root?
output=Error opening device, it doesn't exist.

Make sure that nagios (and apache if you want) has write permission on /dev/rfcomm0.
Check this first:
# ls -l /dev/rfcomm0

Assumming you get:
crw-rw---- 1 root dialout 216, 0 2012-08-10 23:15 /dev/rfcomm0

then add the nagios user to the dialout group:
$ sudo usermod -a -G dialout nagios

and try again.

UPDATE Mon Aug 13 17:57:59 ICT 2012
Set the SUID bit on the command to allow nagios execute gammu on behalf of the root:
# chmod 4755 /usr/bin/gammu

and try again:
# su - nagios -s /bin/bash
$ echo "test" | gammu –sendsms TEXT 0123456789

Comment: `# ls -l /dev/rfcomm0`
`ls: cannot access /dev/rfcomm0: No such file or directory`
Comment: I take it from your above config `port = /dev/rfcomm0`.
Comment: I have connected my phone using blue-tooth and assigned `port = /dev/rfcomm0`. It works and I can send SMS from terminal. I executed `root@khalid:/dev# ls -l` but `rfcomm0` was not found. How SMS is being sent using `/dev/rfcomm0` port(actually it does not exist in `dev` directory)?
Comment: After plugging your phone, type `dmesg` to see which port it is using.
Comment: I have copied output of `dmesg` to this [file](http://www.mediafire.com/?owukq71hzg4j1rf). I could not find out actual port from the output.
Comment: Use a pastebin client tool (fpaste, wgetpaste, ...) to paste some ending lines. Dont't upload to mediafire. Switch to `nagios` user (`su - nagios -s /bin/bash`) and send a testing sms with gammu to see what does it say.
Comment: when I Switch to nagios user, Should I be root to send SMS??
Comment: I connected my mobile phone through USB cable and now nagios sends SMS alert. Problem is that it is not real-time. If any service is down, It takes around two minutes to send SMS alert. What should I do??
Comment: It depends on normal_check_interval, max_check_attempts, ...
Comment: I have changed `interval_length=1` (in nagios.cfg file), `normal_check_interval=1` and `max_check_attempts=1` in host definition. Still it takes around one minute.
Comment: http://nagios.sourceforge.net/docs/3_0/configmain.html#interval_length
Comment: I have read above link and they  have not tested other values for `interval_length` variable. I set it to `1s` that reduced alert time to around one minute. I could not find any way to send sms alert in a second. Is it possible to send SMS alert in one/two second(s)???
Comment: It is possible. But are you sure you want to do this? Post another topic and insert link here.
Comment: http://serverfault.com/questions/422377/how-to-configure-nagios-realtime-sms-alert


Android CTS: adb disconnects after reboot

Question: I've been trying to run Android CTS on my device. On my first few tries, I had success with running the test suite. I then tried to reproduce my steps and faced an error. When running CTS step 28/287 forces the device to reboot. After the device successfully reboots, the ADB connection suddenly disconnects and the test cycle ends early.
I/ModuleListener: [28/287] android.appsecurity.cts.DirectBootHostTest#testDirectBootNative pass
Any help is greatly appreciated. Please let me know if I need to provide additional details. Thanks!
Answer: I figured out why adb would disconnect after a reboot. I'm currently running Ubuntu on VMware. Once a new removable device is connected, a dialogue box pops up asking where to connect the device (Host or VM). If you set a connection rule, the device will connect to the specified destination after a reboot. My connection rule was to connect to the Host, which is why adb lost connection after a reboot. To change the connection rule in VMware version 16.0: Player > Removable Devices > Your device > Disconnect & Forget Connection Rule.


Finding Taylor polynomial for fractional function

Question: I should find Taylor polynomial of a degree $n \in \mathbb{N}$ for function $f(x) =\frac{x}{9+x^2}$ at the point of 0.
For which $x \in \mathbb{R}$ this polynomial converges to the given function $f$ for $n \rightarrow \infty$?

So there is a general formula for Taylor series: $f(a)+\frac {f'(a)}{1!} (x-a)+ \frac{f''(a)}{2!} (x-a)^2+\frac{f^{(3)}(a)}{3!}(x-a)^3+ \cdots. $ I assume, that in this formula for my given data, a=0 and the only thing I should do is to derive the function?
Comment: Yes, your suggestion will work. Also, the series will only converge to the function until it reaches the pole, i.e. for |x|<3.
Comment: Do you know the Taylor expansion of other functions, like $\;\log x\;,\;\;\sin x\;$ and etc.?
Answer: Here are a few pointers:

First, find the Taylor polynomial for $\frac{1}{1-x}$. The geometric series should be of some use! And you can find an explicit formula for the error term too.
Use this to find the Taylor polynomial for $\frac{1}{1+x^2}$. Just replace the symbol $x$ with the symbol $-x^2$.
Use this to find the Taylor polynomial for $\frac{1}{1+(x/3)^2}$. Again, just replace the symbol $x$ with the symbol $x/3$.
Now just multiply by $x/9$.

Now just determine for which values of $x$ your error term goes to zero as $n\to\infty$.
Comment: Yes. You're on the right track. But the question requires a Taylor polynomial of degree $n$, not the series. And you also want to find the error term. So you have to find the difference between $1+x+...+x^n$ and $\frac{1}{1-x}$. The first term is a finite geometric series, so you can easily find a formula for its sum. Then use this to find the error...
Comment: Yes, that's right.
Comment: Right. This means you'll have to approach it as above, from what I can tell.
Comment: OK. ad1) It looks fine - just simple $1 + x + x^2 + x^3 + \cdots $?

ad2) Replacing the symbol will cause $1 - x^2 + x^4 - x^6 + \cdots $

ad3) Another replacement is leading to $1 - \left(\frac{x}{3}\right)^2 + \left(\frac{x}{3}\right)^4 - \left(\frac{x}{3}\right)^6 + \cdots$

ad4) Should I multiply everything like $\frac{x}{9} - \frac{x}{9}\left(\frac{x}{3}\right)^2 + \frac{x}{9}\left(\frac{x}{3}\right)^4 - \frac{x}{9}\left(\frac{x}{3}\right)^6 + \cdots $
Comment: Is the only difference between Taylor series and polynomial, that the sereies goes to infinity, but the polynomial has the last member (the $n^{th}$ one)?
Comment: By the way, the answer given by @Timbuc below is much more efficient if you're allowed to assume the taylor series for log. Mine is approach is uglier, but assumes a little less.
Comment: There is a small problem. We still "don't know", how to integrate (we will be given the possibility of integration in a month)...
Answer: An idea:
$$f(x)=\frac x{9+x^2}=\frac12\;\frac{\frac29x}{1+\frac{x^2}9}\implies$$
$$ \int f(x)\,dx=\frac12\log\left(1+\frac{x^2}9\right)=\frac12\sum_{n=1}^\infty(-1)^{n+1}\frac{x^{2n}}{3^{2n}}\;,\;\;\text{for}\;\;\frac{x^2}9<1\iff -3<x<3\implies$$
$$\frac x{9+x^2}=\left(\int f(x)\,dx\right)'=\frac12\sum_{n=1}^\infty(-1)^{n+1}\frac{2nx^{2n-1}}{9^n}\;,\;\;\text{for}\;\;-3<x<3$$


Using FormState::setError() in Form::submitForm()

Question: I am writing a form in Drupal 8 that provides user values to a web service, which will either act on them or send back an error.
How can I display that error message to the user?
Here's the situation in code:
class FooForm extends BarForm implements FormInterface {

  protected $fooClient;

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state {

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This doesn't seem correct: Posting to a web service is not idempotent.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This throws a LogicException.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }
}

Drupal treats 'validate' and 'submit' as two separate steps, but the web service doesn't. The only way to determine if the values are fully 'valid' is to get the web service to look at them, which is an operation that potentially has side effects.
validateForm() and other form validation handlers are not supposed to contain business logic, since they may get called multiple times during the life of the form, particularly if AJAX is involved.
However, all errors are meant to be resolved before submitForm() and any other submission handlers are called. FormState::setError() enforces this by throwing a LogicException if you try to create any. Also, submitForm() clears away the user's values, and the next page builds the form from scratch.
I've seen this similar question for Drupal 7. Back then, it was possible (if discouraged and ugly) to use form_set_error() in the submit handler or the form builder. As far as I can tell, that flat-out doesn't work in Drupal 8.
How am I supposed to interact with RESTful web services? Is there a way to pass errors up from a form submit handler? Or is there a way to ensure a validation handler runs once, only once, and only if all other validation passes? Or is there some way to do this with multi-step forms?
Comment: Add multiple validation handlers. Submit handler has nothing to do with validation(hence the name). $form['#validate'] = ['validateSomething', 'validateSomethingElse', 'validateSomeCompletelyDifferentThing'];
Comment: I'm aware that I can add a validation handler that just contacts the web service.  However, it's still a validation handler: It's not supposed to contain business logic or have side effects.  Contacting the web service might result in an action on their side.

I've edited the question, I hope it's clearer now?
Answer: The Drupal form system, isn't really built for what you are trying to do. I see two ways of going about this:

Webservice validation
If the webservice can do a validation of the data or such a method can be added, you can use the form system as is, and use ::validateForm to validate via webservice.
Rebuild form
What you can do, instead of doing a "validation" is to delete your ::validateForm method entirely and just send the data to the webservice in the ::submitForm. If the operation fails, you can rebuild the form and display a message to the user. You can make it appear as a validation error even though it technically isn't. Drupal does something like this as well. Fx in NodeForm::save
public function save(array $form, FormStateInterface $form_state) {
  ...
  $node->save();
  ...
  if ($node->id()) {
    ...
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
    $form_state->setRebuild();
  }
}

So basically, you can use $form_state->setRebuild() and drupal_set_message to make something that mimics validation in the submit handler. You can also save data in the store ($form_state->setStorate($data)) which you can use the form method to display error message or something else to the user.
Answer: @googletorp answer works well. I just want to add one more thing: you cannot use setError() in buildForm(), therefore, in order to visually indicate which element has problem, you want to set
$form['THE_PROBLEM_ELEMENT']['#attributes']['class'][] = 'error';


Why does $n(n+1)(2n+1)+6(n+1)^2=(n+1)(n(2n+1)+6(n+1))$?

Question:

I'm not sure how my professor got from:
  $$n(n+1)(2n+1)+6(n+1)^2 ~\text{to}~ (n+1)(n(2n+1)+6(n+1))$$

I have a feeling it's an algebra thing but I just can't seem to get it. Would really appreciate the help.
Comment: Your teacher took out the common factor $(n+1)$ from $n(n+1)(2n+1)$ to leave $n(2n+1)$ and from  $6(n+1)^2$ to leave $6(n+1)$.  For rings (including real numbers) you have distributivity:  $xy+xz=x(y+z)$
Comment: Take (n+1) commonly out side.
Comment: Do you mean $$\frac{n(n+1)(2n+1)}{6}+(n+1)^2$$?
Comment: @the_candyman.  I don't think the OP meant "proof".  I think the OP mean "prof" and is in "my prof" = "my professor".
Comment: @fleablood lol, I fixed it. Thanks.
Answer: You can expand your equation to :
$$n(n+1)(2n+1)+6(n+1)^2 = n(n+1)(2n+1)+6(n+1)(n+1)$$
On the right hand side you will notice that $n+1$ occurs in each group of terms and this can be factored out as follows:
$$n(n+1)(2n+1)+6(n+1)(n+1) = (n+1)\cdot\left[n(2n+1)+6(n+1)\right]$$
Answer: It is an algebra thing.
$\color{blue}{n}\color{green}{(n+1)}\color{blue}{(2n+1)}$ and $\color{red}6\color{green}{(n+1)}^{\color{red}2}$ both have $\color{green}{(n+1)}$ as a common factor.  So the common factor can be factored out:
$\color{blue}{n}\color{green}{(n+1)}\color{blue}{(2n+1)} + \color{red}6\color{green}{(n+1)}^{\color{red}2} = \color{green}{(n+1)}[\color{blue}{n}\color{blue}{(2n+1)} + \color{red}6\color{green}{(n+1)}^{\color{red}1}]$
Answer: One way is to start with $$n(n+1)(2n+1)+6(n+1)^2$$
and factor $(n+1)$ to get $$ (n+1)(n(2n+1)+6(n+1))$$
The other way which is lengthy is to multiply both sides and see if you get the same expressions. ( not recommended)
Comment: Not recommended.  But it *is* convincing!
Comment: Sure it is very convincing.


Babel setup error: "ERROR in ./src/js/index.js"

Question: UPDATE: I fixed the issue. Look in answers.
Goal: Set up Babel.
Issue: I run into an error when I use webpack to create a bundle.js file using the command: npm run dev.
screenshot 1 screenshot 2
./src/js/index.js
import num from "./test";
const x = 45;
console.log(`I imported ${num} from test.js - ${x}`);

webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: ["babel-polyfill", "./src/js/index.js"],
    output: {
        path: path.resolve(__dirname, "dist"),
    filename: "js/bundle.js"
    },
    devServer: {
    contentBase: "./dist"
    },
    plugins: [
    new HtmlWebpackPlugin({
        filename: "index.html",
        template: "./src/index.html"
    })
    ],
    module: {
    rules: [
        {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
                }
        }
        ]
    }
};

Comment: You're missing a module: `npm i -D @babel/core`
Comment: I have the package installed already. It shows up in my package.json file.
Answer: I fixed the error. Turns out I needed to install new Babel packages.
npm install --save-dev @babel/core @babel/preset-env
npm install --save @babel/polyfill

Replace entry in webpack.config.js with:
entry: ["@babel/polyfill", "./src/js/index.js"],

Replace presets in .babelrc with:
{
  "presets": ["@babel/env"]
}

Answer: Looks like you're missing babel-core
I think running:

npm install --save-dev babel-core

Should fix it
Comment: I have the package installed already. It shows up in my package.json file.
Comment: Just saw your other comment about it being in package.json. Try deleting `node_modules`, and then `npm install` again
Comment: Or, to confirm it is indeed installed, open the `node_modules` folder, and see if you can see the `babel-core` folder
Comment: Babel-core is in node_modules.
Comment: what's in the `/.test` file?
Comment: console.log("imported module");
export default 333;
Comment: Purpose of it was to check if the files are connected.
Comment: Did you try deleting `node_modules` and then re-running `npm install`?
Comment: I fixed the issue! Look at the answer I posted if you're interested. Thanks!


Combinatorics - rotating people through different groups / tables

Question: I am trying to figure out a rotation schedule for 46 people. We have 6 tables. 5 tables have 4 groups of 2. 1 table has 3 groups of 2.  We have 6 rounds and people are in groups of 2 for each round. The first round, 1 person in each pair presents their sales pitch and the other person listens. For the second round, they rotate to new tables in new groups and have new partners. The rep that presented is now a listener and the listener becomes a presenter. This goes on for all 6 rounds which means a person presents 3 times and listens 3 times, each time at a new table with a new partner.
Table 1 - 4 groups of 2
Table 2 - 4 groups of 2
Table 3 - 4 groups of 2
Table 4 - 4 groups of 2
Table 5 - 4 groups of 2
Table 6 - 3 groups of 2
I cannot, for the life of me,figure out how to do these rotations.
Comment: If you want it exactly as you have said, then it is impossible.  Reason (if I have understood the problem correctly): you have 46 people and they all have to be at every table once, in 6 rounds.  But table 6 only holds 6 people, so in 6 rounds it will only get a maximum of 36 different people, so at least 10 people must miss out on table 6.  So it seems that you will need to relax your requirements.
Comment: So I either have to bump it to 48 tables or someone will sit at a table 2x
Comment: Even if I bump it to 48 tables or people have to sit at the same table twice, I would still need to figure out how to do it.
Comment: Well, if you change the conditions then it **might** be possible.  But maybe it will still be impossible for different reasons.  Sometimes this sort of scheduling task is impossible for very subtle and complicated reasons.  It could be (emphasize: "could be" - I honestly don't have much of a clue) that you would have to make some pretty major changes.
Comment: David, it is not possible since there are 8 people at a table and only 6 tables. I haven't had to work through a problem like this in a while. Thank you for giving me some things to think about.
Answer: I did a simple trial and error, looks to be correct to me, but someone should look it over again.
Assign a number to each person x=1-46.
After each rotation, new number(y) = mod(3x+8,46)+1.
Thus for Round 1.
Table 1: 1  2   3   4   5   6   7   8
Table 2: 9  10  11  12  13  14  15  16
Table 3: 17 18  19  20  21  22  23  24
Table 4: 25 26  27  28  29  30  31  32
Table 5: 33 34  35  36  37  38  39  40
Table 6: 41 42  43  44  45  46
Round 2
12  15  18  21  24  27  30  33
36  39  42  45  2   5   8   11
14  17  20  23  26  29  32  35
38  41  44  1   4   7   10  13
16  19  22  25  28  31  34  37
40  43  46  3   6   9
Round 3
45  8   17  26  35  44  7   16
25  34  43  6   15  24  33  42
5   14  23  32  41  4   13  22
31  40  3   12  21  30  39  2
11  20  29  38  1   10  19  28
37  46  9   18  27  36
Round 4
6   33  14  41  22  3   30  11
38  19  46  27  8   35  16  43
24  5   32  13  40  21  2   29
10  37  18  45  26  7   34  15
42  23  4   31  12  39  20  1
28  9   36  17  44  25
Round 5
27  16  5   40  29  18  7   42
31  20  9   44  33  22  11  46
35  24  13  2   37  26  15  4
39  28  17  6   41  30  19  8
43  32  21  10  45  34  23  12
1   36  25  14  3   38
Round 6
44  11  24  37  4   17  30  43
10  23  36  3   16  29  42  9
22  35  2   15  28  41  8   21
34  1   14  27  40  7   20  33
46  13  26  39  6   19  32  45
12  25  38  5   18  31
Comment: If I am following this correctly, person #1 ends up at table 4 twice and table 5 twice.


Drive allocation in a RAID 50 array on a HPE DL380 G9

Question: I have a DL380 G9 with 12x8TB 3.5" disks:
<code>| 1 | 4 | 7 | 10 |
| 2 | 5 | 8 | 11 |
| 3 | 6 | 9 | 12 |
</code>
In the Smart Array Controller GUI, if I select all 12 disks and assign them to a RAID 50 array, how will the controller divide the disks for the RAID 5 arrays?
Will drives 1-6 and 7-12 inclusive be in two separate RAID 5 arrays, striped for RAID 0? Or will drives 1-3, 4-6, 7-9, and 10-12 be in four separate RAID 5 arrays striped for RAID 0?
If it's the former by default, is it possible to manually configure the array to the latter?
Comment: Don't do R5/R50, it's 2020 and it's been dangerous for a decade, please don't - R1/10 and R6/60 are the only games in town.
Comment: Single parity RAID (5/50) is dead for >600GB HDDs. https://www.securedatarecovery.com/blog/4-ways-that-raid-5-systems-can-lose-data
Comment: ...it's fine for SSDs though. https://www.starwindsoftware.com/blog/raid-5-was-great-until-high-capacity-hdds-came-into-play-but-ssds-restored-its-former-glory-2
Answer: The number of RAID5 sets for RAID0 should be able to configure in raid utility. In your case you can select 2 (6 disks in RAID5), 3 (4 disks in RAID5) or 4(3 disks in RAID5).
From perfromance and capacity perspective - 2 RAID5 sets is most preferable in your case.
P.S. RAID50 tolerates only one disk failure (second disk failure from same RAID5 set will bring whole system down)


How to compare XLS file to json file?

Question: Hi I have a task to compare some XLS files to json files I have working code but the loop is comparing only first row from xls, does not go to the next one.
def verify_xlsx_file_content_against_json(json, xlsx_path):

    found_configs_ct = 0
    xlsx_reader = XLSXReader()
    data_frame = xlsx_reader.read_xlsx(xlsx_path, "Configuration Set")
    for config in json_definition:
        items_compared = 0
        for item in config["content"]["items"]:
            for index, row in data_frame.iterrows():
                if config["segAlias"] == row["Seg Alias"] and item["itemsOrder"] == row["Items Order"]:
                    found_configs_ct += 1
                    if index == 0:
                        def_platforms = config["platforms"]
                        platforms = ["gp", "ios", "win32", "fb", "amazon"]
                        for platform in platforms:
                            if platform in def_platforms:
                                assert_equal_values(row[convert_def_platform_to_excel_platform_name(platform)], "Y","{" + platform + "} should be True! and is not.")
                            else:
                                assert_equal_values(row[convert_def_platform_to_excel_platform_name(platform)], "N","{" + platform + "} should be False! and is not.")
                        name_from_definition = config["content"]["items"][0]["name"]  # all items have the same name thus index 0 is sufficient
                        assert_equal_values(row["Name"], name_from_definition, "Content name is invalid")
                    Logger.LogInfo(str(item["identifier"]) + ' identifier')
                    Logger.LogInfo(str(row["Identifier"]) + ' Identifier')
                    Logger.LogInfo(str(item["itemsOrder"]) + ' itemsOrder')
                    Logger.LogInfo(str(row["Items Order"]) + ' Items Order')
                    Logger.LogInfo(str(item["dValue"]) + ' dValue')
                    Logger.LogInfo(str(row["D Value, $"]) + ' D Value, $')
                    Logger.LogInfo(str(row["Pack Image"]) + ' PackImage from row  <<<<<<<<<<<<<<<')
                    Logger.LogInfo(str(item["packImage"]) + ' packImage second from item-<<<<<<<<')
                    assert_equal_values(str(item["identifier"]), str(row["Identifier"]), "Identifier is not match!")
                    assert_equal_values(str(item["itemsOrder"]), str(row["Items Order"]), "Items Order is not match!")
                    assert_equal_values(str(item["packImage"]), str(row["Pack Image"]), "packImage is not match!")
                    assert_equal_values(str(item["dValue"]), str(row["D Value, $"]),"dValue  not match!")
                    # assert_equal_values(str(item["remarks"]), str(row["Remarks"]), "Remarks is not match!")
                    items_compared += 1
                    break
        assert_equal_values(items_compared, len(
            config["content"]["items"]), "number of items compared is less than actual items")
    return False
    logging.info("verification done. ---no problems detected--")
    return True  # if code got here, no errors on the way, return True

what I get here is
NFO:root:[2020-02-14 09:33:24.543957] 0 identifier
      INFO:root:[2020-02-14 09:33:24.543957] -1 Identifier
      INFO:root:[2020-02-14 09:33:24.543957] 1 itemsOrder
      INFO:root:[2020-02-14 09:33:24.543957] 1 Items Order
      INFO:root:[2020-02-14 09:33:24.543957] 1.99 dValue
      INFO:root:[2020-02-14 09:33:24.543957] 1.99 D Value, $
      INFO:root:[2020-02-14 09:33:24.544953] 1 identifier
      INFO:root:[2020-02-14 09:33:24.544953] -1 Identifier
      INFO:root:[2020-02-14 09:33:24.544953] 2 itemsOrder
      INFO:root:[2020-02-14 09:33:24.544953] 1 Items Order
      INFO:root:[2020-02-14 09:33:24.544953] 2.99 dValue
      INFO:root:[2020-02-14 09:33:24.544953] 1.99 D Value,
      INFO:root:[2020-02-14 09:33:24.544953] 2 identifier
      INFO:root:[2020-02-14 09:33:24.545949] -1 Identifier

So -1 Identifier is always -1 and should change incrementally (0,1,2... ) like in json file.
How to change this loop to make this code work? and later to assert those files json vs xls
What I did
df = pd.read_excel("download1.xlsx") #xlsx to json
json_from_excel = df.to_json() #json string
print(type(json_from_excel))
print(json_from_excel)
final_dictionary = json.loads(json_from_excel) #dict
print(type(final_dictionary))
print(final_dictionary)

with open('basic.json', 'r') as jason_file:
    data = json.loads(jason_file.read())
    for item in data:
        print(type(item))

and the result is
<class 'str'>
{"Name":{"0":"default_config","1":"default_config","2":"default_config","3":"default_config","4":"default_config","5":"gems1","6":"gems1","7":"gems1","8":"gems1","9":"gems1","10":"gems2","11":"gems2","12":"gems2","13":"gems2","14":"gems2","15":"gems3","16":"gems3","17":"gems3","18":"gems3","19":"gems3"},"Identifier":{"0":11294,"1":11294,"2":11294,"3":11294,"4":11294,"5":11295,"6":11295,"7":11295,"8":11295,"9":11295,"10":11296,"11":11296,"12":11296,"13":11296,"14":11296,"15":11297,"16":11297,"17":11297,"18":11297,"19":11297},"Segment Alias":{"0":"default","1":"default","2":"default","3":"default","4":"default","5":"rhinoQA_1","6":"rhinoQA_1","7":"rhinoQA_1","8":"rhinoQA_1","9":"rhinoQA_1","10":"rhinoQA_2","11":"rhinoQA_2","12":"rhinoQA_2","13":"rhinoQA_2","14":"rhinoQA_2","15":"rhinoQA_3","16":"rhinoQA_3","17":"rhinoQA_3","18":"rhinoQA_3","19":"rhinoQA_3"},"Segment ID":{"0":-1,"1":-1,"2":-1,"3":-1,"4":-1,"5":95365,"6":95365,"7":95365,"8":95365,"9":95365,"10":95366,"11":95366,"12":95366,"13":95366,"14":95366,"15":95367,"16":95367,"17":95367,"18":95367,"19":95367},"GP":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"iOS":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"Y","6":"Y","7":"Y","8":"Y","9":"Y","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"FB":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"Y","11":"Y","12":"Y","13":"Y","14":"Y","15":"N","16":"N","17":"N","18":"N","19":"N"},"Amazon":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"Y","16":"Y","17":"Y","18":"Y","19":"Y"},"Win32":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"Remarks":{"0":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","1":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","2":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","3":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","4":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","5":"*inserted_by_automated_test*","6":"*inserted_by_automated_test*","7":"*inserted_by_automated_test*","8":"*inserted_by_automated_test*","9":"*inserted_by_automated_test*","10":"x1","11":"x1","12":"x1","13":"x1","14":"x1","15":"x3","16":"x3","17":"x3","18":"x3","19":"x3"},"Pack Name":{"0":"test_bingo","1":"test_bingo","2":"test_bingo","3":"test_bingo","4":"test_bingo","5":"test_bingo","6":"test_bingo","7":"test_bingo","8":"test_bingo","9":"test_bingo","10":"test_bingo","11":"test_bingo","12":"test_bingo","13":"test_bingo","14":"test_bingo","15":"test_bingo","16":"test_bingo","17":"test_bingo","18":"test_bingo","19":"test_bingo"},"SKU":{"0":"gems_99","1":"gems_99","2":"gems_99","3":"gems_99","4":"gems_99","5":"gems_99","6":"gems_99","7":"gems_99","8":"gems_99","9":"gems_99","10":"gems_99","11":"gems_99","12":"gems_99","13":"gems_99","14":"gems_99","15":"gems_99","16":"gems_99","17":"gems_99","18":"gems_99","19":"gems_99"},"Sold Item":{"0":"Gems","1":"Gems","2":"Gems","3":"Gems","4":"Gems","5":"Gems","6":"Gems","7":"Gems","8":"Gems","9":"Gems","10":"Gems","11":"Gems","12":"Gems","13":"Gems","14":"Gems","15":"Gems","16":"Gems","17":"Gems","18":"Gems","19":"Gems"},"Items Order":{"0":1,"1":2,"2":3,"3":4,"4":5,"5":1,"6":2,"7":3,"8":4,"9":5,"10":1,"11":2,"12":3,"13":4,"14":5,"15":1,"16":2,"17":3,"18":4,"19":5},"Dollar Value, $":{"0":1.99,"1":2.99,"2":3.99,"3":4.99,"4":5.99,"5":1.99,"6":2.99,"7":3.99,"8":4.99,"9":5.99,"10":1.99,"11":11.99,"12":13.99,"13":14.99,"14":15.99,"15":1.99,"16":2.99,"17":3.99,"18":4.99,"19":5.99},"Item Quantity":{"0":5,"1":15,"2":25,"3":35,"4":45,"5":5,"6":15,"7":25,"8":55,"9":65,"10":5,"11":15,"12":45,"13":55,"14":75,"15":5,"16":15,"17":55,"18":95,"19":85},"Is Best":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"Y","6":"Y","7":"Y","8":"Y","9":"Y","10":"Y","11":"Y","12":"Y","13":"Y","14":"Y","15":"Y","16":"Y","17":"Y","18":"Y","19":"Y"},"Is Popular":{"0":"N","1":"N","2":"N","3":"N","4":"N","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"Footer Type":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1},"Footer Text":{"0":"test_text","1":"test_text","2":"test_text","3":"test_text","4":"test_text","5":"test_text","6":"test_text","7":"test_text","8":"test_text","9":"test_text","10":"test_text","11":"test_text","12":"test_text","13":"test_text","14":"test_text","15":"test_text","16":"test_text","17":"test_text","18":"test_text","19":"test_text"},"Pack Image":{"0":"gems_1.png","1":"gems_2.png","2":"gems_3.png","3":"gems_4.png","4":"gems_5.png","5":"gems_1.png","6":"gems_2.png","7":"gems_3.png","8":"gems_4.png","9":"gems_5.png","10":"gems_1.png","11":"gems_2.png","12":"gems_3.png","13":"gems_4.png","14":"gems_5.png","15":"gems_1.png","16":"gems_2.png","17":"gems_3.png","18":"gems_4.png","19":"gems_5.png"}}
<class 'dict'>
{'Name': {'0': 'default_config', '1': 'default_config', '2': 'default_config', '3': 'default_config', '4': 'default_config', '5': 'gems1', '6': 'gems1', '7': 'gems1', '8': 'gems1', '9': 'gems1', '10': 'gems2', '11': 'gems2', '12': 'gems2', '13': 'gems2', '14': 'gems2', '15': 'gems3', '16': 'gems3', '17': 'gems3', '18': 'gems3', '19': 'gems3'}, 'Identifier': {'0': 11294, '1': 11294, '2': 11294, '3': 11294, '4': 11294, '5': 11295, '6': 11295, '7': 11295, '8': 11295, '9': 11295, '10': 11296, '11': 11296, '12': 11296, '13': 11296, '14': 11296, '15': 11297, '16': 11297, '17': 11297, '18': 11297, '19': 11297}, 'Segment Alias': {'0': 'default', '1': 'default', '2': 'default', '3': 'default', '4': 'default', '5': 'rhinoQA_1', '6': 'rhinoQA_1', '7': 'rhinoQA_1', '8': 'rhinoQA_1', '9': 'rhinoQA_1', '10': 'rhinoQA_2', '11': 'rhinoQA_2', '12': 'rhinoQA_2', '13': 'rhinoQA_2', '14': 'rhinoQA_2', '15': 'rhinoQA_3', '16': 'rhinoQA_3', '17': 'rhinoQA_3', '18': 'rhinoQA_3', '19': 'rhinoQA_3'}, 'Segment ID': {'0': -1, '1': -1, '2': -1, '3': -1, '4': -1, '5': 95365, '6': 95365, '7': 95365, '8': 95365, '9': 95365, '10': 95366, '11': 95366, '12': 95366, '13': 95366, '14': 95366, '15': 95367, '16': 95367, '17': 95367, '18': 95367, '19': 95367}, 'GP': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'iOS': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'Y', '6': 'Y', '7': 'Y', '8': 'Y', '9': 'Y', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'FB': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'Y', '11': 'Y', '12': 'Y', '13': 'Y', '14': 'Y', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Amazon': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'Y', '16': 'Y', '17': 'Y', '18': 'Y', '19': 'Y'}, 'Win32': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Remarks': {'0': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '1': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '2': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '3': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '4': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '5': '*inserted_by_automated_test*', '6': '*inserted_by_automated_test*', '7': '*inserted_by_automated_test*', '8': '*inserted_by_automated_test*', '9': '*inserted_by_automated_test*', '10': 'x1', '11': 'x1', '12': 'x1', '13': 'x1', '14': 'x1', '15': 'x3', '16': 'x3', '17': 'x3', '18': 'x3', '19': 'x3'}, 'Pack Name': {'0': 'test_bingo', '1': 'test_bingo', '2': 'test_bingo', '3': 'test_bingo', '4': 'test_bingo', '5': 'test_bingo', '6': 'test_bingo', '7': 'test_bingo', '8': 'test_bingo', '9': 'test_bingo', '10': 'test_bingo', '11': 'test_bingo', '12': 'test_bingo', '13': 'test_bingo', '14': 'test_bingo', '15': 'test_bingo', '16': 'test_bingo', '17': 'test_bingo', '18': 'test_bingo', '19': 'test_bingo'}, 'SKU': {'0': 'gems_99', '1': 'gems_99', '2': 'gems_99', '3': 'gems_99', '4': 'gems_99', '5': 'gems_99', '6': 'gems_99', '7': 'gems_99', '8': 'gems_99', '9': 'gems_99', '10': 'gems_99', '11': 'gems_99', '12': 'gems_99', '13': 'gems_99', '14': 'gems_99', '15': 'gems_99', '16': 'gems_99', '17': 'gems_99', '18': 'gems_99', '19': 'gems_99'}, 'Sold Item': {'0': 'Gems', '1': 'Gems', '2': 'Gems', '3': 'Gems', '4': 'Gems', '5': 'Gems', '6': 'Gems', '7': 'Gems', '8': 'Gems', '9': 'Gems', '10': 'Gems', '11': 'Gems', '12': 'Gems', '13': 'Gems', '14': 'Gems', '15': 'Gems', '16': 'Gems', '17': 'Gems', '18': 'Gems', '19': 'Gems'}, 'Items Order': {'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 1, '6': 2, '7': 3, '8': 4, '9': 5, '10': 1, '11': 2, '12': 3, '13': 4, '14': 5, '15': 1, '16': 2, '17': 3, '18': 4, '19': 5}, 'Dollar Value, $': {'0': 1.99, '1': 2.99, '2': 3.99, '3': 4.99, '4': 5.99, '5': 1.99, '6': 2.99, '7': 3.99, '8': 4.99, '9': 5.99, '10': 1.99, '11': 11.99, '12': 13.99, '13': 14.99, '14': 15.99, '15': 1.99, '16': 2.99, '17': 3.99, '18': 4.99, '19': 5.99}, 'Item Quantity': {'0': 5, '1': 15, '2': 25, '3': 35, '4': 45, '5': 5, '6': 15, '7': 25, '8': 55, '9': 65, '10': 5, '11': 15, '12': 45, '13': 55, '14': 75, '15': 5, '16': 15, '17': 55, '18': 95, '19': 85}, 'Is Best': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'Y', '6': 'Y', '7': 'Y', '8': 'Y', '9': 'Y', '10': 'Y', '11': 'Y', '12': 'Y', '13': 'Y', '14': 'Y', '15': 'Y', '16': 'Y', '17': 'Y', '18': 'Y', '19': 'Y'}, 'Is Popular': {'0': 'N', '1': 'N', '2': 'N', '3': 'N', '4': 'N', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Footer Type': {'0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1, '10': 1, '11': 1, '12': 1, '13': 1, '14': 1, '15': 1, '16': 1, '17': 1, '18': 1, '19': 1}, 'Footer Text': {'0': 'test_text', '1': 'test_text', '2': 'test_text', '3': 'test_text', '4': 'test_text', '5': 'test_text', '6': 'test_text', '7': 'test_text', '8': 'test_text', '9': 'test_text', '10': 'test_text', '11': 'test_text', '12': 'test_text', '13': 'test_text', '14': 'test_text', '15': 'test_text', '16': 'test_text', '17': 'test_text', '18': 'test_text', '19': 'test_text'}, 'Pack Image': {'0': 'gems_1.png', '1': 'gems_2.png', '2': 'gems_3.png', '3': 'gems_4.png', '4': 'gems_5.png', '5': 'gems_1.png', '6': 'gems_2.png', '7': 'gems_3.png', '8': 'gems_4.png', '9': 'gems_5.png', '10': 'gems_1.png', '11': 'gems_2.png', '12': 'gems_3.png', '13': 'gems_4.png', '14': 'gems_5.png', '15': 'gems_1.png', '16': 'gems_2.png', '17': 'gems_3.png', '18': 'gems_4.png', '19': 'gems_5.png'}}
{'id': 0, 'segmentAlias': 'default', 'userIds': [-1], 'platforms': ['gp'], 'content': {'items': [{'name': 'default_config', 'identifier': 0, 'itemsOrder': 1, 'dollarValue': 1.99, 'remarks': 'default!', 'itemsQuantity': 5, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_1.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 1, 'itemsOrder': 2, 'dollarValue': 2.99, 'remarks': 'default!', 'itemsQuantity': 15, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_2.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 2, 'itemsOrder': 3, 'dollarValue': 3.99, 'remarks': 'default!', 'itemsQuantity': 25, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_3.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 3, 'itemsOrder': 4, 'dollarValue': 4.99, 'remarks': 'default!', 'itemsQuantity': 35, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_4.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 4, 'itemsOrder': 5, 'dollarValue': 5.99, 'remarks': 'default!', 'itemsQuantity': 45, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_5.png', 'SKU': 'gems_99'}]}}
<class 'dict'>
{'id': 1, 'segmentAlias': 's1', 'userIds': [-1], 'platforms': ['ios'], 'content': {'items': [{'name': 'gems1', 'identifier': 0, 'itemsOrder': 1, 'dollarValue': 1.99, 'remarks': 'x', 'itemsQuantity': 5,

I cannot compare those dicts
Comment: How structured is the data? If it is to some extent more or less like a table of data, you can read both the xls and the json with pandas and then make the comparison with it
Answer: You will need to read the excel file and convert it to json with pandas. Also check in which format is your json file when converting from pandas. Maybe you need to change the orientation.
df = pd.read_excel(xlsx, sheet_name=sheet)

json_from_excel = df.to_json(orient='records')

Next you will need to order your json data here is an example function.
def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

And finally you can make the compare.
if ordered(json_from_excel) == ordered(json_data):
   #do something

Comment: so If I want to do an assertion assert ordered(json_from_excel) == ordered(json_from_excel)will this work?
Comment: what is json_data here? How can I assert json to xls file?
Comment: Your ticket says how to compare xls to json .. so you are converting your xls to json with the above code.. and the json_data is the data that you want to compare with.
Comment: so now If I have json file to compare I need to transfer it as a dict?

How to compare XLS file to json file?


How to dynamically set theme objects in ggplot2?

Question: I'm trying to define this function to easily set a custom theme to a ggplot, but I'm having trouble using the functions like element_blank() dynamically.. For example, specifying whether or not to have vertical gridlines as a TRUE/FALSE argument:
qplot(data=df, x=quarter, y=value, geom="line") +
  style(grid.vertical = F)

style = function (grid.vertical = T) {
(theme_foundation() +
 theme(
       panel.grid.major.x = ifelse(grid.vertical == T, element_line(), element_blank())
 ))}

produces..
Error in (function (el, elname)  :
Element panel.grid.major.x must be a element_line object.

Is there a way to make this work?
Answer: It seems that the error is produced by an unpleasant peculiarity of ifelse. I tried the workaround from the accepted answer there, but that did not help. So I guess the simplest way would be to switch to the regular if, though the code doesn't seem to be particularly neat.
style.if = function (grid.vertical = T) {
  t <- theme()
  if (grid.vertical)
    t <- t + theme(panel.grid.major.x = element_line(colour = 'red'))
  else t <- t + theme(panel.grid.major.x = element_blank())
  t
}

ggplot(mtcars, aes(x=wt, y=mpg)) + geom_line() + style.if()
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_line() + style.if(F)

Answer: This has to do with how the ggplot code is checking for types:
...
else if (!inherits(el, eldef$class) && !inherits(el, "element_blank")) {
    stop("Element ", elname, " must be a ", eldef$class,
        " object.")
}

Since we're using the ifelse function, I think this dynamic type checking voodoo will look at ifelse as being the "element" here, so the conditions are never met since it doesn't inherit from element_blank. To solve this, just use regular if/else expression instead of ifelse:
style = function (grid.vertical = T) {
(theme_foundation() +
 theme(
       panel.grid.major.x = if(grid.vertical == T) element_line() else element_blank()
 ))}

I had the exact same problem and this solution worked for me.


How to add a build system that does nothing in Sublime Text 2?

Question: The SublimeOnSaveBuild sublime plugin helps generate CSS file from LESS file, as the process triggered on build, it turns out I have to add a build system to use it, I added one and delete the default configuration but got error on build, any advice? I need the build system do nothing.
Answer: Nvm, I have switched to the less2css plugin which works on saving.


Alterar cor do pin default do Google Maps

Question: Bom dia pessoal, é a minha primeira pergunta aqui, então se eu fizer algo fora do padrão já peço desculpas antecipadas.
Preciso alterar a cor padrão do pin do google maps para algum valor hexadecimal, seria possível? Já antecipo que não posso criar pngs de cada cor e buscar por uma url porque a cor vem do banco de dados.

Segue abaixo o meu código:

var marcador = new MarkerWithLabel
({
  position    : {lat: parseFloat (dados.latitude), lng: parseFloat (dados.longitude)},
  raiseOnDrag : true,
  map         : mapa,
  icon        : // preciso fazer algo aqui para que o pin assuma a co com base no hexadecimal que vem da variável
  visible     : true
});

Desde já agradeço
Answer: Existem alguns marcadores de cores diferentes que você pode usar; azul, vermelho, roxo, amarelo, verde.
Daí você pode usar a estrutura que colocou na pergunta e colocar um desses marcadores como icon:
var marcador = new MarkerWithLabel
({
  position    : {lat: parseFloat (dados.latitude), lng: parseFloat (dados.longitude)},
  raiseOnDrag : true,
  map         : mapa,
  icon        : 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png hexadecimal'
  visible     : true
});

Podes dar uma olhada nesta resposta do soen que é mais ou menos o que você pretende fazer.