Why do pitchers walk other pitchers (in the National League) with some frequency?

Question: In asking this question, I am not referring to exceptional cases like Yovani Gallardo, Madison Bumgarner, or Jake Arrieta, who hit about as well as position players. But I am referring to "most" pitchers, whose batting averages are in the .100s, about half as high as average position players.
I read somewhere that there is a theoretical batting average below which it was right to always throw strikes because the chances of getting the person out was so high that it was worthwhile not to give him a chance to walk, and as a practical matter, there was a somewhat higher threshold below which it made sense to throw mostly strikes, thereby giving the batter a minimal chance to walk.
My best recollection is that the rule is that one should "never" walk a batter (incurring a sure loss) whose average was below .075 even if he all home runs, and that it made sense to never walk a batter with an average as high as .225 if he never made extra base hits.
Don't most National League pitchers fall beneath these thresholds as batters? (Or if I have stated them wrongly, the "corrected" ones?) So why do pitchers often throw enough balls to walk them, when they could get them out by throwing mostly strikes?
Put another way, why does practice differ from theory in this instance?
Comment: So is your question "why are pitchers walked?" or is your question "at what average should a player always be thrown strikes, as there is a low chance of them getting on base?"
Comment: @New-To-IT: The "composite" question is "why are pitchers walked, when (in most cases), their averages are low enough so that there is a low chance of their getting on base? Are other pitchers aware of the latter?
Answer: Pitchers don't try to walk anyone, most walks come from poor execution on the pitchers part/ bad calls by the umpire. Also, pitchers (while hitting) walk less frequently than positions players, indicating that the pitchers throwing are aware that the pitchers hitting can't hit.
Comment: @JeopardyTempest That's a good point. Pitchers have to balance not giving a meatball with not walking.
Comment: Pitchers don't try to walk ALMOST anyone of course (see intentional walks).  I'd say that there's a variable ratio of willingness to walk vs willingness to throw a hitable pitch for each batter, and for a poor hitter, it's almost 0, while for a player like Mike Trout with no one on base, it's quite high.  But think you hit the notable point at least in suggesting that they aren't trying to.
Answer: "In theory, there is no difference between theory and practice. But, in practice, there is." -Jan L. A. van de Snepscheut (at least according to Wikiquote, although variations seem to predate this version)
The question seems to presuppose that a pitcher has absolute control over his pitches. Obviously, that's not true, or you'd never see a walk or hit batsmen with based loaded, a tie score, and the game being in the bottom of the ninth (or in extra innings); however - while rare in the Major Leagues - such things do happen, demonstrating that pitchers don't always execute their craft perfectly, which Frank Anderson's answer already addressed somewhat.
At a bit of a deeper level, I believe there are psychological aspects that can play into this when a pitcher comes up to bat. The pitcher on the mound may relax when his counterpart comes up to bat; in doing so he may lose some focus - enough that his ability to throw strikes is diminished. The flip side of this is that the pitcher who is pitching may get nervous due to thoughts like "This guy is a poor batter, so I must get him out." This sort of extra stress might be heightened if the batting team is threatening to score and the batter before the pitcher was intentionally walked to bring the batting team's pitcher to the plate.
There's also the possibility of walking the pitcher for strategic reasons. (While it might be the defensive team's intention to walk the opposing team's pitcher, they wouldn't issue an obvious intentional walk.) Pitching is probably the most tiring position in the game (if it is not, it is #2 to catching). Sometimes it seems that running the bases tires out a pitcher. Since pitchers usually become less effective when they are tired, a team might walk their opponent's pitcher to wear him out a little faster to either improve their chances of scoring off him, or to get him out of the game faster.


Sorting content from different MySQL tables by date

Question: I have 3 different tables :

News

news_id
news_content
news_pubdate

Songs

song_id
song_link
song_pubdate

Interview

interview_id
interview_artist
interview_content
interview_pubdate

I'm trying to create a timeline on my website to display all the content sorted by the pubdate from my 3 tables in a unique list. Is there a way to do that in MySQL ?
Maybe creating a 'general' table that would include all the ids sorted by date from my 3 other tables? I should then link all the element with PHP. Is it not too much power consuming ?
Comment: I believe all you would need would be a JOIN query. Can you give us an example record for each of the tables please so we can write you such a query?
Answer: Try this and see if it will meet your needs:
<code>SELECT
    `news_id`      AS `id`,
    `news_content` AS `content`,
    `news_pubdate` AS `pubdate`,
    ""             AS `person`,
    "news"         AS `type`
FROM `news`

UNION
SELECT
    `song_id`      AS `id`,
    `song_link`    AS `content`,
    `song_pubdate` AS `pubdate`,
    ""             AS `person`,
    "song"         AS `type`
FROM `song`

UNION
SELECT
    `interview_id`      AS `id`,
    `interview_content` AS `content`,
    `interview_pubdate` AS `pubdate`,
    `interview_artist`  AS `person`,
    "interview"         AS `type`
FROM `interview`

ORDER BY `pubdate`;
</code>
Comment: Working perfectly! Thank you so much!


What code skeleton should I use for Intel 8086 DOS assembly?

Question: Having learned Intel 8080 structure, I'm now trying to learn Intel 8086 and how the programs here are layed out. For now, it's quite intimidating even looking at the basic examples and what's worse, I can't get the difference between two ways of writing code for 8086 I've stumbled upon. Namely, sometimes i see:
.model small
.stack 100h
.code

start:

mov dl, 'a' ; store ascii code of 'a' in dl
mov ah, 2h ; ms-dos character output function
int 21h ; displays character in dl register
mov ax, 4c00h ; return to ms-dos
int 21h

end start

While I also found:
Progr           segment
                assume  cs:Progr, ds:dataSeg, ss:stackSeg

start:          mov     ax,dataSeg
                mov     ds,ax
                mov     ax,stackSeg
                mov     ss,ax
                mov     sp,offset top

            mov     ah,4ch
            mov     al,0
            int     21h
Progr           ends

dataSeg            segment

dataSeg            ends

stackSeg          segment
                dw    100h dup(0)
top     Label word
stackSeg          ends

end start

Obviously, I know that these two do very different things but what baffles me is how different the general syntax is. In the latter we have some "segment assume" while in the former it's just .model, .stack and .code (and sometimes .data, from what I found). Is there any difference? Can I just choose which one suits me better? The former looks a lot easier to understand and clearer but can I just use it instead of the latter?
Comment: The first example uses simplified directives. The second uses verbose directives. (The second is also large model but the first is small model.) Older code uses verbose directives because simplified directives were not available in 1992.
Comment: You can use the old way just fine. The second example is slightly higher level, but very much optional. I've never had to use it myself, but it can be useful when you're writing a larger application. And the abilities depend on your assembler compiler - the difference is very much in the compiler, not the CPU architecture or instruction set.
Comment: @Straightfw : One thing's certain:  RaymondChen knows what he's talking about.  If you doubt, look up his blog "The Old New Thing", or book by the same title.
Comment: @Luaan - I see. In that case, I'll try to hold on to the first example style to not confuse myself too much in the beginning. Thank you :)
Comment: You should refer to "professional assembly language by Richard Blum" a good book.. Also here's a basic link... http://wiki.osdev.org/Assembly
Comment: @SAM - thank you for the recommendation :)
Comment: @Straightfw :) Best of luck! And welcome to 8086 :)
Answer: This depends massively on the operating system you target (or or BIOS or bare metal), the executable format you target, and the assembler you use.
The first example you posted is for MS-DOS .COM programs, the second for MS-DOS .EXE programs, and I assume both are using the Microsoft® assembler.
If you want to use the GNU assembler (e.g. on MirBSD or GNU/Linux) to target i8086 MS-DOS .COM programs, you can use this:
        .intel_syntax noprefix
        .code16
        .text

        .globl  _start
_start: mov     ah,9
        mov     dx,offset msg
        int     0x21
        /* exit(0); ← this is a comment */
        mov     ax,0x4C00
        int     0x21

msg:    .ascii  "Hello, World!\r\n$"

Compile this file (hw.S) with:
$ gcc -c -o hw.o hw.S
$ ld -nostdlib -Ttext 0x0100 -N -e _start -Bstatic --oformat=binary -o hw.com hw.o

I tested the result in DOSBOX under MirBSD/i386, and looked at it in hexdump to see that it's correct.
In contrast to the other solutions, you do not define the origin (org) in the assembly file but on the linker (ld) command line, here.
I've also got an example targetting raw x86 BIOS and another one (bootsector for blocklists) and another one (bootsector for *.tar archives), in case you're interested; they need different origins though, and they require an i386 CPU even though they use the 16-bit mode only.
You can't do *.EXE files that way.
ELKS is also an interesting i8086 target, but I haven't done much with it yet. Do make sure you get a GNU as version new enough to know the .intel_syntax noprefix mode though.


Rewriting in Compound Meter

Question: I am confused on how to rewrite a piece in compound meter. Here are a few examples I have which I need to change to compound meter.
I think I need to just compound 2 measures together?
Answer: Yes, the exercise is asking for the measures to be "compounded together". So in exercise (a), you would remove every other bar line, beginning with the first, to create four measures of 6/8 time.
Just know, the exercise also misleadingly allows one to infer that two measures of 3-time is equivalent to one measure of 6 time. This is mathematically true, but not "musically" true. There is a subtle difference in how a performer would make the music sound.
In 3/16, each beat 1 would be presumed to be of equal emphasis. In 6/16, each beat 1 would be presumed to receive equal emphasis, but each beat 4 (previously a beat 1 in 3/16) would receive a lesser emphasis.
Comment: I don't think ex.b works in anything but 9/8. What do you think? I agree it's pretty poor exercise concerning compound times.
Comment: @LaurencePayne It is within the context of the exercise in the OP.
Comment: @LaurencePayne Fair. I've rewritten to clarify. (P.S. Your caps lock key is stuck. Your point would be just as clear in lowercase.)
Comment: Where's that implication?
Comment: @Tim Changed to "allows the reader to infer". This is a beginning level exercise, and few beginners will understand on their own the difference between 3/8 and 6/8. Personally, I think this exercise is a poor way to introduce compound meter specifically for that reason. 6/8 is more than 3/8 with bar lines removed.
Comment: Ah, I see. Very good point. For a sensitive enough student, all three melodies clearly demand a specific compound meter. The exercise is more subtle than I gave it credit.
Comment: Though @Dom's answer in the linked thread 'Why is meter divided into simple and compound types?' does explain the difference well, I'm afraid this answer shows that you haven't understood it!  A Compound Meter ISN'T two Simple Meter measures joined together.
Comment: @Aaron so your answer contradicts itself!  Anyway, when you say 'compound meter means the combination of two or more simple meters' that's just plain WRONG!
Comment: But not as ANNOYING!   And I'm afraid you're STILL wrong.  3/16, 3/8 or 3/anything_else can be one-in-a-bar (compound single) or three-in-a-bar (simple triple).
Comment: @LaurencePayne Well, I have to give you that.
Comment: @LaurencePayne You're mistaken on this one. See [here](https://www.mymusictheory.com/for-students/grade-5/48-3-time-signatures), [here](https://music.stackexchange.com/questions/99843/why-3-8-is-not-a-compound-time-signature), [here](https://forums.abrsm.org/?showtopic=49966), [here](https://www.dummies.com/art-center/music/piano/understanding-simple-and-compound-time-signatures/), and [here](https://www.google.com/search?q=is+3%2F8+simple+or+compound&rlz=1C1GCEA_enUS754US754&oq=is+3%2F8+simple&aqs=chrome.0.0i457j69i57j0l2j0i22i30l4.3933j1j7&sourceid=chrome&ie=UTF-8).
Comment: "In 3/16, each beat 1 would be presumed to be of equal emphasis": this is one of the things that distinguishes amateurs from professionals.  Nothing should ever have equal emphasis.  Also, in converting to 6 or 9, one must still decide which of the measures becomes 1.
Comment: @phoog Is that a criticism or a compliment? If the latter, how would you put it? I'm trying to get across that first beats get the primary emphasis versus the "secondary" strong beats within a compound meter. Maybe "presumed to be of strongest emphasis within their respective measures"?
Answer: Simple is what it says. Compound is simples joined together - at least as far as this exercise goes. In 2s, 3s or 4s.
The 1st exercise works well when two bars are joined together - the tune doesn't lose its phrasing. But do that with the second, and it just doesn't sound good. Yes, physically, it can be done, but with emphasis every three bars (the emphasised note denoting it's the beginning of a new bar), it works out fine.
Comment: Sorry, @Tim, that ISN'T what 'Compound Meter' means in music.
Comment: @LaurencePayne - in actual fact, judging by the question, you're right - that's exactly what the writer of the question (in the example featured) is thinking!
Comment: I don't think you and I are giving enough credit to the textbook question writer. As you pointed out to me, melody b (and c as well) work better in compound meters. I beginner likely wouldn't pick that up, but a beginner with a good teacher would have a shot. The question could be better presented, but I think its heart is in the right place, so to speak.
Comment: So, for B and C  how do I know what the time signature should be for switching it to compound. Then do I do what I did for the first one and get rid of every other bar line starting with the first one?
Comment: Pretty straightforward. You sing/play it and feel where the divisions can be. Try one, two, three, four bar divisions, and when one feels right, use that.
Comment: @LaurencePayne - edited the answer to hopefully clarify.
Comment: You really can't let such a blatant misuse of musical terminology get past that easily!
Answer: 'Simple' and 'Compound' (as descriptions of meter) don't mean what the writer of the textbook apparently thinks they do!
In musical terms, a 'simple meter' is one where the beats subdivide into 2.  Typically (but not exclusively) a quarter-note beat (quarter-notes split neatly into two eighth-notes).  2/4, 3/4, 4/4 are common 'simple' times.
'Compound meter' is where they subdivide into 3.   Typically a dotted quarter beat (dotted quarter-note splits into three eighth-notes).  3/8, 6/8, 9/8, 12/8 are common 'compound' times.
(Actually, 3/8 and 3/4 are ambiguous.   Counted 'three in a bar' they're Simple.  Counted 'one in a bar' they're Compound. Think about it, before disagreeing!)
'Compound'  DOESN'T mean 'formed from adding together pairs of shorter measures'. 2/4 is Simple Time.  Join pairs of measures to make 4/4, it's still Simple.   12/8 is Compound Time.  Split 8 bars of 12/8 to make 16 of 6/8, it's still Compound.
So the test question is not a very clear one.  It's arguable that the examples are in Compound Meter already!   However, we can assume they want you to concatenate every two or three bars to make a piece in 6/8 or 9/8, and even if you consider my theory that a one-in-the-bar 3/8 is Compound Single, we can agree THOSE are Compound meters!  Maybe even  every four bars to make 12/8.   (I don't think we need to worry about 15/8 etc. here.)   You're also being asked to judge whether, musically, each example does work well when grouped in this way.
Comment: Vote it down all you like, this is still the right answer!

Rewriting in Compound Meter


Generating function value within variable in Jmeter

Question: I want to use the Random function within the variable in Jmeter for example
${demo_variable_g${__Random(1,4,)}}
I am extracting the values for demo_variable using regular expression extractor. I want to generate random number while using the extracted variable value. How do I do that?
Answer: The correct function would be:
${__V(demo_variable_g${__Random(1,4,)})}

From the __V() function documentation

For example, if one has variables A1,A2 and N=1:

${A1} - works OK

${A${N}} - does not work (nested variable reference)

${__V(A${N})} - works OK. A${N} becomes A1, and the __V function returns the value of A1

See Here's What to Do to Combine Multiple JMeter Variables article for explanation and demos


Bootstrap v 3.2 Border across multiple columns

Question: I'm trying to stick to the Bootstrap design paradigm of container > row > column, but I'm admittedly new to this and curious about something.
If I'm only putting content in the columns, as I believe I'm supposed to do, then Bootstrap's CSS puts a 15px gutter at the left and right edges of the page (I know it also puts them between disparate columns.) For design aesthetics I'd like to put a border above my content, and I'd like to do so without having it run into the gutter space.
Plunk included. As you can see, When I try to style the same element containing the content, it results in the border-top attribute (blue and green colored in my example) running into both gutters. When I create a new element above the content and attribute it with margin-left, margin-right values, that seems to work for the left edge of the border but not for the right one (orange color in my example). I just want the border to line up with my text.
What is the best way to accomplish this? I could change the margins or padding for the element itself but then I feel like I'm messing with Bootstrap's plumbing.
Answer: Please check this plunk. I've wrapped the content inside
 with a
 tag and then applied a border-top to that
 tag. Moreover, I've assigned the property of display: block to the  tag inside
 and then applied a border-top to that  tag.
If you want to have the border-top only above the text then please check this plunk.
UPDATE:
To make both the blue and the green border-top to touch, you can use the :after psuedo selector on .opportunity-results like this:
.opportunity-results:after {
     position: absolute;
     content: '';
     border-top: 1px solid blue;
     width: 100%;
     height: 2px;
     left: 15px;
     top: 0px;
}

Here's the plunk for it.
Comment: Thank you. Both your plunks accomplish keeping the border out of the gutters at the edge. Is there anyway to do this while getting the blue and green lines to touch as well?


touch.locationInView not assigning to local variable

Question: I'm trying to get to use locationInView to get the location of a touch.  When I print the locationInView to the console, the correct value is outputted.  But when I try and assign it to a local variable, that variable never gets the value and therefore the rest of my code doesn't work.  Also, this is a subclass of UIControl.
Snippet below:
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool
{
    NSLog("\(touch.locationInView(self))")     // Prints out the correct location
    let newPoint = touch.locationInView(self)  // Never gets assigned to newPoint
    var calculatedIndex: Int?

    for (index, item) in labels.enumerate() {
        if item.bounds.contains(newPoint) {
            calculatedIndex = index
        }
    }

    if calculatedIndex != nil {
        selectedIndex = calculatedIndex!
        sendActionsForControlEvents(.ValueChanged)
    }

    return false
}

Debugger and local variables
Comment: I doubt that actually happens, what is the output of logging / printing `newPoint`?
Comment: I added a snapshot of Xcode and debugger's locals and console, showing what is happening.
Comment: The Xcode debugger is known to have its fair amount of bugs, please just add a NSLog statement after your assignment of newPoint logging newPoint.
Comment: Hmm, ok.  I see that newPoint does have it's value.  The rest of my code still isn't working how I would expect.  I'll need to keep digging...thanks.
Answer: I just ran your code locally and it all worked fine. You are probably deceived by debugger issue to show the value. You may confirm this by printing newPoint.
As for why your rest of the code is not getting executed, I would recommend you to check your labels. I think labels.enumerate is failing which makes your feel that code is not getting executed. Again try to print values rather than relying on debugger.
Comment: Thanks.  I see the debugger was failing me.  I also had a mix up between my bounds and frame, and therefore that wasn't selecting properly like I expected.  Threw a couple NSLog's in there and figured it all out.
Comment: Great... I guess this must be accepted answer. Could you please accept this for the benefit of others.


IF x SWITCH - Simulando

Question: Acredito que todos nós sempre tempos que fazer algumas tratativas em condições com poucos valores.
Fiz um teste entre o IF e o SWITCH.

Todo conteúdo, foi criado para SIMULAR uma estrutura mais idêntica
  possível entre o IF e SWITCH.

Arquivo da classe: ifXswitch.php
<?php

class Teste {

    public function fc_if($v) {

        // Marcador de tempo 1
        $t1 = microtime(true);

        // Script
        if ($v == 1) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(1); }
        elseif ($v == 2) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(2); }
        elseif ($v == 3) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(3); }
        elseif ($v == 4) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(4); }
        elseif ($v == 5) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(5); }
        elseif ($v == 6) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(6); }
        elseif ($v == 7) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(7); }
        elseif ($v == 8) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(8); }
        elseif ($v == 9) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(9); }
        else { echo 'Número inválido'; }

        // Marcador de tempo 2
        $t2 = microtime(true);

        // Tempo final
        $t3 = $t2 - $t1;

        return $t3;
    }

    public function fc_switch($v) {

        // Marcador de tempo 1
        $t1 = microtime(true);

        // Script
        switch ($v) {

            case '1':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(1);
            break;

            case '2':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(2);
            break;

            case '3':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(3);
            break;

            case '4':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(4);
            break;

            case '5':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(5);
            break;

            case '6':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(6);
            break;

            case '7':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(7);
            break;

            case '8':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(8);
            break;

            case '9':
            echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(9);
            break;

            default:
            echo 'Número inválido';
            break;
        }

        // Marcador de tempo 2
        $t2 = microtime(true);

        // Tempo final
        $t3 = $t2 - $t1;

        return $t3;
    }

    public function calcula($v) {

        $vf = pow($v,5);

        sleep(1);

        return $vf;
    }

    public function resultado($t_if, $t_switch) {

        echo '
';
        echo '
 Tempo IF: ' . $t_if;
        echo '
 Tempo SWITCH: ' . $t_switch;

        if ($t_if < $t_switch) $r = 'IF';
        elseif ($t_if == $t_switch) $r = 'Empate';
        elseif ($t_if > $t_switch) $r = 'SWITCH';
        else $r = 'Erro';

        echo '
 Menor tempo: ' . $r;
    }

}

?>

Executor: mitrotime.php
<?php

include_once 'ifXswitch.php';

$exemplo = new Teste();
$t_if = $exemplo -> fc_if(9);
$t_switch = $exemplo -> fc_switch(9);
$exemplo -> resultado($t_if, $t_switch);

?>

Na execução do teste, varia muito, hora ganha o IF hora o SWITCH, e até incrivelmente deu empate uma vez.
Gostaria de saber, entre eles, se algum tem vantagem sobre o outro em algum aspecto (por ex., com números o SWITCH seria melhor !?), ou se trata de necessidade e organização ?
Comment: Possível duplicata de [Qual a diferença entre Switch, Case e If, Else?](https://pt.stackoverflow.com/questions/58192/qual-a-diferen%c3%a7a-entre-switch-case-e-if-else)
Comment: Sempre que precisar comparar performance em PHP, leia [esta resposta](https://pt.stackoverflow.com/a/215063/5878) e as demais.
Comment: Esse exemplo provavelmente não é o melhor pois todo conjunto de ifs poderia ser reduzido a `echo '' . $v . ' elevado a 9 = ' . $this -> calcula($v);`
Comment: @Articuno Atualizada... confere aí por favor...
Comment: É que fiz pensando em manter a "estrutura" igual entre eles, para terem as mesmas quantidades de condições... usei números, mas também poderia ser string... e ainda mesmo assim precisei colocar o `sleep(1)` porque estava dando 0.
Comment: "Em PHP a solução é muito simples se precisa de performance da linguagem. Troque de linguagem. " o Maniero já vem com os 2 pés... rs
Comment: Mesmo o próprio echo seria mais fácil com interpolação: `echo "$x elevado a 9 = {$this->calcula($v)}";`
Comment: Eu estava tentando gerar tempo, porque estava dando `0` :'[
Answer: Se fizer uma execução de mais de um bilhão de loops, talvez você sinta alguma diferença perceptível ao usuário, mas no geral não fazem diferença que tenha significado, 15 condições por exemplo nem notaria nada.
Tenha em mente que cada versão do PHP ter uma performance diferente, a versão 7 inclusive é bem mais eficiente que a 5, também existe a possibilidade de usar "cache" (não tem nada haver com cache do navegador), é semelhante ao JIT (talvez possa ser chamado assim), leia mais em:

https://pt.stackoverflow.com/a/166747/3635

Pra resumir, não existe diferença significativa entre switch e if, o que eles diferem é em suas necessidades, por exemplo da forma que usou o if e switch você escreveu o código já de maneira ineficiente em ambos casos, ou seja boa parte das perdas de performance é a maneira que usamos e não entre os tipos.
Os problemas reais de performance estão na maneira que escrevemos e não em duas funcionalidades da linguagem, claro que tem exceções, mas quase todas são somente em micro-otimização, o que é algo que as pessoas deveriam parar de se preocupar e se preocuparem mais com os erros graves que os programadores cometem que realmente vão afetar a velocidade
Pode vir alguém aqui e falar que switch é melhor, mas isso em PHP não é necessariamente uma realidade, já que a maneira que se escrever os seus IFs pode resultar em algo mais performático (micro-otimização, o que geralmente costuma ser insignificante), e como eu disse existem variações de comportamento entre as versões do PHP, mas não adianta ir muito a fundo.
O que você precisa entender é que IF tem hora, lugar e maneira melhor de trabalhar e o mesmo vale para SWITCH, tem hora, lugar e maneira melhor de trabalhar.
O que vai tornar mais lento ambos é a maneira que você escreve eles, se souber lidar bem com as condições é capaz de que ambos tenham o mesmo resultado (como eu disse use conforme a necessidade).
Outros fatores que podem consumir mais o script, tipo execuções de funções repetidas em cada checagem, que é um erro bastante comum entre programadores, por exemplo:
function foo()
{
     return file_get_contents('./version');
}

if (foo() == 1) {
    echo 'Versão 1 do App, atualize para a versão 2 ou 3, este esta obsoleto';
} elseif (foo() == 2) {
    echo 'Versão 2 do App';
} elseif (foo() == 3) {
    echo 'Versão 3 do App';
}

Veja que no código acima foi executado 3 vezes no minimo (dependendo do conteúdo do arquivo ./version), agora se fizer assim:
$versao = foo();

if ($versao == 1) {
    echo 'Versão 1 do App, atualize para a versão 2 ou 3, este esta obsoleto';
} elseif ($versao == 2) {
    echo 'Versão 2 do App';
} elseif ($versao == 3) {
    echo 'Versão 3 do App';
}

Irá com certeza executar somente uma vez o foo(), e como a resposta já esta salva no $versao, isso com certeza irá tornar o script mais performático.

Agora uma sugestão sobre o seu código, o problema que vejo em seus códigos é a repetição desnecessária, por exemplo isto:
if ($v == 1) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(1); }
elseif ($v == 2) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(2); }
elseif ($v == 3) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(3); }
elseif ($v == 4) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(4); }
elseif ($v == 5) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(5); }
elseif ($v == 6) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(6); }
elseif ($v == 7) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(7); }
elseif ($v == 8) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(8); }
elseif ($v == 9) { echo '
' . $v . ' elevado a 9 = ' . $this -> calcula(9); }
else { echo 'Número inválido'; }

Poderia ser simplesmente isso:
if ($v >= 1 && $v <= 9) {
    echo '
' . $v . ' elevado a 9 = ' . $this -> calcula($v);
} else {
    echo 'Número inválido';
}

Pronto, você terá reduzido o seu código a duas linhas, o que com certeza irá melhorar um pouco a performance do analisador (que faz parte do interpretador de scritps), que foi o que citei no começo da resposta, o problema esta mais em como escrevemos as IFs do que em outros fatores.
Comment: Da mesma forma que você não entendeu a pergunta amigo. Eu fiz uma SIMULAÇÃO para ser IGUAL entre os 2. Parece que eu nem ser fazer um IF da forma que você respondeu. Da mesma forma que deu o -1 para mim por não entender a pergunta, dei o -1 por achar a resposta incorreta. Estamos com entendimentos divergentes nessa questão ! Está tranquilo ! ;]
Comment: @RBZ a resposta não fugiu do contexto, é que voce não entendeu, a respsota indica exatamente que você  esta a se preocupar com coisas e se esquece de entender o essencial da linguagem e que com experiencia de mais de 14 anos com PHP lhe digo, os problemas reais de performance estão na maneira que escrevemos e não em duas features da linguagem, claro que tem exceções, mas quase todas são somente em micro-otimização, o que é algo que as pessoas deveriam parar de se preocupar e se preocuparem mais com os erros graves que os programadores cometem que realmente vão afetar a velocidade.
Comment: A crítica pode ser mais efetiva que o elogio se soubermos recebê-la ! Sempre ouço e processo ! rs Foi um tópico ímpar que a "linguagem de comunicação" atrapalhou a "linguagem de programação" rs !! Obg ! Abs !
Comment: O intuito era só simular as 2 com a mesma quantidade de condições... assim elas iriam percorrer as 9 condições. Quis deixar o mais próximo um do outro !
Comment: Eu entendi, mas era outra ideia a pergunta... acho que já fugiu total do contexto... rs
Comment: Eu entendi tudo o que disse... Por exemplo "repetição desenecessária" que você postou... eu só fiz isso para equiparar exatamente o IF com SWITCH, encher processo para dar tempo.... A pergunta não foi nesse contexto... mas tranquilo... não dá para excluir agora...
Comment: Perai, acho que eu me expressei errado. A sua resposta concordo com isso: "Pra resumir, não existe diferença significativa entre switch e if, o que eles diferem é em suas necessidades", só aqui sim, entendi o que quis dizer. Mas o intuito da simulação foi somente SIMULAR, então eu precisava deixar ao máximo um igual ao outro e "gerar processamento". Eu fiquei "triste", pois você tratou a pergunta como se fosse cheia de erros ! E pelo contrário, eu sempre procuro total eficiência no código... A sua resposta ficou 90% tratando de "erros" que foram propositais entendeu ?
Comment: Quando ao downvoter, foi por esse motivo. Concorda comigo que sua resposta fugiu do contexto da pergunta ? Se você simplesmente tivesse colocado esse pedacinho que citei, já era praticamente 90% da questão. Vou tirar o downvoter porque tem parte correta e parte incorreta, entende !?
Comment: Pode ter total certeza, que eu sei o pessoal que manja demais aqui no SOpt, e claro, eu sempre vou olhar com atenção tudo que falam... sou um mero iniciante, e quanto mais aprendo, menos sei ! rs
Comment: Jamais uso o downvoter atoa, mas como foi que eu fiz a escolha foi sobre isso: a resposta sua focou em 90% em erro de utilização, e os erros foram propositais para a simulação. Entendeu ?
Comment: Pronto ! Perfeito ! Está aí sua resposta: "os problemas reais de performance estão na maneira que escrevemos e não em duas features da linguagem, claro que tem exceções, mas quase todas são somente em micro-otimização, o que é algo que as pessoas deveriam parar de se preocupar e se preocuparem mais com os erros graves que os programadores cometem que realmente vão afetar a velocidade" Incrementando: o IF e o SWITCH são praticamente iguais. ! o foco foi que entrou muito no contexto da estrutura (que foi proposital)... mas está tranquilo ! Agradeço a ajuda com toda sinceridade !
Comment: @RBZ na verdade foi isso que eu disse desde o começo da pergunta, só que com outras palavras, para ser sincero e me perdoe, mas muitas pessoas noto que são assim como você, não é uma critica do mal, mas sim construtiva, geralmente falta um pouco de pratica de leitura para absorver o enunciado da postagem, claro que eu também posso tentar melhorar o texto e torna-lo mais agradável, mas não é fácil de escrever e tornar o texto intuitivo de primeira. De qualquer forma vou editar e postar isso dentro do corpo/conteudo da resposta. Boa sorte e sucesso!

IF x SWITCH - Simulando


How to get apache to send a 404 based on no matching VirtualHost section (based on ServerName) being found?

Question: I am rebuilding an old server.  Only one of the five old sites need to go live and all five of the old sites point to the same IP address.
Unfortunately any time a request is made for one of the old sites via their own unique domain names they are passed the pages from the one site that I'm trying to make live.  I would just like the old sites to display a 404 instead of the one site that I'm actually trying to make live.
As an example:

Site 1 (192.168.0.1) [www.first.com]
Site 2 (192.168.0.1) [www.second.com]
Site 3 (192.168.0.1) [www.third.com]

I want to move site 1 live again.  So I turned on apache on the machine with the IP address of 192.168.0.1, with all of site 1's files in the /var/www directory.  When I browse to 192.168.0.1 or www.first.com I correctly see site 1. When I browse to www.second.com and www.third.com I also receive site 1 which is the problem.
Is there a way I can 404 any request which comes in without www.first.com?
Here is my sites-available:
NameVirtualHost *:80

LogFormat "%h %l %u %t \"%r\" %>s %b" common

<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

<Directory />
  Order Deny,Allow
  Deny from all
  Options None
  AllowOverride None
  Options None
</Directory>

<Directory /var/www>
  Order Allow,Deny
  Allow from all
</Directory>

<VirtualHost *:80>
        ServerName first.com
        ServerAlias www.first.com
        DocumentRoot /var/www
        ErrorLog /var/log/first.com.err
        CustomLog /var/log/first.com.log common
</VirtualHost>

<VirtualHost _default_:*>
        ServerName unknown
        DocumentRoot /var/www_404
</VirtualHost>

Answer: A request with no matching ServerName or ServerAlias will be served by the first block to load; just move your 404'ing VirtualHost to the top (its bindings should match what it's playing default for, so set it to *:80 - the wildcarded vhost won't get any requests without that.)
Answer: For the default VirtualHost, try the following (at the top, not the bottom as you have it):
<VirtualHost _default_:*>
    DocumentRoot /var/www_404
</VirtualHost>

Otherwise, it's going to try to search for a server named "Unknown" if you have it at the bottom ;-)
Alternatively, you can just specify the DocumentRoot outside of your VirtualHost directives to define a default location, as specified in the Apache documentation here
EDIT: Minor correction about the placement
Comment: The tricky part with the first option is that the `_default_:*` port specification will be completely ignored by Apache except for ports other than 80, since there are vhosts set up on that port.  From that doc page, this port specification only catches "an address/port combination that is not used for any other virtual host."
Comment: From the [VirtualHost documentation](http://httpd.apache.org/docs/2.2/vhosts/examples.html#default): "A default vhost never serves a request that was sent to an address/port that is used for name-based vhosts. If the request contained an unknown or no Host: header it is always served from the primary name-based vhost (the vhost for that address/port appearing first in the configuration file)."  Server name of "Unknown" is OK, as long as it's the first name-based vhost to load it'll get unmatched requests.
Comment: True. And the alternative I noted at the bottom will also work. I've revised the answer to clarify it.


Find the Laurent Series for $|z|>3$

Question: Hi this is my question,
$$f(z)=\frac{2}{(z-2)(3-z)}$$
Find the Laurent Series for $|z|>3$ of $f(z)$
I have split it into partial fractions and have ended up with
$$
2\sum_{n=0}^\infty z^n\left(\frac{1}{3^{n+1}}-\frac{1}{2^n}\right)
$$
But I think I may have gone wrong somewhere.
Any help appreciated! Thanks
Comment: I think you should be summing over $n$, not $i$.
Comment: Sorry that was an accident
Answer: By partial fractions, we get
$$\frac{2}{(z-2)(3-z)}=\frac{2}{z-2}+\frac{2}{3-z}=\frac{2/z}{1-\frac{2}{z}}+\frac{-2/z}{1-\frac{3}{z}}=\sum\limits_{n=0}^\infty \frac{2}{z}(\frac{2^n}{z^n}-\frac{3^n}{z^n})$$
$$\sum\limits_{n=0}^\infty \frac{2}{z}(\frac{2^n}{z^n}-\frac{3^n}{z^n})
=2\sum\limits_{n=0}^\infty \frac{1}{z^{n+1}}(2^n-3^n)$$
Note that it is possible to use the expansion $\frac{1}{1-z}=\sum\limits_{n=0}^\infty z^n$ when $|z|<1$.

Find the Laurent Series for $|z|>3$


Setting noindex some pages on NGINX

Question: I want to set noindex some URLs. If any URL contains ?lang= | (start with) /plugin | (start with) /account it should be noindex by adding HTTP header in NGINX configuration.
I tried below code before,
location ~ .*/(?:?lang|plugin|account)/.* {
    add_header X-Robots-Tag "noindex, follow" always;
}

Other NGINX location directives that I use for my website:
(These default directive for my script are working well.)
#Disable access to sensitive files
location ~* /(app|content|lib)/.*\.(po|php|lock|sql)$ {
    deny all;
}
#CORS headers
location ~* /.*\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js) {
    add_header Access-Control-Allow-Origin "*";
}
#Upload path for image content only and set 404 replacement
location ^~ /images/ {
    location ~* (jpe?g|png|gif) {
        log_not_found off;
        error_page 404 /content/images/system/default/404.gif;
    }
    return 403;
}
#Pretty URLs
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$query_string;
}

Although no error messages when I reload the Nginx, the noindex directive doesn't appear.
Answer: location directives only match normalised URIs, which don't include query arguments. This is the reason why you cannot match ?lang.
To match that one, you can use a query argument variable to make the match.
if ($arg_lang) {
    add_header X-Robots-Tag "noindex, follow" always;
}

This snippet should be included in the location / block.
For matching the other cases, I would do the following:
location /plugin {
    add_header X-Robots-Tag "noindex, follow" always;
    try_files $uri $uri/ /index.php?$query_string;
}

location /account {
    add_header X-Robots-Tag "noindex, follow" always;
    try_files $uri $uri/ /index.php?$query_string;
}

It is important to include the try_files statements in these, since only one location block is selected to be used.
Comment: Setting noindex for `?lang` query argument (inside `location /`) is causing 404 error. for these pages which include `?lang` query. But it doesn't matter for my website. I don't use these pages. Thank you! I really appreaciate it!

Setting noindex some pages on NGINX


export mailbox data from a mailbox to a .pst file (Exchange 2007)

Question: I want to delete some old exchange accounts. Therefore I want to backup the mails in these accounts before deleting them. I found the article How to export mailbox data from Microsoft. I want to export to a pst-file. I found out that I have to install Exchange 2007 management tools because the server is 64-bit. Now I downloaded Exchange 2007 and wanted to install the managment tool component. The problem is that my operating system (Windows 7) is not supported.
What options do I have to export the mailbox to a pst-file? Do I need a computer with Windows XP?
EDIT
I start the setup.exe and the only option I have is to use Step 5: Install Microsoft Exchange Server 2007 SP2. Than I make the custom installation and only select Management Tools. Than I get the following error:

It says that I use Windows 7 Professional and the Exchange Server 2007 does not support it. If I click on recommended action I will be redirected to this link. On this page it again is statetd that Windows 7 and Windows Server 2008 R2 is not supported. I should use a compatible computer ...
Comment: Are you running Windows 7 64-bit?
Comment: @JeremyLyons: Windows 7 32-bit.
Comment: Did you ensure you downloaded the 32-bit version of the tools? It lists Windows 7 as a supported OS, which leads me to believe you're trying to install the 64-bit tools on 32-bit Windows 7. http://www.microsoft.com/en-us/download/details.aspx?id=11876
Comment: @JeremyLyons: The file I downloaded is called `E2K7SP2DE32.exe`. There is no option for 32 bit, but the heading and the filename says it is 32 bit. I will describe my steps in detail im my question.
Comment: Others around the web say that you can put the setup.exe file into Windows Vista compatibility mode and right-click run as administrator.
Answer: Ah ha! Forget all of the above. You need the Exchange 2007 SP3 media, which explicitly states that it adds support for Windows 7 and 2008 R2.
http://www.microsoft.com/de-de/download/details.aspx?id=24111
This is why the link I originally posted stated support for Windows 7, which I found confusing after reading the info you provided.
Comment: I had to do a few things: http://thelowedown.wordpress.com/2010/02/12/exchange-2007-exporting-mailboxes-using-windows-7/ and http://technet.microsoft.com/en-us/library/dd285510%28v=exchg.80%29.aspx. The command was `Export-Mailbox -Identity  -PSTFolderPath \.pst
-ExcludeFolders "\Junk E-Mail","\Contacts"`.


IPv6 Socket on Android

Question: I am trying to create an IPv6 TCP connection between two Android devices. However creating the socket always fails.
If I instantiate it like this:
Inet6Address dest = (Inet6Address) InetAddress.getByName(addressString);
Socket socket = new Socket(dest, portNumber);

I get the following exception:
java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EINVAL (Invalid argument)

If I instead instantiate my IPv6Address object like this:
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface wifiInterface = null;
while (networkInterfaces.hasMoreElements()) {
  NetworkInterface networkInterface = networkInterfaces.nextElement();
  if (networkInterface.getDisplayName().equals("wlan0") || networkInterface.getDisplayName().equals("eth0")) {
    wifiInterface = networkInterface;
    break;
  }
}
Inet6Address dest = Inet6Address.getByAddress(null, addressBytes, wifiInterface );
Socket socket = new Socket(dest, portNumber);

I get this error when calling the Socket constructor:
java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EADDRNOTAVAIL (Cannot assign requested address)

This happens both on a Galaxy Nexus with Jelly Bean and a Nexus One with Gingerbread.
Am I doing something wrong? What is the correct way to create a socket like that?
Also: This post suggests using the constructor
Inet6Address getByAddress (String host, byte[] addr, int scope_id)

What would I have to use as scope_id in this case?
Comment: show us dest and portNumber variables values.
Comment: The value of addressString in the first variant would for example be "fe80::9221:55ff:fee3:3303".
The corresponding addressBytes array is [-2, -128, 0, 0, 0, 0, 0, 0, -110, 33, 85, -1, -2, -29, 51, 3].
For the port I am using 3109. This is supposed to be a random port that is not being used for anything else.
Comment: By chance is the router you are connected to support IPv6?
Comment: I can ping all my devices on their IPv6 address. On the Galaxy Nexus the NetworkInterface object even contains the device's IPv6 address and on the Nexus One I can at least read it from /proc/net/if_inet6. So I am pretty sure the router supports it :)
Answer: Since your IP Address is link local, perhaps it MUST be created with a scope ID or Interface so that the OS knows what interface to bind it to.  As for specifying the scope_id, the Android docs seem somewhat lacking.  The Oracle docs here indicate that the scope ID is system specific and cannot be determined programmatically.
So, I would try using the alternate factory method where you explicitly specify the NetworkInterface you wish to use.  See here for details.  There are methods in the NetworkInterface class to discover what interfaces exist on the system.
Comment: Thanks! But isn't that the factory method I used in the second variant, which throws an only slightly different exception?
Comment: You're right!  Sorry about that!  How did you find the NetworkInterface object that you used in that attempt?
Comment: I iterate through all the available interfaces and select the one I need by name and I verified that I am indeed getting back the correct interface.
I added the code in the original post for clarity.

IPv6 Socket on Android


Como calcular o valor total em um table criado dinamicamente?

Question: Tenho o seguinte código que cria uma tabela no jquery. O problema é que eu queria criar um subtotal que somasse todos os valores da coluna total. Mas não estou conseguindo pois a tabela é criada dinamicamente. Alguma sugestão?
Segue o código:
function retorna_pedidos(valor)
{
 let mensagem_pedidos = "Nenhum pedido encontrado";
 let container_mostra_pedidos = $('.mostra_pedidos');
 let quantidade = $('#qtd').val();
 let quantidade_pedidos = "";
 let valorTotal = "";
 let itemHTMLp = "";

 if (valor == null)
 {
   valor = 1;
  }

 $.ajax({
  url: url_base + "pedidos?qtd=" + quantidade + "&page=" + valor,
  type: 'GET',
  dataType: 'json',
  success: function (data)
  {
  var retorno = data.pedidos.data;
  if (retorno == 0)
  {
    $('.classe-pedidos').css('display','none');
    $('.pedido-error-registro').css('display','block');
    $('.pedido-error-registro .mensagem-erro').html(mensagem_pedidos);
  }
  else
  {

    $.each(data, function(key,item) {

      let registros  = item.data.length;
      let current_page = item.current_page;
      let last_page = item.last_page;
      let next_page_url = item.next_page_url;
      let prev_page_url = item.prev_page_url;
      let pedidos = item.data;

      sessionStorage.setItem('pagina',current_page);
      sessionStorage.setItem('last_page',last_page);

      if (next_page_url == null)
      {
        if (current_page == 1)
        {
          $('.action-bar-pedido').html("<< Página Anterior");
        }
        else
        {
          $('.action-bar-pedido').html("<< Página Anterior");
        }
      }
      else if (prev_page_url == null)
      {
        $('.action-bar-pedido').html("Próxima Página >>");
      }
      else if (prev_page_url != null || next_page_url != null)
      {
        $('.action-bar-pedido').html("Próxima Página >><< Página Anterior");
      }

      for (var i in pedidos) {
        id_pedido = pedidos[i].pedidos_id;
        nome_cliente = pedidos[i].nome_cliente;
        nome_produto = pedidos[i].nome_produto;
        data_atual = pedidos[i].data;
        data_pedido = data_atual.split("-").reverse().join("/");
        frete_atual = pedidos[i].frete;
        preco_produto = pedidos[i].preco_produto;
        quantidade_pedidos = pedidos.length;
      //  console.log(pedidos);

        valorTotal =  parseFloat(quantidade_pedidos) * parseFloat(preco_produto) + frete_atual;

        itemHTMLp += "
";
        itemHTMLp += "<input type='checkbox' value='" +  id_pedido + "' name='verifica_check_box[]' id='verifica_check_box' class='flat'/>	";
        itemHTMLp += "" + nome_cliente + "	";
        itemHTMLp += "" + nome_produto + "	";
        itemHTMLp += "" + data_pedido + "	";
        itemHTMLp += "" + frete_atual + "	";
        itemHTMLp += "" + preco_produto + "	";
        itemHTMLp += "" + valorTotal + "	";
        itemHTMLp += "
";
      }
    });
    container_mostra_pedidos.html(itemHTMLp);
  }

},
error: function (data)
{
  console.log(data);
}
});

Comment: Sua dúvida está em como gerar o total ou no momento em qual deve fazer isso?
Se você fizer uma função que calcule o total e chamar ela depois de jogar a tabela no DOM efetivamente, você terá o que deseja. Seria esse seu problema ou seria na função de soma mesmo?
Comment: na verdade seria somar os valores do td valor-total. Que nem produto 1 = 25, produto 2 = 50, total = 75
Comment: @DiegoSantos. Seria somente somar os valores da coluna valor-total, pois ele já faz a soma do produto na variavel valorTotal
Comment: Brother, seu código tem algum erro de chave. Pode postar ele novamente corrigido? Aí eu te ajudo blz...
Comment: Eu tentei rodar ele mas ele já deu problema na interpretação...
Comment: Ok @DiegoSantos. Já arrumei
Answer: Não está igual ao seu, pois como não tenho seus dados não tenho como simular. Mas segue...

$(function(){
var total = 0;
$('.valor-total').each(function () {
    total += parseInt($(this).text());
});

console.log(total);
});

    1
    15
    abc
    22
    def

Comment: Deu certo. Só que tem um problema na paginação. Ele pega os totais de cada página. Daí como que eu posso somar todos eles?
Comment: hummm ai complica um pouco mais. Mas tem certeza que precisa fazer isso? Se o usuário fizer as contas do seu total ele irá achar que tem erro na página pq não bate com as informações exibidas, não? Mas se caso for necessário mesmo, seria mais interessante você voltar essa informação do servidor ou ter acesso ao total já calculado. Pq vc provavelmente pagina sua consulta, correto?
Comment: Mas pior que não tem como fazer assim...kkkkk. Será que não dava para calcular este total antes de ou seja retornar o valor de cada produto do loop e já calculá-lo?
Comment: Aí tem muitas variáveis a considerar... Por exemplo, como que é o retorno que obtém do servidor. Que informações vem nela, entende? Se você retornar todos os resultados possíveis e imagináveis neste retorno é possível somar, porém, não indico de forma alguma, por conta de performance e pq vc não conhece a máquina cliente que está acessando entende? A forma mais simples de resolver é com outra requisição ou se for retorno em json por exemplo, cria um atributo nele já com o valor somado e só pega ele no json. Que tal desta forma?
Comment: Você não quer que o valores venham de todas as páginas da paginação certo ?
Answer: Você pode calcular todos os valores das td percorrendo cada uma com .each() e somando os valores. Chamando a função abaixo você consegue o resultado total:

function total(){
   tt_final = 0;
   subs = $('.valor-total');

   subs.each(function(){
      tt_final += parseFloat($(this).text());
   });

   alert(tt_final);
}

         10

         4

         50

<input type="button" value="Calcular" onclick="total()" />

Observações:

1. Otimize seu código concatenando o código da tabela desta forma:
itemHTMLp += "
"
+"<input type='checkbox' value='1' name='verifica_check_box[]' id='verifica_check_box' class='flat'/>	"
+"fulano	"
+"produto	"
+"14/11/2017	"
+"0	"
+"5	"
+"31	"
+"
";

2. Faltou abrir e fechar a tabela com
 e
:
Pode fazer assim: container_mostra_pedidos.html('
'+itemHTMLp+'
');
Comment: obrigado, mas o container_mostra_pedidos já é uma variável com table.


how to check if pthread_mutex is based on robust futex

Question: I am trying to use robust futex based pthread mutex in Linux because I need to be both fast and robust (recover the "dead" lock). How can I check if the pthread mutex library on any Linux system is based off robust futex?
Thanks!
Comment: If you have deadlock, replacing it with livelock will make things worse.
Comment: no,  by "dead" lock, I meant that the process that holding the mutex crashed.
Answer: If you have the futex(2) system call and if it is used (just strace(1) a 10 line application that uses mutexes) then you have the robust feature as the futex(2) system call only entered the kernel after robustness has been built into it. This does not mean that you are using robust futexes, just that you have the feature in the kernel.
Next you want to know that your libc supports it. Any version above 2.9 supports it. Just check your version.
If you are writing a multi-threaded application then you don't really need the robustness of the futexes since you control the threads and can make sure that threads release the mutexes they use before they die or register a cleanup function to do the lock releasing (there is a pthread api for that). If you are still worried see my notes below about using robust mutexes anyway.
I just want to make it plain & clear that you are going to pay in performance if you want to use robust futexes in a multi-threaded application. The main use of robust futexes is to use them as synchronization primitives in multi-process applications where the chance of one component dying without killing the rest of the components is high compared to the same chance in a multi-threaded application where the abnormal death of a thread means the death of the entire application.
To use robust futexes in either a multi-threaded or a multi-process application you need to mark the futexes as robust by using the undocumented function pthread_mutexattr_setrobust(3). I've submitted a bug report to the manual pages maintainers to add documentation about that function. You need to pass PTHREAD_MUTEX_ROBUST to that function as opposed to PTHREAD_MUTEX_STALLED which is the default.
In a multi-threaded application marking the mutex as robust is all you have to do.
To use robust futexes in a multi-process application you need to also mark the futex as being shared across processes by calling the (fortunately documented) function pthread_mutexattr_setpshared(3) and pass PTHREAD_PROCESS_SHARED to it. This is opposed to the default PTHREAD_PROCESS_PRIVATE.
Actually in strace(1) you will not see acquisition and release of the locks but you will see calls to set_robust_list(2) if your futex is robust.
I hope this helps.
Comment: It seems that in new versions of man-pages the pthread_mutexattr_getrobust function is now properly documented.


Conferir campo no banco

Question: Estou fazendo uma pesquisa no banco pra ver se o valor enviado já existe nele.
Esta é a função que estou utilizando:
 function buscaSubdominio($conexao, $nome_subdominio){

     $query = "select * from subdominio where nome_subdominio = ('{$nome_subdominio}')";
     return mysqli_query($conexao, $query);
   }

Então estou fazendo essa condição em outra página:
 $confere = buscaSubdominio($conexao, $nome_subdominio);

 if($confere == null){
   echo "registro inexistente";
 }
 else{
   echo "registro existente";
 }

Ele me devolve esse erro, podem me ajudar?
 Notice: Undefined property: mysqli_result::$nome_subdominio in C:\xampp   \htdocs\daLuz\subdominio.php on line 8

Comment: Ok, e qual é exatamente o problema ? Explique melhor a situação por favor. Não consegue fazer uma consulta pois o "usuário" está "deslogado" ?
Comment: Coloquei usuário deslogado por que ia perguntar de outra forma, mas esqueci de mudar. vou mudar o título. Este é o erro que vem, mas vou editar: Notice: Undefined property: mysqli_result::$nome_subdominio in C:\xampp\htdocs\daLuz\subdominio.php on line 8
Answer: Talvez seja porque a  variável $nome_subdominio não foi definida antes de ser usada na função.
Comment: ele está vindo via post
Comment: Então seria $_POST['nome_subdominio'] resultando em $confere = buscaSubdominio($conexao, $_POST['nome_subdominio');
Comment: sim @Sumback,  mas é assim eu só coloquei o if aí, mas antes eu pego ele no post e salvo na variavel $nome_subdominio
Comment: Ah sim, entendi. Tente dar um print_r na variável para ver se ela está entrando na função com algum valor e não vazia.
Comment: ele me devolve isso: mysqli_result Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 0 [type] => 0 ), sabe o que posso fazer? eu programo a pouco tempo
Comment: Ele não esta retornando nenhuma linha ([num_rows] => 0). Tente fazer esse select direto no banco, caso funcione mas retorne linhas vazias, então pode ser que as tabelas estejam vazias.
Answer: function buscaSubdominio($conexao, $nome_subdominio){

     $query = "select * from subdominio where nome_subdominio = ('{$nome_subdominio}')";
     $stmt = mysqli_query($conexao, $query);
     $row_cnt = mysqli_num_rows($stmt);

     return $row_cnt;
   }

Conferir campo no banco


Pydev pep8 checking with custom pep8.py (with name checking support), seems to break

Question: I want to use this PEP8 module that has name checking support...
https://github.com/posborne/pep8
However when I select this, nothing happens, NO pep8 checking happens.
Can I do anything?
Pydev version 2.4
Answer: I spent some time trying to debug this. I don't know much about PyDev nor Java, but it would seem that:

PyDev is trying to parse pep8.py using it's own Jython implementation instead of local Python's one (probably they want to make it faster this way). Jython (at least the one I have) cannot parse the "yield" keyword, that's why newer versions of pep8.py don't work.
The older versions don't work either, because PyDev requires some custom-tailored signatures of pep8.py's methods which were not marged into the main stream.

I ended up making this simple Eclipse plugin. I was able to connect latest version of pep8.py with my editors. Hope it helps someone ;)
Answer: You mean that you've enabled pep8 checking and you're setting that file in window > preferences > code analysis > pep8.py > location of pep8.py?
If that is the case, it could be because of some bugfixes which were done in the internal version of PyDev (to work under the PyDev internal Jython 2.1 version)... those were already contributed back to pep8.py, but maybe were not integrated in that branch? (i.e.: pull request: https://github.com/jcrocholl/pep8/pull/49)
If that custom module did something else that doesn't work on Jython 2.1, that'd explain it too.
If that's the case, the proper solution would be fixing that pep8 module to work under Jython 2.1...
Now, if it's something else entirely... Do you have some error in your error log?
Comment: I have a similar issue. I tried many versions of pep8 (including the current git master), none worked. I got various errors in the error log (like "TypeError: __init__() too many arguments; expected 3 got 4" or "SyntaxError: ('invalid syntax', ('D:\\...\\pep8.py', 309, 19, 'yield 0, "E304 blank lines found after function decorator"\n '))"). I am still trying to debug this, but I'm running out of ideas how to grasp it.
Comment: Actually, I just saw that the current version of pep8 is no longer compatible with the internal Jython version that PyDev uses, so, you MUST use the pep8.py version that's shipped with PyDev (in the latest versions at least). It's located at: plugins\org.python.pydev\pysrc\third_party\pep8\pep8.py
Comment: BTW, I needed the latest version of pep8 too, so I made a simple plugin, see here: http://stackoverflow.com/questions/12578941/integrating-external-highlighter-tool-in-eclipse-editor (I also added the link to my response)
Comment: Nice way to integrate your external checker :)


Why are daemons called daemons?

Question: It has been itching me for a long time to know what the historical reason for calling daemon programs or threads "daemon"

Lat: daemon, latin version of the Greek "δαίμων" ("godlike power, fate, god")

god,
a subordinate deity, as the genius of a place or a person's attendant spirit

There are numerous questions clarifying what daemons are and how they behave, but none explaining the origins of the term "daemon" for programs that run in the background like sshd.
Why do we title programs that run in the background as daemons?
Comment: I was wondering, too.  And it's nice that we can get some levity thrown in with all these "why won't this work" questions.  :)
Comment: You can find some answers [here](http://english.stackexchange.com/questions/31430/what-is-the-origin-of-daemon-with-regards-to-computing).
Answer: See the wiki

According to Fernando J. Corbato who worked on Project MAC in 1963 his
  team is the first to use the term daemon. The use of the term daemon
  was inspired by Maxwell's daemon, in physics and thermodynamics as an
  imaginary agent which helped to sort molecules.
"We fancifully began to use the word daemon to describe background
  processes which worked tirelessly to perform system chores."
In the Unix System Administration Handbook, Evi Nemeth states the
  following about daemons:
"Many people equate the word "daemon" with the word "demon", implying
  some kind of satanic connection between UNIX and the underworld. This
  is an egregious misunderstanding. "Daemon" is actually a much older
  form of "demon"; daemons have no particular bias towards good or evil,
  but rather serve to help define a person's character or personality.
  The ancient Greeks' concept of a "personal daemon" was similar to the
  modern concept of a "guardian angel"—eudaemonia is the state of being
  helped or protected by a kindly spirit. As a rule, UNIX systems seem
  to be infested with both daemons and demons."
Answer: According to Wikipedia:
The term was coined by the programmers of MIT's Project MAC. They took the name from Maxwell's demon, an imaginary being from a thought experiment that constantly works in the background, sorting molecules.
Unix systems inherited this terminology. Maxwell's Demon is consistent with Greek mythology's interpretation of a daemon as a supernatural being working in the background, with no particular bias towards good or evil. However, BSD and some of its derivatives have adopted a Christian demon as their mascot rather than a Greek daemon.
More here.
And here.
And here.

Why are daemons called daemons?


Random Forest - Unbalanced Dataset for Training & Test

Question: I am doing a classification modelling(using R and random forests) for a website where only 2% of the visitors convert. Now given the behavior and attributes of a visitor I want to predict probability of conversion.
The data collection process was pretty complicated and finally I had 3 month data available for 3166 cases of conversions & 10,849 non conversions. Normally, I know that the training & test data should have the same proportion of classes.
However, I wanted to use most of the "converted" data to train the model. I randomly took out 100 cases of conversions & 4000 cases of non-conversions to give me 1:40 ratio. This would be my test data.
For training, I took the remaining data which was approximately 1:2 ratio.
After training using Random Forests, when testing, I am getting decent results in terms of sensitivity & specificity but  precision is low around 7-8%
What would be the possible repercussions of my approach? I wanted to get this sorted before I begin fine-tuning my model.
I did not do up-sampling/down-sampling or synthetic data generation because they would also ultimately try to balance my data when training the model but the test data would still reflect the true world scenario.
Any advice would be much appreciated.
EDIT 1:  After the response by Fernando & DarXider, I tried the following 2 things:
a.) Took 200 Positive Class with all of Negative class. Then trained the models separately until Positive class is exhausted. Each model then predicted on the test data, their votes were counted and final probabilities calculated.
b.) Similar to the above except here 200 cases of Negative class were sampled with all of Positive Class.
However, the problem remains when testing. In case of (a) most trees vote for negative class when testing and vice-versa in case of (b).
I will try other suggestions and maybe other techniques and see what happens. I have already started the process of getting more data.. "Fingers crossed"
Code snippet for (a) is below.In case I have made any errors please do tell.. I know its a little inefficient code but am still learning :)
    tr_conv = trdata[trdata$Converted==1,]      ## converted & non-converted
    tr_nc = trdata[trdata$Converted == 0,]

    numr = nrow(tr_conv)         ##calculatin the number of rows
    min_size = 200               ##sample size
    temp = data.frame()          ##empty data frame to store the results
    temp = NA

    while(numr>0){

    a = ifelse((numr - min_size) < min_size,numr,min_size)# sample size
    rm(.Random.seed, envir=globalenv()) ## reset the seed each time
    k = sample(x = 1:numr,size = a)
    tr_conv1 = tr_conv[k,]            ## this sample will be trained on
    tr_conv = tr_conv[-k,]
    numr = nrow(tr_conv)

    # combining with non-converted training data

    comb1 = rbind.data.frame(tr_conv1,tr_nc)
    r1 = randomForest(x = comb1[,1:24],y = comb1$Converted,ntree = 2000,
     mtry = 6,strata = comb1$Converted,norm.votes = FALSE)
    pd = predict(object = r1,norm.votes = F,newdata = tsdata[,1:24]
         ,type = "vote")      ## tsdata is the 4100 test cases
    vt1 = data.frame(pd)
    vt1 = data.frame(vt1[,-1])
    temp = cbind(temp,vt1)

    }
    temp1 = temp[,-1]
    temp1$Yes = rowSums(temp1)    ## total number of yes votes
    tvc = 2000*(ncol(temp1)-1)    ## calculate the total votes cast
    temp1$No = abs(temp1$Yes - tvc)  ## total number of no votes
    myvotes = temp1[,c(16,17)]
    myvotes$yes_prob = myvotes$Yes/tvc  ## yes probabilit calculate
    myvotes$no_prob = 1 - myvotes$yes_prob  ## no probability calculate
    threshold = 0.5
    myvotes$prediction = ifelse(myvotes$yes_prob > threshold,1,0)
    j = confusionMatrix(data =myvotes$prediction,
        reference = tsdata$Converted,positive = "1",
        dnn =c("pred","actual"))

Comment: This is confusing. Your original dataset is 10849:3166, or ~3.4:1, is that right?
Comment: @feranando.. yes that is correct but that is because of limitations in collecting the data. It is a huge process for the website as lots of visitors have to be filtered out and hit-level data from Big Query is then downloaded. That is why the original data set has that ratio but the actual conversions observed on the website is around 2%. Iam sorry for the confusion.
Comment: If the real target rate is 2%, but your data say it's ~29%, there's a problem. You could downsample, but you may miss some patterns. Are you sure this is not a data processing/architeture problem? Either get the whole data or change the concept/thing you're modelling. If you squeeze the model to acomodate this, it will overfit.
Comment: I will give a try to down sampling and darXider''s suggestions. However, in parallel I will also try to get the data once more.but to maintain the 2% in my training data while trying to get as many "conversion points will mean that the entire data I will be working with will blow up.
Comment: @ Fernando   From the ISLR book [video here]( https://www.youtube.com/watch?v=GavRXXEHGqU&list=PL5-da3qGB5IC4vaDba5ClatUmFppXLAhE) they mention that when using Logistic regression we can later adjust the estimated intercept. Is this useful in my case and how could it be brought over to Random forests or I should try logistic regression. Thnx for your help
Comment: How many features do you have? If your input space is complex (lots of features, interactions, etc), I don't think logist. regression would help. Let's wait for more answers.
Comment: @ Fernando, DarXider I just posted an edit based on your suggestions
Answer: If I understood correctly, the real-world scenario has a converted to non-converted ratio of 1:49, which is similar to that for your test data which is 1:40; so far, so good! However, the data you use for training your model has said ratio of about 1:2. Therein lies your problem, and it causes you to have lots of false positives and, thus, bad precision when you apply your trained model to the test data.
I suggest that you have a look at this paper, Adjusting the Outputs of a Classifier to New a Priori Probabilities: A Simple Procedure, published in Neural Computation 14, 21–41 (2001) by Saerens et al. which proposes a method to adjust the posterior probabilities $p(y|x)$ -- obtained by applying your trained model to the test data, where $x$ represents your data and $y = 0, 1$ is the class label -- in a scenario where the proportions of classes, $p(y = 0)$ and $p(y = 1)$, differ between the training and test sets.
You could also try building an ensemble of classifiers in the spirit of the BalanceCascade method (see Exploratory Undersampling for
Class-Imbalance Learning by Xu-Ying Liu, Jianxin Wu, and Zhi-Hua Zhou in IEEE TRANSACTIONS ON SYSTEMS, MAN, AND CYBERNETICS—PART B: CYBERNETICS, VOL. 39, NO. 2, APRIL 2009):

For the first classifier, randomly sample a subset of the minority class from the training set that gives you the said ratio of approximately 1:40 when used with the entire majority class
Train a classifier using this data (using, e.g., the argument class_weight = 'balanced' if you are using scikit-learn).
Setting aside the selected minority samples from the pool of training minority class, perform the next subsampling to arrive at the second dataset.
Used this set to train your second next classifier.
Repeat until you have exhausted the entirety of the minority class members.

Finally, you will have a set of classifiers, trained on non-overlapping subsets of the minority class. You can then combine their predictions (e.g., using majority vote or weighted average) to arrive at the final prediction.
Having said this, the cascade-and-ensemble approach might not be effective in your case since each classifier will be trained on approximately 200 data points, which is a small number, which could lead to low generalization score, but YMMV; it might be worth trying.
Comment: thank you...I will try this and post an update here soon
Comment: R `randomForest` package has a parameter called `strata` which handles that.
Comment: I used the strata parameter but how to adjust it to use 1:40 instead of the default ie. the ratio to the 1 to 0 in the training data.
Comment: Use the `sampsize` parameter, but I don't think you should pass 1:40, it should be `randomForest(..., strata=train$y, sampsize=c(3166, 3166), nodesize=5)`. Assuming y is a 0/1 factor variable.
Answer: Another option is to reuse the minority class: suppose your entire dataset has 10000 rows and you have 200 positive samples (exact 50:1 proportion).
What you can do (I'm not claiming this is a 'good' solution):

Create two datasets: P with all "1" examples and N with all "0" examples.
Shuffle the N dataset.
Fit 50 different models like this:

model_1 uses all of P and samples 1 to 200 of N.
model_2 uses all of P and samples 201 to 400 of N.
...
model_50 uses all of P and samples 9801 to 10000 of N.
When applying this model just take the average of these 50 models. This may or may not work, depending on your data. To validate you could set aside some of the data and apply the same idea.
Comment: this is good. Let me get back to you with the results.
Comment: This is the actually the EasyEnsemble method from the paper Exploratory Undersampling for Class-Imbalance Learning, which I have mentioned in my answer above and which contains the BalanceCascade method which I have referred to. It usually works well, depending on the dataset, of course. The problem which you might face while using this method is, however, the same problem you are currently facing, that is, the ratio of the P to N in the 50 training sets is 1:1, but each trained model will be independently applied to a test set which has a ratio of 1:40. again, YMMV.
Comment: BalanceCascade is a cool name! OP has 3166 P samples for each sub-model, so assuming there's a pattern, the P:N ratio on the test set doesn't matter, what matters is the hidden pattern on these samples (3166 may or may not be enough).
Comment: The OP is already using a training set with a 1:2 ratio of P to N classes (~ 3000 P's and ~ 6000 of N's); it's close enough to the 1:1 ratio used in EasyEnsemble (your answer) that if there were such a pattern in the data, the OP would see better scores when applying the ensemble model to the test data. Maybe ~ 3000 P examples is still not enough, but my guess is that the 1:40 ratio of P to N in the test set is what is really causing the pain. I'm waiting to see the reply by the OP though. This is an interesting problem (I am dealing with a similar one myself right now).


Java detect and replace linebreaks with \n

Question: I get this String from my database:
Test Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item Zusammenführen
fsd
fsa
df
asdf
as
dfs
fd
sad
f
sadf
sad

Now I need to encode all LineBreaks to \n so I can produce proper JSON objects out of the String because JSON doesn't support linebreaks. How can I detect and replace all LineBreaks in the existing String with \n?
I already tried .replace() and replaceAll(). But I need a way to detect the linebreaks First so I can replace them.
Some additional informations:
After trying out several replace-functions mentioned here the JSON still looks like this:
   { "id": 182,
     "status": "eing",
     "text": "KORE_AI_6",
     "beschreibung": "Eins
Zwei
Drei",
         "tags": "KORE"
       },

And it should look like
   { "id": 182,
     "status": "eing",
     "text": "KORE_AI_6",
     "beschreibung": "Eins\nZwei\nDrei",
     "tags": "KORE"
   },

Comment: If the line breaks you have are not `\n`, what are they?
Comment: If the lines aren't separated by `\n`, perhaps they are separated by Unicode line separators or paragraph separators.  Try `s.replaceAll("[\\p{Zl}\\p{Zp}]|\\r?\\n", "\n")`.
Comment: Unfortunately a search for \n dies Not get Any results. I Dont know, this is why i am asking.
Comment: can you also post the code that searches for `\n` ? Is the string in your question the actual string you get from the db or something you see with a viewer ?
Comment: I know tried your solution VGR, but sadly the JSON object still hast its linebreaks and not /n.
Answer: If the String you get from the database is called jsonString you can use this regex :
String result = jsonString.replaceAll("[\r\n]+", "\n");

This will match the most common line breaks \r\n \n \r. Mind you, this will also replace multiple empty lines with one empty line.
Comment: I tried your solution, but the JSON string still has linebreaks which cause errors in the JSON parser of the client.
Answer: I solved this problem for me. Unfortunately it seems like that .replace() like stated above in other comments and answers did the job, but the map.put() operations after reverted the changes again.
To solve it I used the StringEscapeUtils from org.apache.commons.lang3.StringEscapeUtils and used the escapeJson() method like this:
escapeUtils.escapeJson(map.get("BESCHREIBUNG").toString())


How do I use the Rules module to unpublish content when End Date is hit?

Question: I have a Content type called Event, has a Start Date and End Date.
How do I use the Rules module (version 8.3.0-alpha1) to:

Publish the Event on the Start Date and
Unpublish it on the End Date?

My priority is to Unpublish the content when the End Date is hit.
Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content based on a supplied End Date?
Comment: Which release of the [Rules](https://www.drupal.org/project/rules) module for D8 are you using? Anything that is not "**alfa**"? If it is **alfa**, then there is a simple answer to your "how do I use", i.e.: don't use Rules ... yet.
Comment: @Pierre.Vriens if rules isn't the way to go what would be a better way to unpublish a piece of content based on a supplied end date.
Comment: You didn't answer to my prior comment (= which version of rules are you using?). Though you added an interesting extra comment (which really belongs in your actual question where I tried to add it to, feel free to refine/correct that edit if needed). And to answer your last comment for "a better way": using rules with D7 (instead of D8) ... if you're willing to consider D7 ... sorry, but for D8 I don't know of a better way.
Comment: @Pierre.Vriens I am using 8.3.0-alpha1. My entire site is already built in Drupal 8 and we can't regress back to 7.
Comment: Interesting business opportunity then to get your question resolved ... using custom code I assume ... until the [Rules](https://www.drupal.org/project/rules) module is production ready?
Answer: I have this functionality on a D7 site I run, and we use the Scheduler module instead. Looks like there is an alpha release for D8 you could try: https://www.drupal.org/project/scheduler
Comment: We are gonna give the Scheduler a go and see if we can get it running in D8 thanks for the suggestion.
Answer: You may want to look at https://www.drupal.org/project/business_rules module which seems to be much further along than D8 version of Rules. It, unlike Rules, does have an Unpublish action. The rest, at least in D7, would be to use Views Rules to make a View of all items past their end date and then you could use this View in Rules to loop through all the items and unpublish. Sadly, Views Rules is another module which has not made the D8 cut; but perhaps Business Rules has some sort of Views integration.
Comment: This answer contains wrong information. Rules has always been able to set the published status - this appears as "node.status (Published)" in the data selector, just like the node title appears as "node.title (Title)". Additionally, the question is "How do I use the Rules module ..." - it is not asking for alternatives or speculative suggestions ("but perhaps" means you haven't even tried this yourself, so you don't even know if it will work).
Comment: @anonymous, did you see the post above? "Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content based on a supplied End Date?" But yes, i see that D8 Rules can set Publish as a "set data value". Cool. Not 100% sure how the loop would be done in Rules now that Views Rules has fallen by the wayside; but perhaps it is there. I have also, recently, discovered what seems like a bug in Business Rules where it unpublishes ALL entities rather than the one triggering the rule. Although this seems like a bug to me; it might actually work for your use case.


Setting Radio button using Ruby and Watir

Question: Right i am having issues with a section of code. I know how to set radio buttons i can do it on most websites. But when trying to set a value given by this code below i cannot make it work. I have tried "waiting until", "parent setting" using the label ect and searched through all sorts. Could any one point me in the right direction.

        <input class="styled" type="radio" value="1" name="clocksource"></input>

            Internal

        <input class="styled" type="radio" value="3" name="clocksource"></input>

            External AES50

        <input class="styled" type="radio" checked="checked" value="2"       name="clocksource"></input>

            External Snake

I get this error :
[remote server] file:///email@example.com/components/command_processor.js:8210:in `fxdriver.preconditions.visible': Element is not currently visible and so may not be interacted with

Thanks
Maximillion
Comment: It worked fine for me using your html snippet. Perhaps you need to provide more of the page, for example the related stylesheets.
Comment: Right ok, I can't do that at the moment, the strange thing is if i do a
'browser.radio(:name => 'clocksource', :value => '1').exist?'
on all three options they all say true, yet try and alter them and it says not visible.
Comment: Also when I do a .value it claims a value of one when the display clearly shows 3 is highlighted.
Comment: `.exist?` only checks that the element exists in the DOM. It does not check if the element is visible to the user, which is what your exception is complaining about. If you use `.visible?` instead, it will likely be `false`. When you did `.value` were you doing `browser.radio(:name => 'clocksource').value`? If so, then getting "1" is correct. Watir returns the first matching radio button, not the radio button that is checked.
Comment: Ah I see misunderstanding on my part there, you are right .visible shows up as false for all three. I was doing .value no question mark, don't know if that makes any difference. I have very little knowledge of web page code, why would something which is an active control not be visible? something to do with code construction?
Comment: For the `.value` part, the question mark is not actually part of the code; it was meant to be the punctuation of the sentence. An active control should be visible, which means there could be a bug (in one of the gems) or we are interpreting the information/code incorrectly. Did you try stepping through your script manually using `irb` to verify that the control is visible/usable when expected?
Comment: I tried stepping through with IRB and they always appear as not visible despite them being active controls. Even if i interact with the page and click the radio button then see if they are visible they are still false
Comment: Seems rather strange. I would suggest creating a page that reproduces the problem.
Comment: Ah i didn't create the page not really possible.
Comment: Is it a public page that we can access? Alternatively, try saving the entire page (you may also need the stylesheets and any javascript). Then see if you can reproduce the problem on there.
Comment: Try using .present? instead of .exists?. exists tells you if the element exists in the page BUT does not distinguish wether the element is clickable or if it hidden or controlled by some js event. .present? does a .exist? and then additionally checks if it is .enabled? and only returns true if both conditions are met. If it turns out the element is not visible, when it does become visible on the screen the dom may not be being updated to reflect this from the test suite, so although it looks to you like it is on the page, webdriver just throws a hissy fit.
Comment: Ok sound I will try this, we had a look at the code and they are definitely active from the load. It may be that I just have to leave it and move on. But we have other pages which operate the same and they are ok. I might have to learn some HTML and Java script so I can diagnose this kinda stuff.
Comment: Yeah no matter what i do they are never visible, despite the fact you can click them, we checked the html and they are not hidden so i would say it is an issue with ruby or watir-webdriver. bit annoying but never-mind. Still works for other bits of work. Thanks for all your help, I learned something regardless. If you ever hear of this being sorted or other people talking about it let me know. Cheers
Comment: Check to see if there is more than one of them.  `b.radios(:name => 'clocksource').size.  Without seeing the actual page and being able to play with it, it's very hard for me to troubleshoot directly.
Comment: There is only one set with the name, but thanks anyway. I actually found the issue, it turned out to be the javascript overlay which they were using to make the page look nicer, this was tricking watir into thinking the control was not active.
Answer: I suspect you have a timing issue. Try this:
Watir::Wait.until { @browser.element.visible?, thing  }

Comment: I actually tried that already, i found the issue was actually down to the implementation of the page i was trying to test. The elements were never visible due to the style sheets.


Precalculus equation solving involving square roots

Question: Solve the equation:
$$\sqrt x = \frac{3}{\sqrt x}+ \sqrt {x+3}$$
My approach was to multiply both sides with $\sqrt x$:
$$x = 3 + \sqrt {x+3} \sqrt x$$
$$(x - 3)^2 = (x+3)x$$
$$x^2 - 6x + 9 = 3x + x^2$$
$$9x-9 = 0$$
$$x = 1$$
...but this is clearly a false solution since 1 $\neq$ 5.
I sort of run out of steam here and have no more ideas. Is there a mistake in the math or does this just mean that there are no solutions (since the only solution that can be reached is a false one that was introduced by squaring)?
Comment: This does indeed show that the equation has no solutions, since you have shown that if $x $ is a solution, then $x=1$. But since $x=1$ isn't a solution, there are no solutions.
Comment: I don't see any mistakes. And you are right to assume there are no solutions.
Answer: Your algebra is correct and it does mean no solution exists. You could have in fact concluded no solution exists directly as follows:
(i) For all $x\geq 0$, we have $\sqrt{x+3} > \sqrt{x}$ and $\dfrac3{\sqrt{x}} > 0$.
(ii) Hence, $\sqrt{x+3} + \dfrac3{\sqrt{x}} > \sqrt{x}$ for all $x \geq 0$.
(iii) Hence, equality can never occur.


Is this disco/funk guitar effect a wah-wah pedal or something different?

Question: I'm no guitarist and this might be an 'obvious' question to those who know - but there's a backing-guitar effect often heard in many funky/disco songs which I can only describe as a sort of "wakka-wakka" sound!
It's probably easier to hear than describe, so I've included a couple of clips (Bee Gees, other artists are available) to demonstrate below.
Is this effect classed as a "wah-wah" sound, a combination of techniques, or something different altogether?
Example #1 (Nights on Broadway): Guitar enters at approx 30 secs:

Example #2 (Night Fever): Effect heard clearly from 1:25:
Comment: Note that, in addition to the probably correct assertion that it is a Wah pedal, a very popular funk effect is the envelope follower aka Autowah. This effect is essentially the wah with some sort of volume (voltage?) trigger where the louder/harder you play, the more pronounced the effect can be. Adjustable by knobs of course.
Comment: In addition to the wah pedal it does sound like one of the brothers Gibb is using percussive strumming with the wah pedals. Wah pedal do work well with a bit of percussive strumming.
Answer: Yes I concur, in both examples the rhythm guitar is using a wah wah pedal.
Let's explore this a little further. The early versions of the wah wah pedal used a filter to make variations in the peak response frequency of the guitar input depending on where the pedal was positioned. Rocking the pedal back and forth opens and closes this filter response. Now a days you can find many effect pedals with an automated version of the wah effect by driving the filter with an adjustable variable speed oscillator.
There is considerable technique in using a wah wah pedal and some brands are favored over others. Good technique is more than merely rocking the pedal back and forth, it has to do with timing and where the musician places the upper and lower bound of the pedal excursion that creates the right effect for the song. This effect pedal is likely one of the most expressive of all the effects because it allows for human touch while playing albeit it is usually a foot. You should also take a look at Peter Frampton's talk box which is a close relative to the wha wha effect.
As sited in this wiki article "Chet Atkins had used a similar, self-designed device on his late 1950's recordings of "Hot Toddy" and Slinkey."
source: http://en.wikipedia.org/wiki/Wah-wah_pedal
However, the most notable examples came late in the 1960's with Cream's "White Room", Jimi Hendrix's "Voodoo Child (Slight Return)".
If one searches long enough you might find some non main stream electronic music wizard doing something similar before Atkins with using manually controlled filters and any of a variety of audio sources.
Comment: +1 One thing I would add, regarding the specific "wakka-wakka" sound as heard on "Night Fever" (the other one has been taken down, so I can't comment on that) is that it is achieved by muting the strings with the left hand and strumming the rhythm, whilst rocking the wah. Additional expression can be added by occasionaly easing the muting, going for a note or chord. A similar approach can be heard on the intro to "Voodoo Child (Slight Return)" (just before the main lick).
Answer: Yes it's a Wah-wah pedal. Pretty standard funky line. I love it!
Answer: This effect used to puzzle me a great deal when I heard it as a child, because I couldn't imagine how it was made.
In addition to what's already been said: I don't think an autowah can be used to create that specific wakka-wakka scratching effect. I've tried it, it sounds indeed vaguely similar but not the real funky thing that blows your socks off.
I think that's because an autowah is triggered by the envelope voltage: it will be on the "AH" side of the "OO-AH" vowel scale when the output of the guitar is strongest, which is more typically when you play an open chord, rather than quickly strumming (wholly or partially) dampened strings.
It's exactly the noise component added by dampening the strings that sound most like voice phonemes when filtered because of their noisier / richer range of frequencies. This not only gives you the "OO" and the "AAH" phonemes but a whole range of plosive sounds like "K", "B" etcetera - hence the label "wakka guitar" that's sometimes used. When I first heard it I thought of it as "that kookabakka sound" :)
I've also experimented with vocoders, and there it is similarly important to have a signal that is rich enough in noise and / or harmonics in order for the vocoder filter to have something to sink its teeth into, so to speak. For instance, a pure sine tone cannot be filtered to sound like a vowel at all. It will only vary in volume when used with a vocoder or wah pedal because its spectrum contains one line only.
That's why I think that playing the funky wah-wakka-wah guitar is a very specific skill. It's not so much a matter of having the right stomp box but of mastering the skill of playing really good rhythm guitar, using dampening and working the wah-pedal together in the right way. It can then produce really curious effects.
I still think that the theme from "Shaft" is the golden standard of wah-wakka-wah guitar playing. Made in 1971, it is quite a bit earlier than "Le Freak" from Chic.
Answer: Nile Rodgers, of Chic fame, is largely responsible for the disco guitar style, that he adapted from the funk and ryhtm&blues styles that he learned playing with the Apollo theatre house band, Parliament Funkadelic, etc. This can be heard for example in Chic's eponymous first album from 1977:

However the more typical disco guitar sound (pardon the pun :-), with intensive usage of the wah, seems not to have been a Rodger's invention, as he first uses it (as far as I know) in the 1978 album C'est Chic, after 1977's Saturday Night Fever.

So Alan Kendall, the Bee Gees guitarist, seems to have been the creator of this sound, or at least the first to use it in a widely successful disco sound recording. Kendall's guitar (and composition) work in Saturday NF is so important in the overall result that is fully credited with creative rights.


Input size issue when using lapply to mutate with R

Question: I have mylist which contains 2 lists, with sample data below.
Using class(mylist[[1]]) gives  "grouped_df" "tbl_df" "tbl" "data.frame"
[[1]]
# A tibble: 2 x 5
# Groups:   Year, Commodity [2]
   Year Commodity Commodity.Code value1_k value2_k
  <int> <chr>     <int>          <dbl>    <dbl>
1  2010 A         721            100      100
2  2010 B         792            200      200

[[2]]
# A tibble: 2 x 5
# Groups:   Year, Commodity [2]
   Year Commodity Commodity.Code value1_m value2_m
  <int> <chr>     <int>          <dbl>    <dbl>
1  2010 A         721            100      100
2  2010 B         792            200      200

I tried using mutate() to add a new column div to both tibbles, with the value derived by dividing the 4th by the 5th column, using the code below:
mylist2 <- lapply(1:2, function(i){
  mylist[[i]] %>% mutate(div=.[[4]] /.[[5]])
})

This brings up the error below:
 Error: Problem with `mutate()` input `div`.
x Input `div` can't be recycled to size 1.
i Input `div` is `.[[4]]/.[[5]]`.
i Input `div` must be size 1, not 2.
i The error occurred in group 1: Year = 2010, Commodity = "A".

Trying to reproduce the problem
I tried to reproduce the problem with dataset cars,
but the code worked this time.
cars1 <- cars +1
cars2 <- cars +2
cars_all <- list(cars1,cars2)

lapply(1:2, function(i){
  cars_all[[i]] %>% mutate(div = .[[1]] / .[[2]])
})

Comparing both list of lists, I take note that the classes are different, i.e.

class(cars_all[[1]]) gives "data.frame"
class(mylist[[1]]) gives  "grouped_df" "tbl_df" "tbl" "data.frame"

However, I tried using as.data.frame before applying lapply, but the problem persists.
I use lapply because the actual mylist contains more lists;
I use index form to perform division instead of column names because the column names are different (and important, to be preserved) across lists.
My goal is to add the extra column with its value derived through division as mentioned.
If there are better methods out there to achieve this please let me know.
Your help is much appreciated.
Answer: It looks like the grouping is what's causing the issue. Here is a reproducible example:
library(tidyverse)

df1 <- tibble::tribble(
  ~Year, ~Commodity, ~Commodity.Code, ~value1_k, ~value2_k,
  2010,        "A",             721,       100,       100,
  2010,        "B",             792,       200,       200
) %>%
  group_by(Year, Commodity)

df2 <- tibble::tribble(
  ~Year, ~Commodity, ~Commodity.Code, ~value1_k, ~value2_k,
  2011,        "C",            7242,       111,       123,
  2011,        "D",            7421,       222,       234
) %>%
  group_by(Year, Commodity)

str(df1)
#>grouped_df[,5] [2 × 5] (S3: grouped_df/tbl_df/tbl/data.frame)
str(df2)
#>grouped_df[,5] [2 × 5] (S3: grouped_df/tbl_df/tbl/data.frame)

mylist <- list(df1, df2)

mylist2 <- lapply(1:2, function(i){
  mylist[[i]] %>% mutate(div=.[[4]] /.[[5]])
})
#>Error: Problem with `mutate()` input `div`.
#>x Input `div` can't be recycled to size 1.
#>ℹ Input `div` is `.[[4]]/.[[5]]`.
#>ℹ Input `div` must be size 1, not 2.
#>ℹ The error occurred in group 1: Year = 2010, Commodity = "A".

mylist2 <- lapply(1:2, function(i){
  mylist[[i]] %>% ungroup() %>% mutate(div=.[[4]] /.[[5]])
})
mylist2
#>[[1]]
#> A tibble: 2 x 6
#>   Year Commodity Commodity.Code value1_k value2_k   div
#>  <dbl> <chr>              <dbl>    <dbl>    <dbl> <dbl>
#>1  2010 A                    721      100      100     1
#>2  2010 B                    792      200      200     1

#>[[2]]
#> A tibble: 2 x 6
#>   Year Commodity Commodity.Code value1_k value2_k   div
#>  <dbl> <chr>              <dbl>    <dbl>    <dbl> <dbl>
#>1  2011 C                   7242      111      123 0.902
#>2  2011 D                   7421      222      234 0.949

Does this work on your 'real' data?
Comment: Yes! It worked!! I picked up R from scratch and didn't understand the basics. Will look up later on more info about groupings. Thank you so much for your time.
Comment: No problem at all - thank you for including all the necessary info in your question