hook_node_view OR template_preprocess_page

Question: I have some data to be extracted from external sources. I want to display those data in a custom template tpl page ( page--zzz.tpl.php ) . I had implemented hook_node_view in my module, and with the node->nid, output the data to be displayed on a node.tpl.php page.
However, the designer wanted to use the full width of the page, so I had to display the collected data in the page-zzz.tpl page, instead of just in the node.tpl.php, so I have moved my function for collecting the data from my module to the template.tpl.php, and inside the function template_preprocess_page, with the node->nid, I collect the same data.
Is that correct? Everything would have been much easier if I had been able to access to the $page variable inside of the hook_node_view function. I tried but I did not succeed!!!
Please advice me. Now it is working but I am hesitating whether there was need to move the collecting data function from my module to the template tpl page.
Answer: hook_node_view() is not really suitable for loading anymore data. There is a hook_node_load() hook, which you'll receive an array of all nodes that site is about to load.
Note that this is only for loading, and that doesn't mean the user is on a node/XYZ page. You will probably need to add a URL argument match to make sure you load only the data related to the given node. Otherwise, pull all the information at once, and store them in each $node variable, which is passed by reference (all PHP 5 objects are).
The reason to use node_load hook over node_view hooks is that all modules implementing preprocess and view hooks now have access to this new piece of node. Otherwise, a hook_node_view is OK.
Secondly, you do not need to load them again in hook_preprocess_page at all. For Drupal 7 and later, hook_page_alter() is recommended. Since you store the data in hook_node_view/load hook, simply place the content in the regions you need. If this is theme specific, hook_preprocess_page() is better, but most of the contribs that take over entire page contents tend to use hook_preprocess_page(). Besides, you will have access to the renderable array because other preprocess functions are not executed at that moment.
You can get the current node like below (make sure you add arg() conditions to check the page router is node/%node)
$node = menu_get_object();

This $node object will contain the data you stored in the load/view hook. Make sure you pass the first argument to hook_page_alter(&$build) by reference, and place the content anywhere you want like god.
Comment: Thanks for your detailed reply, that I will study carefully. However, I thought that the region was exclusive of $page, i. e., print render ( $page[name_of_region] ) would print the region, I didn't know that it was accessible through $node.
Comment: Store raw data in the `node_load` hook. Process them in the `page_alter` hook.


An elementary example of Ito's integral

Question: Let $m(t,\omega)=\sum_{j \ge 0}B_{(j+1)2^{-n}}(\omega)I_{[j.2^{-n},(j+1)2^{-n})}(t)$ where $B(t)$ is the Brownian motion and $I_[.]$ is the standard indicator function, Can some body explain me why
$$
E[\int_0^T m(t,\omega)dB_t(\omega)]=\sum_{j \ge 0} E[(B_{t_{j+1}}-B_{t_j})^2]
$$
This is a solved example from chapter 3 of stochastic differential equations, Oksandel.
Answer: $$
E[\int_0^T m(t,\omega)dB_t(\omega)]=\sum_{j \ge 0} E[\int_{t_j}^{t_{j+1}} B_{(j+1)2^{-n}}  dB_t]
$$
$$
=\sum_{j \ge 0} E[B_{t_{j+1}} \left(B_{t_{j+1}} - B_{t_j} \right) ] = \frac12 \sum_{j \ge 0} E[\left(B_{t_{j+1}} - B_{t_j} \right)^2 ]
$$
Comment: @Cornido, the absence of 1/2 in the book crated a confusion. Thanks for the answer.

An elementary example of Ito's integral


Passar valor de uma variável php para uma variável JS de outro arquivo php

Question: Tenho o seguinte codigo no meu arquivo finalizar-compra.php:

          </input>

Basciamente esse código verifica se o usuario selecionou a opção delivery e adiciona a taxa de entrega no valor final da compra.
Tenho tambem esse código no arquivo validarDesconto.

<?php

include_once ("conexao.php");

if(isset($_POST['cupom'])){

$buscacupom = $_POST['cupom'];

    $conscupom = $pdo->prepare("SELECT * FROM cupom WHERE nome='$buscacupom'");
    $conscupom->execute();

    $sql = "SELECT valor FROM cupom WHERE nome='$buscacupom'";

    $valorcupom = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);

    $fetchAll = $conscupom->fetchAll();

    if ($conscupom->rowCount() == 0)
        {

        }
    else{
        echo json_encode(array('cupom' => 'R$'.$valorcupom['valor'].',00'));

        }
    }

        ?>

Ele verifica no banco se o cupom digitado existe ou não no banco e retorna o valor do cupom dentro de um strong na página finalizar-compra.php
A minha dúvida é:
O valor do cupom é salvo dentro da variável $valorcupom no arquivo validarDesconto.php. Como eu passo esse valor para uma variável JS, assim somando no if citado la no começo. Vou exemplificar:
Eu precisaria que o IF ficasse assim:

if (document.getElementById("tipoentrega").value == 'Delivery') {
                      valor = delivery + valordesconto;
                    } else {
                      valor = reitrada + valordesconto;
                    }

O valordesconto teria o valor da variável $valorcupom que busca no banco no arquivo validarDesconto.php
Comment: No caso, o arquivo JS que recebe a variável do PHP está no mesmo arquivo PHP ou em arquivo diferente?
Comment: Quem faz a busca do valor e armazena em uma variável php é o validarDesconto.php e quem precisa receber o valor da variável php em uma variável JS é o arquivo finalziar-compra.php. Os dois arquivos são PHP e o script JS fica dentro do arquivo finalziar-compra.php
Answer: Vou fazer em exemplo para você pela quarta forma.

Se você não quiser sair da página validarDesconto.php você pode usar o AJAX.

Página: validarDesconto.php
<?php

$variavel_a_ser_passada = 100;

?>

<form id="form">
    <input type="hidden" name="variavel" value="<?php echo $variavel_a_ser_passada; ?>"/>

    <input type="submit">
</form>

Página: finalziar-compra.php
<?php

$variavel = $_POST["variavel"];

?>

Agora, se você quiser sair da página validarDesconto.php, basta retirar o e.preventDefault() ou então, para ficar um código mais resumido, pode elimiar o Jquery e fazer um evento submit do próprio javascript no formulário.
Comment: Junte as suas duas respostas em uma. O Stack Overflow não é fórum, somos um site de perguntas e respostas, da maneira que publicou o conteúdo ele está fora do nosso formato. Veja [answer].
Answer: Existem várias formas de fazer isto.
Formas:

Fazer um require_once no PHP ( Pior forma que considero, pois essa função envia todo o conteúdo do PHP )

Fazer uma conexão XML com a função XMLHttpRequest do Javascript (Segunda pior forma que considero, já que esta função envia somente o conteúdo interpretado pelo PHP -> É melhor que a primeira, porém têm esse probleminha)

Usar o IMPORT e EXPORT do Javascript (Uma das melhores forma que considero, já que com estas funções eu posso exportar somente a variável)

Enviar um POST de uma página PHP para outra. E se não quiser sair da página, basta enviar com AJAX o valor. (Uma forma que considero boa também, pois não necessita enviar todo o conteúdo de uma página, somente a variável )

...
Se você queiser aprender sobre a terceira opção, recomendo este vídeo https://www.youtube.com/watch?v=6Avdyl8YgWg
Comment: Entendi a sua resposta. Eu assisti o vídeo da terceira opção, mas ele mostra a importação e a exportação entre dois arquivos JS certo? No caso, eu precisaria exportar o valor de uma variável PHP para uma variável JS de outro arquivo PHP. Se possível, me mostra um exemplo da 4 opção
Comment: Não interaja com o autor da pergunta ou outros usuários através das respostas. Se precisar interagir ou oferecer orientação adicional use o campo de comentários.


Form submit with radio in table has data in form_state['input'] and not in form_state['values']

Question: While developing a form for Drupal 7, I need a few radio groups, placed inside a table (one radio group per table row). The radios are defined as '#type' => 'radio' (not radios) and grouped together using the same name attribute per group. Nevertheless, when the form is submitted, the radio selections are not in the $form_state['values'] array, but in $form_state['input'].
As you can see from the screenshots, all data is stored in input, with the radios being outside the 'undefined' array, even though I placed them in $form['undefined'][$key][x]. In values only the select and textfield data is retained.
Any ideas? It's been two days now that I'm trying to resolve this :(
Thank you in advance.
function game_insert_form($form, &$form_state) {
  dpm($form_state, 'form_state');

  $test_data = array(
    '2' => 'Alfa',
    '4' => 'Beta',
    '6' => 'Gamma',
    '8' => 'Delta',
  );

  $header = array(
      t('Name'),
      array('data' => t('Existing'), 'colspan' => 2),
      array('data' => t('New'), 'colspan' => 2),
  );
  $form['undefined'] = array(
      '#tree' => TRUE,
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => array(),
  );
  foreach ($test_data as $key => $data) {
    // Label
    $label = array('#markup' => $data);
    $children = array(&$label);
    $row = array(array('data' => &$label));
    unset($label);
    // radio 0
    $radio0 = array(
      '#type' => 'radio',
      '#return_value' => 0,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio0'] = &$radio0;
    $row[] = array('data' => &$radio0);
    // dropdown
    $select = array(
      '#type' => 'select',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      /*'#states' => array(
        'enabled' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
        'required' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
      ),*/
    );
    $children['select'] = &$select;
    $row[] = array('data' => &$select);
    // radio 1
    $radio1 = array(
      '#type' => 'radio',
      '#return_value' => 1,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio1'] = &$radio1;
    $row[] = array('data' => &$radio1);
    // textfield
    $textfield = array(
      '#type' => 'textfield',
      '#maxlength' => 40,
      '#size'=> 40,
    );
    $children['textfield'] = &$textfield;
    $row[] = array('data' => &$textfield);

    $form['undefined'][$key] = $children;
    $form['undefined']['#rows'][] = $row;
    unset($radio0);
    unset($select);
    unset($radio1);
    unset($textfield);
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}

function game_insert_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
}

Comment: I run into a similar issue myself and I have been wondering how you dealt with this. The only thing to be working so far is be using `$form_state['input']` to get back the values but don't know if it is correct and where exactly it happens.
Comment: @Wtower thanx for reminding me to post the answer :)
Answer: At last I managed to find the answer (after a lot of experimentation). The following code works fine for me. I am not sure if everything is needed, but I won't touch it as long as it works.

Pay attetion that I use an associative array for the #rows array, in order to be able to find the correct row without keeping track of indexes.
The most bizzare part is that I had to add $form[$key]['#type'] = 'value'; to hold the selected value.
The '#name' => $key, is obviously used to group the radios
together per row.
The '#id' => drupal_html_id($key . '[' . $item . ']'), was also
added, but I'm not sure if it's needed.

Obviously one does not need to use a seperate column for the label, but I display it this way because in my code I use drop downs and other controls instead of the labels shown here.
Here is the code:
function game_test_form($form, &$form_state) {
  dpm($form_state, 'form_state');
  $test_data = array(
    'alfa' => array(1, 2, 3),
    'beta' => array(1, 2, 3),
  );
  $header = array(
      t('Name'),
      array('data' => t('First'), 'colspan' => 2),
      array('data' => t('Second'), 'colspan' => 2),
      array('data' => t('Third'), 'colspan' => 2),
  );
  $form['undefined'] = array(
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array(
      // The keys here are used later on for the correct #row insertion
      'alfa' => array('title' => t('Alfa')),
      'beta' => array('title' => t('Beta')),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $table = &$form['undefined'];
  foreach ($test_data as $key => $data) {
    // This stores the value in the $form_state['values']. It must be outside the table.
    $form[$key]['#type'] = 'value';
    foreach($data as $item) {
      $element = array(
        '#type' => 'radio',
        // this value will be assigned to the $form_state['values'][$key]
        '#return_value' => $item,
        '#default_value' => isset($form_state['values'][$key]) ? $form_state['values'][$key] : 0,
        // Radio group stored in input[#name] with the selected radio's #return_value as value
        '#name' => $key,
        '#id' => drupal_html_id($key . '[' . $item . ']'),
      );
      // Attach the radio to the logical tree, so as to be included in $form_state['values']
      $table[$key][$item] = &$element;
      // Attach the radio to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => &$element);
      unset($element);
      // Attach its label to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => array('#markup' => 'Label ' . $item));
    }
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}
function game_test_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
  $form_state['rebuild'] = TRUE;
}

Comment: Wow, the "bizarre part" is a life saver! Thanks, it also applies to Drupal 8.


Generics with class with two or more types (Interfaces) error

Question: this is my class:
public class MyTreeMap
< K extends CharSequence, V extends CharSequence & Map > {
}

And my Main:
{MyTreeMap< String, String > s = new MyTreeMap < >();}

What is the error?
Netbeans Give me this error:
type argument String is not within bounds of type-variable K
  where K is a type-variable:
    K extends CharSequence declared in class MyTreeMap
type argument String is not within bounds of type-variable V
  where V is a type-variable:
    V extends String,Map declared in class MyTreeMap
Answer: The part: V extends CharSequence & Map means your second type needs to extend both which String does not.  Could you be looking for a Map of CharSequences?
public class MyTreeMap< K extends CharSequence, V extends Map<K, CharSequence> > {}

Following up on your comment, you can't use generics to accept two different object with different types (how would it know what to return when you call get).  You could create a wrapper class called ValidTreeType that has a Map and String property and make a Map of these.
Comment: thanks for reply, i want this: for example: put(" ", " " ) or put (" " , new HashMap<>()); is this valid code?
Comment: So it can take a CharSequence OR a Map?  This is actually not possible (it violates what Generics are trying to do (how would it know what to return when you call .get())
Comment: but your implementation can take this: put (" " , " " )?
Comment: My brain is a little fried trying to figure out how to instantiate the class I wrote :P  But I think my update addresses the limitations of Generics
Comment: ok. thanks for the reply.. (good explication), i want to complicate mi life jeje


What does "fly swatter" mean in jazz?

Question: I play a jazz song called "Fly's last boogie" and in the notes there's a star with a description "fly swatter on four". Does it mean I should literally hit with a fly swatter or is this some kind of jazz term?
Comment: For drummers, the brushes are known colloquially as 'fly swatters'.
Comment: @Tim - that's the answer, man. Please post as such with examples? :)
Comment: I would speculate that in the original recording or perhaps the intention of the composer, the (a) drummer would hit the snare with the brush every 4th beat, and that was an intrinsic part of the piece, obviously a pun with the title. The transcriber or composer made a point of notating that even  a  reduction (?) score or lead sheet.
Comment: Can you post the score or a link to the sheet music?
Comment: @CarlWitthoft Ok then https://drive.google.com/file/d/0BwubCx2m0mVuQXVHQmczX01hbFk/view?usp=sharing  It might be even legal in my country :)
Comment: @Tim That's what I googled but it seemed really strange to me to hit once with a fly swatter on four (about once every 4 seconds in the song). Also I am supposed to play drums while playing piano or what? :)
Answer: Only clue I have is that drummers use  'fly swatters' aka brushes. It seems odd that the tune needs a brush stroke, so to speak, on 4, but I don't know what happens on the rest of the bar, never having met or played this piece. For once, Google knows as little as I !

What does "fly swatter" mean in jazz?


Problems about Vector spaces

Question: Show that the set $V = \{p(x):p(x)$ is a polynomial with real coefficients and $p(3)=0\}$ is a vector space.
The p(3)=0 is throwing me off. To show V is closed under vector addition, I would show that for some polynomial f(x) and g(x) f(x)+g(x) would have to be closed under vector addition but how would p(3)=0 fit into f(x)+g(x).
Comment: what is $f(3)+g(3)$ if $f(3)=g(3)=0$?
Comment: Oh, I see. Thank you, feel dumb now.
Comment: no need. everybody has such moments.
Answer: We already know that the set of all polynomials is a vector space, so all you have to do is to prove that $V$ is a vector subspace of it using vector subspaces criterion, i.e, $0\in V$ and $\forall P,Q\in V,\forall a,b\in\mathbb{F},\, P+(-Q)\in V$ where $\mathbb{F}$ is the field where we're working (generally $\mathbb{R}$ or $\mathbb{C}$). The way you prove the last thing is similar to how you can show what you're asking for: closure under $+$, i.e:$$\forall P,Q\in V,\,P+Q\in V$$
So let $P,Q\in V$ (they are arbitrary choosen which fits with $\forall P,Q\in V$). Thus $P(3)=Q(3)=0$.
Now, since $V$ equals the set of polynomials for which 3 is a root, we have:$$P+Q\in V\Leftrightarrow(P+Q)(3)=0$$
But we know that $(P+Q)(X)=P(X)+Q(X)$ so in particular $(P+Q)(3)=P(3)+Q(3)$. What can you say?

Problems about Vector spaces


Kinetic Rhythm in Pop Music

Question: This is something I've noticed that I don't hear anyone really talking about...
Essentially it's the way that separate rhythmic elements of most pop songs interact in a kinetic way with one another. Almost as though they were sparking off of one another(when one is playing the other one often isn't)...and this seems not to fit into any traditional counterpoint style.
One of the best examples of this is Owl City - Fireflies... it's a good example partly because of how distinct and crisp the 3 melodic/rhythmic sections interweave with one another.
Anyway, is there a name for this? I have a hard time coming up with bass lines, not to mention bass lines that spark off the melody this way. Are there any principles I can look up and learn for this?
Comment: I'm not sure if there is a specific term for what you're talking about, but it may be related to a "hocket," which involves a single melody beginning split up between several interlocking melodic voices. So, we might be able to describe what you're hearing as "rhythmic hocketing."
Comment: From the example you give, I cannot understand what you are describing.  Can you describe it more accurately - perhaps give time stamps for when they happen in that example or another.
Comment: What do you mean by "kinetic"? This is a physics term that isn't part of the standard musical lexicon.
Comment: Right, I do mean kinetic in the physics sense. There's a strong sense of movement that happens from the nature of the relationship of the two separate lines. They run into each other like billiard balls. One is in motion, and it often stops when the other one is going. There's a sense that the dynamic way the lines interact with one another is very propulsive.
Comment: You mention bass lines. Do you mean kinetic like Newton's pendulum, i.e. the end of the melody leads into a short bass solo / bridge? I think I would describe it as the melody being passed around, if that helps, but I don't know of any technical term for that. It seems like something that might pop up in counterpoint literature.
Comment: I had to look up "hocket." This video https://www.youtube.com/watch?v=rfco2jnGtn4 seems to do a good job of showing the Medieval origin and contemporary pop examples.
Answer: (Note that this answer expounds on a comment originally made by Peter.)
One term that may be helpful is hocket. In music of the Middle Ages, hocket describes a single melody that is shared among at least two voices. Often this results in a situation where, as one voice is playing, the other is resting, and vice-versa. This seems exactly in line with your description of voices "sparking off of one another (when one is playing the other one often isn't)."
Even though this concept originated centuries ago, the concept is still alive and well today; we encounter it relatively often in current popular music.
Another related term is composite rhythm; this is the rhythm created by all of the articulations in multiple voices. This is connected to the concept of hocket because, when one considers the multiple voices of the hocket, the composite rhythm of these voices shows how they created a single unified line.

Kinetic Rhythm in Pop Music


WPF Animation Pause/Continue

Question: I'm experimenting with WPF animations, and I'm a bit stuck. Here's what I need to do:
MouseOver:
Fade In (0% to 100% opacity in 2 seconds)
MouseOut:
Pause for 2 seconds
Fade Out (100% to 0% opacity in 2 seconds)
I've got the Fade In and Fade Out effects, but I can't figure out how to implement the Pause, or even if it's possible.
Answer: Here's some XAML that shows how to do what you're after (you can paste the entire thing into Kaxaml to try it out:
<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid Background="Red">
    <Grid.Triggers>
      <EventTrigger RoutedEvent="Grid.Loaded">
        <EventTrigger.Actions>
          <BeginStoryboard>
            <Storyboard RepeatBehavior="Forever">
              <DoubleAnimation Storyboard.TargetProperty="Opacity"
                               From="1" To="0"
                               Duration="0:00:02"
                               BeginTime="0:00:02" />
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger.Actions>
      </EventTrigger>
    </Grid.Triggers>
  </Grid>
</Page>

The trick is to use the BeginTime propertly of the DoubleAnimation class.

WPF Animation Pause/Continue


Make bootstrap nav in mobile, expanding from left side instead of dropping down.

Question: More of a backend guy, just looking for some direction on customizing bootstrap in XS to basically act like the amazon phone app.
I want the nav expand menu button to have the nav pop out from the left instead of dropping down. Is there a good way to do this in bootstrap, or is it best to just write something custom? If custom is best, would it be best to try and override the data-target/data-toggle or just do a js onClick and run my code?
There will also be expandable sub menu's/drop down menus like Amazons instant video and apps, is that something best written custom or is there a good way to do it in bootstrap? I know the drop downs in bootstrap, but not really seeing how to  expand a menu option.
Thanx ahead of time.
Answer: Here's an example of using Bootstrap components with custom code and jQuerys toggleClass to initiate the mobile off-canvas menu. If you're going to use a Framework you should use as much built in functionality as possible which I think this example does: jsfiddle

            <button data-toggle="collapse-side" data-target=".side-collapse" data-target-2=".side-collapse-container" type="button" class="navbar-toggle">Toggle navigation
            </button> Brand

Link (current)

Link

 Dropdown

Link

Link

Link

Link

Link

                <form class="navbar-form navbar-left" role="search">

                        <input type="text" class="form-control" placeholder="Search" />

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

Link

 Dropdown

Link

Link

Link

Link

Link

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×

            </button> Warning! This is an Off-Canvas Mobile Menu


`randomForest` predict() for continuous variable: unexpected output?

Question: I am trying to understand how predict() in randomForest() in R computes the predicted values for a continuous y? My understanding is it should, for a single tree, for observation i, average over all observations falling in the same node than i, eventually removing the i observation itself. Is this correct?
However, doing this manually in R, I don't get the same result. I get actually results changing every time...

i=1, t = 1: seems to remove last one, not i
i=2, t = 1: seems to remove all, but i
i=1, t = 2: seems to remove i (what I expect)

I don't understand this averaging of the trees?
Example with i=1, t=1
Example with data(swiss), predicting first observation (Courtelary), from first tree:

my code, all obs in same node: 81.5
my code, all obs in same node, except i: 81.93333
predict(): returns 82.8
my code, all obs in same node, except last: 82.8

library(randomForest)
#> randomForest 4.6-14
#> Type rfNews() to see new features/changes/bug fixes.

data(swiss)

## run forest
set.seed(111)
swiss.rf <- randomForest(Fertility ~ ., data=swiss)

## predict first obs, from first tree only:
i <- 1
t <-  1
pred_i_t <- predict(swiss.rf, newdata =swiss[i,], predict.all=TRUE)$individual[t]

## get node values, extract obs in that node
nodes_tree1 <- attr(predict(swiss.rf, newdata =swiss, nodes = TRUE), "nodes")[,t]
same_node <- swiss[nodes_tree1 == nodes_tree1[i],]

same_node
#>            Fertility Agriculture Examination Education Catholic
#> Courtelary      80.2        17.0          15        12     9.96
#> Moutier         85.8        36.5          12         7    33.77
#> Gruyere         82.4        53.3          12         7    97.67
#> Val de Ruz      77.6        37.6          15         7     4.97
#>            Infant.Mortality
#> Courtelary             22.2
#> Moutier                20.3
#> Gruyere                21.0
#> Val de Ruz             20.0

mean(same_node$Fertility)
#> [1] 81.5
mean(same_node$Fertility[-i])
#> [1] 81.93333
mean(same_node$Fertility[-nrow(same_node)])
#> [1] 82.8
pred_i_t
#> [1] 82.8

Created on 2018-10-24 by the reprex package (v0.2.1)
Answer: I found the issue: the randomForest is also bootstrapping (bagging) the observations, and hence one needs to average over the resampled observations, not the initial sample ones.
So the averaging is done over the observations that were found in the node on a given bootstrap sample. This is obtained using the keep.inbag=TRUE argument. For this case `i=1, t=1', it shows that (1,1,1,0), i.e. last observation was not drawn in that specific sample, which explains the result!
See code:
library(randomForest)
#> randomForest 4.6-14
#> Type rfNews() to see new features/changes/bug fixes.

data(swiss)

## run forest
set.seed(111)
swiss.rf <- randomForest(Fertility ~ ., data=swiss, keep.inbag=TRUE)

## predict first obs, from first tree only:
i <- 1
t <-  1
pred_i_t <- predict(swiss.rf, newdata =swiss[i,], predict.all=TRUE)$individual[t]

## get node values, extract obs in that node
nodes_tree1 <- attr(predict(swiss.rf, newdata =swiss, nodes = TRUE), "nodes")[,t]
bag_tree1 <- swiss.rf$inbag

swiss$node <-  nodes_tree1
swiss$bag <-  swiss.rf$inbag[, t]

obs_i_tree_t <- subset(swiss, node == nodes_tree1[i])

with(obs_i_tree_t, weighted.mean(Fertility, bag))
#> [1] 82.8
pred_i_t
#> [1] 82.8

Created on 2018-10-26 by the reprex package (v0.2.1)
Comment: Well, this is what random forest algorithm does...
Comment: haha, fair point @Tim, although it is not always clear whether random forest includes the bagging step or not. Interestingly, there is some work suggesting to do the opposite now, using the out of bag sample fore prediction, not the in-bag one, which reduces the bias of the prediction, see https://arxiv.org/pdf/1510.04342.pdf


Proving by contradiction that $A \subset B \implies \sup(A) \leq \sup(B)$, for $A$ and $B$ bounded subsets of $\Bbb{R}$

Question: Yesterday I saw a question related to calculus 1 in which they asked for a proof for the following:

Let $A$ and $B$ be two bounded subsets of $\mathbb R$.
$$A \subset B \implies \sup(A) \leq \sup(B)$$

The moment I saw it, reasoning by reductio ad absurdum came to my mind. So my personal proof would be:

Let's assume that the assertion
$$A \subset B \implies \sup(A) > \sup(B)$$
is true and we find a contradiction: $\sup(A) > \sup(B)$, since $\sup(B)$ is the smallest upper bound of $B$ and $\sup(A)$ strictly greater than $\sup(B)$ then this means that $\sup(A)$ which can belong to set $A$ does not belong to set $B$ and this is a contradiction because $A$ is included in $B$.
So we have shown by contradiction that the assertion $A \subset B \implies \sup(A) \leq \sup(B)$ is true.

Many teachers proved the same assertion with direct reasoning, but I preferred the absurd reasoning. What do you think about it? Is my proof true?
Thanks already.
Comment: The proof does not work as it is because the supremum of a set needn't be an element of that set.
Comment: The fact that $\sup(A)$ can be an element of $A$ isn't enough, because your argument seems to require that it's necessarily an element of $A$. Also, the negation of $A \subset B \implies \sup(A) \le \sup(B)$ is not $A \subset B \implies \sup(A) > \sup(B)$. The assertion to be proved is implicitly universal: "for all sets $A$ and $B$, $A \subset B \implies \sup(A) \le \sup(B)$". Thus its negation is existential: "there exist sets $A$ and $B$ such that $A \subset B$ and $\sup(A) > \sup(B)$" (note "and", not "$\implies"). Fortunately this highlights the fact that you only need one counterexample!
Comment: A proof is not true or false $-$ it is valid or invalid (you could also say it is correct or incorrect). A _statement_ is true or false.
Comment: @GregMartin A single example would suffice to establish "there exist sets...", but we want to show that this statement is false. I don't know how a counterexample would be useful.
Answer: The proof isn't correct.  There's a problem with the word "can" in the phrase "sup $A$ which can belong to $A$."   "Can" is not enough.  Take a simpler example:
Prove that if $x < y$ then $x^2 < y^2$.
First note that the statement is not true.  We have $-3 < -2$ but $(-3)^2 > (-2)^2$.   But pretend we didn't notice that and we use your method of proof:
Since $x$ and $y$ can both be positive, we have $x^2 < xy < y^2$, therefore we're done.
Nope.  The statement is true in special cases, but not in all cases.  "Can" takes to special cases.   I guess your prove works in the special case that sup $A$ does belong to $A$, but what about the other cases?
Comment: I get it, that's a special case, in general we could say: because sup(A) > sup(B), then ∃ x ∈ A and x > sup (B). So in this case sup(B) < x < sup(A) x belongs to A but doesn't belong to B and this is a contradiction because A is included in B.
Comment: I think you need a bit more than that.  How do you know that $x > $ sup $B$?     Let $\epsilon = $ sup $A - $ sup $B$.  Then consider the interval of radius $\epsilon/2$ about sup $A$.  Does it contain an element of $A$?  Is it bigger than  sup $B$?
Comment: it is because sup(A) is greater than sup(B), that an x which belongs to A could be greater than sup(B) but at the same time less than sup(A).
Comment: Do you find it true this time?
Comment: @AmineNsr There is ambiguity in your language. Your phrase _"an x which belongs to A could be greater than sup(B)"_ can be understood in two different ways: (_i_) it is possible that such $x$ exists; (_ii_) it is always possible to find such $x$, in other words, such an $x$ _always_ exists. You need to figure out which one you require, (i) or (ii). Then you need to prove your claim. [I am not B. Goddard]
Comment: @paperskilltrees "an x which belongs to A could be greater than sup(B)" meant  ∃ x ∈ A such that sup(B) < x.
Answer: As others have pointed out, your argument contains some flaws. That being said, here's how I would do a (very verbose) contradiction argument: assume that $A \subset B$, where $B$ is a bounded subset of $\mathbb{R}$. Assume, to the contrary, that $\sup A > \sup B$. Because $A \subset B$, it follows that $a \in A \Rightarrow a \in B$. By definition, for every $$b \in B, b \le \sup B < \sup A,$$ by our assumption. However, this also implies that $\sup B$ is an upper bound of $A$. That is, for every $a \in A, a \le \sup B < \sup A$, and so $\sup B$ is a smaller upper bound than $\sup A$, which is impossible!


Assignment to expression with array type

Question: I am new to coding in C and had a question about the "assignment to expression with array type" error. From my understanding (correct me if I'm wrong), using char* in conjunction with malloc() allocates memory on the heap, which we can read and write to. Using a char var[], allocates memory on the stack frame, which we can also read and write to. I thought that these two would be similar to work with, but apparently they are quite different.
Using the code below, I was able to remove the first char in a string on the heap (by incrementing the pointer to the string).
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    char* test = malloc(20 * sizeof(char));
    strcpy(test, "XHello World!");
    test = &test[1];
    printf("%s\n", test); // Hello World!
}

Trying to do the same operation with a char var[] though, I ran into the "assignment to expression with array type" error. My code is below.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    char test[20] = "XHello World!";
    test = &test[1]; // assignment to array type error
    // test = test + 1 // same error
    // test = *(test + 1); // same error
    // test += sizeof(char); // same error
    printf("%s\n", test);
}

In the above code, I thought that since test is a pointer, and &test[1] is also a pointer (just like in the first example), assignment would work the same. Could someone explain why this isn't the case? Any help would be greatly appreciated!
My actual goal was to extract a string from some brackets (eg, [HELLO]), and I was trying to use the above technique to remove the opening bracket, and test[strcspn(test, ']')] = '\0' to remove the closing bracket. Maybe this is a bad approach entirely?
Comment: You could achieve the same ouput with `printf("%s\n", &test[1]);` but you cannot reassign an array variable. In any case, the first example is poor practice because it will not be so simple to `free` the memory you allocated.
Comment: Test is **not** a pointer in your second example - it's an array and its value can't be changed.
Comment: Also relevant: https://stackoverflow.com/questions/7882735/why-cant-i-assign-arrays-as-a-b/7883036#7883036
Comment: And: https://stackoverflow.com/questions/61099179/referencing-a-variable-to-an-existing-array
Answer: No, arrays are not pointers and vice-versa.
You cannot assign to an array type, that's not a lvalue.
Answer: Array is not a pointer. Arrays only decay to pointers causing a lots of confusion when people learn C language.
You cant assign arrays in C. You only assign scalar types (integers, pointers, structs and unions) but not the arrays.
Structs can be used as a workaround if you want to copy the array
struct bar
{
    char c[20];
};

int main(void)
{
    struct bar b = {.c = "Hello World!!"};
    struct bar x;

    x = b;   // it is correct and will copy the whole struct `b` to struct `x`
}


How to update one component based on event handler of another component?

Question: I have two components in my index.js file (Header and Sidebar) like below
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import {
    BrowserRouter as Router,
    Route
} from "react-router-dom";
import './index.scss';
import './responsive.scss';
import Sidebar from './sidebar';
import Header from './header';
import Home from './home';
import Products from './products';
import Variant from './variant';
import Variety from './variety';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
    <Router>

            <Sidebar />

                <Route exact path="/" component={Home} />
                <Route path="/products" component={Products} />
                <Route path="/variant" component={Variant} />
                <Route path="/variety" component={Variety} />

    </Router>
    , document.getElementById('root'));

serviceWorker.unregister();

I have a button in my Header component and I want to add an onClick event handler to it, so when clicked the sidebar in Sidebar component would be toggled.
Now my problem is that I can not connect these two components. I have even tried to use what is suggested in this link How To Pass Events Between Components, but the problem is that the event targets the change of all the elements defined in the children's components.
I have read something about the createPortal() but it was suggested to access the DOM outside the component and since I am trying to access a component from another one I'm not sure if I should be doing that.
Your help is appreciated in advance.
Answer: In order to connect components you should use a store to share the application state across all components. Something like Redux or similar would do it.
The main idea is that you change the state in the Header component, and Sidebar will be listening to this state and update itself if needed.
Answer: There are few ways.

You can use Redux.
Use React Context API https://reactjs.org/docs/context.html OR

You can do something like following
// IN MAIN FILE
state ={
    sidebarOpen : false
}

<sidebar  sidebarOpen = { this.state.sidebarOpen} />

toggleSidebar(){
    //UPDATE STATE
    this.setState({
        sidebarOpen : !(this.state.sidebarOpen)
    })
}

// IN HEADER

onButtonClick(){
    this.props.toggleSidebar()
}

IN SIDEBAR

componentWillReceiveProps(props){
    //LOGIC FOR UPDATING SIDEBAR YOU WILL RECIEVE UPDATED STATE HERE
}

Answer: First,simply about connecting these two components.The data transfer in React is suggested in pass from the father component to the child component.This is Lifting State Up.So normally, use callback to change the father component of header and pass the data back to sidebar.And now redux works well with react.So,simply set a state for Sidebar,and bind a function in onClick of Header.And add something in onClick.like this:

<sidebar  sidebar = { this.state.sidebar} />

BTW,react provides us some ways to pass data.For example,context is used when component nesting is complex and it's hard to find the common father component.
Second,"the event targets the change of all the elements defined in the children's components".This problem is because of how the react works.You can use shouldComponentUpdate to avoid it.But not recommend here.
Third,about React Portal,it's added to React v16.It's used to render the child component outside the father component.This answer is good, if you want to know about it.How to use ReactDOM.createPortal() in React 16?. siderbar and header component are in the same levels.so I don't think it's nesscessary.
Answer: As answered by everyone, these are some good solutions. But you have mentioned your constraints also. You can try below one also.
let showSidebar = true;

// Function to handle toggle
const handleClick = () => {
  showSidebar = !showSidebar
  renderApp()
}

// Make renderApp function
const renderApp = () => {
 ReactDOM.render(
    <Router>

             // call this function onClick inside your Header component
            { showSidebar && <Sidebar /> }      // toggle the Sidebar

                <Route exact path="/" component={Home} />
                <Route path="/products" component={Products} />
                <Route path="/variant" component={Variant} />
                <Route path="/variety" component={Variety} />

    </Router>
    , document.getElementById('root'));
};
renderApp(); // Call renderApp for the first time

serviceWorker.unregister();


Bash get n characters before a specified character

Question: This is the string:
Volume: 0:  120% 1:  128%

I want to get 3 characters before "%" character. So output must be like 120 128 for this example. How can i do that?
Answer: Assuming you actually want everything between whitespace and a % (which is the same for this example), you could do:
awk '{print $NF}' RS=% ORS=' '

Answer: You can use this grep:
$ grep -Po '...(?=%)' file
120
128

Which is the same as:
grep -Po '.{3}(?=%)' file

or this if you want to make sure you get digits:
grep -Po '[0-9]{3}(?=%)' file

Explanation
The idea underlying is to print three characters before % is found. (?=%) indicates this and is called a "look-ahead".
With -Po we indicate grep that it can use Perl regular expressions (-P) and to just print the matches (-o).


MS Access query problem, with criteria in short text field

Question: I am trying to make a query to only list computers with over 500 MB of ram, the RAM field is short text with both "MB" and "GB" at the end of the string. the problem i am having is I cant seem to code the expression right and I keep having various errors on everything i have tried so far.
I'm not looking for the solution but it would be appreciated or point me in the direction of what I should read up on. Thanks in advance
Comment: Can you post an example of your input and expected output? And what code have you already tried?
Comment: What have you tried so far?
Answer: In the query, you can filter on the value alone and on MB/GB:
<code>Where (Val([RAM]) >= 500 And InStr([RAM], "MB") > 0) Or (Val([RAM]) >= 0.5 And InStr([RAM], "GB") > 0)
</code>
Comment: Thank you, only thing  had to do was change Value to Val and it worked :)..


Invalid Layer Save Flag - only ALL_SAVE_FLAGS is allowed android API 28+

Question: Estou tendo este problema depois de alterar a targetSdkVersion de 25 para 28, estou tendo que realizar esta alteração pois é necessário este sdk para publicar na loja do google.
A exception gerada:
java.lang.IllegalArgumentException: Invalid Layer Save Flag - only ALL_SAVE_FLAGS is allowed
        at android.graphics.Canvas.checkValidSaveFlags(Canvas.java:442)
        at android.graphics.Canvas.saveLayer(Canvas.java:519)
        at com.mikepenz.materialdrawer.view.BezelImageView.onDraw(BezelImageView.java:209)
        at android.view.View.draw(View.java:22213)
        at android.view.View.updateDisplayListIfDirty(View.java:21089)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.view.View.updateDisplayListIfDirty(View.java:21080)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.view.View.updateDisplayListIfDirty(View.java:21080)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.view.View.updateDisplayListIfDirty(View.java:21080)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.widget.ListView.drawChild(ListView.java:3613)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.widget.AbsListView.dispatchDraw(AbsListView.java:2668)
        at android.widget.ListView.dispatchDraw(ListView.java:3608)
        at android.view.View.draw(View.java:22216)
        at android.widget.AbsListView.draw(AbsListView.java:4369)
        at android.view.View.updateDisplayListIfDirty(View.java:21089)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.view.View.draw(View.java:22216)
        at android.view.View.updateDisplayListIfDirty(View.java:21089)
        at android.view.View.draw(View.java:21944)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4419)
        at android.support.v4.widget.DrawerLayout.drawChild(DrawerLayout.java:1379)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4180)
        at android.view.View.updateDisplayListIfDirty(View.java:21080)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4403)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4376)
        at android.view.View.updateDisplayListIfDirty(View.java:21049)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4403)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4376)
        at android.view.View.updateDisplayListIfDirty(View.java:21049)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4403)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4376)
        at android.view.View.updateDisplayListIfDirty(View.java:21049)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4403)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4376)
        at android.view.View.updateDisplayListIfDirty(View.java:21049)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4403)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4376)
        at android.view.View.updateDisplayListIfDirty(View.java:21049)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:559)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:565)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:642)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:4058)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3785)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3060)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1888)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8122)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
        at android.view.Choreographer.doCallbacks(Choreographer.java:796)
2020-04-13 13:16:46.209 31317-31317/br.com.desen.amauditores E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:731)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7464)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)

Observei que na classe BezelImageView.java existe uma chamada para saveLayer:
cacheCanvas.saveLayer(mBoundsF, mMaskedPaint,
                        Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);

Porém esta classe nao pode ser alterada para deixar como default ALL_SAVE_FLAGS
Alguém ja passou por isso e poderia me ajudar?
Comment: Se a sua dúvida tiver sido respondida, por favor, aceite a resposta. Veja mais detalhes em [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079)
Answer: Você está utilizando uma versão desatualizada do com.mikepenz.materialdrawer. Dando uma pesquisada no GitHub deles, encontrei esse issue onde o mantenedor do repositório diz

Essas flags não são mais aplicadas em versões recentes.
Por favor, atualize o MaterialDrawer.

Veja as versões disponíveis e atualize o seu gradle de acordo.
Siga o guia de migração passo a passo. Veja a sua versão atual e compare com uma mais recente do que ela para saber o que mudou. O guia de migração possui diversos exemplos do tipo "renomeie X para Y".
Com isso, você conseguirá chegar à uma versão que não tenha esse problema (aparentemente, a versão mais antiga sem esse problema é a v6.0.9). Recomendo fortemente fazer o passo a passo até a versão mais recente (v8.0.0 no guia de migração) para corrigir possíveis bugs que você ainda não percebeu e evitar novos problemas de migração por ter uma versão tão antiga.
Comment: Estou utilizando uma versão muito antiga: compile('com.mikepenz.materialdrawer:library:2.9.8@aar') {
        transitive = true
}
Quanto tento migrar para uma versao mais recente:
compile group: 'com.mikepenz', name: 'materialdrawer', version: '8.0.1'
me proporciona outro erro:
C:\Users\hcs01\.android\build-cache\bb3a14d3dfbcfbe9711ebec71497bfb1b45d6b70\output\res\font\materialdrawerfont_font_v5_0_0.ttf: Error: The file name must end with .xml
Comment: Dê uma olhada no guia de migração, que coloquei na resposta. Migre de uma versão para outra, não da `2.9.8` para a `8.0.1`. Ao migrar, faça um *clear build* do seu projeto, leia no guia o que precisará mudar em código e veja se ocorre algum erro. Faça isso progressivamente até chegar na versão desejada.
Comment: Ok, vou serguir o guia de migração, obrigado.


Android : don't show Notification if app is shown

Question: 1/I don't want to notify user if this one is already running my app in foreground,
is it possible before create nofification to check if my app is not in front ?
2/if app is in background, is it possible to bring last state in front ?
I know that Os can destroy some Activity, but is it possible to restore last state, don't start a new Intent?
because if i start a new Intent and i push back, old Intent appear it's not very beautiful to have 2 identical intent launch.
Thanks
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Intent notificationIntent = new Intent(this, z_finish.class);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);

Comment: possible duplicate of [How to detect if any of my activity is front-most and visible to user?](http://stackoverflow.com/questions/3136187/how-to-detect-if-any-of-my-activity-is-front-most-and-visible-to-user)
Comment: Right, but you did not accept any anwser from this post, Note that my Notification are done in an Service in background and yours?
Answer: is it possible before create nofification to check if my app is not in front ?
Your activities will have to tell the service when they are being paused and resumed; the service can then decide whether to display the Notification or not.

if app is in background, is it
  possible to bring last state in front
  ?

I am not quite certain what "last state" is. Try FLAG_ACTIVITY_CLEAR_TOP in your Intent.
Comment: So in each Activity i store a variable in getSharedPreferences (for exemple) when onPause is call and modify my variable again when onResume is call, right ?
i wanted to bring app in front but don't start a new Intent, i found how to do, i start a fake Activity & i make finish, so last Activity is bring in front.
Comment: I also tried this... make a fake Activity that just calls "finish", sending the user back to the last Activity.  Problem is, if they press "back" until they're out of the app, they can't get back into it by using the notification (it just closes itself back to their home screen.)  http://stackoverflow.com/questions/3568250/use-a-persistent-notification-to-allow-the-user-to-return-to-running-android-app
Answer: if your app is in singletask mode then the last state will be saved even if you relaunch it


Need Help in Starting to Learn Guitars?

Question: I am a beginning guitar player. I enjoyed playing in my childhood, but for some reason I was not able to learn.
But now I want to learn guitar. I wasn't sure whether to buy an electric guitar or a classic guitar to start with. I'm currently teaching myself by referring to this guide.
I've heard that electric guitar is better to start with for now rather than starting with a classical guitar because it's very difficult to learn for new people. Is this correct? What are some of the main things I need to focus on when learning guitar?
Is it a good idea to start off teaching myself or should I take classes? I've heard that it might be better to take lessons rather than self-teaching, but I'm not sure.
Answer: I highly recommend you learn to play on an acoustic guitar, and with an instructor if possible.
Selecting a guitar:
The two major kinds of guitars for your purposes are electric guitars and acoustic guitars.
Acoustic guitars are further divided into two types: Steel-string or "folk" guitars on the one hand, and nylon-string or "classical" guitars on the other hand. Both are good kinds of guitars to learn on. The nylon-string classical guitar requires less strength in your fretting hand, and calluses will take less time to build up. However, if you have smaller hands, the steel-string "folk" guitar will be easier for you to learn, because the fretboard is narrower than on a classical guitar.
One of the hardest parts of learning how to play guitar is building up strength in your fretting hand, the hand you will use to press the strings down to the fretboard (usually the left hand); and also building up calluses on your fingertips. While these take more time on an acoustic guitar than on an electric guitar, I still recommend learning acoustic guitar first for this reason: It's not difficult to learn to play the electric guitar after having originally learned to play on the acoustic guitar, but the reverse is not true. Making the leap from electric to acoustic guitar is more difficult.
Electric guitars introduce additional elements of complexity, including different pickup combinations, and (on some guitars) additional mechanical elements. A simpler instrument will allow you to concentrate on learning chords and notes rather than learning about pickup combinations and amplifier settings. Also, the amplifier on an electric guitar is really a part of the instrument, and guitar amps can be somewhat complex.
Learning on your own versus learning with a teacher or a group:
Learning an instrument on your own can be frustrating, particularly if it's your first instrument. It's certainly possible to learn mostly on your own, particularly if you're very dedicated and patient. Learning any instrument requires patience and, most importantly, practice.
A good teacher will tailor their lessons to address your weaknesses. If you have difficulties in a particular area, an experienced instructor will spend more time in that area. (A good sign of a bad teacher is when they don't do this and rigidly stick to a predetermined lesson plan.) However, this is more expensive than learning on your own or in a group.
Learning on your own offers you the opportunity to go at your own pace, and it can be inexpensive. However, this can be a detriment; knowing that you have a lesson on Tuesday is a good impetus to practice before then!
If you have a friend who plays guitar well, that friend is a great resource if they have the time and are willing to teach you.
If you can't afford lessons for an extended period of time, consider combining the two approaches: Pay for a few lessons to get you started, then learn on your own.
Conclusion
In summary, the best way to learn guitar is with an acoustic instrument that's good enough that you'll like playing it, but within your means. If possible, I suggest learning with a teacher or a group, but there's no correct way to do this. While it may not be as pleasurable or as quick, you can learn on any guitar, and completely on your own. Whatever you do, remember that you need to pus in the time practicing, but playing guitar is supposed to be fun; it won't take long before it is.
Comment: @Sankar - I've used this as the basis for a longer article, more [here](http://magnificentnose.com/2011/03/11/what-you-need-to-know-to-learn-to-play-guitar/) if you're interested.
Comment: Disagree that electric is harder to learn on.  You don't *have* to fiddle around with the pickups and amp, once you get some sound coming out it's really no different than an acoustic as far as learning your first chords and strumming goes.  I also found the lighter-gauge strings made it easier to get good sound, but that might just be me (I have fairly small hands).
Comment: Nothing is an absolute, of course. As the conclusion says, there's no single "right" way to do this, but there are methods that will make it easier in the long run. If you find it easier to learn on an electric, then go for it!
Answer: I will awnser differently. Start on the guitar you want to start out with.
For example, if you dream of playing electric guitar, and you are stuck playing an acoustic guitar which does nothing for you, you will abandon your project.
It is better to start on the instrument that will truly motivate you.
Comment: This is so true.  When I was a kid, my dad insisted on buying me an expensive acoustic and all I ever really wanted to play was electric.  I played for a year or so and got decent as a beginner.  Now, 30 years later, I finally have the electric I wanted and am really enjoying playing again.
Comment: There's an additional point: If you live in a place that you can't play a guitar, not even an acoustic, you can learn on an electric with headphones.
Answer: IMO an electric guitar is not the best to get started with.
You will have to learn not just to play the guitar but to handle the electronics in it, and the amplifier.
And you'll never know whether something you hear is due to your playing or to the way the amplifier worked what you played.
You'll also get into a tendency to hide your mistakes by adding more and more effects on the amplifier (this is how many "popstars" get away with being abysmal musicians).
And of course there's the initial cost of getting started, which would include not just a guitar but also an amplifier, cables, etc.
Rather I'd say start with a steel string acoustic guitar. An honest, down to earth, and relatively cheap instrument.
As most beginners want to start on a rather low budget as they're not certain what they want (or if they want to keep it up at all) they end up buying relatively cheap instruments.
If from that same low budget you don't also have to buy an amplifier (which will eat up about half that budget) and cables (a good cable can cost you $100+), you're going to end up with a far superior instrument that not only makes you sound better but will be easier to play and last longer before you find yourself running up against the technical limitations of what your instrument can do (and thus will want to invest in a more expensive, higher end, instrument).
To learn to play, having a good teacher at your disposal is a very nice thing to have.
If you don't, make sure you get the best instructional material you can get your hands on ("free youtube videos" are NOT good instructional material, even if some of them are good the majority are junk, same with "free instruction websites").
I like the stuff from Legacy Learning Systems (http://www.learnandmaster.com) (no, I get no kickbacks, just a happy customer). Not only is it high quality instruction (with the instructors actively participating in the support forums) but the community is great as well.
Sadly I had to cut short my training because of health problems (arthritis like symptoms in my hands) but as far as I got I had a good experience.
Comment: Not sure where OP lives, but around me the "big box" stores have both electric and acoustic "getting started" kits for about $100.  One of my nephews got the acoustic and his brother got the electric and both guitars seemed to be of about equal "quality" (Fender *Starcaster*s).  Both had some fret buzz and cheap tuning machines, but overall adequate for beginners.
Comment: I've seen those kits, and consider them wholly inappropriate to start with. In fact I used to have one, and it was so bad it caused me to give up playing for over a decade until I figured out it wasn't me that caused the constant failure but the terribly bad instrument (and that was an Epiphone, so a major brand kit)
Answer: That is a broad question Sankar. If I were you I'd go have a read of these questions:

What is the first scale
What is the best way to learn
Learn guitar chords

And in general, practice first on an acoustic, as you will build up the strength you need to develop speed and accuracy later.
Answer: Much good here, but I feel lead to be the contrary voice and champion the electric guitar. Not only for the repertoire reason (learning to play acoustic when you want to play thrash isn't quite right), but the strings are lighter with less tension, and are more conductive to melodic playing.
Yeah, it's a start toward the pedal sickness, but really, worse things than that, right?

Need Help in Starting to Learn Guitars?


Como habilitar um botão após input ser preenchido

Question: Estou precisando fazer com que um botão de "próximo" fique desabilitado enquanto o usuário não digitar dentro do input
Answer: Você pode usar o jquery para fazer isso:

$(document).ready(function(){
  $('#campo').on('input', function(){
    $('#manda').prop('disabled', $(this).val().length < 3);
  });
});

Campo:
    <input id="campo" type="text">
  <button id="manda" disabled>Mandar</button>

Agora ele irá fazer uma verificação, depois de 3 caracteres, ele troca a propriedade para diferente do valor que ele possui, no caso remove o disabled do button e você consegue prosseguir.
Comment: Tem a possibilidade desse botão só habilitar quando chegar a um número de caractere?
Comment: Pronto amigo, editei para mostrar que agora ele vai somente habilitar o campo, quando o usuário digitar mais do que 3 caracteres.
Comment: Sim, mas o menos trabalhoso é usar o jquery. Não sei, questão de praticidade e costume mesmo, minha opinião. Talvez trocando o precisa por "pode" melhore a minha colocação.
Comment: Pode substituir a condicional da prop por `$('#manda').prop('disabled', $(this).val().length > 3);` que vai funcionar igual, porém o código fica um pouco mais limpo.
Answer: Você pode criar um evento que escuta quando algo é digitado no campo e habilitar/desabilitar o botão:

document.body.querySelector("#texto").addEventListener("input", function(){

   var botao_proximo = document.body.querySelector("#proximo");

   // habilita o botão com 3 ou mais caracteres digitados
   botao_proximo.disabled = this.value.length >= 3 ? false : true;

});
<input type="text" id="texto">

<button id="proximo" type="button" disabled>Próximo</button>

Se quiser que a ação ocorra após tirar o foco do campo, troque o
  "input" por "blur".


Why is this derivation well-defined?

Question: I'm reading Fulton's algebraic curves (page 105) and I'm trying to prove $\tilde D$ is well-defined:

Let's define $\tilde D$ as $\tilde D(z)=y^{-1}(Dx-zDy)$, then if $z=\frac{x_1}{y_1}=\frac{x_2}{y_2}$, we have
$$\tilde D(z)=y_1^{-1}(Dx_1-zDy_1)\ \text{and}\ \tilde D(z)=y_2^{-1}(Dx_2-zDy_2)$$
How can we prove these expression are equal?
Thanks
Answer: We have $x_1y_2=x_2y_1$. Apply $D$ on both sides and notice that the result states precisely that your two expressions are equal.
By the way: You should include more context in your question. What kind of derivative is $D$? From your other question (https://math.stackexchange.com/questions/1156918/bad-notation-in-fultons-algebraic-curves-book) I could get the information that $R$ is supposed to be a $k$-algebra and $D$ is a $k$-derivation.
Comment: And thank you for pointing this up. Next time I will try to give more context to my question.

Why is this derivation well-defined?


Estou com problema para para fazer um arquivo.css

Question: Olá, sou novo aqui novo, e estou estudando front-End, mas estou com problemas, quando salvo um arquivo em css, para adicionar no HTML, esse mesmo arquivo fica vazio, mesmo eu salvando ele como (.css) e não muda o que eu editei!
OBs= o arquivo mesmo eu salvando .css o arquivo fica sem extensao. desde ja agradeço!!
Answer: Você esta usando Bloco de Notas? Se sim, na hora que você for salvar o arquivo, mude a codificação para Unicode. No caso dos arquivos já criados você pode usar o CMD para renomear.
Comment: @LucasOlimpio você mudou a codificação para unicode na hora de salvar para resolver? Ou teve que fazer alguma outra coisa?
Comment: Olá, eu uso o sublime, e salvo  o arquivo por ele, mas fica como apenas arquivo!
Comment: Como você está salvando o tipo de arquivo ? Na hora de salvar tem a opção "Tipo", onde é predefinido como "Todos os arquivos", você precisa selecionar o css lá e colocar a extenção .css no nome do seu arquivo.
Comment: Oi, consegui resolver o problem, era um erro bobo meu, mas agradeço a ajuda de todos, como faço para dar ponto ou algo para vcs?
Comment: Algum de nós resolveu seu problema ?
Comment: o problema era um erro na hora de salvar o arquivo, mas oq vale e a intenção!
Comment: Eu só consigo utilizar o sublime abrindo ele como administrador, e não sei o porque disso...


Listar várias ul dentro de uma li usando AJAX

Question: Como eu posso listar varios ul dentro de uma li, dinamicamente, com AJAX?
Algo como ul>li>ul>li>ul>li
A dúvida surgiu pois estou fazendo uma rede linear de um sistema de MMN e não consigo carregar dinamicamente a ul após a primeira li.
Comment: Tem de explicar melhor o que pretende faze e qual o resultado que quer. Bem como algum código que tenha tentado.
Comment: o resultado que eu gostaria seria igual a esse: https://www.dropbox.com/s/69zegxe72ko4kb8/Capturar.PNG?dl=0
Comment: Você consegue gerar seu conteúdo de lado servidor, ou utiliza dados de algum servidor fora do seu controle?
Comment: sim o sistema já está selecionando a tabela no db e enviando via json para o ajax eu quero ver como que faz para listar isso no html :S
Comment: Oi, Eduardo, em vez de adicionar informações aqui nos comentários, clique em [edit] e inclua esses detalhes na própria pergunta. Não editei eu mesmo porquê parece que a imagem tem detalhes de particulares; se puder faça um exemplo genérico.
Answer: Se entendi bem, quer colocar dinamicamente um
 dentro de um
 retornado por AJAX e se bem entendi quer fazê-lo com JQUERY. Coloco aqui um exemplo que responde ao que entendi na pergunta.
html:

No JQUERY:
$("ul#teste li").each(function () {
    var retorno_ajax = "

sub-linha1

sub-linha2

";
    $(this).html(retorno_ajax);
});

O each acede ao conteúdo dinâmico também. Não esquecer que o .html irá eliminar o conteúdo anterior e colocar o novo que para o exemplo resulta. No entanto se pretender adicionar o retorno ao conteúdo existente dentro da lientão utilize o append.


Memory leak while running WMI query to Win32_PageFileUsage class on Server 2008 SP2

Question: Running WMI query against Win32_PageFileUsage class causes a memory leak. In my situation it is being done to 200 servers every 5 minutes. After about 3 hours the memory leak is nearly 10 GB. I think it is somehow relaited to that fact, that the pagefile does not exist. The value is "0". Here is my code:
...
ObjectQuery pageFileUsageQuery =
        new ObjectQuery("SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage");
m_PageFileUsageSearcher = new ManagementObjectSearcher(managementScope, pageFileUsageQuery);
...
var pageFileUsageCollection = m_PageFileUsageSearcher.Get();
double currentUsage = 0;
double maxSize = 0;

foreach (ManagementBaseObject managementBaseObject in pageFileUsageCollection)
{
        string result = managementBaseObject["CurrentUsage"].ToString();
        currentUsage += double.Parse(result);
}

The system is Windows Server 2008 SP2. Maybe somebody has any ideas?
Comment: I think this will answer your question: http://stackoverflow.com/questions/11896282/c-sharp-using-clause-fails-to-call-dispose/11896367#11896367
Answer: ManagementObjectSearcher implements IDisposable(as does ManagementObjectCollection and ManagementBaseObject). You should dispose of these... perhaps with well placed using statements.
ObjectQuery pageFileUsageQuery =
        new ObjectQuery("SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage");
using(m_PageFileUsageSearcher = new ManagementObjectSearcher(managementScope, pageFileUsageQuery))
{
    ...
    using(var pageFileUsageCollection = m_PageFileUsageSearcher.Get())
    {
        double currentUsage = 0;
        double maxSize = 0;

        foreach (ManagementBaseObject managementBaseObject in pageFileUsageCollection)
        {
            try
            {
                string result = managementBaseObject["CurrentUsage"].ToString();
                currentUsage += double.Parse(result);
            }
            finally
            {
                managementBaseObject.Dispose();
            }
        }
    }
}

Comment: :( Unfortunately it didn't help.
Comment: No success. I've disposed all objects and memory add on every cycle by 8kB. See the same problem by this post. https://stackoverflow.com/questions/8922601/wmi-memory-leak-solution
Answer: As per comment above by michael-graczyk, there is a bug in the Dispose of …
Calling GC.WaitForPendingFinalizers() once is enough to fix it
though we do not consider it a solution really, just a workaround.


How to cut a shape out of the middle of CALayer

Question: I'm not sure if this is possible but I have been trying to create a pause button out of CALayers. I have created a circle and can add the pause rectangles into the middle fine. However the pause lines are of a specified colour and I want them to be transparent to see through to the backgrounds view.
Currently I have a custom view, which has a circle layer and then the pause layers. Is there a way to cut out the rectangles from the circle layer so whatever view it is placed on shows through there
Thanks in advance
Comment: Have you looked at the `mask` property? How far did that get you?
Comment: I created a small rect using CAShapeLayer and set this as the .mask property for the circle layer, but then all but the line disappeared, as its obviously clipping anything outside that lines path
Comment: Did you try and [search for something like "calayer invert mask"](http://stackoverflow.com/search?q=calayer+invert+mask) and look at those results? The [very first search result](http://stackoverflow.com/a/15376745/608157) seems to be what you are asking for.
Comment: Not sure how i missed that one, just having a look at it now, thanks!
Answer: You can fill the pause rectangle with transparent color.
<code>[layer setFillColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:.7].CGColor];
</code>
or
<code>CGContextSetFillColorWithColor(cpntext, [UIColor colorWithRed:1 green:0 blue:0 alpha:.7].CGColor);
</code>
see the .7 alpha i used.
For example below code creates a transparent rectangle
<code>    CAShapeLayer *layer =[CAShapeLayer layer];
    [layer setFrame:CGRectMake(0, 0, 100, 100)];
    UIBezierPath *path =[UIBezierPath bezierPathWithRect:CGRectMake(20, 20, 20, 80)];

    [layer setFillColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:.7].CGColor];
    [layer setPath:path.CGPath];
    [self.view.layer addSublayer:layer];
</code>


qqplot result and normality for ANOVA

Question: The independent variable is promotion, and it is assigned to 3 groups. The dependent variable is sales revenue. I have 172 observations of sales revenue for promotion group 1, 188 for group 2 and 188 for group 3.
With this dataset, I want to know which promotion is more effective at increasing sales revenue.
I first thought of doing ANOVA with Tukey test to answer the question.
To see whether to do ANOVA I checked the normality assumption with qqplot and the plot seems to tell me that residuals are a bit bimodally distributed and Shapiro-Wilk's null hypothesis is rejected as well (Is the sample size is too big for shapiro-wilk test?).
I want to know if I can continue to do ANOVA with the data. If not, what statistical analysis is best for this case? Also, when the sample size is only 22 with the same qqplot result (say, null hypothesis of Sapiro-Wilk is not rejected) , can I do ANOVA?

Thanks!
Comment: It seems you have the following data: three types of promotions with about 180 observations of sales revenue per promotion type. What question(s) do you want to ask of your data and what assumptions are you willing to make?
Comment: @dipetkov oops, sorry for an incomplete info. about the case. I will edit the article. Yes, about 180 observations of sales revenue per promotion type (172, 188, 188) and I want to know whether promotion is effective at increasing sales revenue, and if so, which promotion type is more so. Thanks!
Comment: Is one of the three types of promotion "no promotion"? Or in other words, is one of the types a natural reference level to compare the other two groups against?
Comment: @dipetkov No, it's not a natural reference level. all promotion types are with sales revenue, and there is no sales revenue information without any promotion.
Comment: Then it's not possible to answer the question "does promotion increase sales". But you can compare your three promotion strategies for relative effectiveness.
Comment: @ yeah, but can I do ANOVA despite a bit of bimodality?
Comment: Before trusting an ANOVA I'd want to see residuals by group. What is the source of the bimodality? // Of course, nothing can stop you from pushing _Enter_ on an ANOVA procedure in whatever software you're using. But to what purpose? Maybe try Kruskal-Wallis?
Comment: @BruceET Thanks for your comment. I am doing Kruskal right now, but I am worried about post-hoc test. I guess I can do Fisher's LSD (since I have 3 groups) or Dunn's test but have little knowledge about them. Now I am searching and studying but can u please recommend one so that I can include it in my study list?
Comment: Fisher's LSD or Tukey's HSD would be _ad hoc_ tests for ANOVA. Dunn for K-W.
Answer: You don't need ANOVA (and its distributional assumptions) to compare three groups. You can use the Kruskal-Wallis test to check whether the three promotions have the same revenue distribution. Validity of assumptions aside, both the parametric (ANOVA) and the non-parametric (Kruskal-Wallis) tests only tell you whether to accept or reject the null hypothesis that the three promotion strategies have the same effect on revenue. If the null hypothesis is rejected, you don't actually learn which promotion is most effective.
Then you dive deeper and test the pairwise differences among the groups. However, it is possible that all pairwise comparisons are insignificant even though the overall test is significant, or the other way around. You also have to consider how to adjust for doing all these tests. See here and here.
Instead of hypothesis testing you can do estimation. Here is how this analysis might proceed in three steps.
Start by plotting your data. Three (aligned) histograms, one for each promotion strategy, will be wonderfully informative and show if the revenue distributions are qualitative different and how. The how cold be important since a promotion might increase sales on average or perhaps it might induce a few customers to spend a lot more.
Say the exploratory data analysis suggests to compare the center of the revenue distribution. Then you can decide to use the mean (sensitive to big spenders) or the median (more robust). You choose the median.
Finally you use the bootstrap to estimate the median revenue for each promotion strategy. This will give you so much more information than an accept/reject statement of the null hypothesis that the promotion strategies are equally effective.
Comment: This is a very interesting thing to study about. But, the purpose of analysis is limited to finding out which promotion is relatively more effective only, and how much more is not included. But, still, I honestly did not know about estimation steps you mentioned here. Very helpful for my own study. Thank you so much.
Comment: I've done a bit of research on bootstrap and I think it's really interesting! But, I get to have a lot of questions. I got the result from kruskal + dunn that median difference between type 2 vs. 3 and type 2 vs. 1 are significant, and by looking at the median of type 1, 2, 3 I got to conclude that 1 and 3 are more effective than 2. What if I continue the analysis to find out 'how much more' with bootstrap? Is it a good idea to find out the statistical significance from traditional test then use bootstrap? (kruskal + bootstrap combination)

qqplot result and normality for ANOVA


Show that $2n\choose n$ is divisible by $2n-1$

Question: I have found many questions asking to prove $2n\choose n$ is divisible $2$, but I also observed by trying the first few "$n$" that $2n\choose n$ is divisible  by $2n-1$.
It sure seems true when $2n-1$ is prime, but is it true in general for all $n$?
Comment: Hint:  math induction on $n$.
Comment: Looking at the binomial coefficient definition according to the binomial theorem shows its definitely true if 2n-1 is prime
Answer: Catalan's numbers $\{ C_n\}_{n \ge 1}$ are defined by
$$C_n=\frac{1}{n+1}\binom{2n}{n}$$
these are known to be integers for all $n \ge 1$.
Now, for $n \ge 2$,
$$\binom{2n}{n}=\frac{2n \cdot (2n-1) \cdot ((2n-2)!)}{n \cdot ((n-1)!) \cdot n \cdot ((n-1)!)} = 2 \cdot \frac{1}{n} \binom{2n-2}{n-1} \cdot (2n-1) = 2C_{n-1} \cdot (2n-1)$$
This shows that $(2n-1)$ always divides $\binom{2n}{n}$, and the quotient is $2C_{n-1}$.
Comment: An easy proof that $C_n$ is an integer is that $C_n = \binom{2n}{n} - \binom{2n}{n-1}$.
Comment: And I almost put a comment "Catalan Numbers related but not the same" and pulled it because I was sure there would be a link ... great answer.
Answer: Since
$$
\binom{2n}{n}=2\frac{2n-1}n\binom{2n-2}{n-1}
$$
we get
$$
2n\binom{2n}{n}=4(2n-1)\binom{2n-2}{n-1}
$$
and therefore,
$$
\bbox[5px,border:2px solid #C0A000]{\binom{2n}{n}=\left[4\binom{2n-2}{n-1}-\binom{2n}{n}\right](2n-1)}
$$
Answer: The case when $2n-1$ is prime is trivial. This is true, as we know that $\binom{2n}{n}$ is integer, so then we have that
$$\binom{2n}{n} = \frac{(2n)!}{(n!)^2} = \frac{(n+1) \cdots (2n-1)\cdot 2n}{n!}$$
and $2n-1$ doesn't appear in the prime factorization in the denominator.
Now assume that $2n-1$ is composite and $p$ is a prime divisor of it. Obviously we must have $p \le \frac{2n-1}{2} \implies p < n$. Then if $p \mid m \le n$ we get that $m$ contributes in the prime factorization of $(n!)^2$ twice, but similarly $m$ and $2m$ contribute by at least the same amount in $(2n)!$. Obviously $2n-1$ can't be equal to $m$ ($m \le n$) nor to $2m$ ($2n-1$ is odd), so the numerator has at least one more contributor of $p$. So we get that $p^k \mid \binom{2n}{n}$, where $k$ is the highest power of $p$ dividing $2n-1$. This is true for every prime divisor of $2n-1$, so we get
$$2n-1 \mid \binom{2n}{n} $$
Hence the proof.
Answer: $$\frac{\binom{2n-1}{n-1}}{2n-1}\in\mathbb N.$$
See here: To prove $n\binom{2n-1}{n-1}$ is divisible by $n(2n-1)$
Thus, $$\frac{\binom{2n}{n}}{2n-1}=2\cdot\frac{\binom{2n-1}{n-1}}{2n-1}\in\mathbb N$$
Answer: Note that $\dbinom{2n}{n}$ is an integer. Note also that $1$ divides $\binom  21 $ and assume $n>1$ hereafter.
$\begin{align}
\dbinom{2n}{n} &= \dfrac{2n!}{n!\cdot n!} \\ &= \dfrac{2n\cdot (2n-1)\cdots (n+1)}{n\cdot (n-1)\cdots 1}\\
&= \dfrac{(2n)(2n-1)}{n\cdot n}\dbinom{2(n-1)}{n-1}\\
&= 2\dfrac{2n-1}{n}\dbinom{2(n-1)}{n-1}\\
\end{align}$
Now $\gcd(2n-1,n)=1$ so $n$ must divide  $2\dbinom{2(n-1)}{n-1}$, that is, $2\dbinom{2(n-1)}{n-1}= kn$ for some integer $k$.
Then $\dbinom{2n}{n} = k(2n-1)$ as required.
Answer: Simply expand  and seperate the factorial in the numerator.

Clearly,  is a factor in the numerator. Therefore,  is indeed divisible by .
Comment: This leaves open whether there are sufficient divisors of $2n{-}1$ in the denominator to mean that the result is not divisible by $2n{-}1$.