Handlebars helper - object not working

Question: I am iterating through an array controller to display items - and within this view I am trying to perform a custom Handlebar helper with the context of the current address - however within my helper, the object is undefined.
View:
{{#each temporaryUser.addresses}}
    {{#view App.AddressView addressBinding="this"}}
        {{addressActions view.address}}
        {{{view.address.display}}}
        Delete
    {{/view}}
 {{/each}}

Handlebars.registerHelper('addressActions', function (address) {
    var display = '
';

    if (address.current && address.permanent) {
        display += '
This is my current residential, and permanent address:
';
    }
    else if (address.current && !address.permanent) {
        display += '
This is my current residential address:
';
        display += 'Make permanent residential address';
    }
    else if (!address.current && address.permanent) {
        display += '
This is my permanent address:
';
        display += 'Make current residential address';
    }
    else {
        display += 'Make current residential address
';
        display += 'Make permanent residential address';
    }
    display += '
';

    return new Handlebars.SafeString(display);
});

Answer: This is not the way a helper works. You need to fetch the context yourself from an options object:
Ember.Handlebars.registerHelper('addressActions', function(path, options) {
  // passed context objects are stored in options.contexts
  // as you are only passing one context, it is the first one in the array
  var address = options.contexts.objectAt(0);
}

It works this way, since you may be passing multiple contexts to your helper.
Comment: Your way doesn't work. I got a similar helper working with: `Ember.Handlebars.helper('ternary', function(condition, a, b) {
  return condition === 'true' ? a : b;
});`, which I made up from combining various documentations...

Handlebars helper - object not working


Devo criar uma class para cada "input", ou apenas métodos de uma class "form" são o suficiente?

Question: Pois bem, estou com uma dúvida lógica. Comecei a aprender PHP OO recentemente, então essa questão é mais para fins educativos do que qualquer outra coisa.
Meu objetivo é criar uma class "form" que irá construir formulários HTML. Esta class terá atributos como "id", "name", "method" e "action" e métodos como openForm() - para iniciar o formulário com tais atributos, closeForm() - para fechar o formulário, e os padrões como set e get para os atributos.
Minha ideia inicial era criar métodos para cada input deste formulário nesta mesma class, como por exemplo newInputText(), que criaria um input do tipo texto, newButtonSubmit(), que criaria um botão submit e assim por diante (vale notar que cada um destes métodos teria seus próprios parâmetros HTML como "id", "name", "class" e assim por diante).
Minha dúvida é: a criação dos inputs e buttons, por exemplo, deve se dar através de métodos da class "form", OU eu deveria criar uma nova class separada para cada um deles, com seus próprios atributos e métodos? Qual seria a forma mais "otimizada" para tal aplicação?
Exemplo hipotético de código:
$form1 = new Form("teste", "teste", "#");

$form1->openForm();

$form1->newInput("input1", "input1", "Oi");
$form1->newButtonSubmit("btnSend", "btnSend", "Enviar");

$form1->closeForm();

Comment: Costuma ser interessante você generalizar primeiro para depois especificar. Por exemplo, ter o método `Form::input` que gera a *tag* `input`, sendo capaz de lidar com todos as suas propriedades, como método genérico; e, se desejado, criar outros como `Form::inputText` e `Form::inputPassword` que utilizam o método genérico, definindo as propriedades necessárias.
Comment: Normalmente os frameworks usam métodos estáticos pq não tem necessidade de guarda valores, fica algo como `Form::input(array('name' => 'nome', 'id' => 'nome', 'class' => 'css-input'))`
Comment: Tente trabalhar com o uso de Namespaces e Princípio da Responsabilidade Única (onde uma classe deve ter apenas UMA responsabilidade). Pois assim você terá um maior reaproveitamento de código e a manutenção fica menos dolorosa.
Answer: "Devo criar uma class para cada "input", ou apenas métodos de uma class "form" são o suficiente?"
O paradigma OO é usado por diversas linguagens.
Ele tem o objetivo de ser extensível e fz com q o programador escreva (-)código.
Os frameworks oo(PHP) existem pra serem utilizados, seguindo suas apis.
Estude a API pra não passar trabalho "reinventando a roda".
Tenho certeza q a API do frm q vc usa já resolveu este problema q vc tem.
*Eu começaria dando uma olhada na documentação da "class Form".
Pra descobrir quais métodos ela possui q são úteis p seu propósito.
Quase sempre tem exemplos úteis p ajudar a entender.
Reinventar a roda é sempre 1 decisão ruim.
Pode n dar problema hoje, mas vai dar amanhã.


Necessity of the Hahn Banach Theorem for the Gateaux Mean Value Theorem

Question: The following theorem is in Drabek, Milota's Nonlinear Analysis. Like Drabek and Milota, I won't assume a priori Gateaux differentials are continuous nor linear.
Theorem. Let $X,Y$ be normed spaces, and $f: X \rightarrow Y$ a map (perhaps not continuous). Fix $a,b \in X$. Suppose that the Gateaux differential $df(a+t(b-a); b-a)$ exists for all $t \in [0,1]$. Then, we have the estimate
$$ ||f(b)-f(a)||_Y \leq \sup_{t \in [0,1]} ||df(a+t(b-a) ; b-a) ||_Y.$$
The proof uses the Hahn-Banach Theorem (or a corollary thereof) by taking a linear functional $\varphi \in X^*$ such that $||\varphi||_{X^*}=1$ and $\varphi(f(b)-f(a)) = ||f(b)-f(a)||$.
I would like to know if the use of the Hahn-Banach Theorem - or more generally, the Axiom of Choice - is needed to prove the theorem (that is, does there exist a proof that does not make use of choice principles)? I would also be interested in weaker choice principles, such as dependent or countable choice.
I have also tried to modify the argument I saw in Cartan's Differential Calculus in the proof of the Mean Value Theorem for differentiable maps $[a,b] \rightarrow Y$, $Y$ a normed space (the argument requires no choice principles); see Theorem 3.1.1, page 37-39 in Cartan. Somewhat in analogy to Cartan's argument, I have tried to define
$$E= \{t \in [0,1] | \text{ for every neighbourhood } U \text{ of } 0, \text{ there is } p \in U \text{ such that } |p| ||f(b)-f(a)||_Y > ||f(a+t(b-a) + p(b-a)) - f(a+t(b-a)) ||_Y \}.$$
Then perhaps one could show $E$ is open in $\mathbb R$ and one notes that $\inf E \notin E$. I am not sure exactly how to proceed to obtain a contradiction (as in Cartan's proof), however. My ideas for this attempt aren't well-formed, but I thought it would be useful to mention Cartan's proof.
Perhaps this stackexchange question is also useful: Does one need the Hahn-Banach theorem to prove the mean value inequality for maps into a normed space?, though I'm interested in the version of the Mean Value theorem involving Gateaux derivatives as stated above.
Thanks in advance.
Edit: for reference, I'll include Cartan's Theorem here and a sketch of the proof. (The theorem is stated for Banach $Y$, but completeness is in fact unnecessary). It is the proof of Theorem 3.1.1 I have tried to modify to my particular case, but it seems that I am unsure how to proceed.
Theorem (Cartan, 3.1.1). Let $Y$ be normed, let $f:[c,d] \rightarrow Y, g:[c,d] \rightarrow \mathbb R$ be maps. Suppose that the right derivatives $f'_{+}, g'_{+}$ exists at all points in $(c,d)$, and assume that $||f'_{+}(x)|| \leq g'_{+}(x)$ for all $x \in (c,d)$. Then, $$||f(d)-f(c)|| \leq g(d)-g(c).$$
Sketch: Following Cartan, one fixes $\varepsilon>0$ and puts $$U = \{x \in [c,d] | ||f(x)-f(c)|| > g(x)-g(c)+ \varepsilon(x-c) \}.$$ Aiming for a contradiction, suppose $U$ is not empty. Then, $U$ is open and let us define $\alpha= \inf U$; then, $\alpha \notin U$, and in fact, $\alpha>c$. By the existence of the right derivatives, there is a $\delta>0$ such that for any $\alpha<t<\alpha+\delta$, one has
$$ - \frac{\varepsilon}{2} + \left | \left | \frac{f(t)-f(\alpha)}{t-\alpha} \right | \right | \leq || f'_{+}(\alpha) || \leq g'_{+}(\alpha) < \frac{g(t)-g(\alpha)}{t-\alpha} + \frac{\varepsilon}{2}.$$ It follows that $||f(t)-f(\alpha)|| < g(t)-g(\alpha) + \varepsilon(t-\alpha)$ for every $\alpha<t<\alpha+\delta$.
Since $\alpha \notin U$, we also have $||f(\alpha)-f(c)|| \leq g(\alpha)-g(c)-\varepsilon(\alpha-c)$. If $t \in (\alpha, \alpha+\delta)$, then
\begin{align*} ||f(t)-f(c)|| &\leq ||f(t) - f(\alpha)|| + ||f(\alpha)-f(c) || \\
& \leq (g(t)-g(\alpha) + \varepsilon(t-\alpha) ) + (g(\alpha)-g(c)+ \varepsilon(\alpha-c) \\
&= g(t)-g(c)+\varepsilon(t-c).
\end{align*}
So, $(\alpha, \alpha+\delta) \cap U = \emptyset$ and supposedly $\alpha = \inf U$, which is impossible. So in fact $U=\emptyset$, and thus $b \in U^c$, from which it follows $||f(b)-f(a)|| \leq g(b)-g(a)+\varepsilon(b-a)$ and $\varepsilon$ was arbitrary. $\blacksquare$
Remark: the Theorem remains true if right differentiability is assumed for all but countably many points in $(c,d)$.
Corollary (Cartan, 3.3.1). Let $X,Y$ be normed, let $f:U \rightarrow Y $ be a map (where $U \subseteq X$ is open and not empty) and fix $x,y \in U$. Suppose the line segment between $x$ and $y$ is contained in $U$, and suppose that $f$ is Frechet differentiable on $U$. Then, $$||f(x)-f(y)||_Y \leq \sup ||f'(\zeta)||_Y ||x-y||_X,$$ where the sup is taken over the line segment between $x$ and $y$.
(The corollary follows from applying Theorem 3.1.1 to $g:= f \circ \psi$, where $\psi:[0,1] \rightarrow X, t \mapsto tx+(1-t)y$).
Comment: Do I get it correctly that the only difference between the Theorem in your question and Cartan's Theorem 3.1.1 is that you do not have the continuity of $f$?
Comment: What is precisely your definition of Gateaux derivative? Does it involve a one-sided or a two-sided limit?
Comment: Let $f:X \rightarrow Y$ be a map of real or complex normed spaces, and let $x_0, h \in X$. Then, if the limit $\lim_{t \to 0} \frac{f(x_0+th)-f(x_0)}{t}$ exists, I will either say the Gateaux differential exists or that the directional derivative of $f$ at $x_0$ in direction $h$ exists (I use both terms synonymously), and I denote this limit by $df(x_0 ; h)$. The limit here is a two sided limit if $X$ is a real vector space. I will state it explicitly if I assume that the map $h \mapsto  df(x_0; h)$ is continuous or linear, but I don't take this as part of the definition.
Comment: (Comment continued) Cartan's Theorem is a result for differentiable maps on the compact interval $[c,d] \subseteq \mathbb R$ that map into a normed space. Cartan proves as a corollary of 3.1.1 the mean value theorem for Frechet derivatives (Thm. 3.3.1 I believe). Yes, the theorem in my question is only concerned with the line segment with endpoints $a,b \in X$, and yes I do not assume continuity of $f$. Though I am unsure how or if it is possible to give a choiceless proof. I'm not sure if I answered your question, so don't hesitate to let me know if you need more clarification.
Answer: Let us define the function $\varphi : \mathbb{R} \to Y$ via
$$ \varphi(t) := f( a + t \, (b-a)).$$
Since the Gateaux differential $df ( a + t \, (b-a); b-a)$ exists for all $t \in [0,1]$, we have that $\varphi$ is differentiable at $t \in [0,1]$ with
$$ \varphi'(t) = df( a + t \, (b-a); b-a).$$
This follows directly from the definition. From this, we infer that $\varphi$ is continuous on $[0,1]$. Now, you can apply Theorem 3.1.1 from Cartan.


How to link subdirs lib with QMake?

Question: I have a Qt project (called "scanner") built with QMake, where I have 2 subprojects : a static library called "scannerlib" and an application using that lib, called "app" (which, at the moment, is just a main.cpp file)
My "scanner" folder contains the file scanner.pro :
QT += core testlib
QT -= gui

CONFIG += c++14
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = subdirs

SUBDIRS = app scannerlib

app.depends = scannerlib

And two subfolders, containing a .pro file and source file related.
scannerlib/scannerlib.pro :
TARGET = scannerlib
TEMPLATE = lib
CONFIG += staticlib

#I ommited SOURCES and HEADERS here for brevity

app/app.pro :
TARGET = app
TEMPLATE = app
SOURCES = main.cpp
INCLUDEPATH += ../scannerlib
LIBS += -L../scannerlib -lscannerlib

I successfully build libscanner, but I can't link it in "app".

error : cannot find -lscannerlib

After checking, libscannerlib.a has been successfully built, so it should not be a problem.
If I remove -lscannerlib, I get an undefined reference. Which seems legit.
I can get a successful build if I move the created "libscannerlib.a" from the build folder to scanner/scannerlib, which allows qmake to find it.
So, the problem looks like it comes from "-L../scannerlib". What should I put there in such a way that qmake find the lib in the build folder ?
Answer: You may use DESTDIR in your both scannerlib and app projects.
scannerlib/scannerlib.pro :
TARGET = scannerlib
TEMPLATE = lib
CONFIG += staticlib
DESTDIR = ../bin

app/app.pro :
TARGET = app
TEMPLATE = app
SOURCES = main.cpp
DESTDIR = ../bin
INCLUDEPATH += ../scannerlib
LIBS *= -L$$OUT_PWD/$$DESTDIR -lscannerlib

Comment: need to use `$$PWD/../bin` instead `../bin`, dont know why.

How to link subdirs lib with QMake?


Studies showing the brain chemical reactions when listening to depressive music

Question: I have been listening for some time "classical"(not the proper meaning of the word) music. Many works, such as Schubert's, capture incredibly well the feeling of sadness. Other works seem to create joy(Vivaldi's Spring from Four Seasons) and other such as Mozart's 25th symphony seem to induce a state of mind that is neither joyful or sad. On a neurological level, what is happening when one listens to depressive music? Are there any studies conducted?
The reason for asking this question is that I feel, as the ancient greeks did, that music enchants humans, and thus having a very powerful effect on the brain, say, capable of transforming a multi-millionaire into a hobo.
Comment: Historically, music has been much more efficacious at turning hobos into multi-millionaires.  For turning multi-millionaires into hobos, you want heroin.
Comment: @Codeswitcher Your statement kind of gets me on the wrong foot with you since it should suggest that the entertainers referred to as artists today are musicians. I can't see how you would gain anything material from music.
Answer: Currently there are a few hundreds of medical / scientific works devoted to the effect of music on depression. You can see the full list (and have some access to abstracts) in NCBI PubMed database, and some (like this one) are even specifically focused on Mozart.
From the works, looks like music actually helps people to withstand stress and depression. Also sad songs were invented to help psychologically; nobody would create or sing them if doing so would make to feel worse.
Comment: I have provided the PubMed link to show scientific works annotated with both "music" and "depression" keywords. This definitely covers studies that have been mentioned in the question but may also include some non relevant results.
Comment: The questioner didn't ask about the effect of music on depression.  The questioner asked about the effect of putatively depressogenic music on presumably non-depressed subjects.
Answer: I don't have an answer, but I have a pointer to likely source for an answer: Robert Jourdain's Music, The Brain, and Ecstasy: How Music Captures Our Imagination is likely the book you are looking for.
(I would be more specific, but I can't find my copy at the moment.)
Comment: @MeaningfulUsername I recall thinking _This Is Your Brain On Music_ was a perfectly fine book, but it didn't make much of an impression on me past that.  (I find most popular press books about music pretty cringe-inducing, so that's actually higher praise than it sounds.)
Comment: Looks interesting! Didn't have it at my local library, so I'll check out [This is your brain on music](http://www.amazon.com/This-Your-Brain-Music-Obsession/dp/0452288525), which also seems related. I can recommend [Musicophilia](http://www.amazon.com/Musicophilia-Tales-Revised-Expanded-Edition/dp/1400033535/), which is about how certain conditions alter the perception and appreciation of music. Very interesting, and can help in understand what music does to people, and how strange this obsession really is.


Ajuda com exercício

Question: Alguém pode me ajudar a corrigir este exercício? Estou tentando finalizar estas linhas e não consigo:

module.exports = function restaurantBill(bill) {

/*
  1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
  de multiplique a conta em 10%.
*/

var tax = restaurantBill*0.10;

/*
  2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
  mais impostos
*/

var total = restaurantBill+tax/5;

/*
  3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
  símbolo $ antes (por exemplo: $ 11).
*/

return "$"+total;
};

Observações:
Imagine que você saiu para comer com seus quatro melhores amigos. A conta total de consumo é de 50 reais, mas para isso você deve adicionar 10% de imposto. Você quer dividir a conta igualmente entre os cinco.
Para isso você criou este programa.
Siga as etapas abaixo para completar o programa e determinar quanto deve pagar cada um.

Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado de multiplique a conta em 10%. Dica: 10% em decimal é escrito 0,10.
Crie uma variável chamada total e atribua-lhe o resultado da adição de conta mais impostos
Retorne o valor que cada um deve pagar (total dividido por 5), com o símbolo $ antes (por exemplo: $ 11). Dica: você deve usar a cadeia de caracteres (concatenação de strings) para imprimir com o símbolo $ adiante.

Exemplo:
var output = restaurantBill(50);
console.log(output); // --> $11

Comment: tem parte q deveria ser do comentario, mas n está com o // pra escapar do resto dos comandos
Comment: Dá algum erro na tela?
Um detalhe interessante é em ``restaurantBill+tax/5``, que deve ser ``(restaurantBill+tax)/5`` (senão ele vai fazer tax/5 e depois somar restaurantBill. Ou ainda colocar a divisão em ``return "$"+total/5;``
Comment: Não deixe de marcar a pergunta escolhida como aceita. Veja como em https://i.stack.imgur.com/evLUR.png e veja porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Olá Pessoal! Graças a Vocês consegui finalizar e identificar o meu erro! Muito obrigada! Abraço!
Answer: Você está usando a própria função para fazer o cálculo! Para obter o retorno certo, você deve passar nas fórmulas o parâmetro que a função recebe, que no caso é  bill.
Corrigindo seu código, ficaria:
module.exports = function restaurantBill(bill) {

    /*
      1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
      de multiplique a conta em 10%.
    */

    var tax = bill*0.10;

    /*
      2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
      mais impostos
    */

    var total = (bill+tax)/5;

    /*
      3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
      símbolo $ antes (por exemplo: $ 11).
    */

    return "$"+total;
};

Comment: var total = (bill+tax)/5;
Comment: Verdade @LeoCaracciolo! Tinha apenas copiado o código, vou alterar aqui! (:
Comment: Outra coisa, como se faz para chamar a função?
Comment: você pode chama-la da seguinte forma: `restaurantBill(20)` dentro do script!
Comment: Acredito que vá dar um erro `message": "Uncaught ReferenceError: module is not defined",`
Comment: Sim, terá que fazer um `import { restaurantBill } from 'nome-arquivo';` correto?
Comment: https://pt.stackoverflow.com/questions/55084/quando-usar-module-exports-ou-exports-no-node-js
Comment: Olá Pessoal! Graças a Vocês consegui finalizar e identificar o meu erro! Muito obrigada! Abraço!
Answer: Erros na sua função: Usando a própria função nos cálculos.
Ao invés de var tax = restaurantBill*0.10;
pode ser var tax = restaurantBill.arguments[0]*0.10;
Ao invés de var total = restaurantBill+tax/5;
pode ser var total = (restaurantBill.arguments[0]+tax)/5;
Eu digo "pode" porque há outra alternativa a exemplo das outras repostas aqui publicadas. Mas achei que deveria ampliar o leque de opções.

Quando uma função recebe valores de parâmetro da instrução que invoca a função, esses valores de parâmetro são atribuídos silenciosamente à propriedade arguments do objeto function. Essa propriedade é um array de valores, com o valor de cada parâmetro sendo atribuído a uma entrada de índice baseado em zero no array - mesmo que não haja parâmetros definidos. Você poderá usar a notação de array (nomeFunção.arguments[i]) para extrair os valores de quaisquer parâmetros que desejar.

Veja o exemplo abaixo onde os parâmetros são valor e quantidade de pessoas

function restaurantBill(bill) {

   return "$"+((restaurantBill.arguments[0]+(restaurantBill.arguments[0]*.10)))/restaurantBill.arguments[1];

};
console.log (restaurantBill(50,5));

A seguir seu script funcionando:

    function restaurantBill(bill) {
        /*
          1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
          de multiplique a conta em 10%.
        */
        var tax = restaurantBill.arguments[0]*0.10;

        /*
          2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
          mais impostos
        */

        var total = (restaurantBill.arguments[0]+tax)/5;

        /*
          3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
          símbolo $ antes (por exemplo: $ 11).
        */

         return "$"+total;

    };
    var output = restaurantBill(50);
    console.log(output); // --> $11

Outra forma:

    function restaurantBill(bill) {
        /*
          1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
          de multiplique a conta em 10%.
        */
        var tax = bill*0.10;

        /*
          2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
          mais impostos
        */

        var total = (bill+tax)/5;

        /*
          3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
          símbolo $ antes (por exemplo: $ 11).
        */

         return "$"+total;

    };
    var output = restaurantBill(50);
    console.log(output); // --> $11

A sintaxe formal para uma função é a seguinte:
 function nomeFunção ( [parâmetro] ....[parâmetro]) {
    instrução(ões)
 }

Os parâmetros (também conhecidos como argumentos) oferecem um mecanismo para "entregar" um valor de uma instrução para outra por meio de uma chamada de função.
Quando uma função recebe parâmetros, ela atribui os valores recebidos aos nomes de variável especificados nos parentesis da definição da função.
Considere o seguinte segmento de script:
function restaurantBill(bill) {
 alerta(bill);
}
restaurantBill("Yra Rodrigues");

Após a função ser definida no script, a próxima instrução chama essa mesma função, passando uma string (Yra Rodrigues) como parâmetro. A definição da função atribui automaticamente a string à variavel bill. Portanto, antes que a instrução alert() dentro da função seja executada, bill é avaliada como Yra Rodrigues

Conclusão: use bill e não restaurantBill dentro da função!!!
errado bill+tax/5; vai somar bill com a divisão de tax por 5
correto (bill+tax)/5; vai dividir por 5 a soma de bill + tax

sem muitas delongas pode-se fazer assim

function restaurantBill(bill) {

   return "$"+((bill+(bill*.10)))/5;

};
console.log (restaurantBill(50));
Comment: Creio que atribuir a função à uma variável possa acabar confundindo mais ainda alguém que está começando os estudos em Javascript.
Comment: Tanto faz, ela fez isso na chamada da função `var output = restaurantBill(50);`
Comment: Olá Pessoal! Graças a Vocês consegui finalizar e identificar o meu erro! Muito obrigada! Abraço!
Answer: Você cometeu alguns erros no seu código, mas nada que seja para se flagelar.

Você não precisa usar o module.export no seu código por momento, ainda mais para um exercício tão simples.
Veja que ao fazer os cálculos, ao invés de chamar o parâmetro da função que seria (bill) você esta chamando a própria função em si.
Quando for fazer contas onde haja uma mutiplicação ou uma divisão e você precise atribuir uma taxa ao valor total antes de dividi-lo, não se esqueça de usar parenteses, para que ele faça a adição primeiro antes da divisão.
var total = (bill + tax) / 5;
De mais você estava no caminho correto, so faltou atribuir uma nova variável para receber o resultado de retorno da função e depois apresenta-lo via console.log.

Segue o código abaixo, abraços.
   function restaurantBill(bill) {

/*
    1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
    de multiplique a conta em 10%.
*/

var tax = bill * 0.10;

/*
    2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
    mais impostos
*/

var total = (bill + tax) / 5;

/*
    3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
    símbolo $ antes (por exemplo: $ 11).
*/

return "$" + total;
};

var output = restaurantBill(50);
console.log(output);

Comment: Olá Pessoal! Graças a Vocês consegui finalizar e identificar o meu erro! Muito obrigada! Abraço!
Answer: Você estava chamando a função dentro dela mesma, e na hora da divisão não fez a soma antes, confira agora se da certo:
var module = function restaurantBill(bill) {
    /*
      1. Crie uma variável chamada tax (imposto em inglês) e atribua-lhe o resultado
      de multiplique a conta em 10%.
    */

    var tax = bill*0.10;

    /*
      2. Crie uma variável chamada total e atribua-lhe o resultado da adição de conta
      mais impostos
    */

    var total = bill+tax;

    /*
      3. Retorne o valor que cada um deve pagar (total dividido por 5), com o
      símbolo $ antes (por exemplo: $ 11).
    */

    var result = "$ "+(total/5);

    return result;
};

Comment: Isso! Trocando o **restaurantBill** por **bill** resolve o problema. E a correção na divisão, claro.
Comment: Olá Pessoal! Graças a Vocês consegui finalizar e identificar o meu erro! Muito obrigada! Abraço!
Comment: como se faz para chamar a função?
Comment: chama o  `module()` dentro do `

Ajuda com exercício


Box Cox Transformation makes Out of sample Forecast Error worse?

Question: I am doing a regression on time series data. I have 60 lagged predictors which I will call x to predict a continuous variable y. I used the BoxCox function from the forecast package to transform y and then performed a linear regression of y on x. I did a one step ahead forecast over 5.5 months of data and found that the BoxCox function made the forecast error worse. I am using mae and rmse as critera for accuracy
It was better to simply perform no transformation. I am trying to reconcile this because I learned BoxCox in school and it was grilled into our heads that it is necessary to do but now it seems like it is a waste of time. Is my approach and conclusions about BoxCox right, or is simply that my data cannot benefit from BoxCox?
Comment: Ahhh .. But the statistical requirements are on the errors from a model and not the original data.thus transforming the original series can easily lead to a false positive conclusion (other than a Box-Cox lambda of 1.0 ) as the original data has not been conditioned on a useful equation ( other than a simple mean model ) . What I am saying here is that you can easily get a false (Box-Cox coefficient reading by analyzing the original data.
Comment: Your comment "I learned BoxCox in school and it was grilled into our heads" probably means that you were probably trained as an econometrician whom generally start with a model before they see the data rather than vice-versa or somewhere in between. Transformations are like drugs ... some are good for you and some are not. Please review http://stats.stackexchange.com/questions/18844/when-and-why-to-take-the-log-of-a-distribution-of-numbers for discussion that I think is relevant.
Comment: BoxCox is a wonderful transformation because it encompasses wide range of transformation such as log, reciprocal, square root, cube root and more importantly $ \textbf{no transformation}$. So if you user BoxCox transformation on the time series procedure correctly and if it doesn't require transformation, then box cox procedure should have recommended no transformation
Comment: @forecaster ...thus it is not a placebo i.e. no downside effects as you are stating but a possibly (probably !) a rather dangerous (false) alternative to a useful model thus confounding/confusing the subsequent model identification phase
Comment: .... see http://stats.stackexchange.com/questions/8955/advice-on-explaining-heterogeneity-heteroscedasticty and review @probabilityislogic superb comments about when and why to transform .
Comment: @Irishstat I 100% agree with you that transformation is necessary iff your linear parametric model violates normality assumption of the $\textbf{error term}$ that too if you are looking at p values, confidence interval. Otherwise there is no need for transformation
Answer:
It's difficult to respond to whatever you were actually taught because you don't give us access to it. If you had a quote or a reference or something...
I would be surprised if "Box-Cox is necessary" would have been presented as a general, unbending rule.

You present nothing of the criteria by which you judge the forecasts, but if, for example you use MSPE on the original scale (i.e. you transform back then measure performance using square error loss in predictions), then even when the Box Cox leads to exactly the right model you might still on that basis conclude it was worse.

Box Cox has parameters (at least 1, depending on what your model is and what you consider for transformation), so - as with adding parameters anywhere else - it may sometimes be advantageous and sometimes not -- even when it leads to the "correct" model it may lead to actually worse predictions, measured on either the original or the transformed scale.
Comment: Sorry I forgot to add, I am using mae and rmse as critera for accuracy.


Office Add-in development: Connect to SharePoint site and get data

Question: I would like to ask how would I make my Office add-in connect to SharePoint? I need to get all the document name uploaded in there and have it download the selected file.
Thanks!
Answer: You can access files stored in SharePoint and OneDrive via the Microsoft Graph. You can find information about this here - https://graph.microsoft.io/en-us/


Can pearson's correlation coefficient be converted to Cohen's kappa?

Question: I'm interested in meta-analysing the agreement between two measures. Depending on whether the variables are continuous/categorical/binary, different studies present agreement as either:

A Pearson's correlation coefficient (for continuous variables)
Intraclass correlation coefficient/weighted kappa (for categorical/ordinal variables)
Cohen's kappa (for binary variables)

I understand that intraclass correlation coefficient is equivalent to a weighted kappa under certain conditions, which increases the comparability between the ICC and kappa.
Is there a way to convert a Pearson's correlation coefficient to an equivalent of Cohen's kappa?
Comment: Even data are just binary (so correlation becomes the phi coefficient), correlation is not comparable with kappa. They differ in the denominator. So, if you don't have the 2x2 table itself, from which these associations are computed, you're at a deadlock.
Answer: Consider the following scenario
One rater rates the objects as 1,2,3
Second rater rates them 3,4,5
The correlation is 1 but the value of unweighted kappa is -0.12 and weighted (with quadratic weights) is 0.25
So, in general, they are not even close.
Credits: analysis done with function cohen.kappa from the R psych package and the cor function from R stats


Groups With Exactly One Maximal Subgroup

Question: I understand that when $G$ has exactly one maximal subgroup (inclusion-wise), then $G$ has to be cyclic.
But is it possible to determine all possible groups with exactly one maximal subgroup?
Comment: Is $G$ finite ?
Comment: It does not have to be. If $G$ is finite, I can prove that those are the groups of order $p^n$, for $n > 1$.
Comment: I don't understand the question. All maximal subgroups are proper by definition.
Comment: Ok, that is redundant.
Answer: If you know that the group must be cyclic then classifying all such groups is easy, at least in the finite case, because the lattice of subgroups of a cyclic group of order $n$ is isomorphic to the lattice of divisors of $n$. This lattice has a single maximal element (different from $n$) iff $n$ is a prime power.
Comment: BTW, here is a proof that if a finite group has exactly one maximal subgroup, then it must be cyclic: http://math.stackexchange.com/a/39954/589
Comment: A full proof is at http://groupprops.subwiki.org/wiki/Cyclic_of_prime_power_order_iff_not_generated_by_proper_subgroups.


Cartela de bingo em c

Question: Estava resolvendo um exercício da faculdade sobre matrizes e acabei travando.
Ex: Construa um programa para gerar automaticamente números entre 0 e 99 de uma cartela de bingo.
Sabendo que cada cartela deverá conter 5 linhas de 5 números, gere estes dados de modo que não tenha
números repetidos dentro das cartelas. O programa deve exibir na tela a cartela gerada.
Eu tentei resolver dessa forma :
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define n 5

int main ()
{
  int a[n][n],cont;

  srand(time(NULL));

      for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            a[i][j]==-1;
        }
    }
    // Preencher a matriz com valores n repitidos o "do/while" compararia td os valores da matriz e caso tenha repeticao aumemta um contador q executa o looping

    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            do
            {
                cont=0;
                a[i][j]=rand()%99;

                for (int l=0;l<n;l++)
                {
                    for (int c=0;c<n;c++)
                    {
                      if (a[i][j]==a[l][c] && (i!=l && j!=c))
                        cont++;
                    }
                }
             } while(cont!=0);
        }
    }

                for (int l=0;l<n;l++)
                {
                    for (int c=0;c<n;c++)
                    {
                       printf(" \t %d ", a[l][c]);
                    }
                    printf("\n");
                }

return 0;
}

Mas não funcionou e não tenho ideia de como resolver.
Comment: includes quais biblioteca?
Answer: Username 7873, montei uma função que talvez te ajude. A ideia é NÃO repetir os número nunca.
   Monto duas listas: Uma lista com todos os números que serão sorteados (essa lista sempre diminui de tamanho com .RemoveAt) e uma lista que receberá os números que já foram sorteados.
   No caso do BINGO são 75 NÚMEROS pois, são 15 números para cada letra! Desta forma: A Letra "B" vai de 1 até 15, a "I" vai de 16 até 30, a letra "N" vai de 31 até 45, a letra "G" vai de 46 até 60 e a letra "O" vai de 61 até 75.
   Depois eu vou RETIRANDO (.RemoveAt) os números de uma lista e sorteando com um número a menos (INDEX) o número interno da array permanece "inalterado" (os que já foram sorteados caem fora...).
   Detalhe... está em C#, mas acho que você conseguirá ter uma ideia. A função "SORTEIA" receberá sempre 1 número a menos para sortear...
public static List<Resultado> SorteiaNumeros(string StrNumero)
{
    List<int> strListaNumero = new List<int>();
    List<Resultado> strLista = new List<Resultado>();
    int intPosicaoSorteada;
    int IntContador = Convert.ToInt32(StrNumero);

    //Pegar todos os números que podem ser sorteados e colocar em uma lista.
    for (int i = 1; i <= IntContador; i++)
    {
        strListaNumero.Add(i);
    }

    // ir retirando os números da lista conforme o INDEX.
    do
    {
        intPosicaoSorteada = Convert.ToInt32(Sorteia(strListaNumero.Count.ToString()));

        strLista.Add(new Resultado
        {
            Posicao = (strLista.Count + 1).ToString(),
            Nome = Convert.ToString(strLista.Count + 1) + " - " + strListaNumero[intPosicaoSorteada - 1] + ".",
            Ordem = strListaNumero[intPosicaoSorteada - 1].ToString()
        });

        strListaNumero.RemoveAt(intPosicaoSorteada - 1);

    } while (strListaNumero.Count > 0);

    return strLista;
}

public static string Sorteia(string StrNumero)
{
    Random randNum = new Random();
    return randNum.Next(1, Convert.ToInt32(StrNumero) + 1).ToString();
}

Answer: eu fiz algumas alterações no seu codigo e parece ta funcionando
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
  int a[5][5], cont, i, j, c, l;

  srand(time(NULL));

    // Preencher a matriz com valores n repitidos o "do/while" compararia td os valores da matriz e caso tenha repeticao aumemta um contador q executa o looping

    for (i=0;i<5;i++){
        for (j=0;j<5;j++){
            do{
                cont=0;
                a[i][j]=rand()%99;

                for (l=0;l<5;l++){
                    for (c=0;c<5;c++){
                      if (a[i][j]==a[l][c] && (i!=l && j!=c)){
                      cont++;
                      }
                    }
                }
             } while(cont!=0);
        }
    }

                for (l=0;l<5;l++)
                {
                    for (c=0;c<5;c++)
                    {
                       printf(" \t %d ", a[l][c]);
                    }
                    printf("\n");
                }
    return 0;
}

Comment: User158513, sua resposta pode ser útil! porém ajudará mais o autor da pergunta se você  comentar o código com as melhorias realizadas

Cartela de bingo em c


Cálculo de Idade usando Period

Question: Tenho este código abaixo em Java que não compila e não consigo achar o erro. Já fiz as modificações orientadas e o número de erros passou para apenas 1.
O método calculoIdade e validarData retorna agora o tipo Period, mas ao executar ainda apresenta erro de tipo no método validarData.
import java.time.*;
import java.util.*;

public class Data {

  private int dia, mes, ano;
  String data;

  public void validarData() {

    if (dia > 0 && dia < 32 && mes > 0 && mes < 13 && ano > 0
        && ((mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12)
            || ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia <= 30)
            || (mes == 2 && (dia <= 29 && ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)) || dia <= 28))) {
      data = "Data válida";
    } else {
      data = "Data inválida";
    }
  }

  public Double calculoIdade(int dia,int mes, int ano) {
        if (validarData()) {
            LocalDate data = LocalDate.of(dia, mes, ano);
            LocalDate now = LocalDate.now();
            if (ano <= 2020) {
                Period diff = Period.between(data, now);
            }
        } else {
            System.out.println("Quantidade de dias excede o total de dias do mês");
        }
    }

  public void main(String[] args) {
    Scanner leia = new Scanner(System.in);
    System.out.print("Digite o dia: ");
    dia = leia.nextInt();
    System.out.print("Digite o mês: ");
    mes = leia.nextInt();
    System.out.print("Digite o ano: ");
    ano = leia.nextInt();
    System.out.println("Idade: %d anos, %d meses e %d dias", diff.getYears(), diff.getMonths(), diff.getDays());
    System.out.println(+dia + "/" + mes + "/" + ano + " " + data);
  }

}

Após as correções, o código ficou assim:
import java.time.*;
import java.util.*;

public class Main {

  private static int dia, mes, ano;
  private String  data;
  private Period diff;

  public Period validarData() {

    if (dia > 0 && dia < 32 && mes > 0 && mes < 13 && ano > 0
        && ((mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12)
            || ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia <= 30)
            || (mes == 2 && (dia <= 29 && ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)) || dia <= 28))) {
      data = "Data válida";
    } else {
      data = "Data inválida";
    }
  }

  public Period calculoIdade(int dia,int mes, int ano) {
        if (validarData()) {
            LocalDate l = LocalDate.of(dia, mes, ano);
            LocalDate now = LocalDate.now();
            if (ano <= 2020) {
                Period diff = Period.between(l, now);
            }
        } else {
            System.out.println("Quantidade de dias excede o total de dias do mês");
        }
    }

  public void main(String[] args) {
    Scanner leia = new Scanner(System.in);
    System.out.print("Digite o dia: ");
    dia = leia.nextInt();
    System.out.print("Digite o mês: ");
    mes = leia.nextInt();
    System.out.print("Digite o ano: ");
    ano = leia.nextInt();
    System.out.println("Idade: " + diff.getYears() + " anos, " + diff.getMonths() + " meses, "
                        + diff.getDays() + " dias");
    System.out.println(+dia + "/" + mes + "/" + ano + " " + data);
  }

}

Com isto, resultou apenas em 1 erro, conforme abaixo:
Main.java:24: error: incompatible types: Period cannot be converted
to boolean
        if (validarData()) {
                       ^
1 error

O que posso fazer?
Answer: O problema é que você fez if (validarData()), e a condição do if deve ser um boolean. Mas você declarou que o método validarData retorna um Period, que não é um boolean.
Outro detalhe é que o método  validarData não está retornando nada. Se você declarar que ele retorna algo, em algum ponto dele deve ter um return para retornar o valor.
Além disso, a variável diff que está no main não é a mesma que está dentro de calculoIdade. Variáveis criadas dentro de um método são locais ao método e não ficam visíveis em outros pontos do programa. E depois que você lê os valores do dia, mês e ano, faltou chamar o método para calcular a idade.
Outro detalhe é que LocalDate.of recebe os valores do ano, mês e dia, nessa ordem (você estava passando na ordem errada).
Enfim, uma forma (ainda não ideal, na minha opinião - deixei uma alternativa ao final) de resolver esses problemas seria:
static boolean validarData(int dia, int mes, int ano) {
    // em vez de fazer um if gigante, quebre em várias condições
    if (mes < 1 || mes > 12) { // verifica mês inválido
        return false;
    }

    // se chegou aqui, é porque o mês é válido, então agora verifica o dia
    int qtdDias;
    if (mes == 2) {
        if (ano % 4 == 0 && ((ano % 100) != 0 || (ano % 400) == 0)) {
            qtdDias = 29;
        } else {
            qtdDias = 28;
        }
    } else if (mes == 4 || mes == 6 || mes == 9 || mes == 11) {
        qtdDias = 30;
    } else {
        qtdDias = 31;
    }
    return 1 <= dia && dia <= qtdDias;
}

static Period calculoIdade(int dia, int mes, int ano) {
    if (validarData(dia, mes, ano)) {
        if (ano <= 2020) {
            return Period.between(LocalDate.of(ano, mes, dia), LocalDate.now());
        }
    } else {
        // mudei a mensagem porque há mais de um motivo para ser inválida (mês negativo, por exemplo), então deixei a mensagem genérica
        System.out.println("Data inválida");
    }
    // se a data for inválida ou o ano for maior que 2020, retorna null
    return null;
}

public static void main(String[] args) {
    Scanner leia = new Scanner(System.in);
    System.out.print("Digite o dia: ");
    int dia = leia.nextInt();
    System.out.print("Digite o mês: ");
    int mes = leia.nextInt();
    System.out.print("Digite o ano: ");
    int ano = leia.nextInt();

    Period idade = calculoIdade(dia, mes, ano);
    if (idade != null) { // se não for null, é porque foi calculado
        System.out.printf("Idade: %d anos, %d meses e %d dias\n", idade.getYears(), idade.getMonths(), idade.getDays());
        System.out.printf("%02d/%02d/%d\n", dia, mes, ano); // %02d garante que valores como "2" sejam mostrados como "02"
    }
}

Mas na verdade não precisa de nada disso. A própria classe LocalDate já verifica se a data é válida, lançando uma exceção caso não seja. Então basta usar o que já tem pronto, adicionando apenas o caso especial que verifica se o ano não é maior que 2020 (se bem que acho melhor verificar simplesmente se a data está no futuro, em vez de fixar um ano). Para formatar a data, também tem coisas prontas, não precisa reinventar a roda:
public static void main(String[] args) {
    Scanner leia = new Scanner(System.in);
    System.out.print("Digite o dia: ");
    int dia = leia.nextInt();
    System.out.print("Digite o mês: ");
    int mes = leia.nextInt();
    System.out.print("Digite o ano: ");
    int ano = leia.nextInt();

    try {
        LocalDate dataNasc = LocalDate.of(ano, mes, dia);
        LocalDate hoje = LocalDate.now();
        if (dataNasc.isAfter(hoje)) {
            System.out.println("Data de nascimento no futuro, não é possível calcular idade");
        } else {
            Period idade = Period.between(dataNasc, hoje);
            System.out.printf("Idade: %d anos, %d meses e %d dias\n", idade.getYears(), idade.getMonths(), idade.getDays());
            System.out.printf(DateTimeFormatter.ofPattern("dd/MM/uuuu").format(dataNasc));
        }
    } catch (DateTimeException e) { // se a data for inválida, LocalDate.of lança esta exceção
        System.out.println("Data inválida: " + e.getMessage());
    }
}

Comment: Prezado @hkotsubo, muito obrigado, agora funcionou.

Cálculo de Idade usando Period


how solve this proplem on models django?

Question: Finished creating the models file, typed python manage.py  makemigrations main and I get a reply back, 'no installed app with label 'main'.  when I do python manage.py migrate, it says Apply all migrations: admin, auth, contenttypes, sessions.  I even spent considerable time double checking my spelling and it is correct.  Any ideas on how I can fix it?
Comment: share the `INSTALLED_APPS` setting.
Comment: i add that but didnt work
Answer: your app.py must look like this:
from django.apps import AppConfig

class MainConfig(AppConfig):
    name = 'main'
    verbose_name = 'Some Name'

Answer: You need to add your app main to the INSTALLED_APPS setting [Django-doc] in the settings.py:
# settings.py

INSTALLED_APPS = [
    # …,
    'main'
]
Comment: INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main.apps.MainCnfing',
Comment: @Majd: share the `MainConfig`, [edit](https://stackoverflow.com/posts/65556404/edit) your question (there is also a "typo" in `MainCnfing` (should be `MainConfig`).
Comment: from django.db import models

# Create your models here.
class ToDoList(models.Model):
 name = models.CharField(max_length=200)

 def __str__(self):
  return self.name

class Item(modeLs.Model):
 todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
 text = models.CharField(max_Length=300)
 complete = models.BooleanField()

    def __str__(self):
     return self.text
Comment: @Majd: that is not the app config, but the model... [edit](https://stackoverflow.com/posts/65556404/edit) your question...
Comment: yes comment one on setting comment two on models all things true but with error
Comment: @Majd: but you are still not providing the app config... The problem is not in the models, since that file is, based on the error *never loaded*, so very likely a problem in the `MainConfig`...


Zabbix 5.4.3 - How to monitor a string in a webpage and define a trigger when it changes

Question: I am using Zabbix 5.4.3 to monitor all of my company hosts.
I want to monitor a local website address (eg. https://172.30.200.1:44443/login) which is our firewall webpage.
It has got two linked WANs, one with our primary public IP and another which is a 4G backup connection without public IP (random access IP).
When the connection of the primary one goes down, the firewall automatically switches from one WAN to the another and the IP changes.
On the firewall webpage, the current used IP is always showed and updated. (see image for reference)

Is there a way to set a trigger which shows that the IP has changed from our primary to the secondary random one based on the checks on this string?
I need simply a trigger which shows "IP CHANGED FROM THE PRIMARY TO THE OTHER" and nothing more.
I am able to perform a webscenario configuration inside the firewall host setup in Zabbix (with also a login), but I can't understand how to setup a trigger of this kind.
Let me know guys.
Answer: Hi you can active "required string" functionality of web monitoring. It use regular expression pattern. Ciao!
Required string:
Required regular expression pattern.
Unless retrieved content (HTML) matches the required pattern the step will fail. If empty, no check on required string is performed.
For example:
Homepage of Zabbix
Welcome.admin
Note: Referencing regular expressions created in the Zabbix frontend is not supported in this field.
User macros and {HOST.} macros are supported.
https://www.zabbix.com/documentation/5.4/en/manual/web_monitoring
Answer: You can create a data element of the "HTTP agent" type and use a regular expression to take the IP address from the page source code, then configure the trigger:
<code> last(http_agent_item) <> last(http_agent_item,#2:now-(your interval))
</code>


Proving $ n! \geq 2^{n-1} $

Question:
Prove that $$ n! \geq 2^{n-1}$$ for $n \geq 1$.

My initial solution by induction goes like this.
For $n = 1 : 1 \geq 1 $.
Assuming that $$ n ! \geq 2^{n-1}.$$
Then for $n+1$,
$$ (n+1)! = 2^{n+1-1} $$
so
$$ n!(n+1) = 2^{n-1} \cdot 2 $$
How I can finish?
Comment: In the last line, clearly $n\ge1$ by hypothesis; so $n+1\ge2$ is true. Thus you obtain the statement desired.
Answer: Use your induction hypothesis and $n+1>2$.
Comment: As the induction step is for $n\geq 2$, $n+1$ will be strictly greater than $2$, so there's no need for equality.
Answer: Hint: $(n+1)! = (n+1) \cdot n! \geq (n+1) \cdot 2^{n-1} \geq 2 \cdot 2^{n-1} = 2^{(n +1) -1}.$
Answer: Why use induction here? Just consider $\frac{1 \cdot 2 \ldots n}{2 \cdot 2 \ldots 2}$ There are $n-1$ terms in the numerator after the first one and $n-1$ in the denominator. Clearly the numerator is monotone increasing and $k>2 \ \forall \ k \geq 2$, so the fraction is greater than 1.

Proving $ n! \geq 2^{n-1} $


Question about the abbreviation for 2 instruments in an orchestra score

Question: I'm learning an orchestra score and I'm really new to that. I'm figuring out what instruments are included in this score, and I get most of them (correct me if there is any mistake). However, I'm pretty confused about the Br. and K-B here.
Also, what is the difference between the two Viol.?
Comment: What is the composition title and author? In what language or country the score was published? Could it be they are e.g. German abbreviations?
Comment: @user1079505 This is the first symphony of Brahms. Unfortunately, I'm not sure about the language which confused me either :(
Comment: @user1079505 Based on my observation, I guess it's in English or German
Answer: Br. is short for Bratsche, which is german for Viola.
K-B. is short for Kontrabass, which is german for Contrabass a.k.a. Double bass.
The two Viol. parts are both Violins. An orchestra has two sections for the violins (firsts and seconds), these make up the largest portion of the orchestra. Sometimes they will play the same notes but it is very common that they play independently.
(Sometimes these sections will themselves divide (divisi) to play different lines of music)
P.S. Since you are new to orchestral scores and german — it's worth pointing out that the clarinets in "B", are really clarinets  in B-flat.  B-flat is B in german, and B is H.
Comment: @CarlWitthoft Hornists, for historical reasons, don't expect to see key signatures, ever. It's just one of those things that drive composers and conductors crazy. I guarantee that the horns are in unison/octaves in mm. 179-180 here; if nothing else, if the C's written in the E-flat horn part were meant to be concert pitch, they would make absolutely no sense against the 2nd violins and violas playing an A-flat minor arpeggio with a C-flat in the middle of it.
Comment: @MusicalChicken — You're right that "Hr." is short for Horn (in german and english). Before horns had valves they used a collection of different crooks (tubes of specific lengths). The particular crook that was attached would set the tuning of the instrument to a certain key. The "Es" is german for E-flat. So it's a horn with the E-flat crook attached.
Comment: @MusicalChicken:  Another important thing to remember is that because of the E-flat transposition, the horn staves in that section are actually in unison (not in minor thirds as it might appear.)  If you're not familiar with the concept of "transposing instruments", [Wikipedia has a reasonable summary.](https://en.wikipedia.org/wiki/Transposing_instrument)
Comment: @phoog HaHa. I missed that!
Comment: Trivia: The word "Bratsche" comes from the Italian "viola da braccio".
Comment: Thank you for answering! Could you explain what is Hr. (Es) is here? THX!
Comment: and there are some horrible jokes based on the name "bratsche" .
Comment: Also, when a part has two players (as in the woodwinds here) and a passage has only one part indicated, you will sometimes see the Italian *a due* (abbreviated a2) to indicate that both players are to play the section.
Comment: @DjinTonic I'm a bit surprised that you mention the woodwinds there, since the instrument where _a 2_ is actually used is the E-flat horns.
Comment: @PaulZ  You are correct & I apologize for misleading folks.
Comment: As an addendum to the current correct answer The horn named Es is what is known as the English horn which is actually a miss translation of the German word Engel which means Angel. This word is confused because Engels means English while Engel means angel. The English horn does not auctually have anything to do with England. Here is an interesting follow-up question. What key is the piece in and what interval is the transposing instruments operate under?
Comment: An English Horn / Cor Anglais is in the oboe family. One would  be placed directly under the oboe in the score, and it'd be in F. In german it'd be called "Englisches Horn (F)" / "Engl. Hr. (F)".

The horns in this score are (the unrelated brass instrument) the Natural Horn, which are like the modern (French) Horn, but without valves.
Comment: @ElementsinSpace In German it would be "Englischhorn" or sometimes  "Englisch Horn".
Comment: @PiedPiper — The Dolmetsch Online music dictionary lists both variations:  "Englisches Horn" and "Englischhorn".  But I don't speak german, so I don't understand the significance of the difference in spelling.


Is there an equivalent to OR clause in CONTAINSTABLE - FULL TEXT INDEX

Question: I am trying to find a solution in order to improve the String searching process and I selected FULL-TEXT INDEX Strategy.
However, after implementing it, I still can see there is a performance hit when it comes to search by using multiple strings using multiple Full-Text Index tables with OR clauses.
(E.x. WHERE CONTAINS(F.*,'%Gayan%') OR CONTAINS(P.FirstName,'%John%'))
As a solution, I am trying to use CONTAINSTABLE expecting a performance improvement.
Now, I am facing an issue with CONTAINSTABLE when it comes to joining tables with a LEFT JOIN
Please go through the example below.
Query 1
SELECT F.Name,p.*
        FROM P.Role PR
INNER JOIN P.Building F ON PR.PID = F.PID
LEFT JOIN CONTAINSTABLE(P.Building,*,'%John%') AS FFTIndex ON F.ID = FFTIndex.[Key]
LEFT JOIN P.Relationship PRSHIP ON PR.id = prship.ToRoleID
LEFT JOIN P.Role PR2 ON PRSHIP.ToRoleID = PR2.ID
LEFT JOIN P.Person p ON pr2.ID = p.PID
LEFT JOIN CONTAINSTABLE(P.Person,FirstName,'%John%') AS PFTIndex ON P.ID = PFTIndex.[Key]
WHERE F.Name IS NOT NULL

This produces the below result.

Query 2
SELECT F.Name,p.*
FROM P.Role PR
INNER JOIN P.Building F ON PR.PID = F.PID
INNER JOIN P.Relationship PRSHIP ON PR.id = prship.ToRoleID
INNER JOIN P.Role PR2 ON PRSHIP.ToRoleID = PR2.ID
INNER JOIN P.Person p ON pr2.ID = p.PID
WHERE CONTAINS(F.*,'%Gayan%') OR CONTAINS(P.FirstName,'%John%')
AND F.Name IS NOT NULL

Result

Expectation
To use query 1 in a way that works as the behavior of an SQL SERVER OR clause. As I can understand Query 1's CONTAINSTABLE, joins the data with the building table, and the rest of the results are going to ignore so that the CONTAINSTABLE of the Person table gets data that already contains the keyword filtered from the building table.
If the keyword = Building, I want to match the keyword in both the tables regardless of searching a saved record in both the tables. Having a record in each table is enough.
Summary
Query 2 performs well but is creates a slowness when the words in the indexes are growing. Query 1 seems optimized(When it comes to multiple online resources and MS Documentation),
however, it does not give me the expected output.
Is there any way to solve this problem?
I am not strictly attached to CONTAINSTABLE. Suggesting another optimization method will also be considerable.
Thank you.
Answer: Hard to say definitively without your full data set but a couple of options to explore
Remove Invalid % Wildcards
Why are you using '%SearchTerm%'? Does performance improve if you use the search term without the wildcards (%)? If you want a word that matches a prefix, try something like
WHERE CONTAINS (String,'"SearchTerm*"')
Try Temp Tables
My guess is CONTAINS is slightly faster than CONTAINSTABLE as it doesn't calculate a rank, but I don't know if anyone has ever attempted to benchmark it. Either way, I'd try saving off the matches to a temp table before joining up to the rest of the tables. This will allow the optimizer to create a better execution plan
SELECT ID INTO #Temp
FROM YourTable
WHERE CONTAINS (String,'"SearchTerm"')

SELECT *
FROM #Temp
INNER JOIN...

Optimize Full Text Index by Removing Noisy Words
You might find you have some noisy words aka words that reoccur many times in your data that are meaningless like "the" or perhaps some business jargon. Adding these to your stop list will mean your full text index will ignore them, making your index smaller thus faster
The query below will list indexed words with the most frequent at the top
Select *
From sys.dm_fts_index_keywords(Db_Id(),Object_Id('dbo.YourTable') /*Replace with your table name*/)
Order By document_count Desc

This OR That Criteria
For your WHERE CONTAINS(F.*,'%Gayan%') OR CONTAINS(P.FirstName,'%John%') criteria where you want this or that, is tricky. OR clauses generally perform even when using simple equality operators.
I'd try either doing two queries and union the results like:
SELECT * FROM Table1 F
/*Other joins and stuff*/
WHERE CONTAINS(F.*,'%Gayan%')
UNION
SELECT * FROM Table2 P
/*Other joins and stuff*/
WHERE CONTAINS(P.FirstName,'%John%')

OR this is much more work, but you could load all your data into giant denormalized table with all your columns. Then apply a full text index to that table and adjust your search criteria that way. It'd probably be the fastest method searching, but then you'd have to ensure the data is sync between the denormalized table and the underlying normalized tables
SELECT B.*,P.* INTO DenormalizedTable
FROM Building AS B
INNER JOIN People AS P

CREATE FULL TEXT INDEX ft ON DenormalizedTable
etc...


Almost Sure Convergence of a Series of Random Variables

Question: Let $\psi(x) = x^2$ when $|x| \leq 1$ and $\psi(x) = |x|$ when $|x| \geq 1$. Show that if $X_1, X_2, \dots$ are independent with $\mathbb{E} X_n = 0$ and $\sum_{n=1}^\infty \mathbb{E} \psi(X_n) < \infty$, then $\sum_{n=1}^\infty X_n$ converges a.s.
This is Durrett exercise 2.5.6.
My thoughts:
We know by Kolmogorov's two-series test that if $\sum_{n=1}^\infty \text{Var}X_n < \infty$ that the series converges almost surely, and here $\psi$ is in some sense a "pseudo variance", but I'm not sure where to get started. Any help would be much appreciated.
Answer: The conditions given in the question does not necessarily imply that $\sum_{n=1}^\infty \text{Var} X_n <\infty$. Here is an example: Let $X_n$ take the values $2^n$ and $-2^n$, each with probability $p_n = 1/3^n$ and take the value $0$ with probability $1-2p_n.$ Then, $\psi(X_n) = \min(X_n^2, |X_n|) = |X_n|,$ hence $$\sum_{n=1}^\infty \text{E}\psi(X_n) = \sum_{n=1}^\infty \text{E}|X_n| = \sum_{n=1}^\infty 2^n \frac{2}{3^n} <\infty.$$ But, $$\sum_{n=1}^\infty \text{Var}X_n =\sum_{n=1}^\infty \text{E}(X_n^2) = \sum_{n=1}^\infty 4^n \frac{2}{3^n} =\infty.$$
The Kolmogorov three series theorem still applies. Define $Y_n = X_n I_{|X_n|\le 1}.$ Then,
(i) We have $$P(|X_n|\ge 1) = \text{E}(I_{|X_n|\ge 1})\le \text{E}(|X_n| I_{|X_n|\ge 1}) \le \text{E}\psi(X_n).$$ Hence $$\sum_{n=1}^\infty P(X_n\neq Y_n) = \sum_{n=1}^\infty P(|X_n|\ge 1) \le \sum_{n=1}^\infty \text{E}\psi(X_n) <\infty.$$
(ii) To show that $\sum_{n=1}^\infty \text{E}Y_n $ converges, observe that $$\text{E}Y_n=\text{E}(X_n I_{|X_n|\le 1}) = \text{E}(X_n - X_n I_{|X_n|\ge 1}) = - \text{E}(X_n I_{|X_n|\ge 1}),$$ and we already showed above that $\sum_{n=1}^{\infty} \text{E}(X_n I_{|X_n|\ge 1}) \le \sum_{n=1}^{\infty} \text{E}\psi(X_n)<\infty.$
(iii) We have $Y_n^2 \le \psi(X_n),$ hence $$\sum_{n=1}^\infty \text{E}(Y_n^2) \le \sum_{n=1}^\infty \text{E}\psi(X_n) < \infty.$$
So all the conditions are met and the conclusion follows from Kolmogorov three series theorem.
Answer: Let $Y_n=X_n I_{|X_n| \leq 1}$. First observe that $\sum EY_n^{2} <\infty$ and $\sum  E|X_n| I_{|X_n| >1} <\infty$. Using this second property we see that $\sum P(|X_n| >1) <\infty$. By Borel Cantelli Lemma $|X_n| \leq 1$ for all $n$ sufficiently large with probability $1$. Now Note that $\sum var(Y_n) <\infty$ so $\sum Y_n$ converges almost surely. Combining these two facts we see that $\sum X_n$ converges almost surely.
Comment: Sorry to nitpick, but how is that Chebyshev? There is no variance here... Isn't it just $$\mathbb{P}\{|X_n| > 1\} = \mathbb{E}[ \mathbf{1}_{\{|X_n| > 1\}}] \leq \mathbb{E}[ |X_n|\mathbf{1}_{\{|X_n| > 1\}}]$$? (Besides that, +1)
Comment: Yes, that's what I understood (cf. my comment). Nice argument...


how to make flutter video player responsive?

Question: I was trying to make a webpage with a default video playing but in full screen  it looks fine but when changing size it getting worst. Like this image how to fix this issue
<code>class WelcomePage extends StatefulWidget {

VideoPlayerController? _videoCOntroller;

@override
void initState() {
super.initState();
  _videoCOntroller!.initialize().then((value) {
  _videoCOntroller!.play();
  _videoCOntroller!.setLooping(true);
});
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
  body: Column(
    children: [
      Stack(
        children: [
          Container(
            color: Colors.amber,
            height: size.height,
            width: size.width,
            child: FittedBox(
              fit: BoxFit.cover,
              child: Container(
                height: size.height,
                width: size.width,
                child: VideoPlayer(_videoCOntroller!),
              ),
            ),

          ),
          Positioned(
            height: size.height,
            width: size.width,
            child:
                child:

</code>
Answer: You set size.width to height of Container instead of size.height:
<code>          child: Container(
            height: size.width,
            width: size.width,
            child: VideoPlayer(_videoCOntroller!),
          ),
</code>
And if changing that doesn't solve your problem. Change BoxFit.cover to BoxFit.fill.
Edit 1: I think this is a bug. The issue about Android will be solved with video_player 2.1.6 but I don't know the situation of web. You may want to checkout this issue on github
Comment: i do both of it and no change at all
Answer: The problem was using stack inside a column just removing that could fic the issue


Como converter data e hora com JavaScript?

Question: Tenho uma string de data no seguinte formato:

Dec 11, 2017 01:00AM.

Preciso converter a data para o seguinte formato:

11/12/2017

e a hora para este formato:

01:00.

Eu pensei em tratar a data por meio de uma condicional e substituir os meses conforme o desejado, mas isso não irá funcionar para a hora, pois são muitas variações. Deve haver uma função no JavaScript que faz essa conversão, como posso converter data e hora com JavaScript?
Comment: Para manipulações com formatos de data e hora eu recomendo usar o componente Moment js que já faz de forma segura e sem chance de erros de cálculo e etc. https://momentjs.com/
Comment: com o Moment basta você chamar dessa forma: moment("Dec 11, 2017 01:00AM", "lll").format("L") e ai adicionar a hora ou usar um formato customizado.
Comment: A questão aqui é que como está vindo em format inglês "Dec" o Date.parse falha porque ele estará configurado para o Brasil, então você vai ter que fazer mesmo um código na mão, construindo uma data na mão baseado nas abreviações de mês em inglês :-\
Comment: Fazer isso na unha é um tiro no pé :-(
Comment: O foco principal da dificuldade na pergunta, acho eu, estaria no formato  da data recebida que não é um formato válido, portanto, não acho que seja `possível duplicata`, pois que, esse problema pontual não está sendo abordado nos outros posts.
Answer: Se a data está vindo nesses formatos
Dec 11, 2017 01:00AM  ou  Dec 11, 2017 01:00PM
temos que tratá-la para um formato válido (AM ou PM separados por um espaço)
Dec 11, 2017 01:00 AM ou  Dec 11, 2017 01:00 PM
E isto pode ser feito usando o método substr()  que retorna os caracteres em uma string começando na localização especificada através do número especificado de caracteres:
var recebida = ("Dec 11, 2017 01:00AM");
recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

Feita a devida formatação, é possível encontrar vários posts que resolverão sua dificuldade

toLocaleString() - função nativa do Javascript - string de data/hora no formato localizado no seu sistema

var recebida = ("Dec 11, 2017 01:00AM");

recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

var data = new Date(recebida);

var resultado = data.toLocaleString();

console.log (resultado);

Exemplo 1 - Dec 11, 2017 01:00AM

var recebida = ("Dec 11, 2017 01:00AM");

recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

var data = new Date(recebida);

var resultado = data.toLocaleString();

console.log (resultado);

Exemplo 2 - Dec 11, 2017 01:00PM

var recebida = ("Dec 11, 2017 01:00PM");

recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

var data = new Date(recebida);

var resultado = data.toLocaleString();

console.log (resultado);

Exemplo 3 - Se não quiser apresentar os segundos faça
  resultado = resultado.substr(0,16);

var recebida = ("Dec 11, 2017 01:00PM");

recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

var data = new Date(recebida);

var resultado = data.toLocaleString();

resultado = resultado.substr(0,16);

console.log (resultado);

Sem configurações do local

    var recebida = ("Dec 11, 2017 01:00AM");
    recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

    var data = new Date(recebida);
    var dia = data.getDate();
    if (dia.toString().length == 1)
      dia = "0"+dia;
    var mes = data.getMonth()+1;
    if (mes.toString().length == 1)
      mes = "0"+mes;
    var ano = data.getFullYear();
    var hora = data.getHours();
    if (hora.toString().length == 1)
      hora = "0"+hora;
    var minutos = data.getMinutes();
    if (minutos.toString().length == 1)
      minutos = "0"+minutos;
    console.log (dia+"/"+mes+"/"+ano+ " "+hora+":"+minutos);

Ou resumidamente

var recebida = ("Dec 11, 2017 01:00PM");
recebida = recebida.substr(0,18)+" "+recebida.substr(-2);

var data = new Date(recebida);

var dataFormatada = ("0" + data.getDate()).substr(-2) + "/" + ("0" + (data.getMonth() + 1)).substr(-2) + "/" + data.getFullYear() +" " + ("0"+ data.getHours()).substr(-2)+":"+("0"+ data.getMinutes()).substr(-2);

console.log(dataFormatada);
Comment: Obrigado pela resposta! Funciona perfeitamente aqui no console, mas no aplicativo Code (zapier.com/help/code/#requiring-or-using-external-libraries) do Zapier o output fica nesse formato: `Mon Dec 11 2017`. Acredito ser por causa das configurações do local, ao usar o `toLocaleString()`, pois a empresa fica no USA.
Comment: @FábioJunioAlvesSousa, veja se a alternativa `Sem configurações do local` na resposta atende!
Comment: Perfeito! Funcionou plenamente! Muito grato Leo.
Answer: Utilizando o componente Moment.js fica muito fácil.
Basta baixar ou linkar a biblioteca em:
https://momentjs.com/
E usar o código em javascript:
var data = moment("Dec 11, 2017 01:00AM", "lll").format("DD/MM/YYYY HH:mm");

Vai escrever '11/12/2017 01:00' na variável data.
Comment: acho que essa tag é abrangente demais para dizer que é somente javascript puro.
Comment: Obrigado pela resposta, mas estou utilizando o aplicativo Code (https://zapier.com/help/code/#requiring-or-using-external-libraries) da ferramenta online Zapier, e nesse aplicativo não consigo linkar bibliotecas externas.
Comment: Você pode carregar via javascript, não vejo como o aplicativo pode te bloquear. :-\
Comment: Na documentação consta o seguinte:

"Infelizmente, você não pode exigir bibliotecas externas ou instalar ou importar bibliotecas comumente referidas como "módulos npm". Somente a biblioteca padrão node.js e o fetch pacote estão disponíveis no aplicativo Código. fetch já está incluído no namespace."
Comment: Essa data neste formato vem de onde exatamente? quem está formatando desta forma?
Comment: Ela vem da agenda Google, e o aplicativo da agenda do Zapier que faz a formatação.
Comment: @Zorkind Apesar de estar correta, quando uma pergunta é marcada com a *tag* [tag:javascript], subentendesse que o AP, deseja uma resposta com JavaScript puro, sem uso de nenhuma biblioteca ou API de terceiros.
Comment: Quem votou negativo, por favor, explicar o motivo.


ways to pivoting data and render the result to HTML in Django

Question: I have the data looks like:
ws=[{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 4>},
    {'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 5>},
    {'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 6>},
    {'a': datetime.date(2020, 8, 31), 'b': <BB: 02>, 'c': <CC: 9>},
    {'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 4>},
    {'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 5>},
    {'a': datetime.date(2020, 9, 1), 'b': <BB: 02>, 'c': <CC: 3>}]

And i wish to make it look like next, then render it to HTML.
\ a
b\ |2020-08-31| 2020-09-01|
---|----------|-----------|-----
01 |c= 4,5,6  |c= 4,5     |
02 |c= 9      |c= 3       |

Even though spending days of effort, i still do not have any
idea. If someone can kindly give me some guidance, i will
very very appreciate.
Comment: Can you use pandas? its pivoting functionality is robust.
Comment: Hi, thanks for ur kindly advice. Per ur recommendation, i had tried the pandas,"pivot_table," but get the error message "not supported between instances of 'cc' and 'cc'. I cannot figure out what happen on it. Could you give me some more details guidance?
Answer: Working from your dictionary called ws:
import pandas as pd

# convert the dic w to a dataframe:
pd.DataFrame.from_dict(ws)

# cast dataframe column types
pd.to_datetime(df['a'], format='%Y-%m0%d'))))
df['b'] = df['b'].astype(str)
df['c'] = df['c'].astype(str)

# pivot, (a) changing the default aggfunc to join the strings (b)
# set the column to be a, the index to be b:
df.pivot_table(columns='a', values='c', index='b', aggfunc={'c':lambda x: " ".join(x)}).fillna('')

Output:
a                      2020-08-31       2020-09-01
b
<BB: 01>  <CC: 4> <CC: 5> <CC: 6>  <CC: 4> <CC: 5>
<BB: 02>                  <CC: 9>          <CC: 3>

To render the dataframe in html, just use:
df.to_html()


Background image resizing to fit

Question: I'm trying to make the background image as professional as possible so I'm thinking it's best to resize it based on the size of the browser or the resolution (not sure what's usually used, but I think browser size makes sense here). The idea is if the viewer screen is small, the background image gets smaller, and as the screen gets bigger, the image expands to fit its maximum size.
I will try a CSS or even Javascript (JQuery) solution as needed.
Answer: I guess you're looking for something like that:
http://css-tricks.com/how-to-resizeable-background-image/
Comment: I just used this 3 days ago and it works awesomely. Just remember to zero your margins and padding of the container the background is applied to, so that it renders the same across all browsers.
Answer: You will need to stick to CSS 3 background-size property to achieve this: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm
Without using CSS 3 you cannot resize the background image in any way on the client.

Background image resizing to fit


Can we access any files in phone directory after an apk file has been installed?

Question: I'm developing an Android App, a Book. It is a long with many contents paragraph. I'm thinking about dividing that paragraph into small paragraphs and store them in database using SQLite Database by creating a table with these attributes: ID,Title,Path,... I store those small paragraph in text files and copy them into phone directory. I want to ask that can we access those files by their path in phone directory? if yes then how to do it?
Answer: //Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

I hope its useful to you..
Comment: this really helpful for me


android java.lang.VerifyError on startactivity in 1.6

Question: I implement a project which contain a activity group mainActivity.
This main activity contains 3 other activity groups.
When I try to start myaccountactivity which is an activitygroup, it works for api more than 1.6 but if i tried to run it on 1.6 i get following wrror
<code>11-23 12:22:15.005: ERROR/AndroidRuntime(412): java.lang.VerifyError: com.myproject.android.MyAccountActivity
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at java.lang.Class.newInstanceImpl(Native Method)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at java.lang.Class.newInstance(Class.java:1472)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.Instrumentation.newActivity(Instrumentation.java:1097)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2316)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2242)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at com.myproject.android.myproject.showMyAccountAtivity(myproject.java:396)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at com.myproject.android.myproject.onActivityResult(myproject.java:456)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.Activity.dispatchActivityResult(Activity.java:3625)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityGroup.dispatchActivityResult(ActivityGroup.java:123)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3220)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3266)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.access$2600(ActivityThread.java:116)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.os.Looper.loop(Looper.java:123)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at android.app.ActivityThread.main(ActivityThread.java:4203)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at java.lang.reflect.Method.invokeNative(Native Method)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at java.lang.reflect.Method.invoke(Method.java:521)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
11-23 12:22:15.005: ERROR/AndroidRuntime(412):     at dalvik.system.NativeStart.main(Native Method)
</code>
I tried to fins out solution but no use. Please if anyody knows how to solve or knows reason why it is coming let me know..
Thanks
Answer: You're using functions from an SDK past 1.6, but you claim in your manifest that your app runs fine on 1.6. Set your build target to 1.6 to see which ones.
Comment: I use super.onBackPressed() which causes verify error in 1.6 but runs smoothly in version 2.0 and more. Sorry for the previous answer.
Comment: Have a look at this blog post on the Android Developers blog on how to handle onBackPressed() in versions of Android prior to 2.0: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html


Learning keyboard from a piano teacher

Question: I have an electric keyboard (unweighted) and I want to learn how to play it. I don't want to learn piano as the keys are weighted and it would throw me off (as there is no need for muscle strengthening with the keyboard). However, the only teachers in my area are piano teachers!
What are my options, and what would you recommend me doing?
EDIT: My eyes are looking at the seaboard as a main instrument, and I want to develop the skills to play it before I get it. It is known for its very sensitive keys, and I do not want to develop a muscle memory that will make me play it too hard. Also, I wish to play jazz and fusion, not classical, so the keyboard is just a tool with whom I could change the sound to any sound I hear in my head.
Comment: It isn't obvious to a complete beginner, but the "muscle strength" you need to play a keyboard efficiently doesn't come from "strengthening your fingers" but from your arms and even your shoulders. The thing you have to develop is muscle *control*, not strength, and that is pretty much the same for all keyboard instruments.
Comment: First, if you plan to do all your at-home practicing on an unweighted keyboard, and just don't want to be thrown off by working with a real piano during lessons, that's something to bring up with prospective teachers. My teacher has a Hammond and a piano in his studio; I'm sure he's not the only one who has an unweighted keyboard handy. Second, you say "I want to learn how to play it": Are you *entirely certain* that you already have sufficient skill and experience with the instrument to make the judgment that weighted keys are a waste of your time?
Comment: I have experience with music, and I know what I want from my instrument. That is why I think that the keyboard is better *for me* than the guitar. I don't want to play classical repertoire, but jazz and fusion. I want to play an electric keyboard for composition and because of the wide array of sounds at hand - which the piano is incapable of.
Comment: What's wrong with using a weighted keyboard as a motherboard, and MIDI-ing it to get a plethora of sounds? Works for me, although for organ-type playing, ordinary synth feel keys do work better. Probably, you'll need both!
Comment: The instrument I wish to take on later in life, when I have both money and skills, is the seaboard - which is a lot closer to the ordinary electric keyboard than to the piano (but even more sensitive - and a lot more dynamic)
Answer: The black and white bits do the same sort of job with either. As in they all produce sounds related to where they are situated on the board. And reading the dots will be the same, too. So, you'll need to know what they represent, regardless of how they get pressed. Most piano teachers will have been asked to teach keyboard at some time - although some will not want the job. In the initial stages,though, a piano teacher willing to help will still be a great help. It's hard to understand how much muscle strength you won't have to use by not playing piano. Most modern keyboards have velocity sensitivity, so the faster/harder you press keys, the louder the sound is, so there is still some muscle strength needed to get the most out of it. I reckon keyboard (organ etc.) players find it harder to cross over than vice versa - I play and teach both.
Answer: Any accordion teachers in your vicinity?  Keys are unweighted and not even velocity-sensitive, and accompaniment is semi-automatic.  Also somewhat more portable than a reasonable keyboard.
That being said, the bellows make it a more directly expressive instrument than a keyboard (though an expression pedal might help with that once you are hooked).  And you don't have the expedient of using great digital sound samples as a substitute for expressive playing.
So it is only loosely related to keyboard play, but so are pianos.  If the teacher situation would be better, it might be worth a try.
Comment: I don't see how accordion teachers are relevant to my question. I specifically said that the instrument of choice is an electric keyboard, and they are not related at all except for the layout of the keys in the right hand - different position, different ways of making sound.
Answer: As a piano teacher myself, I can easily say that it makes no difference whether a student plays on a keyboard or a piano. The basics of learning to play are the same. I recommend going to a piano teacher because I never did, and it took me much longer to learn to play than it would for someone who took lessons. Being self taught is good in its own way, but I still wish I'd taken lessons. If you are worried about wasting time learning about finger strengthening when you do not feel the need, then simply inform your teacher of this. I'm sure they will have no trouble understanding.
Also I would like to mention that muscle strengthening is not something taught but something that will come. Whether you feel it's necessary or not, playing keyboard will build and strengthen muscles that you wouldn't otherwise use. Your fingers will become strong by repeated use on any keyboard, whether the keys are weighted or not. You may even find that learning on a weighted keyed piano will make it easier to play a nonweighted keyboard. I started learning on a keyboard, and once I began to play on a piano with weighted keys, I found it very difficult for a while. Learning both will help you to be more versatile and flexible with styles and composition.
Just some thoughts for you to consider. Hope this helps!
Comment: Thank you for your answer ^^ However, from playing guitar, I am afraid that it will feel like two guitars with an extreme action difference - resulting in using too much effort on the keyboard.
Answer: You're over-thinking this.  Go to a piano teacher.  Tell them what keyboard you have.
Comment: Really. It is that simple. You might ask the teacher first if they would be agreeable about your not playing the weighted key instrument. They may even have an electronic keyboard to play for the lessons. There might be a few teachers who wouldn't go for this, but I'm betting most would.
Answer: you know, y`d better have an acoustic piano and several digital pianos with heavy real keys of various action and synthesizers and midi keys with light keys, I had experience at learning keyboards using a synthesizer with thin light keys. It is OK, but the key touch should be trained to play on pianos then, especially when you play a difficult virtuoso music like Chopin and Bach... no digital piano and synths in the world, including top-expensive models has a dynamic and sound color range and depth like a good acoustic one like tempered tuned Steinway or Petroff or a good Kawai...
Comment: If we're going to be specific - the seaboard has a similar dynamic and a lot more sound color range - it's a synthesizer, and sounds pretty damn good. Plus, you can do vibrato on it by just wiggling your finger.
Answer: Look for a piano teacher who can teach the style you want to learn on a synthesizer.
However I will point out that great synth players are at their foundation great pianists.  And don't worry about your fingers muscle memory, I'm not really sure what you think will happen...I've not experienced anything like that happening nor heard any student say anything about that.
You're right through, we needore people teaching other specific styles, especially for keyboard and synth.

Learning keyboard from a piano teacher


How to get process id of calling process if elevated via sudo

Question: I have a service on Ubuntu which elevate new process using sudo command and then call bash script XY.
From this bash script XY I need to find process id of the service which called the process.
Parent process id ($$) does not work, probably because sudo elevation.
Answer: Try this test.sh
#!/bin/bash

ps -ef | awk '$2 == "'$PPID'" { print $3 }'

Run it with :
$ chmod +x test.sh
$ sudo ./test.sh
$ echo "Sudo should print $$."


How would I copy the effects of Sugarcult with just an amp?

Question: I'm having trouble finding a dial setting on my amp for clarity and the best combination of effects for Sugarcult's pop/punk effects. The amp I have is an old Vox amp, nothing special. It does not have numbers around the dials, so number settings won't work. I will edit with the model when or if I find it.
Comment: It's going to be hard for us to answer this. First, we don't know the *exact* equipment you have, and we would have to know that to even begin to suggest anything. Second, we can't know how things sound to you, so we can't know what sounds you will like and what sounds you won't like. There is no "best" combination of effects. You just have to play around and experiment until you find a sound that you like. It may take several years.
Comment: DIY is a big part of punk culture, as is "play first ask questions later." Try stuff until you like it!
Comment: Ahhh… now you've added what band… the trouble with copying Sugarcult, or Green Day [they both use the same tricks] is that you're not trying to emulate one sound, but two. Everything is double-tracked. Best you're going to do is add a 20ms single delay, possibly thin the delay in EQ before it hits the amp, though it's never going to be the same. I'll also revise my start point up to 8 from 7, or swap to a higher-gain amp. Neither of those bands really has a punk sound at all, it's actually a punk attitude that gives them the vibe. The sound is much more modern rock than punk.
Comment: Tentative vote that this could stay open, if we remove 'pedals' from the equation, as that definitely gets too broad. We're often asked 'how do I copy this sound' & maybe knowing where to even start may help. no-one can know when you need to stop, but maybe where to start…
Comment: Meh. Sometimes I think we're a bit quick on the trigger to close.
Comment: @Tetsujin Ok suppose we answered this as a "how do I copy this sound?" question. We still need a reference sound to copy, and one is not included in the question. "Clarity" and "best combination … for punk/rock" are insufficient descriptors.
Comment: @ToddWilcox I'm not sure if you would be able to tell the effects on the song I'm trying to play, but Sugarcult is the band, it's a pop/punk band, I believe it's similar to Green Day and blink-182. You might be able to tell the effects they use in their songs if you listen to a few.
Comment: ↑ above comment added to answer
Answer: No-one can tell you exactly what settings, most especially on an old amp. Amongst the reasons are…

Amps vary in response to input. Change guitar, or change technique, you change the sound

Amps 'sag' over time & become softer-sounding. People do think to change the valves every decade or two, but very few ever know that the capacitors also need changing.

Vox amps, in particular, can be very soft when old. Some few were made with an extra 'top boost' & these are much more controllable.

The only real guidance anyone can give - especially if you're aiming for pop/punk - is imagine every dial goes from 0 at its minimum setting to 10 at its maximum; or alternatively think of it like a clock face. Then start with everything set at 7; that's about 2 o'clock as a clock face.
Work from there.
Just because it's a Vox doesn't mean you'll get a specific sound from it. Look at Vox's own 'hall of fame' list - few of these artists sound alike, even though we're told they all use the same make of amp…
One other thing to note - & this is actually very important, though forgotten or ignored by most people.
Every favourite guitar sound you've ever heard has been the sound of a guitar amp/speaker combo miked up [then recorded].  Unless you are standing at the front of a small stage or in the rehearsal room with the guitarist whose sound you like, you have only ever heard it miked.
One other thing to add
Get the amp sound right first, then think about pedals. Pedals add to the amp sound, they don't replace it.
Late edit after actual band to be emulated was added…
Ahhh… now you've added what band… the trouble with copying Sugarcult, or Green Day [they both use the same tricks] is that you're not trying to emulate one sound, but two. Everything is double-tracked. Best you're going to do is add a 20ms single delay, possibly thin the delay in EQ before it hits the amp, though it's never going to be the same.
I'll also revise my amp start point up to 8 from 7, swap to a higher-gain amp, or put a simple fuzz in front, dialled back to quite gentle, just to brighten & compress a little.
Neither of those bands really has a punk sound at all, it's actually a punk attitude that gives them the vibe. The sound is much more modern rock than punk.
For a bit of added history - Hugh Cornwell [Stranglers] used a Vox, but Steve Jones [Sex Pistols] & Joe Strummer [Clash] both  used Fenders.
Answer: Firstly, we need to know what pedals you could use. Then what guitar you have. Then what strings are on that guitar. Then which pickups are on it. Even how you use your pick! (like where along the strings you pluck, and how).
Even then what Vox amp it actually is!
But with all that information, there are so many variables, that it becomes impossible to help you more, as when you listen to your genre, you'll realise there's not just one sound that's used.
So, sorry, I hope I've explained in an 'answer' that there's actually no answer!


Is "test statistic" a value or a random variable?

Question: I am a student taking my first Statistics course now. I am confused by the term "test statistic".
In the following (I saw this in some textbooks), $t$ seems to be a specific value calculated from a specific sample.
$$
t=\frac{\overline{x} - \mu_0}{s / \sqrt{n}}
$$
However, in the following (I saw this in some other textbooks), $T$ seems to be a random variable.
$$
T=\frac{\overline{X} - \mu_0}{S / \sqrt{n}}
$$
So, does the term "test statistic" mean a specific value or a random variable, or both?
Comment: A [test statistic](http://en.wikipedia.org/wiki/Test_statistic) is a [statistic](http://en.wikipedia.org/wiki/Statistic). So a random variable. One speaks of the value of a test statistic when looking at an observation of it.
Answer: The short answer is "yes".
The tradition in notation is to use an upper case letter (T in the above) to represent a random variable, and a lower case letter (t) to represent a specific value computed or observed of that random variable.
T is a random variable because it represents the results of calculating from a sample chosen randomly.  Once you take the sample (and the randomness is over) then you can calculate t, the specific value, and make conclusions based on how t compares to the distribution of T.
So the test statistic is a random variable when we think about all the values it could take on based on all the different samples we could collect.  But once we collect a single sample, we calculate a specific value of the test statistic.
Answer: A test statistic is a statistic used in making a decision about the null hypothesis.
A statistic is a realized value (e.g. t): A statistic is a numerical value that states something about a sample. As statistics are used to estimate the value of a population parameter, they are themselves values. Because (long enough) samples are different all the time, the statistics (the numerical statements about the samples) will differ. A probability distribution of a statistic obtained through a large number of samples drawn from a specific population is called its sampling distribution --- a distribution of that statistic, considered as a random variable.
A statistic is a random variable (e.g. T): A statistic is any function of the data (unchanged from sample to sample). The data are described by random variables (of some suitable dimension). As any function of a random variable is itself a random variable, a statistic is a random variable.
It almost always clear from context what meaning is intended, especially when the upper/low-case convention is observed.
Comment: So, is a statistic a realized numerical value or a random variable (or both)?
Answer: A test statistic is an observation specific to your observed data that follows a probability distribution under a given assumption. This assumption is usually called the $H_0$.
For instance, in your sample the test statistic (called t-statistic) depends on the observed data ($\bar{x}$ and $s$ are both derived from the data).
Under the assumption that your mean is $\mu_0$, the statistic you computed will follow a certain distribution. The probability of this value of the statistic occurring is then determined under the assumption. If that value is deemed to be low, the assumption ($H_0$) is rejected.
If we reject the $H_0$ assumption, this does not mean that the assumption we made was guaranteed to be untrue. If it was true and we rejected it because of the low probability of the test statistic under $H_0$, we call it a type I error.
On the other hand, if we accept the assumption this does not mean that our assumption for sure was true. If the assumption was untrue and we accepted it because it had high enough probability under our wrong assumption, this is called type II error.
The statistic is a specific value and it is only if we accept certain assumptions as given that we can assume it follows a specific probability distribution.
This principle holds for all test statistics, not just for the t-statistic you mention here.