Is there a mathematic reason why Standard tuning for guitar is number 1 in the series of tunings? Could AI find it given a guitar with no tuning?

Question: Physics, Mathematics, and Linguistic Stack Exchange simply refuse to accept questions about the mathematics of tablature and guitar.
But what is tablature besides lines and numbers?
These sites often say I should ask these questions on Music Practice and Theory, but I have never seen a question about the mathematics of tuning.
Mathematics SE said this is not a mathematic question. I think they just don't understand how guitar works. What do you think?
Here's my question:
The algorithm for Standard tuning EADGBE is 055545. This means start with the lowest string E = 0, then tune the next higher string to the first string, fret 5. The third string is tuned to second string fret 5, fourth string to third string fret 5, fifth string is tuned to the fourth string fret 4, and finally the sixth string is tuned to the fifth string fret 5. So that is 055545.
Most guitarists agree that 055545 is the best, and then there is a series of alternative tunings that are very good but less common. And then there are a group of tunings which are not used generally but have been used on rare occasions. And then there are a lot of tunings that are useless.
So the probability of Standard tuning 055545 is very high and the probability of Lute tuning 055555 is almost zero.
Playing chords in 055555 is very difficult.
It seems like there a form of least action calculus on the guitar tunings in which Standard tuning is at a minimum value and no one can find a better tuning because it does not exist.
So my question is whether a computer could calculate that Standard tuning is the best given a guitar with 6 strings and no tuning?
Comment: Right away the biggest difficulty in your question is you have neither qualitatively nor quantitatively defined what a "better tuning" or "best tuning" is. With a qualitative definition, musicians could speak about the qualities of different tunings and how they fit with "better" or "best". With a quantitative definition, mathematicians and computer scientists could speak to numerical relationships and algorithms that would help determine which tuning is "best". With neither kind of definition, no one can give any meaningful answer.
Comment: Welcome! There are certainly plenty of math-y questions here, mostly about acoustics and temperaments. Quick note, talk about how the different Stack Exchanges behave or should behave should be on the "meta" section of each. Meanwhile, it seems to me the real difficulty here is in applying objective approaches to subjective phenomena. Which tuning is "the best"? By what standard? what makes it "best"? But when we talk about "most guitarists agree," and the "probability" of a tuning, then this is about collecting data on common usages. That's sociological research, a soft science. ...
Comment: Your line "playing chords in 055555 is very difficult" suggests a "goal-oriented" fallacy when viewing music history. Rarely are instruments "invented" to suit a musical need; more often, they evolve and then practices evolve around them. Saxophone is a good example of an exception, engineered by one guy and laid out in a logical way. But many instruments exhibit "QWERTY phenomenon": the QWERTY keyboard is less efficient, but we keep using it because everyone is used to it this way and it would be hard to make a different version "stick."
Comment: I'm confused. How do you know other stacks don't like this question? You seem to have zero prior activity anywhere on the stack exchange network.
Comment: @ToddWilcox - unregistered account. Could have 6 all in the same name & no-one would ever find them, realistically. [Unless you go looking - https://math.stackexchange.com/questions/4817767/how-do-i-calculate-the-euler-characteristic-betti-number-and-genus-for-musical ]
Comment: This question seems to me like "Why is standard tuning objectively the best" but asked in a very roundabout way.  And that isn't a good question.  Unless I'm misunderstanding something.
Comment: You'd have to ask a computer. We're just musicians. … but why would you want to start on E, A & end up on C, F? That way madness lies.
Comment: ... It comes along with the questions that always attend such research, like "what were the study methods, what was the pool of who was surveyed, how well can we extrapolate from that data to make assertions about entire cohorts," etc. We certainly can't talk about "what all guitarists do" because they're not all surveyed; it would be anecdotal conjecture. And even with the most rigorous research, we wouldn't have "best," we'd have "most common."
Comment: Why don't you just ask an AI: "What is the best way to tune a 6 string fretted instrument for playing melody and chords"? See what it comes up with.
Comment: What is wrong with Drop D tuning - 075545? Power chords are so much easier with this tuning, and even classical guitar music uses this tuning at times (see Fernando Sor for more details)!
Comment: Wow, that math.se question is something. I don't understand any of it even though I'm familiar with some of the math it refers and I suspect it got closed because nobody else does either.
Comment: "the probability of Lute tuning 055555 is almost zero": note that so-called lute tuning isn't how lutes are tuned.  The reasons behind standard guitar tuning are primarily historical, not mathematical, and based on principles established on instruments other than the guitar, before the guitar even existed in its present form.
Comment: I read this question not as "What is the best guitar tuning?", but as "Is there some mathematical description of guitar tunings that, when asked for the optimal one, will return the current standard tuning?" Is this a correct interpretation?
Answer: I assume that an algorithm or AI could come up with a different useful tuning, but I suspect it would be a slight variation of the currently popular tunings. After all, the tuning is very much limited by the practicalities of moving your fingers around the fretboard. That's why a violin is tuned differently (in fifths) than a guitar, because of the difference in scale length.
Let's look at this practically. How do we avoid the algorithm being influenced by the current guitar tuning status quo? We could e.g. look at piano music instead; it is probaby the instrument that's most similar in its use to guitar, a polyphonic instrument used both for accompaniment and melody, in many different genres. Analyze piano music in different genres and styles, and list the most commonly used chords, scales and arpeggios, and also the more advanced things that might be interesting to have.
Then explain to the algorithm what kind of fingerings are possible, and which are easy and which are hard. You could use the existing guitar corpus for this. Then, let the algorithm try every possible tuning, and see what percentage of basic and more advanced chords, scales and arpeggios are possible. The tuning which covers all the basics and has the most of the advanced features, wins.
Why do I think that the result will be close to EADGBE? Because there isn't actually that much wiggle room.
Choose larger intervals, like fifths, and the stretches become too large for the average player's hands. If you tune in diminished fifths, like FBFBFB, you have too many of the same note, and too many notes that only fit in diminished or dominant chords. Even just one diminished fifth may make some shapes a literal stretch.
If you tune in fourths, which some people do, you have the advantage of easy transposition of shapes across the strings and frets, but you lose the same-note top and bottom string, which will make most chords more complicated (although e.g. the thumb-over technique might help here).
Choose smaller intervals, and it becomes difficult to play common major or minor chords, with their succession of 3, 4 and 5 semitone intervals. And playing common scales in a fixed position will be replaced by playing diagonally across the fretboard, and thus a lot more hand movement.
If the algorithm finds other useful tunings, they will probably be standard tuning with the major third between other strings, like EADGCE or EADF#BE, or maybe with two major thirds, like EAC#F#BD#. Maybe you could throw in a minor third, but I doubt that would make anything easier to play. Of course there are a couple of alternate tunings already in use, like all-fourths and DADGAD and drop-D, which are clearly useful in some styles, but they are not generally used across genres.
It goes without saying that in order for a new tuning to actually gain traction, it would have to be both demonstrably superior to current standard tuning, and have advantages for all genres of music and styles of playing. Otherwise, it will just be another niche thing that some players use sometimes.
Comment: Welcome to Music: Practice & Theory.  Thanks for posting a great first answer!
Comment: With that said, the proportion of tunings with more than one third among their fourths is much smaller. On the other hand, including a fifth somewhere might be possible as well, and maybe even a diminished fifth. I agree that, if you want to use the guitar for roughly the same things as today, the optimal tuning is likely rather close to the current one, in the sense that most intervals would be fourths.
Comment: This is a good answer. I would personally put just somewhat more emphasis on the second-to-last paragraph, about the possible variations. Moving the third around and _transposing_  leaves you with many tunings. 4 fourths and one major third thus gives you a few dozen tunings that are possible without changing the pitch or timbre too much compared to the current standard, and among these there are many possible choices that are not obviously inferior to the standard tuning. If you include 2 major thirds the total number about doubles, and and a major and a minor third the number doubles again.
Answer: I posit that the answer is no, an AI/algorithm could not determine the ideal tuning. Or, rather, it would agree that the standard tuning is ideal, but not on any objective, mathematical basis, but because the calculation would have to be based on biased information.
The question presents the computer with an unresolvable chicken and egg problem.
Guitar spec, sans strings
Suppose we give a computer complete specifications of all six-string guitars — dimensions, properties of the building materials — and ask for an ideal tuning that would, on average, be best across all such guitars.
Guitar string design
The computer would then ask, "what are the properties of the strings?" This information, however, is biased toward a specific tuning. Guitar strings are designed with the standard tuning in mind. In fact, this is already true of the rest of the guitar: the instrument is built with the answer to the tuning question already in mind.
But, let's ignore these problems and give our computer complete specifications for all strings designed for six-string guitars (including, of course, the type of guitar they're intended for).
Analysis of guitar music
But now our computer asks, "ideal for what kind of music?" Here again, there's a built-in bias toward standard tuning, since the guitar is designed with a certain musical repertoire in mind, and the music is written for an instrument designed with certain properties — such as a presumed tuning.
We give our computer access to all of the music every written or arranged for guitar. But this presents still another problem: who is going to be playing this music?
Mechanics of the human hand
Now we have to give the computer a complete specification of the human hand — or sufficiently broad access to human hand information to come up with a working range of parameters like length and diameter of each finger, dexterity, speed, span between fingers, ....
Conclusion
Finally, given all of these factors, it seems inevitable that the computer would spit out the standard tuning, because the standard standard tuning was derived from these factors and subsequently reinforced by them.
Answer: Depending on what objective function you give a constraint optimization problem solving algorithm you will probably find different optimums. (Solutions usually vary as well depending on start point and other particulars unless the problem is very simple). If you will only ever play one song always and that song only has one chord - guess what? Tuning the guitar for that chord would be optimal. Unless you are optimizing for unplayability/difficulty... So it depends very heavily on what you will play/optimize for. I would also reject your proposal that all fourths tuning make chords harder, on the contrary it makes all (sane) ≤4 string chords easier, it is only 5 and 6 string chords that get slightly trickier. (And I think if I ever get 6 fingers in addition to the thumb it would be the go to choice for me always...)
Comment: Does it have to be a _machine learning_ algorithm? If you can write a fitness for purpose X (which remains to be clearly explicated by the OP) evaluator function, it's quite trivial to even brute-force try all possible combinations.
Comment: How is a 'fitness for purpose X evaluator function' any different from an objective function in an optimization problem? Sounds like a synonym to me? I just assumed he had a corpus of music he wanted to optimize over, that is why I said machine learning. I guess maybe he could just write an AI that sends an email asking every person in the world what their favorite tuning is as well, then it would definitely be a different thing than machine learning.
Comment: To me machine learning is just a synonym for a good old optimization problem with constraints like in calculus... not sure what you mean with it. Changed so it doesn't say machine learning now.
Comment: But I disagree that it is a finite set, I would say the amount of music that can be played is at least a countably infinite set, because you can always tweak it a little to get a new song.
Comment: The finite set is the set of possible tunings. "Machine learning is just a synonym to optimization problem" is so technically true it must come from  a person who doesn't have much experience with it.
Comment: "amount of music that can be played" ... where did that come from? Do you mean that it's your "purpose X" and maybe even the OP's? Or everyone else's, self-evidently, as a matter of course? My point was that the OP didn't explicate his idea of what the purpose of a guitar tuning system should be, in this supposed optimization problem. It may have been, ease of playing some kinds of chords. Is that also the reason of existence for guitars, or all instruments in general, everywhere ever. Dunno! Maybe it can be proven with mathematics or AI, like the meaning of life. My precalc table says 42.
Comment: In my example I say "if you will only ever play one song with one chord, tune according to that chord". The expansion of that in my mind is all the music that he wants to play should be partitioned into subsets where each subset has a different optimal tuning. I have taken a course in AI and read multiple papers about multiple subfields and is reasonably well versed in torch, tensorflow, and openvino. I just don't get your arbitrary deliniation of the AI field. To me machine learning just means tweaking a couple of million of weights.
Comment: And I honestly don't think traversal search over all possible music would work. It just sounds like you are viewing a different problem. And I also reject the number of tunings being different. There is a huge difference between 440Hz and 442Hz. Maybe somewhere like 20000 different possibilities per string. And then the factorial for all strings together. And then check against all songs you want to play. It grows huge. And I can promise you some songs are easier in other tunings, so there is no optimum for all taken together.
Comment: So then you get the powerset of all songs as well. Maybe even retuning in the middle of a song! Now it grows truly unweildly.
Comment: Ok fair, I assumed the optimum would be for playing the guitar. I doubt the resale value or design of the guitar would be affected. Although tuning too hard is not good because then the guitar could loose its tuning in the middle of the night, so that could be what the objective function was. But honestly I think you know s/he wanted to know which tuning would allow me to play most music in an easy way, that feels like the default problem to solve.
Comment: (I guess in your case, the "tweaking of weights" was done by hand by you, and that is why you did not consider it machine learning? I guess it would be a stretch to call that learning, that is more like just evaluating, but you would probably have to change your objective function so the learning happens inside you instead)
Comment: (In an even longer stretch, you could consider the characters of the source code of your program being the weights)
Comment: The problem is that you call everything weights, the word loses its meaning
Comment: There are people who disagree that 440Hz and 442Hz is a huge difference, but it would be a separate discussion.
Comment: No it doesn't, is is just independent variables. They do not lose their meaning. The only thing that makes stuff harder is that you cannot do vanilla calculus since they are not nice scalar values, but that is just some tweaking on the algorithm to fix. Stop making baseless questioning of my statements please. It is a measurable difference, anyone who says it is not a difference has either not a trained ear or not a tuning app.
Comment: Seems I messed up, I don't know what the model variables are called. But it is them I mean anyway. I don't think anyone restricts you to use scalar fields, and you can probably make any kind of learning method you like, genetic algorithm, backpropagation, A*, I don't know, it was a decade ago I took the class.
Answer: ChatGPT 3.5 answers the same way as humans on this exchange, because AI just rehashes existing human generated text.
The reason isn't specifically mathematical, it's practical for accommodating the shape of a hand, and learning time tested techniques.
ChatGPT transcript:
What is the best way to tune a guitar?
ChatGPT
To tune a guitar, you can use a tuner device, a tuning app, or tune by ear. Start with the low E string and adjust each string until it matches the correct pitch: E, A, D, G, B, E. Alternatively, you can use the fifth fret method, where you match the pitch of the open string with the fifth fret of the next higher string.
User
Why is that the most popular tuning?
ChatGPT
The standard tuning (EADGBE) is widely used because it provides a balanced arrangement of notes across the fretboard, making it versatile for various playing styles and music genres. This tuning allows for easy chord shapes, scale patterns, and a good balance of tension and resonance on the guitar. While alternate tunings exist for specific styles or effects, the standard tuning remains popular due to its versatility and familiarity.
Message ChatGPT…
ChatGPT can make mistakes. Consider checking important
Comment: "could AI...?" Right in the title. So, it seems about AI, mixed up with a "mathematical" hope.
Comment: The question isn't about AI. It's about whether there's a mathematical calculation that would predict the ideal tuning.
Comment: Yes, AI is mentioned in the title, but based on the question itself, and the use of "mathematical" and "calculate", clearly the interest is not in a lookup-based AI but rather an AI (or, rather, an algorithm) that, given appropriate parameters, could independently determine the ideal tuning. It's a poorly articulated question, but obviously not one written with ChatGPT in mind, since the answer in that case is trivial.
Comment: AI encompasses much more than language models, even though language models have had the most attention recently


Passando variáveis de AJAX para ASP

Question: Tenho um FORM de contato que usa uma função em AJAX para validar e devolver um PARÂMETRO de sucesso que me permite enviar a mensagem SEM o visitante sair da página de contato.
Normalmente, uso estes FORMs em páginas HTML e a função PROCESSA e ENVIA a mensagem no backend, sem intervenção nenhuma.
Funciona! mas só se o servidor rodar PHP.
Num servidor WINDOWS não funciona. Isto porque dentro do AJAX vou precisar carregar a página que trata e envia as variáveis no formato de e-mail. Num servidor WINDOWS precisarei de uma página em ASP clássico.
A função no HTML funciona, no ASP funciona, mas não consigo fazer o ajax enviar para a página ASP, as variáveis vindas do FORM, para que o ASP capture e trate a mensagem.
Vou colar aqui o trecho em questão:

var dataString = '?name=' + name + '&email=' + email + '&message=' + message + '&fone=' + fone;
// alert (dataString);return false;

        $.ajax({
            type:"GET",
            url:"contact.asp",
            data:dataString,
            success:function () {
                $('#af-form').prepend("Sua mensagem foi enviada! Em breve entraremos em contato.
 ");
                $('#af-form')[0].reset();
            }
        });
        return false;

Se eu criar uma página PHP com as mesmas instruções da página ASP, o AJAX envia os dados corretamente (mas obviamente não processa).
Então o que preciso é ALTERAR a maneira como o conteúdo de datastring está sendo passado. E aí, amigos, só pedindo ajuda aos universitários.
* ATENÇÃO *
1) Leia a questão com atenção;
2) Abstenha-se de respostas do tipo "Tá, mas porque ASP?"
3) Sugira caminhos alternativos, mas procure manter a integridade da função.
4) Seja gentil e educado com quem sabe menos que você.
[]'s
Comment: Hélio, veja se esse link te ajuda: https://goo.gl/1ao3BR .
Comment: É uma abordagem interessante (obrigado!), mas ela parte do pressuposto que meu documento de origem é um ASPX. Na verdade o que tenho em mãos é um HTML.
Answer: Você pode fazer o seu ajax assim.
let name;
let email:
name = document.getElementById('name');
email= document.getElementById('email');

//voê pode setar o email ao inves do getElementById com o $ com jquery
//exemplo:
name = $('#name').val();
email = $('#email').val();

// alert (dataString);return false;

        $.ajax({
            type:"GET",
            url:"contact.asp",
            data : { name : name, email : email },
            // se não funcionar utilizar com o encodeURIComponent
            // data : { name : encodeURIComponent(name), email : encodeURIComponent(email)},
            success:function () {
                $('#af-form').prepend("Sua mensagem foi enviada! Em breve entraremos em contato.
 ");
                $('#af-form')[0].reset();
            }
        });
        return false;

ou ainda

name = document.getElementById('name');
email= document.getElementById('email');

$.ajax({
            type:"GET",
            url:"contact.asp?name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email),
            success:function () {
                $('#af-form').prepend("Sua mensagem foi enviada! Em breve entraremos em contato.
 ");
                $('#af-form')[0].reset();
            }
        });
        return false;

o input deve conter o id
<input type="text" id="name" />

Para resgatar os dados no Asp você deve fazer assim para method GET
dim name
name = Request.QueryString("name")

Para resgatar os dados no Asp você deve fazer assim para method POST
dim name
name = Request.Form("name")

Se me lembro bem esse abaixo deve funcionar nos 2
dim name
name = Request("name")

Aconselho a sempre remover as aspas simples antes de inserir isso no banco de dados se for o caso para não haver sql injection
dim name
name = Request.QueryString("name").Replace("'","")

Não tive chance de testar o código mas deve funcionar.
Comment: Perfeito, bro. Há apenas um detalhezinho a ajustar relativo à codificação. mas a função cumpre o que se espera! Obrigado, valeu!!

Passando variáveis de AJAX para ASP


Understanding the limit of the ratio $\frac{\mu(B(x,r))}{m(B(x,r))}$ as r goes to 0

Question: We work in $\mathbb{R}$. Let $B(x,r)=\{y: |x-y|<r\}$. Let $\mu$ be any Borel Measure induced by a right continous increasing function and $m$ the Lebesgue Measure. What can we say about $lim_{r\to 0}\frac{\mu(B(x,r))}{m(B(x,r))}$ for $\mu$ almost every x? Is it a positive number for $\mu$ almost every x? Is it the case that as r gets very small, $u(B(x,r))$ is at best of order r? What about the limit? Is it the case that the limit is non zero for $\mu$ almost every x? Thanks guys.
Comment: If $\mu\ll m$ this is pretty much covered by the Lebesgue differentiation theorem.  See Bogachev's *Measure Theory*, p.367, 368, for $m$-almost everywhere results.   But that's not the $\mu$-almost everywhere result you want.
Answer: If $\mu  = \delta_0$, then clearly $\mu(B (0, r)) =1$ independently of $r $.  Thus, there's no hope of getting some kind of control over this with respect to $r $.
However, if $\mu $ and $m $ are mutually singular and $\mu $ is a Radon measure on $\mathbb {R}^{d}$, then
$$\limsup_{r \to 0} \frac {\mu (B (x, r))} { m (B (x, r))} = \infty $$
for $\mu $-a.e. $x $.  The same limit is zero for $m $-a.e. $x $.
On the other hand, if $\mu $ is absolutely continuous with respect to $m$, then
$$\lim_{r \to 0} \frac {\mu (B (x, r))} { m (B (x, r))} = \frac {d \mu}{d m}(x) $$
for $m $-a.e. $x $.
In general, $\mu $ can be decomposed into a sum of absolutely continuous and singular measures, and then the limit will be determined by which measure "sees" $x $.
Comment: Hello, thanks for the response, do you mean limit as r goes to 0 instead of goes to infinity?
Comment: How do you get the claim in the case of a singular measure? Do you have a reference?
Comment: Also is it the case that for $\mu$ almost every x, $d\mu/dm$ is positive? (if $\mu$ is the measure induced by increasing right continuous function?
Comment: No, it's not true that $\frac{d \mu}{d m}$ is positive $\mu$-a.e.  Think about what would happen if $d \mu = \chi_{[0,1]} dx + d \delta_{2}$.  Then $\frac{d \mu}{d m} = \chi_{[0,1]}$, which vanishes in any neighborhood of $2$.
Comment: @PhoemueX, I learned this in the first volume of the harmonic analysis series by Muscalu and Schlag.  If you want, ask a new question and I will explain how to prove this.
Comment: fourierwho, sorry I meant if the measure has no atoms, is it true that the derivative is positive u a.e. ?
Comment: No, there's no reason why $\frac{d \mu}{dm}$ should be positive $\mu$-a.e.  In fact, $\frac{d \mu}{dm}$ is positive $\mu$-a.e. if and only if $\mu \ll m$.  This is a fact about the Lebesgue decomposition and has nothing to do with Lebesgue measure.


Suppose X and Y are independent Poisson random variables with respective parameters $\lambda$ and 2$\lambda$. Find $E[Y-2*X|X+Y=10]$

Question: Suppose X and Y are independent Poisson random variables with respective parameters $\lambda$ and 2$\lambda$. Find $E[Y-2*X|X+Y=10]$
So, I've tried to tackle the problem several different ways, including just assuming the sum of to Poisson distributions = P($\lambda_1$+$\lambda_2$) =$2\lambda - 2*\lambda=0$ and also that
$E[Y-2*X|X+Y=10]$ = $E[Y|X+Y=10]$+$E[-2*X|X+Y=10]$
= $E[Y|X+Y=10]$-2$E[X|X+Y=10]$
and
$E[Y|X+Y=10]$= Bin(n=X+Y=10,p=($\frac{2\lambda}{2\lambda+\lambda})=\frac{2}{3}$)
$E[X|X+Y=10]$= Bin(n=X+Y=10,p=($\frac{\lambda}{2\lambda+\lambda})=\frac{1}{3}$)
=> Bin(10,$\frac{2}{3}$) - Bin(10,$\frac{1}{3}$) = $\frac{20}{3}$-2*$\frac{10}{3}$ = 0
However, my professor seems to be suggesting that this does not equal 0. Is there a step I'm missing from this process or a part of this probability I'm failing to understand?
Comment: The information you need (explained in several different ways) is at https://stats.stackexchange.com/questions/429564/conditional-probability-poisson-and-exponential/429589#429589.  Although your answer is correct, the notation makes no sense at several points, which is what your professor may be objecting to.  In particular, most people would interpret expressions like "$\operatorname{Bin}(10,2/3)$" as referring either to *distributions* or *random variables,* but not to expectations.
Comment: The point where the conditional probability was replaced by a probability is invalid: it's tantamount to supposing the condition $X+Y=10$ doesn't affect anything. One way to see why not is to replace "10" everywhere by "0". You would wind up concluding $E[Y-2X\mid X+Y=0]=0-3\lambda$ but that's obviously incorrect because $X+Y=0$ implies $X=Y=0,$ whence $Y-2X=0$ whose expectation is $0,$ not $-3\lambda.$
Comment: Cool - I've also had someone suggest E[Y-2X|X+Y=10]=E[Y-2X|Y=10-X]=E[10-X-2X]=10-3*E[X]=10-3*lambda (since E[X]=lambda). Would you know if those statements actually equivalent, or am I going down the wrong path?
Answer: We can look at a more general case that I believe will help solve this problem.
\begin{eqnarray*}
P(X|X+Y=n) &=& \frac{P(X=x, Y=n-x)}{P(Z=n)}\\
&=& \frac{P(X=x)P(Y=n-x)}{P(Z=n)} \\
&=& {n \choose x} \left( \frac{\lambda_1}{\lambda_1+\lambda_2} \right)^x \left( \frac{\lambda_2}{\lambda_1+\lambda_2} \right)^{n-x}
\end{eqnarray*}
Which is a binomial pmf with $p = \left( \frac{\lambda_1}{\lambda_1+\lambda_2} \right)$ and expected value $E(X|X+Y=n) = np = n \left( \frac{\lambda_1}{\lambda_1+\lambda_2} \right)$


Classe estacionamento em Python

Question: Estou aprendendo a programar em Python.
Neste momento preciso de implementar uma class que tem as seguintes características:
Uma classe chamada estacionamento, que simula o funcionamento de um parque de estacionamento.
-A classe recebe um inteiro e determina a lotação do parque
-A classe devolve um objeto com os seguintes métodos:
Entra(): corresponde à entrada de um carro
-Sai(): corresponde à saída de um carro
-Lugares(): indica o número de lugares livres no estacionamento.
Estou com dificuldades em criar o codigo.
Não estou a conseguir fazer com que A classe recebe um inteiro e determina a lotação do parque
Codigo
Comment: Pode editar sua pergunta pra incluir o que já tentou e onde não deu certo?
Comment: já coloquei lá o codigo. no entanto nao estou sendo capaz de fazer o input do inteiro.
Answer: Sua classe de controle estacionamento pode ser algo como:
class Estacionamento:

    def __init__( self, max_vagas ):
        self.max_vagas = max_vagas
        self.vagas_ocupadas = 0

    def maximo( self ):
        return self.max_vagas

    def disponiveis( self ):
        return self.max_vagas - self.vagas_ocupadas

    def ocupadas( self ):
        return self.vagas_ocupadas

    def entra( self ):
        if( self.vagas_ocupadas == self.max_vagas ):
            raise Exception('Estacionamento estah lotado!')
        self.vagas_ocupadas += 1

    def sai( self ):
        if( self.vagas_ocupadas == 0 ):
            raise Exception('Estacionamento estah vazio!')
        self.vagas_ocupadas -= 1

Testando:
n = int(input('Entre com a lotacao maxima do estacionamento: '))

e = Estacionamento(n)

e.entra()
e.entra()
e.entra()
e.entra()
e.sai()

print( e.maximo() )
print( e.disponiveis() )
print( e.ocupadas() )

Saída:
Entre com a lotacao maxima do estacionamento: 20
20
17
3

Comment: Tente algo como: `n = int(input('Entre com a lotacao maxima do estacionamento: '))`
Comment: @JoaoPeixotoFernandes: feito!
Comment: Ok!! muitoobrigado pela ajuda. Mas como faço para pedir ao utilizador um inteiro!?
Comment: Ou seja -A classe recebe um inteiro e determina a lotação do parque
Comment: Consegui! Antes de declarar a class. mas não esta atualizar os lugares!
Comment: muito obrigado pela disponibilidade e ajuda!! Funciona! obrigado

Classe estacionamento em Python


Simple combination question

Question: Seven managers and eight sales reps volunteer to attend a seminar.  How many ways could 5 people be selected to go if there must be at least one manager and one sales rep?
The correct answer is found by making up 4 cases:
1 manager, 4 reps
2 managers, 3 reps
3 managers, 2 reps
4 managers, 1 rep
or
$_7C_1 \times _8C_4 + _7C_2 \times _8C_3 + _7C_3 \times _8C_2 + _7C_4 \times _8C_1 = 2926$
My original guess was just to find ways to choose 1 manager from 8, 1 sales rep from 7 and the remaining 3 from the remaining 13 or $_8C_1 \times _7C_1 \times _{13}C_3 = 16016$
Why does this not work?
Answer: Notice that by doing what you did you count combinations more than once.
More figuratively: Let $M_1,M_2,\ldots,M_7$ be your seven managers, and $R_1,\ldots,R_8$ be the reps.
consider the combination $\langle M_1,M_2,R_1,R_2,R_3\rangle$. By using the method you used you encounter this combination at least twice (six times to be more exact, be I leave it to you to figure why):
Once when you choose $M_1$ to be the one manager out of 8, and some $R_i$ as the rep, and you select $M_2$ as one of the 3 of 13 other employees, and again when $M_2$ is chosen to be the manager, and $M_1$ is selected as one of the 3 in 13.
This is why you got a lot more results than the correct answer
Hope this helps
Shai :)
Answer: Because you are counting same configuration multiple times in the second approach. Let M denote managers and R denote reps. Suppose you picked M1 and R1 first and M2, M3 and M4 from the rest. The same configuration is obtained by picking M2 and R1 first and M1, M3 and M4 from the rest.
Comment: This illistrates the difference between a combination and permutation.  If managers are denoted A, B, ...,G and sales reps are denoted 1,2,...,8, your question is to find the number of different five digit combinations with at least one letter and one number (where the order of the five digits does NOT matter).  This is what you computed in the first method (a combination problem).  In your second method, you are counting the number of five digit combinations containing at least one letter and one number, where the order matters to some extent.  This is a type of permutation problem.
Comment: I understand.  Then is my first approach the most organized, or efficient way to go about this (without using generating functions, of course)
Comment: I think the most efficient way is to first count the number of choices without any constraint on managers and sales reps, then subtract the number with no managers and the number with no sales reps (there being no choices with no managers and no sales reps).

Simple combination question


Multiplying by -1 not working to return a negative number

Question: The following line in the swapDigits function below does not seem to work to convert the number a negative number.
swappedNumber = Number(numberStringArray.join("")) * -1;

If I multiply a positive number by -1 in the console it correctly makes the number negative but that does not seem to work in the code below. How can I make the swappedNumber negative? Thank you.
// swapDigits

const swapDigits = (number) => {
  let swappedNumber = 0;

  if (number < 0) {
    number = Math.abs(number);

    const numberString = number.toString();
    console.log(numberString);
    const numberStringArray = [];

    if (numberString.length % 2 == 0) {
      for (let i = 0; i < numberString.length; i = i + 2) {
        numberStringArray.push(numberString[i + 1]);
        numberStringArray.push(numberString[i]);
      }
      swappedNumber = Number(numberStringArray.join(""));
    } else {
      numberStringArray.push(numberString[0]);
      for (let i = 1; i < numberString.length; i = i + 2) {
        numberStringArray.push(numberString[i + 1]);
        numberStringArray.push(numberString[i]);
      }
      swappedNumber = Number(numberStringArray.join("")) * -1;
    }
  } else {
    const numberString = number.toString();
    console.log(numberString);
    const numberStringArray = [];

    if (numberString.length % 2 == 0) {
      for (let i = 0; i < numberString.length; i = i + 2) {
        numberStringArray.push(numberString[i + 1]);
        numberStringArray.push(numberString[i]);
      }
      swappedNumber = Number(numberStringArray.join(""));
    } else {
      numberStringArray.push(numberString[0]);
      for (let i = 1; i < numberString.length; i = i + 2) {
        numberStringArray.push(numberString[i + 1]);
        numberStringArray.push(numberString[i]);
      }
      swappedNumber = Number(numberStringArray.join(""));
    }
  }

  return swappedNumber;
};

const even = swapDigits(-564783);
console.log(even); // logs 657438 instead of -657438

const odd = swapDigits(512364783);
console.log(odd);

Comment: How specifically have you identified that exact line as the source of the problem?  If that exact line is the source of the problem, how is the rest of the code relevant?  What exact values are observed on that exact line and what is the exact result?  This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193).  When you step through the code in a debugger, which operation first produces an unexpected result?  What were the values used in that operation?  What was the result?  What result was expected?  Why?
Answer: The first branch of your "if" doesn't multiply the number by -1:
if (numberString.length % 2 == 0) {
      for (let i = 0; i < numberString.length; i = i + 2) {
        numberStringArray.push(numberString[i + 1]);
        numberStringArray.push(numberString[i]);
      }
      swappedNumber = Number(numberStringArray.join(""));
}

So if there's an even number of digits, you won't negate the number.
Answer: You can simplify your logic by capturing the sign, before calling absolute value.
You can also swap without a temporary variable by using an XOR swap.

const swapDigits = (n) => {
  const
    sign = n < 0 ? -1 : 1,
    digits = Math.abs(n).toString(10).split('').map(d => parseInt(d, 10));
  for (let i = 0; i < digits.length; i+=2) {
    if (digits[i + 1]) {
      digits[i]     ^= digits[i + 1];
      digits[i + 1] ^= digits[i];
      digits[i]     ^= digits[i + 1];
    }
  }
  return sign * parseInt(digits.join(''), 10);
};

console.log(swapDigits(-564783));   // even = -657438
console.log(swapDigits(512364783)); // odd  = 1532468703


Fibonacci Number Formula for nth term

Question: Hey is there any known combinatorial formula for nth fibonacci number?
(n+1)th fibonacci number is given by summation of r=0 to (round)n/2:C(n-r,r)
Can someone verify the formula?Help!
Comment: You'll find proofs of your formula [here](http://math.stackexchange.com/questions/1079825/prove-that-f-n-n-1-choose-0-n-2-choose-1-n-3-choose-2-ldots-where?rq=1) and at the earlier questions linked from there.
Comment: See the first formula here http://en.wikipedia.org/wiki/Fibonacci_number#Use_in_mathematics and substitute $n\rightarrow n+1$
Answer: Hint: Try to incorporate Binet's formula: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html
$$Fib(n) = \frac{\phi^n - \frac{(-1)^n}{\phi^n}}{\sqrt{5}}$$
Comment: I need a combinatorial formula!
Comment: Right, just that I thought I should add a hint which may help you get an answer eventually...

Fibonacci Number Formula for nth term


How do I change my Admin theme?

Question: I'm brand new to Drupal and have just installed Drupal 7. When I was configuring it, I originally selected "Stark" as my Admin theme, thinking I would create my own CSS later. In trying to learn Drupal and add content, I have decided that I would like to change my Admin theme. I went to the Admin tool bar (across the top) and clicked "Appearance" and changed my theme there, I even disabled the "Stark" theme, but my Admin theme is still defaulting to the Stark theme. How do I change this?
Answer: Go to admin/appearance and you will see a fieldgroup called "Administration theme" at the bottom.
Comment: I did that already - it does not work! I have my Admin theme at the very bottom set to "Garland" and I have the check box selected for "Use the administration theme when editing or creating content" and I have saved the configuration (several times!) It is NOT working! What's up with that?
Answer: I found the error
the code not working because i use Bootstrap theme, and administration theme use Seven theme, just change the administration theme to bootstrap or put the code under Seven code

How do I change my Admin theme?


MS Access SQL code - Changing data in the rows already in a table

Question: I'm trying this code to update the a table called "sec0411_employees that has a "credit_limit" column.
update sec0411_employees
set credit_limit = '27.00'
where credit_limit in '15.00';
Here is the data, notice multiple entries of '15.00' in the credit_limit column.
Thanks for any help!
Paul
Comment: Wow... your amazing! It updated the 3 rows! Thanks so much... I guess my apostrophes around '27.00' and '15.00' were throwing errors. Your the best... thanks again
Answer: Is this what you want?
<code>update sec0411_employees
    set credit_limit = 27.00
    where credit_limit = 15.00;
</code>
Comment: Wow... your amazing! It updated the 3 rows. Thanks so munch!


create a folder structure with name and date +7 days

Question: i want to create a folder name with a start of W1 09-09-2021 (this is the name of the folder)
i want the second one to be W2 + 7 days is there a way to create that in batch ? for let say 6 months ?
Regards
Comment: Why did you use a date which nobody but you, could be sure of the format? Is it `W$_ dd-MM-yyyy`, or `W$_ MM-dd-yyyy`? Could you please also explain how batch-file is related to your question? because your above comment clearly shows that you're using powershell. Please also do not add code to the comments, [edit] your question to include it properly formatted.
Comment: Yes it possible ;P What have you tried so far? [mre] ? Hint: `(Get-Date 09-09-2021).AddDays(7)` (Powershell)
Comment: hello i try to use mkdir command to create w1 and so on but cannot find a way to do it in batch :-(
Comment: hello i found a way to create the folder name mkdir $(1..20 | %{"W$_"})   but how to add the date next to it and on folder to add 7 days
Comment: Since when does Week number 1 start at 09-09-2021 ????
Answer: You can use something like this. The could be more compressed but since you're a beginner I believe will learn more if I leave it like this.
Remember to update the $folderPath variable using the destination Full Path where the new folders should be created.
$startDate = [datetime]'09-09-2021'
$endDate = $startDate.AddMonths(6)
$startWeek = 1
$folderPath = "X:\fullPath\to\newFolders"
$datesToExclude = @(
    '12-30-2021' # This will Exclude 30 of December 2021
) | ForEach-Object {$_ -as [datetime]}

do
{
    if($startDate -notin $datesToExclude)
    {
        $folderName = "W{0} {1}" -f $startWeek, $startDate.ToString('MM-dd-yyyy')
        $newFolderPath = Join-Path $folderPath -ChildPath $folderName
        New-Item $newFolderPath -ItemType Directory
    }

    $startDate = $startDate.AddDays(7)
    $startWeek++

}until($startDate -ge $endDate)

New folders should look like this from W1 until W26:
W1 09-09-2021
W2 09-16-2021
W3 09-23-2021
W4 09-30-2021
...
...
...
W24 02-17-2022
W25 02-24-2022
W26 03-03-2022

Comment: THANKS alot Santiago
Comment: if im already in the correct folder should i just discard the path ?
Comment: @PierreAuger If your current directory is the same as where the folders will be created you can set the variable to a `dot` like this: `$folderPath = "."`
Comment: thanks alot it work great  one more thing can we exclude some date to be created like the 30 of december ?
Comment: one more thing it start on the 16 i want the first folder to be w1 on 09-09-2021 i try to play with start date but it keep starting at 16
Comment: @PierreAuger yeah it is, I edited the code. Just update the variable `$datesToExclude` use a `DateTime` format like what I'm doing for testing. If the answer was helpful to you and solved your problem, consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it.
Comment: whe do you add $datesToExclude ?
Comment: something like that :  $startDate = [datetime]'02-09-2021'
$endDate = $startDate.AddMonths(6)
$datesToExclude = 30-12-2021
$startWeek = 1
$folderPath = "."

do
{
    $startDate = $startDate.AddDays(7)
    $folderName = "W{0} {1}" -f $startWeek, $startDate.ToString('dd-MM-yyyy')
    $newFolderPath = Join-Path $folderPath -ChildPath $folderName
    $startWeek++

    New-Item $newFolderPath -ItemType Directory

}until($startDate -ge $endDate)
Comment: @PierreAuger please read the edited code, the answer is there, you just need to update the `$datesToExclude` variable. Regarding  ***"i want the first folder to be w1 on 09-09-2021"***, this was my bad and should be fixed now.
Comment: it work ty except the dates to exclude but i will found out TY
Comment: @PierreAuger ok, last edit, see my comment in the code. I only added `'12-30-2021'` to be excluded but you can add multiple dates there using the same `Date Format`.
Comment: @PierreAuger no problem, happy to help :)


BDD/TDD with Revit API

Question: My question is relevant to this question, but I've somehow moved a step further and implemented a test framework using nunit.
When I run the test framework addin inside Revit, the testing framework somehow locks the test assemblies making it impossible to recompile the test assemblies. To get around it, I tried making a shadow copy so the nunit test runner runs on the copied assemblies. But once I run the tests for the first time, the subsequent test runs does not work on updated copies. It is like the test runner caches the dlls and always tries to run tests on cached copy.
So each time the test assembly is updated, I need to close-reopen Revit to run the tests which is a real pain. The main reason I implemented the testing framework for Revit was to be able to do BDD/TDD using Revit API.
This is a code snippet of how I run the tests:
    TestPackage theTestPackage = new TestPackage(testDll);
    RemoteTestRunner testRunner = new RemoteTestRunner();
    testRunner.Load(theTestPackage);
    TestResult testResult = testRunner.Run(new NullListener());

Does anyone have any idea how to solve this?
Answer: You can try loading the assemby for testing with the Assembly.Load(byte[]) method. I'm not sure if your test runner can handle this, but this will give you an assembly to work on that is loaded from a byte stream in memory. Therefore the original assembly file can be recompiled anytime and you can have as many concurrent versions of this assembly loaded as you like. They are all separate, with separate types.
I use a similar strategy with the RevitPythonShell script loadplugin.py for loading plugins at runtime and then exercising them for testing. This seems to work quite well except for WPF controls defined in XAML. I suspect the XAML parser and loader keeps a cache of the types, but haven't been able to look into this yet due to time constraints.
Comment: Thanks Daren, I eventually had to modify the nunit TestAssemblyBuilder class to load assembly from byte array. hopefully I can start some TDD stuff with Revit now!
As for XAML testing you mentioned, not sure whats your setup but I do not really test the controls as I'm using MVVM; I just test the ViewModels.

BDD/TDD with Revit API


PDO mostrando dados de conexão caso disparo do catch dentro do alert(result)

Question: Porque no meu alert(result) do ajax o catch do PDO está mostrando as minhas informações de conexão ao banco de dados conforme mostra a imagem a seguir: http://puu.sh/bel2Z/e7f230ab8d.png
Código:
    $pdo = new PDO("mysql:host=localhost; dbname=meubanco", "meuuser", "minhasenha");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = $pdo->prepare("INSERT INTO wp_contatos VALUES ('', :nome, :email, :message, :data)");
    try {
        $sql->execute(array(
            "nome"      => $_POST['nome'],
            "email"     => $_POST['email'],
            "message"   => $_POST['message'],
            "data"      => date("Y-m-d h:i:s")
        ));

        $resposta = "Sua solicitação foi recebida com sucesso. Em breve entraremos em contato.";

    } catch(PDOException $e) {

        $resposta = "Sua solicitação não foi recebida com sucesso. Favor entrar em contato pelo telefone 0800";

    }

    echo $resposta;

}

Answer: Verifique seu usuário e senhas do banco de dados. Eles podem estar errados.
$pdo = new PDO("mysql:host=localhost; dbname=meubanco", "meuuser", "minhasenha");

Para garantir que as informações da conexão não sejam exibidas, é recomendado você desativar o error_reporting no servidor de produção
Você pode fazer isso a partir do arquivo php.ini, alterando a diretiva display_error para off
display_errors = off

Ou diretamente via código, com a função error_reporting.
<?php

error_reporting(0);

Outra coisa que você pode fazer para evitar a mensagem de erro é colocar a conexão com o banco dentro do bloco try:
    try {
        $pdo = new PDO("mysql:host=localhost; dbname=meubanco", "meuuser", "minhasenha");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql = $pdo->prepare("INSERT INTO wp_contatos VALUES ('', :nome, :email, :message, :data)");

        $sql->execute(array(
            "nome"      => $_POST['nome'],
            "email"     => $_POST['email'],
            "message"   => $_POST['message'],
            "data"      => date("Y-m-d h:i:s")
        ));

        $resposta = "Sua solicitação foi recebida com sucesso. Em breve entraremos em contato.";

    } catch(PDOException $e) {
        $resposta = "Sua solicitação não foi recebida com sucesso. Favor entrar em contato pelo telefone 0800";
    }

    echo $resposta;
}

Nesse caso seria exibido a mensagem da exceção.
Comment: Justamente, mas se por algum motivo tiver erro nestas infos, o PDO vai mostrar todos os dados de conexão?
Comment: Caso a configuração do servidor produção esteja configurado para exibir erros esteja ativado, sim ele irá exibir.
Comment: Posso configurar no arquivo de conexão para ele não mostrar estes erros? Vai que o banco cai por exemplo, ai todo mundo fica sabendo das infos !!!
Comment: Veja a edição da minha resposta. O ideal é desativar no arquivo `php.ini` do servidor.


Parsing nested arrays in JSON data swift

Question: I'm currently working with trying to extract bits of information from a complicated json based database.  After NSJSONSerialization.JSONObjectWithData I get output like follows (some returns added for clarity)
 [
 "title": Recorder Suite In A Minor - Viola Concerto - Tafelmusik,
 "estimated_weight": 85,
 "year": 0,
 "thumb": ,

"identifiers": <__NSArrayI 0x600000089970>(
{
description = Text;
type = Barcode;
value = 4891030501560;
},
{
description = Printed;
type = Barcode;
value = "4 891030 501560";
},
{
type = ASIN;
value = B0000013L9;
},
{
type = "Mould SID Code";
value = "ifpi 8412";
},
{
type = "Matrix / Runout";
value = "CD PLANT AB 8550156 CDM01";
},
{
description = "SPARS Code";
type = Other;
value = DDD;
},
{
type = "Label Code";
value = "LC 9158";
}
),
"id": 885370,
"date_changed": 2014-06-17T03:53:03-07:00,
"master_url": https://api.discogs.com/masters/495830,

etc … ]

In particular, I need to know how to get the information out of the nested array.  Note that the array is not (obviously) a nested dictionary - given the equal signs and the repeated keys.  Any help with how to parse this would be appreciated.
Answer: I would use a Pod like SwiftyJSON.
First, you need to install CocoaPods, and then go for SwiftyJSON.
I would parse nested arrays in the following manner:
let json = JSON(data: dataFromNetworking)
if let items = json["items"].array {
    for item in items {
        if let title = item["title"].string {
            println(title)
        }
    }
}

Check out the documentation and Usage section of SwiftyJSON for more info.
Cheers...
Comment: Why do you suggest SwiftyJSON? The OP has already parsed the JSON properly with NSJSONSerialization. The question isn't about parsing JSON. It's about how to extract the desired data from the resulting arrays/dictionaries.
Comment: The OP needs help with extracting information from a nested array. SwiftyJSON provides a clean method to parse the JSON file properly AND extract information even from a nested array.
Comment: Thanks Indeed! Swifty JSON made pulling the data out a LOT easier. . .
Comment: Glad you solved the issue. Please accept the answer so that other people can benefit too.


Java Applet's URLConnection to PHP has no effect

Question: I've studied up on the Oracle documentation and examples and still can't get this to work.
I have a Java Applet that is simply trying to send a text field to a PHP script via POST, using URLConnection and OutputStreamWriter. The Java side seems to work fine, no exceptions are thrown, but PHP is not showing any output on my page. I am a PHP noob so please bear with me on that part.
Here is the relevant Java portion:
    try {
            URL url = new URL("myphpfile.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            out = new OutputStreamWriter(con.getOutputStream());
            String outstring = "field1=" + field1 + "&field2=" + field2;
            out.write(outstring);

            out.close();

    }
    catch (Exception e) {
        System.out.println("HTTPConnection error: " + e);
        return;
    }

and here is the relevant PHP code:
    <?php
            $field1= $_POST['field1'];
            $field2= $_POST['field2'];
            print "

Column1	Column2

" .
                 $field1 . "	" . $field2 . "

";
    ?>

All I see are the table headers Column1 and Column2 (let's just keep these names generic for testing purposes). What am I doing wrong? Do I need to tell my PHP script to check when my Java code does the write?
Comment: you dont send POST request, look at http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily
Comment: Thanks. After reading that, it seems like the only difference is that I need to explicity set "con.setRequestMethod("POST");" correct?
Comment: Unfortunately, none of the techniques on that question had any effect for me.
Answer: Not USE $_POST ,USE $_REQUEST OR $_GET
WHERE TO SET $field1 and $field2 in your php script?
Try  URL url = new URL("myphpfile.php?field1=" + field1 + "&field2=" + field2);
Comment: Thank you, I will try that out. Sorry, my variable names were incorrect. I have edited it!
Comment: The GET/REQUEST did not work either. I wonder if it's a problem with how I write the php output to the page that the applet is on? It doesn't seem to update the page with the text at all. The php code is referenced in my html page via an iframe...is there a better way to do that?
Comment: Yep, I already tried passing the fields in via the URL and PHP still didn't pick it up. I decided to use Java=>Javascript=>PHP instead which works.
Answer: Well, I feel like I've tried every possible thing that can be tried with PHP, so I eventually went with JSObject. Now THAT was easy.
Working Java code:
JSObject window = JSObject.getWindow(this);

// invoke JavaScript function
String result = "

Column1	Column2

"
+ field1 + "	" + field2 + "

";
window.call("writeResult", new Object[] {result});

Relevant working Javascript:
function writeResult(result) {
        var resultElem =
            document.getElementById("anHTMLtagID");
        resultElem.innerHTML = result;
    }

From here I can even send the results from Javascript to PHP via Ajax to do database-related actions. Yay!


Popular Clientdataset em tempo de execução para executar uma consulta SQL ? Delphi

Question: Preciso configurar o CDS para guardar o resultado da consulta, mas sem arrastar os componentes, já que neste caso não estou usando nenhum form, mas me retorna erro 'Invalid Field Type' nos campos informados.
Segue meu código:
begin
  CDSEstoque  := TClientDataSet.Create(Application);
  SDSEstoque.Close;
  CDSEstoque.Close;

  CDSEstoque.FieldDefs.Clear;
  CDSEstoque.FieldDefs.add('ID_PRODUTO', ftInteger);
  CDSEstoque.FieldDefs.add('NOME_PRODUTO', ftString, 50);
  CDSEstoque.FieldDefs.add('NCM', ftString, 8);
  CDSEstoque.FieldDefs.add('QTDADE', ftCurrency);
  CDSEstoque.FieldDefs.add('CUSTO_TOTAL', ftCurrency);
  CDSEstoque.FieldDefs.add('CUSTO_UNI', ftCurrency);
  CDSEstoque.FieldDefs.add('UND', ftString, 2);
  CDSEstoque.CreateDataSet;

  DataEstoque := FormatDateTime('yyyy-mm-dd', pDataFim);

  SDSEstoque.SQLConnection := TDBExpress.getConexao;
  SDSEstoque.CommandText   := 'SELECT M.ID_PRODUTO, A.NOME_PRODUTO, A.NCM, SUM(M.QUANTIDADE) AS QTDADE, ' +
  'SUM(M.VALOR_TOTAL) AS CUSTO_TOTAL, '+
  '(SUM(M.VALOR_TOTAL) / SUM(M.QUANTIDADE)) AS CUSTO_UNI, B.SIGLA AS UND '+
  'FROM movimento_produto M '+
  'INNER JOIN produto A ON (A.ID = M.ID_PRODUTO) '+
  'INNER JOIN unidade_produto B ON (B.ID = A.ID_UNIDADE) '+
  'WHERE (M.DATA_MOVIMENTO <= '+QuotedStr(DataEstoque)+') '+
  'AND QTDADE > 0 GROUP BY M.ID_PRODUTO ORDER BY A.NOME_PRODUTO;';

  CDSEstoque.Open;
  SDSEstoque.Open;
end;

Comment: não poderia ser o campo de quantidade que está declarado como currency no clientdataset? `CDSEstoque.FieldDefs.add('QTDADE', ftCurrency);` , geralmente campos de qtde. são integer
Comment: mas a quantidade pode ser quebrado, por exemplo 1,5 1,7
Comment: E outra dúvida seria, se estou criando o CDS corretamente
Comment: O que é "SDSEstoque"? E onde está sendo relacionado o CDS com um DataSetProvider?
Answer: Resolvi alterando o CDSEstoque, de TClientDataSet para TSQLQuery, e o código ficou assim:
procedure PopulaCDSBlocoH(pDataFim: TDate);
var
   SQL, DataEstoque: String;
   cdsTemp:           TClientDataSet;
begin
   CDSEstoque  := TSQLQuery.Create(nil);
   DataEstoque := FormatDateTime('yyyy-mm-dd', pDataFim);

   SQL         :=  'SELECT M.ID_PRODUTO, A.NOME_PRODUTO, A.NCM, SUM(M.QUANTIDADE) AS QTDADE, ' +
   'SUM(M.VALOR_TOTAL) AS CUSTO_TOTAL, '+
   '(SUM(M.VALOR_TOTAL) / SUM(M.QUANTIDADE)) AS CUSTO_UNI, B.SIGLA AS UND '+
   'FROM movimento_produto M '+
   'INNER JOIN produto A ON (A.ID = M.ID_PRODUTO) '+
   'INNER JOIN unidade_produto B ON (B.ID = A.ID_UNIDADE) '+
   'WHERE (M.DATA_MOVIMENTO <= '+QuotedStr(DataEstoque)+') '+
   'AND M.QUANTIDADE > 0 GROUP BY M.ID_PRODUTO ORDER BY A.NOME_PRODUTO';

   CDSEstoque.SQLConnection := TDBExpress.getConexao;
   CDSEstoque.SQL.Text      := SQL;
   CDSEstoque.Open;
   CDSEstoque.First;

end;


Como adicionar uma classe de CSS a imagens que não carregaram?

Question: Tenho uma página de HTML com inúmeras imagens apresentadas da seguinte forma:

Se alguma das imagens não carregar por motivo A ou B, vão existir quebras no layout ou em alguns navegadores, vai aparecer o quadrado da imagem com o texto alternativo, tornado todo o aspecto um bocadinho feio.
Pergunta
Como posso através de jQuery adicionar uma classe de CSS às imagens cuja acção de carregar a mesma falhou ?
Exemplo:

Comment: Se a imagem for externa (e.g. imgur) com uma url inválida a imagem não irá gerar error 404, portanto soluções utilizando o evento `error` podem não contemplar todos casos.
Answer: A maneira mais "natural" seria usar o onerror (jQuery: error), mas é preciso cuidado pois esse evento somente será capturado se ele ocorrer depois que o handler já tiver sido adicionado. Por isso, uma solução seria colocar o script que adiciona a classe no princípio do documento (head, ou início do body - antes de qualquer img). Para não ficar muito pesado, uma solução sem jQuery:

...

Exemplo no jsFiddle.
Uma maneira alternativa, baseada nesta resposta no SO em inglês, parece funcionar corretamente caso seja necessário colocar o JavaScript no final (no onLoad do documento, por exemplo).
$('img').each(function() {
    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
        $(this).addClass('failToLoad');
    }
});

Exemplo. A vantagem desse técnica é que não é necessário qualquer alteração nas tags HTML.
Comment: Vale observar que o exemplo no jsFiddle esta rodando no evento `onLoad`. Para este código funcionar ele deve estar depois de todos elementos `img` ou em um dos eventos: `DOMContentLoaded` ou `Load`
Comment: Alias, testando mais eu notei que a segunda alternativa só funciona no evento `load`. Pois se as imagens não estiverem em cache a propriedade `complete` nem sempre será `true`.
Comment: @BrunoLM Verdade, isso também me ocorreu quando vi o código pela primeira vez. Imagino que, das três uma: 1) o `complete` já estará pronto quando o script executar; 2) o `load` da imagem vai executar (dando a chance de limpar a classe); 3) o `error` da imagem vai executar. De modo que a primeira alternativa me parece mais confiável IMHO.
Answer: Você pode atribuir um evento de error nas imagens desejadas e adicionar a classe failToLoad
Exemplo
$("#falha")
.on('error',function(){
   $(this).addClass('failToLoad');
   console.log('Essa imagem nao carregou');
})
.attr('src','falha.png');

Lembrando que você não pode recuperar o erro após a imagem e o DOM serem carregados, já que o browser já irá ter propagado o evento de erro ao carregar a imagem, por isso você deve inserir o src após anexar o evento nela.
Essa dificuldade é destacada na API do jQuery .error()
Exemplo JsFiddle
Solução
Uma solução automática seria utilizar as tags data-*

HTML

JavaScript

//Para cada  da página
$('img').each(function(){
    //Selecionar essa imagem
    $(this)
    //Atribuir o evento de erro
    .on('error', function(){
        //Caso ocorra o erro, adicionar a classe failToLoad
        $(this).addClass('failToLoad');
    })
    //Definir o src da imagem recuperando do atributo data-src
    .attr('src',$(this).data('src'));
});

Assim, todas as suas imagens que tiverem erro ao carregar, automaticamente irão ganhar a classe failToLoad
Solução JsFiddle
Answer:
Para novos elementos inseridos dinamicamente é possível fazer utilizando o MutationObserver. E para as demais imagens basta obtê-las e adicionar o evento.
var observer = new MutationObserver(
    function(mutations)
    {
        for (var m in mutations)
        {
            var mutation = mutations[m];

            if (mutation.addedNodes) // todos nodos adicionados
            {
                for (var i = 0; i < mutation.addedNodes.length; ++i)
                {
                    var node = mutation.addedNodes[i];

                    if (node.nodeName == "IMG") // se for imagem
                    {
                        // adiciona o evento "error"
                        // caso o erro ocorra, a classe será adicionada
                        node.addEventListener("error", function() {
                            node.className += " failToLoad";
                        }, false);
                    }
                }
            }
        }
    }
);

// inicia o observer
observer.observe(document, { childList: true, subtree: true });

E para os elementos já existentes na página:
$(function() { // quando a página carregar o DOM

    // para todas imagens da página
    $("img").each(function(i,e) {

        // adiciona o evento
        e.addEventListener("error", function(imgEvents) {
            var img = e;

            e.className += " failToLoad"; // em caso de erro adiciona classe

        }, false);

    });
});

Veja este exemplo no jsFiddle. Note que imagens inseridas dinamicamente também são validadas. Neste exemplo o script está sendo inserido entre a tag .
Note que se a imagem for externa, por exemplo o imgur, e você passar um link inválido o site não irá gerar o erro 404 ao invés disso ele ira gerar uma imagem padrão.


CLLocationDistance not working - swift

Question: I'm having problems with this code, I can't calculate the distance between two locations. I've already searched all over the internet but I could not solve it. Here is my didUpdateLocations function:
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {

    var userLocation:CLLocation = locations[0] as CLLocation
    var startLocation = userLocation
    var endLocation = userLocation
    if x == 0 {
        var startLocation = userLocation
        star.text = "\(startLocation)"
    }
    if x > 0 {
        var endLocation = userLocation
        end.text = "\(endLocation)"
        let distance: CLLocationDistance = startLocation.distanceFromLocation(endLocation)
        println(distance)
    }
    x = x + 1
}

Comment: I also looked at your answer but .. what are you trying to achieve?
Comment: I'm trying to do a Run app, and in this code i want to know the distance of start-point to end-point.
Answer: You just need to declare you  var startLocation as an optional but not inside your function.
var startLocation :CLLocation!

then inside your didUpdate function you just test if the startLocation var is nil:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if startLocation == nil {
        startLocation = locations.first as? CLLocation
    }
    let distance = startLocation.distanceFromLocation(locations.last as! CLLocation)
    println( "\(startLocation)")
    println( "\(locations.last as! CLLocation)")
    println("DISTANCE: \(distance)")
}

Answer: Tks a lot!
I've to do this changes
var startLocation :CLLocation!
var endLocation :CLLocation!

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

     var userLocation:CLLocation = locations[0] as CLLocation

    if startLocation == nil {
        startLocation = locations.first as? CLLocation
    }
    endLocation = locations.last as? CLLocation

    let distance = startLocation.distanceFromLocation(endLocation)

        println("DISTANCE: \(distance)")
        VDistancia.text = "\(distance)"
        VInical.text = "\(startLocation)"
        VSpeed.text = "\(userLocation.speed)"

}

It's works! The values aren't correct, but I'll search how fix it. tks!

CLLocationDistance not working - swift


How to perform clicks in BrowserWindow of an Electron app?

Question: I am writing and Electron app. It has a main browser window. Then from there I open another BrowserWindow. Now I want to programmatically click on a button that is present on the child browser window. How can I achieve that ?
Let's assume that my code in the render process of the main window is as follows :
const childWindow = new BrowserWindow({
        width: 800,
        height: 600,
    })
childWindow.loadUrl('...')
// wait for the window to settle
setTimeout(()=>{
    // the code to click the button
}, 3000)

Answer: You can make use of preloads, which are basically scripts that run inside an Electron browser window
const childWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        preload: path.join(/* path to preload script*/),
        contextIsolation: false,
        enableRemoteModule: true
    }
})
childWindow.loadUrl('...')

// my preload script

document.addEventListener('DOMContentLoaded', () => {
    //get your element using getElementById or querySelector.. etc
    // then perform the .click() on that element
});


Função de pesquisar em agenda em C

Question: Olá, estou fazendo uma agenda em C e já fiz as partes de cadastrar contato, listar todos os contatos e deletar um contato, porém preciso elaborar a parte de pesquisar o contato, e também pesquisar contatos que iniciam com uma dada letra, mas não estou conseguindo... Vou deixar meu código abaixo para ver se alguém consegue me ajudar a identificar onde estou errando.
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

typedef struct
{
    char nome[50];
    char telefone[16];
    int bd;
    char bdm[10];
} Agenda;

int adicionarContato(Agenda **c, int quant, int tam)
{
    if (quant < tam)
    {
        Agenda *novo = malloc(sizeof(Agenda));
        printf("\nDigite o nome do contato a ser salvo: ");
        scanf("%s", &novo->nome);
        printf("\ndigite o seu telefone: ");
        scanf("%s", &novo->telefone);
        printf("\nDigite o dia do seu aniversário ");
        scanf("%d", &novo->bd);
        printf("\n digite o mês do seu nascimento: ");
        scanf("%s", &novo->bdm);
        c[quant] = novo;
        return 1;
    }
    else
    {
        printf("\n Lista cheia.\n");
        return 0;
    }
}

int deleteContact(Agenda **c, int quant)
{
    int id;

    QntContatos(c, quant);

    printf("\n\t Digite o número do usuário que você quer deletar: \n");
    scanf("%d", &id);
    getchar();
    id--;
    if (id >= 0 && id < quant)
    {
        free(c[id]); //evitar vazamento de memória
        if (id < quant - 1)
        {
            c[id] = c[quant - 1];
        }
        return -1;
    }
    else
    {
        printf("\n\t código errado;\n");
        return 0;
    }
}

void QntContatos(Agenda **c, int quant)
{
    int i;

    printf("\n Lista de contatos: \n");
    for (i = 0; i < quant; i++)
    {
        printf("\t%d = aniversário: %2d de %s\t nome do contato: %s \t telefone: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->nome, c[i]->telefone);
    }
}

void Pesquisar(int quant, Agenda **c)
{
    int i;
    char nomeBuscado[30];

    for (i = 0; i < quant; i++)
    {
        printf("\n digite o nome a ser pesquisado: \n");
        scanf("%s", &nomeBuscado);
        getchar();

        if (strcmp(nomeBuscado, c[i]->nome) == 0)
        {
            printf("o nome: %s foi encontrado com sucesso", c[i]->nome);
        }
        else
        {
            printf("o nome não foi encontrado");
        }
    }
}

int main()
{

    Agenda *contatos[50];
    char arquivo[] = ("agenda.txt");
    int opcao, tam = 50, quant = 0;

    do
    {
        printf(" \n\t0 - exit\n\t1 - Cadastrar contato na agenda\n\t2 - Remover contato\n\t3- Imprimir contatos\n\t4- Pesquisar contato\n\t");
        scanf("%d", &opcao);
        getchar();

        switch (opcao)
        {
        case 1:
            quant += adicionarContato(contatos, quant, tam);
            break;
        case 2:
            quant += deleteContact(contatos, quant);
            break;
        case 3:
            QntContatos(contatos, quant);
            break;
        case 4:
            Pesquisar(contatos, quant);
            break;
        }
    } while (opcao != 0);

    return 0;
}
</code>
Answer: Você está pedindo o nome a ser pesquisado a cada loop, deveria ser:
<code>void Pesquisar(int quant, Agenda **c)
{
    int i;
    char nomeBuscado[30];

    printf("\n digite o nome a ser pesquisado: \n");
    scanf("%s", &nomeBuscado);
    getchar();

    for (i = 0; i < quant; i++)
    {
        if (strcmp(nomeBuscado, c[i]->nome) == 0)
        {
            printf("o nome: %s foi encontrado com sucesso", c[i]->nome);
        }
        else
        {
            printf("o nome não foi encontrado");
        }
    }
}
</code>

Função de pesquisar em agenda em C


SoapClient "Could not connect to host" exception with one WSDL API

Question: I have a problem with one WSDL connection with API, after moving to a new OVH VPS machine, so it's maybe some kind of strange misconfiguration.
Other WSDL that I use with SoapClient, work fine, without problems. I'm able to use file_get_contents on the address, but when I use SoapClient I gives a exception "Could not connect to host", when trying to use a procedure from that API.
Any ideas? I've tried some stream_context with some SSL options. What's the funniest, on the other OVH VPS is working fine.
System is Debian 8 with PHP 5.6.19 onboard.
Addresss of the WSDL is here: https://api-test.paczkawruchu.pl/WebServicePwR/WebServicePwRTest.asmx?WSDL
Answer: After consultation with WSDL provider, and checking logs on both sides, we found the anwser. It looks like PHP 5.6 have some problems, and you have to change parameters to SOAP 1.2. This resolved finally the problem. Resolution could be found here, in first comment:
SOAP PHP fault parsing WSDL: failed to load external entity?
// options for ssl in php 5.6.5
$opts = array(
    'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)
);
// SOAP 1.2 client
$params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );
$oSoapClient = new SoapClient ( $url . "?WSDL", $params );

Comment: But best : add "openssl.cafile=C:/path/to/ssl/cacert.pem" to php.ini !
Comment: Or just $params = [ 'soap_version' => SOAP_1_2, 'stream_context' => stream_context_create(['ssl' => ['verify_peer'=>false]]) ]
for me...


How do I properly test NIC teaming in Windows Server 2012 R2

Question: I'm trying out NIC teaming in Windows Server 2012 R2 and I am not getting the testing results I expect. My setup is a PCI-X 64-bit 133 MHz Intel Pro 1000/GT Quad on one server, and four individual Realtek 8111 gigabit PCI-E x1 cards on the other server. All are connected to a managed gigabit switch that supports LACP. I have configured all of the relevant different NIC teaming modes the same on both servers (switch dependent/switch independent, address hash/dynamic) but I receive the same results of only 1 Gbps transfer rate no matter which of the four possible settings I choose. The NIC team on both servers consists of all four network connections and it appears as a 4 Gbps network adapter to the server.
I am using PassMark Advanced Network test, which includes a server and client component, and performs the network transfers entirely in RAM so as to achieve the full possible throughput.
The way I performed the test was to open two instances of the server component on one 2012 server, and open two instances of the client component on the other 2012 server. I connect both client components to the IP address of the NIC team adapter on the other server, but I use a different port number for each client.
When I perform the test by starting one client, I receive 1 Gbps throughput. When I start the test on the other client, instead of gaining another 1 Gbps, both clients drop to 500 Mbps. I thought that by using different port numbers, the stream would get hashed differently and therefore use another physical connection, resulting in each of the two streams achieving 1 Gbps.
I am beginning to wonder if it is my testing methodology, and perhaps there is a better way to test than the way I am doing it, because it seems like everything is configured correctly by using Switch Dependent mode with Address Hashing (though like I said, I have tried all combinations and received the same results).
Answer: I think it would depend on which mode you picked (switch dependent/switch independent) and how your traffic is transferred. Client->Server Server-> Client. If you are in switch independent mode you only have 1 port for inbound on the server and all ports will do outbound. I guess it just depends on how your test is running is it coming from the server or to the server.


Erro: The constructor VelocityTemplate(InputStream) is undefined

Question: import java.io.Serializable;
import java.util.Locale;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.velocity.tools.generic.NumberTool;

import com.outjected.email.impl.templating.velocity.VelocityTemplate;

@Named
@RequestScoped
public class EnvioPedidoEmailBean implements Serializable {

private static final long serialVersionUID = 1L;

@Inject
private Mailer mailer;

@Inject
@PedidoEdicao
private Pedido pedido;

public void enviarPedido() {
    MailMessage message = mailer.novaMensagem();

    message.to(this.pedido.getCliente().getEmail())
        .subject("Pedido " + this.pedido.getId())
        .bodyHtml(new VelocityTemplate(getClass().getResourceAsStream("/emails/pedido.template")))
        .put("pedido", this.pedido)
        .put("numberTool", new NumberTool())
        .put("locale", new Locale("pt", "BR"))
        .send();

Dependencia
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
    <scope>compile</scope>
</dependency>

Esse erro continua mesmo com alteração da versão da dependencia...
Erro na linha 37:
.bodyHtml(new
VelocityTemplate(getClass().getResourceAsStream("/emails/pedido.template")))

Comment: Essa classe `MailMessage` vem de qual biblioteca?
Comment: import com.outjected.email.api.MailMessage;
Answer: Na verdade eu substituí a linha:
.bodyHtml(new VelocityTemplate(getClass().getResourceAsStream("/emails/apontamento.template")))

Por:
.bodyHtml(new VelocityTemplate(new File("/emails/apontamento.template")))

E funcionou...


Disable CKEditor on summary

Question: When I use the widget "field-type-text-with-summary" with the CKEditor, my summary is shown in the CKEditor-format. Can I prevent this and display the field with the plain-format? Hooking into the form, I haven't found a format for the summary; there is just one for the whole body field.
using CKEditor module.
Comment: Are you using the CKEditor module, or the WYSIWYG module?
Comment: the CKEditor module
Comment: OK, I think using WYSIWYG instead of CKEditor will help your issue. See my answer below.
Comment: thank you, but I want/need to use the CKEditor module for better configuration.
Comment: and in drupal8 ?
Answer: I solved this for the CKEditor module for Drupal 7 by altering the widget itself using hook_field_widget_WIDGET_TYPE_form_alter():
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 * Set the '#wysiwyg'-attribute to false for the summary fields.
 */
function YOURMODULE_field_widget_text_textarea_with_summary_form_alter(&$element, &$form_state, $context) {
  if (isset($element['summary']) && !isset($element['summary']['#wysiwyg'])) $element['summary']['#wysiwyg'] = false;
}

Hope this helps!
Comment: I used `$element['summary']['#wysiwyg'] = false;` in my hook_form_alter where I create the form. Works like a charm +1
Answer: I believe the easier path is going with WYSIWYG module.
If you want to go with CKEditor, it sets the editor using hook_element_info_alter. It changes the widget for any form element of the type text_format, in every form built with drupal.
I went looking for the pre_render function CKEditor uses to set the editor up, and figured out a way to prevent it from showing up in summary fields only. First, we'll have to swap the CKEditor pre_render function for one of our own:
function MYMODULE_element_info_alter(&$types) {
  if (!empty($types['text_format']['#pre_render'])) {
    $types['text_format']['#pre_render'] = array_diff($types['text_format']['#pre_render'], array('ckeditor_pre_render_text_format'));
  }
  $types['text_format']['#pre_render'][] = 'MYMODULE_ckeditor_pre_render_text_format';
}

Your module must run its code after CKEditor, and you better declare it depends on CKEditor in the .info file.
Then copy the ckeditor_pre_render_text_format from CKEditor module to your module and change its name to MYMODULE_ckeditor_pre_render_text_format. You will notice it already has an if clause that checks whether $element['summary'] and loads CKEditor for both value and system. Just delete the line that sets it for summary. In version 1.4 (latest stable) the line looks like this:
$element['summary'] = ckeditor_load_by_field($element['summary'], $element['format']['format'], FALSE);

Comment: and in drupal8?
Answer: Drupal doesn't have an input format for the summary: Both the summary and the body use the same input format.
Answer: Rather than use the CKEditor module use WYSIWYG (and place the CKEditor library in the sites/all/libraries directory). It will only apply the editor of choice to a particular input format so you don't need to mess around with disabling the editor on textareas where it's not needed. Using CKEditor with the WYSIWYG module will not apply the editor to the summary (like you want), although it is possible with hooks to add one if needed.
Answer: It is odd that the CKEditor module does not have this option. But until that happens, I created a module that inserts a #wysiwyg=FALSE via a #process function.
Use the CKeditor plain summary module.
Answer: You may be able to implement hook_form_alter and use the #wysiwyg parameter with a value of FALSE. I used this in Fill PDF to aid in preventing the WYSIWYG editor from appearing without having to set a separate ignore rule.
See this issue: http://drupal.org/node/285200 - looks like it's just been re-implemented. I never knew it had been removed!
Answer: Might have to take an approach similar to http://drupal.org/project/excerpt, (Drupal 6). Some details from the module's project page:

Excerpt module allows you to enter a separate excerpt/summary/teaser for a node, which does not have to be a cut off version of the body.
Even though Drupal 6 provides similar functionality, Excerpt is useful for various reasons, for instance, when also using editors like TinyMCE.

Have a look at the hooks used and something might be useful.

Disable CKEditor on summary


Effective search space vs guided search space

Question: In ISLR (Intro to Stat Learning using R by James, Witten, Hastie, Tibs), in the section on Forward Selection on page 208, the footer states:

Though forward stepwise selection considers $p(p+1)/2 + 1$ models, it performs a guided search over the model space, and so the effective model space considered contains substantially more than $p(p+1)/2 + 1$ models.

What do they mean by substantially more?  How much more, for example?
Answer: Since there are no answers to this question even after a year, I can try answering the first part of your question. Or atleast, almost answer it.
Say we have 4 predictors a,b,c,d. Hence p=4. Now let's apply the Forward selection Algorithm.
First Iteration (Find best model with one predictor) ->
4 options : (a),(b),(c),(d) -> suppose the best performing Model is the one with b
Second Iteration (Find best model with 2 predictors) ->
3 options : (b,a),(b,c),(b,d) -> suppose the best performing model among this is the one with (b,c)
Third Iteration (Find best model with 3 predictors) ->
2 options : (b,c,a) , (b,c,d) -> suppose the best performing model among this is the one with (b,c,a)
Fourth Iteration (here k=p, i.e all predictors are used)
1 option : (a,b,c,d) -> Suppose this model doesn't perform as good as (b,c,a).
So we choose model (b,c,a) as the best model.
Now we know that all the possible combinations of models is 2^p for Subset Selection (page 206). In this case 2^4= 16 models. Let's see them all :-
(0),(a),(b),(c),(d),(a,b),(a,c),(b,c),(a,d),(b,d),(c,d),(a,b,c),(a,b,d),(a,d,c),(b,d,c),(a,b,c,d)
Whereas in our example the Forward selection went through only 1+p(p+1)/2 models
(0),(a),(b),(c),(d),(b,a),(b,c),(b,d),(b,c,a),(b,c,d),(b,c,a,d)  : 11 models
Of course Subset Selection brings us closest to the truth (at a high computational cost though).
If suppose the best true model is (a,c). Although the Forward Selection did not assess it, it has assessed (b,c,a) with contains a and c, and so is close to the true model (a,c).
In this way we can also say that the Forward Selection Algorithm came close to assessing (c,d) as well because it assessed (b,c,d). So if the truth had been lying here, this iteration (3rd) would have given a (b,c,d).
So, although the search is guided (filtered) in each iteration, the effective model space considered is in fact more than just the 1+p(p+1)/2 models. However I'm not sure by 'how much'.
I hope my understanding is correct. If not, kindly correct me. I would be grateful.
Thank you!
Comment: Thanks for the answer.  Wouldn't this argument hold true for any guided search?  According to this argument, any guided search would be effectively searching something larger.  Also, the model that considers all the parameters, (a, b, c, d), would effectively have considered all combinations, right?
Comment: @user650654 Before answering your questions let me make it clear that guided is searching something smaller (and not larger, as per your question). i.e the guiding avoids a full search. Our main intention was to REDUCE THE COST of the algorithm by bringing down the search from 2^p to 1+p(p+1)/2.
Comment: @user650654 How the effective search of the models is indeed larger than what is actually searched is answered. Kindly vote if you have found this answer useful. :)


Formatar campo CPF ou CNPJ usando Regex

Question: Gostaria de uma expressão regular(REGEX) para formatar o campo de CPF ou CNPJ
Este é o codigo que cheguei até agora:
<code>    String cpf ="09551130401";
    cpf = cpf.replaceAll("(\\d{2})(\\d{3})(\\d{3})(\\d{4})(\\d{2})", "$1.$2.$3-$4");
    System.out.println(cpf);
</code>
Answer: CNPJ: (^\d{2}.\d{3}.\d{3}/\d{4}-\d{2}$)
CPF: (^\d{3}\x2E\d{3}\x2E\d{3}\x2D\d{2}$)
Usando Bean Validation, você pode definir um padrão para a sua variável.
<code>@Pattern(regexp = "(^\d{3}\x2E\d{3}\x2E\d{3}\x2D\d{2}$)")
private String cpf;
</code>
Busquei estas expressões aqui  e as testei neste site.

Formatar campo CPF ou CNPJ usando Regex


Facebook like/share content locker

Question: I was looking at stackoverflow the answer and the closest one was "Check if user liked page"
What I want to do is not to check if someone liked, but unlock contend when someone like/share. I dont want to check everytime if someone already like it and then decide to show him content. Everytime someone is visiting mine site I want him to share it again. It can be done without facebook aplication. As expample I can provide this link:
http://strefavideo.pl/?videos=wepchnal-go-pod-pociag-zobacz-jak-to-sie-skonczylo
As you can see, there is an video, which you can watch ONLY if you share by clicking "udostępnij" and than confirming this share.
If I'm wrong and there already is topic like this at stackoverflow than Im sorry and plz lead me to it. If there isnt one, than plz help me :)
Answer: If you're using wordpress this is the best plugin to you: http://codecanyon.net/item/advanced-facebook-content-locker/1506489. I'm using it for my free mp3 download site

Facebook like/share content locker


Substituição de JavaScript If else com boolean

Question: Estou com uma dúvida em um código de JavaScript.
Estou tentando fazer um código de comparação, porém quero retirar as palavras "true" e "false" e substituir por outras palavra que posso colocar.
Estou usando If else mas será que isso ajuda?

    JavaScript Comparison

 x = 5; y =5 => x == y

Obrigado pessoal!
Comment: A tua pergunta não está muito clara. Podes explicar melhor o que queres fazer e dar um exemplo?
Comment: Se queres retirar as palavras true ou false retire document.write(x == y);
Comment: Usando o setter talvez você consiga: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/set
Answer: Se vai ajudar ou não depende do contexto em que esse javascript for aplicado pois as instruções condicionais são usadas para executar ações diferentes com base em diferentes condições.
A instrução  if é usada para especificar um bloco de código JavaScript a ser executado se a condição for verdadeira.
A instrução  else é usada para especificar um bloco de código JavaScript a ser executado se a condição for falsa.
Use a instrução else if  para especificar uma nova condição, se a primeira condição for falsa.
Exemplo if else
if(x==y) {
    document.write("palavra aleatória");;
} else {
    document.write("palavra aleatória2");
}

ou usando a notação ternária
    var resultado = (x == y) ? document.write('palavra aleatória') : document.write('palavra aleatória2');

Exemplo if - else if - else
 if(x< y) {
    document.write("palavra aleatória");;
} else if(x == y) {
    document.write("palavra aleatória2");
} else {
    document.write("palavra aleatória3");
}

Muitas vezes, na programação, você vai precisar de um tipo de dados que só pode ter um de dois valores, como

SIM NÃO
LIGADO DESLIGADO
VERDADEIRO FALSO (true false)

Nesse caso você pode usar a função booleana para descobrir se uma expressão (ou uma variável) é verdadeira:
document.write(5 == 5);
Nota: Letras maiúsculas nas instruções (If, IF, Else etccc) gera um erro de JavaScript.


Exercise 1.6 [Goldbach 1752] of An introduction to number theory

Question: Prove that  if $f\in \mathbb Z[x]$ has the property that $f(n)$ is prime for all $n\ge 1$, then $f$ must be a constant.
This is a Exercise of An introduction to number theory.  In fact, I am not sure what is $\mathbb Z[x]$. Is it  integer value  function ? Besides, how to show it ?
Answer: The notation $\mathbb{Z}[X]$ stands for the set of all polynomials with coefficients in $\mathbb{Z}$.
Answer: Hint Let $f(1)=p$.
Show that for each $k$ you have
$$p | f(kp+1)-f(1)$$
Deduce that $f(kp+1)$ is divisible by $p$, and since $f(kp+1)$ is prime...
Comment: @lanse7pty If a polynomial takes one value infinitely many times, it must be constant...You don't need so show that $f(2)=f(1)$, only that $f(x)=p$ has infinitely many solutions.
Comment: How to show $f(2)=f(1)$ ? In my try ,it is equal to show $\forall p,q$ are primes, there are $a,b\in \mathbb Z$ such that $ap=bq+1$.


Correct way to share a view in the index page

Question: I'm a Ruby-on-Rails newbie, just starting out.
I have an MVC called "account_types", generated via scaffold to produce:

controllers/account_types_controller.rb
helpers/account_types_helper.rb
models/account_type.rb
views/account_types/_form, edit, index etc...

Going to localhost:3000/account_types gives me the index view.
What I'd like to do is display the same data as selected from the account_types index method in the application index page as a list.
I wrote a new view called account_types/_list.html_erb as follows:

<% @account_types.each do |account| %>

<% account.label %>

<% end %>

I then edited home/index.html.erb (This is based on examples given in other questions on SO):
<%= render :partial => 'account_types/list', :module_types => @module_types %>

However I get

undefined method `each' for nil:NilClass

and the error displays the code from account_types/_list.html.erb where I've written
<% @account_types.each do |account| %>

The scaffolded views work fine, why aren't mine?
Are partials the right thing to use here?
Thanks in advance.
Answer: What is the correct way to define an application-wide partial and its variables in rails says to use a before_filter on ApplicationController.
Answer: You pass :module_types to partial, but use account_types. As I can see you just need to change your index.html.erb to:
<%= render :partial => 'account_types/list', :account_types => @module_types %>

Comment: I think I have it working now. http://stackoverflow.com/questions/8869291/what-is-the-correct-way-to-define-an-application-wide-partial-and-its-variables says to use a `before_filter` on  `ApplicationController`. I've put that in, and suddenly the `account_types` variable is available to every controller. This is exactly what I needed.
Comment: Sorry, as above I've confused everyone with module_types - that was something else I was trying - it should have been account_types.

`<%= render :partial => 'account_types/list', :account_types => @account_types %> still gives the same error message.
Comment: I've created a new project to recreate this problem. I've set everything up as before.

If I don't add (amp)account_types = AccountType.all to home_controller.rb, I get the same error about nil.each

If I add (amp)account_types = AccountType.all to home_controller.rb then I get an li for each record, but no lists of data (which is strange in itself). However, (amp)account_types is already defined in account_types_controller.rb, so in the interests of DRY, can I somehow use the index controller from account_types instead of having to rewrite it in the home controller to use it in the home view?
Answer: You can use partials for this if you want, though it would be unnecessary in this case as far as I can tell (they are for sharing chunks of code between several views). In order to get this code to work you'll need to define @account_types in your controller with something like
@account_types = AccountType.all

You can see exact line in your account_types_controller.rb under index action. :module_types => @module_types is not necessary here, since I doubt you defined @module_types either and you don't use module_types in your partial at all.
It's obvious, that you don't understand how Rails works, so I suggest reading through a good tutorial (like this one) before you proceed with whatever you have in mind.
Comment: Oops. module_types was something else I was trying. It was supposed to be account_types. Sorry.

I've got `@account_types = AccountType.all` in the controller. The trouble is that my custom view can't seem to access the variable @account_types, so it is complaining that it's nil. How do I get my custom view to access @account_types the same way `AccountTypesController.index` works?
Comment: Well, you can forcefully pass it as with `:account_types => @account_types`, but then you'll need to change `@account_types` in your partial to `account_types`.


How to split a RichTextBox , and retain values in an array as integer values

Question: First of all,sorry for my bad english , i'm still learning.Now let's go back to my problem:
-I have a RichTextBox,where i introduce values like:
4112
3125
780
5680 etc.
-every value has a new line.What i mean is , after i introduce a value,i press ENTER.
All i want is,to save this values in an array,but as integer elements,not characters.How can I do that?
I tried with SplitChar method,but i don't understand this method,because i'm beginner in C#.
My try:
public void ViewMyTextBoxContents(){

//Create a string array and store the contents of the Lines property.
string[] tempArray = RichTextBox1.Lines;

// Loop through the array and send the contents of the array to debug window.
for(int counter=0; counter < tempArray.Length;counter++)
{
   System.Diagnostics.Debug.WriteLine(tempArray[counter]);
} }

But still,not working ..Thanks for help!!!Have a nice day!
Answer: int[] arr = richTextBox1.Lines.Select(x => Int32.Parse(x)).ToArray();

Basically, you're missing the Int32.Parse(tempArray[counter]) part. This parses the string to an int.
Adapting your code to do the same:
string[] tempArray = richTextBox1.Lines;

int[] resultArr = new int[tempArray.Length];
for (int counter = 0; counter < tempArray.Length; counter++)
{
    resultArr[counter] = Int32.Parse(tempArray[counter]);
}


How to generate a synthesizable pseudo random generator from 1 to 52 System Verilog

Question: Could someone explain how to create a pseudo number generator that has a range of 1 to 51 and can have its value placed within something like the for loop. This has to be in System Verilog and synthesizable. I have read about some CRC and LFSRs but was not quite sure how to modify them to fit it within the specified values I needed (1-52) and how to fit it within a for loop as most examples took up an entire module.
Thank you for your time.
initial begin
for(int i = 0; i < 52; i++) begin

        int j = // insert PSEUDO RANDOM NUM GEN 0 to 51

            if(array[j] == 0)begin
                i = i-1;
                continue;
            end
            else
            array2[i] = array[j];
             array[j] = 0;
        end
end

(array and array2 both have 52 values of bit size 4)
Answer: I don't know what is your application, but what you could do is to generate numbers in the modular ring mod 53 (53 is a prime number). Since you did not mention any other requirement I will take the simplest generator I could imagine, that can be performed without multiplications and will generate numbers, 1 <= n < 52.
function [5:0] next_item(input logic [5:0] v);
  if(v < 26) begin
    next_item = (v << 1); // 2 * v % 53 = 2 * v
  end
  else if(v > 26) begin
    // (2 * v) % 53 = (2 * v - 52 - 1) % 53 = 2 * (v - 26) - 1
    next_item = (((v - 26) << 2) - 1);
  end
  else begin
    // v = 26, you want to exclude 2 * v % 53 = 52, so we skip it
    // by applying the next item again, and it will be
    next_item = 51;
  end
endfunction

And you could use it like this
parameter SEED = 20; // any number 1 <= N < 52 you like
initial begin
int j = SEED;
for(int i = 0; i < 52; i++) begin

      if(array[j-1] == 0)begin
        i = i-1;
        continue;
      end
      else begin
       array2[i] = array[k];
      end

      j = next_item(j);
end

Comment: thank you for this, this program was made to create an array of playing card values so a deck of 52 2-9 Ace, Joker, King, and Queen. and then use randomization to randomize values from the first array to the second array. just a question tho when I tried compiling it said "object "param" is not declared" I tried then setting SEED as an int but j always came back as Info "32'sb00000000000000000000000000......" from $display right after the function call, and this is causing an infinite loop.
Comment: Sorry, I was meant to write `parameter`