Woocommerce - Change currency depending on billing country

Question: I'm trying to change the currency depending on the customer's billing country. Is it possible to do that maybe with an override of the "tax calculation" function as it is updated when the customer change the country ?
At the moment, I have this function (function.php) :
add_filter('wcml_client_currency','change_currency');

function change_currency($client_currency){
   global $woocommerce;
   $country = $woocommerce->customer->get_country();
   if($country == 'CH') {
       $client_currency = 'CHF'; //currency code
   } else {
       $client_currency = 'EUR'; //currency code
   }
   return $client_currency;
}

Thanks for your help.
Comment: did you found solution ?
Answer: You can use this following code:
add_filter('woocommerce_get_price', 'return_custom_price', $product, 2);

function return_custom_price($price, $product) {
global $post, $woocommerce;
$tot_qty = $woocommerce->cart->cart_contents_count;
// Array containing country codes
$county = array('NZ', 'AU', 'GB', 'IE');
// Amount to increase by
//$amount = 10;
change_existing_currency_symbol('NZD$', 'NZD');

if($woocommerce->customer->get_shipping_country() == 'NZ'){
    $amount = 0.00;
    $amount = 26.19;
}
else if($woocommerce->customer->get_shipping_country() == 'GB'){
    $amount = 0.00;
    $amount = 19.04;
}
else if($woocommerce->customer->get_shipping_country() == 'IE'){
    $amount = 0.00;
    $amount = 19.04;
}
else {
    $amount = 0.00;
    $amount = 28.19;
}

//echo $amount;
// If the custromers shipping country is in the array
if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ){
    // Return the price plus the $amount
   return $new_price = $amount;
   die();
} else {
    // Otherwise just return the normal price
    return $price;
    die();
}
}

add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);

function change_existing_currency_symbol( $currency_symbol, $currency ) {
    global $post, $woocommerce;
    $my_country = $woocommerce->customer->get_shipping_country();
     switch( $my_country ) {
          case 'GB': $currency_symbol = '£';
          break;

          case 'NZ': $currency_symbol = '$';
          break;

          case 'IE': $currency_symbol = '€';
          break;

          default:
                    $currency_symbol = '$';

     }
     return $currency_symbol;
}


Finding Elasticity of Discount with Consumers

Question: I was wondering what the best method to go about this would be. I have one year's worth of data and its related to air-travel. So I have ticket fares, passengers sent, discount applied on each ticket and some other variables such as GMV and revenue.
The data is for one airline and one flight only that is flying on a specific route, not multiple flights and multiple routes.
I want to estimate the elasticity between the discount rate ( the discount applied on each ticket ) and the number of passengers. That is, should the discount rate change by 1% how much would the number of passengers sent change by?
A regression in perhaps a log log form was the approach I was thinking but I want to avoid a spurious regression and ending up deriving incorrect assumptions.
Any ideas about changes to my approach? Should I perhaps use macro-economic variables too or should a different regression method be used altogether. Something what I was worried about was that elasticity is bound not to be constant. Because of travel has seasons, I'm assuming the elasticity is going to be highly inelastic when in peak travel season but elastic otherwise. So should I run the regression in batches of months?
Answer: If I understand correctly, you have multiple observations of the same flight with your treatment variable (discount rate), along with other variables like time and whatever GMV stands for (is this gross merchandise value, i.e. what was sold on flight)?
This is a causal inference problem and regression is one way you can try to get the causal effect of interest as you describe. Really, you are looking for the causal effect of discount rate on the number of passengers sent. What I would start with before touching any model (or analyzing the data formally) is to first illustrate all of the important variables and relationships that cause changes in the number of passengers and/or changes in the discount rate. For example, you mention seasonality. This makes sense - I could believe that the discount rate given by the airline fluctuates depending on the season, and traveling naturally has seasonal patterns. This is a likely confounder and you should control for this (include month/quarter in the regression). Are there other variables that cause the airliner to change their discount rates? Are there other variables that cause variation in the number of passengers sent, irrespective of the discount rate? If yes, include these variables in the regression.
Does the current pandemic affect your data? Does your data have a natural trend in terms of the number of passengers (if so, then adding time might be useful to include).
Basically, I recommend creating a directed acyclic graph and illustrating, using domain knowledge and common sense, the causal relationships between your variables. Once you have this, then you can figure out what variables you should and should not include in your regression model to ensure an unbiased effect estimate. I don't think we can give much more advice than that because ultimately, you need to start with identifying the causal effect of interest fitst before moving to actually estimating it with statistics/ML.
Comment: Thank you very much for your detailed response and recommendation. GMV does stand for gross merchandise value.
Comment: I was thinking along the same lines as well and started identifying the relationships between the variables. Can you tell me why you suggest using a directed acyclic graph particularly?
Comment: @MSasta I suggest the directed acyclic graph because in my opinion, it is the easiest way to hypothesize what you know in a format that is clear. Using the directed acyclic graph, you can then proceed to identify the causal effect of interest, i.e. figure out the variables that you need to include in your regression model to obtain an unbiased coefficient by "blocking" on these variables, while also avoiding the mistake of including variables in your model that can actually lead to bias. There are many textbooks that talk about this, here's one:
Comment: https://matheusfacure.github.io/python-causality-handbook/04-Graphical-Causal-Models.html, also basically any book by Judea Pearl and Statistical Rethinking by Richard McElreath
Comment: Basically, once you have the DAG, hopefully you can identify the causal effect of interest by blocking on the variables that lead to indirect associations between discount rate and number of passengers. Include these variables in your regression, and you should get the unbiased effect that you are looking for if your DAG is mostly correct.
Comment: Once again thank you for your detailed response @aranglol, ill look into the DAG, this puts me on a good track going forward!


Problem for proving a subspace

Question: I have this problem:

Let (V,⟨−, −⟩) be a finite dimensional real inner product space. Prove that the set
of self-adjoint linear maps T : V → V is a subspace of the set of all linear maps
T : V → V .

I know I must prove 1. non-empty 2. closure under scalar mult. 3. closure under vec. add.
I proved non-empty using the definition of adjoint and the 0 map.
I am kind of stuck for the other two. I know, for example, for scalar multiplication, by definition $\lambda T(v) = (\lambda T)(v)$, and I am not sure what there is to show. My professor had stated that I could use the properties of the adjoint, but I am not sure where they come in use.
All I can really say is that I know that if T is self-adjoint then it corresponds to a symmetric matrix, and the scalar multiple of a symmetric matrix is still symmetric. Is this the right path?
Answer: Here are some hints.
Suppose $T,U$ are self-adjoint operators on the (finite dimensional) real inner product space $V$ and $\lambda$ is a real number.
What you have to show are thee two following facts:

$(T+U)^*=T^*+U^*$
$(\lambda T)^*=\lambda T^*$

where $T^*$ is the adjoint operator of $T$.
(actually these are the standard properties of adjoint operators)
And then together with the assumptions $T=T^*,U=U^*$, you may make your conclusion.
Comment: Okay, so to show the set of self-adjoint operators forms a subspace, as you said you need to prove (1) closed under scalar multiplication and (2) closed under vector addition. For example, (1) could followed from the properties $(\lambda T)^*=\lambda T^*$ and the assumption $T^*=T$. These two facts will give you $(\lambda T)^*=\lambda T^*=\lambda T$ and thus $\lambda T$ is self-adjiont, which shows (1)
Comment: Well, those two propositions you stated, we are allowed to use. I am not sure how to apply them to this situation though.
Comment: Could you mimic the proof for (1) to show (2)?
Comment: $(T+U)^* = T^* + U^* = T + U$. Thanks for your help.

Problem for proving a subspace


Copiando uma imagem de uma div para outra - Métodos em Jscript

Question: Estou com uma imagem e uma div conteudo-img. Ao clicar na imagem ela tem  que ser copiada para a div conteudo-img, quais métodos posso usar para fazer esta cópia e qual a mais viável via  javaScript.

#images{
float:left;
}

#conteudo-img{
width: 300px;
height: 300px;
border: 1px solid #f1f;
float: left;
}

 #images{
  float:left;
 }

 #conteudo-img{
  width: 300px;
  height: 300px;
  border: 1px solid #f1f;
  float: left;
 }

Answer: Podes usar target.appendChild(image.cloneNode()); onde .cloneNode() é o método que procuras para duplicar elementos do DOM. Se usares .cloneNode(true) em elementos que tenham descendência (que não é o caso do teu HTML) podes incluir nessa cópia a descendência também.

const images = document.getElementById('images');
const target = document.getElementById('conteudo-img');
images.addEventListener('click', function(e) {
  const image = e.target;
  target.appendChild(image.cloneNode());
});
#images {
  float: left;
}

#conteudo-img {
  width: 300px;
  height: 300px;
  border: 1px solid #f1f;
  float: left;
}

Comment: @Sora exato, podes ler mais sobre isso aqui: https://pt.stackoverflow.com/a/206121/129
Comment: O que seria este `const`? É como definir uma variável?
Comment: Ao invés de passar a id da div como parâmetro, posso passar a class também por exemplo??
Comment: @Sora depende. Se houver só um elemento podes usar `.querySelector('nomeDaClasse')`. Se tiveres vários elementos com essa classe tens de iterar. Mostra o caso de HTML que tens que posso dar um exemplo.
Comment: Alterei a minha pergunta e fiz um novo código onde requer o nome da classe como parâmetro
Comment: @Sora a minha resposta é válida na mesma se quiseres copiar só a `img`. Ou queres copiar a `div` à volta da img?
Comment: Somente a img, pensei que não era válida por causa desta linha:
`const images = document.getElementById('images');`
Porém testei e deu certo, vou marcar sua resposta como válida em breve
Obrigado @Sergio !!
Answer: Você pode fazer assim com JS

let img = document.querySelectorAll('img')

for(let i = 0; i < img.length; i++){
  img[i].onclick = function(){
    let attrImage = this.getAttribute('src')

    document.getElementById('conteudo-img').innerHTML = ''
  }
}
#images{
float:left;
}

#conteudo-img{
width: 300px;
height: 300px;
border: 1px solid #f1f;
float: left;
}

Ou tambem pode usar jquery

$('img').on('click', function(){
  var image = $(this).attr('src')

  $('#conteudo-img').append('')
})
#images{
float:left;
}

#conteudo-img{
width: 300px;
height: 300px;
border: 1px solid #f1f;
float: left;
}

Comment: Vou estudar esta codificação, vlw !!!
Comment: A resposta é válida mas se vais usar HTML acho mais seguro fazer append de `this.outerHTML`. Fica menos dependente de variacões no HTML como classes ou campos `data-` que esses elementos possam ter.
Comment: @Sergio Com toda certeza rsrs seu exemplo é muito mais valido do que o meu. Eu quis apenas mostrar uma forma de como fazer.
Comment: Não concordo com _"muito mais valido do que o meu"_. A tua resposta é boa/válida. Foi só um comentário/sugestão.
Comment: @Sergio estou sempre aprendendo com suas dicas aqui, sempre acompanho suas respostas. Valeu ;)


javax.ws.rs.core.Response.readEntity Method not found

Question: I have this error in my Spring Boot application. I've looked at similar posts and I'm not using RestEasyClient. How can I determine this error's root cause?
ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at
java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoSuchMethodError: 'java.lang.Object javax.ws.rs.core.Response.readEntity(java.lang.Class)'

Comment: Please post your dependencies.
Answer: Problem is jsr311-api when I exclude this from my pom,problem is resolved
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>


Problemas com template de função em c++ (Referência não definida para os métodos da classe)

Question: Olá!
Eu estou tentando compilar o seguinte código:
main:

#include "lista.h"

using namespace std;

int main(){
    no<int> *n;
    n = new no<int>(4);
    n->setProx(new no<int>(5));
    cout << n->obterValor() << endl;
    return 0;
}```

lista.h
#ifndef lista_h
#define lista_h

#include <iostream>

using namespace std;

template<typename type> class no{
private:
    type v;
    no *prox;
public:
    no(type v);
    void setProx(no* prox);
    type obterValor();
    no<type>* obterProx();
};

#endif

lista.cpp
#include "lista.h"
template<typename type>
no<type>::no(type v){
    this->v = v;
    this->prox = NULL;
}

template<typename type>
void no<type>::setProx(no<type>* prox){
    this->prox = prox;
}

template<typename type>
type no<type>::obterValor(){
    return this->v;
}

template<typename type>
no<type>* no<type>::obterProx(){
    return this->prox;
}

Quando eu compilo, conforme está no makefile:
all:    lista.o main.o
    g++ -o exe lista.o main.o
lista.o:    lista.cpp   lista.h
    g++ -c lista.cpp
main.o: main.cpp    lista.h
    g++ -c main.cpp
go:
    ./exe
clean:
    rm *.o && rm exe

E aí o terminal me retorna isso:
g++ -c main.cpp
g++ -o exe lista.o main.o
/usr/bin/ld: main.o: na função "main":
main.cpp:(.text+0x25): referência não definida para "no<int>::no(int)"
/usr/bin/ld: main.cpp:(.text+0x44): referência não definida para "no<int>::no(int)"
/usr/bin/ld: main.cpp:(.text+0x54): referência não definida para "no<int>::setProx(no<int>*)"
/usr/bin/ld: main.cpp:(.text+0x60): referência não definida para "no<int>::obterValor()"
collect2: error: ld returned 1 exit status
make: *** [makefile:2: all] Error 1

Não entendi o porquê destas referências indefinidas para as funções. Os arquivos main.cpp e lista.cpp são compilados e geram o objeto '.o', mas o erro está na hora de criar o executável.
Answer: O erro de referências não definidas é um erro do linker e quer dizer que o compilador sabe que a função foi declarada mas não sabe onde está a implementação. Isso aconteceu com o seu código pq um template não é um tipo definido e sim um molde para definir tipos no futuro. Toda vez que um tipo de template novo é declarado, o compilador busca pelo template para instanciar o novo tipo. Por isso que, por exemplo, no<int> é um tipo diferente de no<float>.
Quando vc compilou lista.o, o compilador não sabia da existência do tipo no<int> (declarado em main.cpp) e por isso não compilou a implementação para no<int>. Aí quando vc compilou main.o, o compilador tentou criar o tipo no<int> e encontrou a declaração do template no cabeçalho lista.h, mas não encontrou a definição dos métodos que estão em lista.cpp.
A solução é colocar a definição dos métodos de no no mesmo cabeçalho lista.h:
#ifndef lista_h                                                                                #define lista_h

#include <iostream>

using namespace std;

template<typename type> class no{
private:
    type v;
    no *prox;
public:
    no(type v);
    void setProx(no* prox);
    type obterValor();
    no<type>* obterProx();
};

template<typename type>
no<type>::no(type v){
    this->v = v;
    this->prox = NULL;
}

template<typename type>
void no<type>::setProx(no<type>* prox){
    this->prox = prox;
}

template<typename type>
type no<type>::obterValor(){
    return this->v;
}

template<typename type>
no<type>* no<type>::obterProx(){
    return this->prox;
}

#endif

Eu sei que é estranho, mas esse é o padrão para definir templates em cabeçalhos.
Compilar lista.o é desnecessário, então sugiro que vc mude o seu makefile também:
all:
        g++ main.cpp -o exe

go:
        ./exe

clean:
        rm *.o && rm exe


Placing shape behind icon as hover state

Question: I'm trying to place a shape behind an icon so when you hover the shape will show behind the icon. This is my html code:

Marketing

and this is the CSS:
.icon .hover1:hover {
  background-image: url(images/marketing_2.png);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-size: cover;
}

Currently the shape is not showing up properly. Not sure what to do now as I'm pretty new to all of this.
Icon with text underneath
Shape I want to place behind icon when I hover
Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Comment: Why do I suspect that your marketing icon is not transparent?
Answer: Is it useful for you or not?

.hover1:hover .img2{
   display: block;

}

.img2{
  display:none;
  z-index: -1;
  position: absolute;
  top: -2px;
  right: 36%;
  width: 180px;
  height: auto;
  transition: all 0.5s ease-in;
}

.hover1{
    width:fit-content;
    height:fit-content;

}

.img1{
  width:50px;
  height:auto;
    margin-top:30px;
}

div{
  text-align:center;
}

h3{
  margin-top:0px;
}

Marketing

Comment: This placed a large version of the background shape in the middle of the screen. It did not appear directly behind the icon on hover.
Answer: I think this CSS must help you what do you want
.icon .hover1{
            position: absolute;
            top: 10%;
            left: 10%;
            z-index: 1
        }
        .icon .hover1:hover{
            position: absolute;
            top: 10%;
            left: 10%;
            background-image: url(https://i.stack.imgur.com/JB1Xw.png);
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
            z-index: 0
        }

Comment: set your position as you want
Comment: I'm afraid this did not work. It placed the icon up the top left of the screen and nothing happened on hover.
Comment: This site will need to be responsive also


Modeling outliers in maximum likelihood estimation with gradient descent

Question: Consider a set of 3D points $X = \{x_1, x_2, ...x_n\} $ with $ x_i\in\mathbb{R}^3$ on which we want to fit an arbitrary probability distribution. The distribution we want to fit models some geometrical shape, like a sphere, a torus or a cylinder, but in principle this detail is irrelevant for my question. Just assume we can evaluate the PDF of the distribution.
Assuming there is no closed form solution for the maximum likelihood estimate of the parameters of the distribution, we can use an iterative gradient descent method to minimize the negative log likelihood:
$$
\mathcal L = \sum_{x \in X} -\log(P(x \, | \,\theta))
$$
where $P(x \, | \,\theta)$ is the probability density function and $\theta$ is the vector of parameters to optimize.
However, imagine that the points we are trying to fit include some blobs of outliers, which cannot be modelled with our distribution. Inspired by this paper [1], I thought one way to handle the outliers could be to include a constant hyper-parameter $\Omega$ in the loss function which gives each point a minimum probability:
$$
\mathcal L = \sum_{x \in X} -\log(P(x \, | \,\theta) + \Omega)
$$
This way, the loss won't go to infinity as soon as one outlier point is not well fitted by the distribution and has $P(x \, | \,\theta) \approx 0.$ Having tried this in practice, I can confirm this allows fitting the object of interest while ignoring the blobs of outlier points, even in cases where the number of outlier points outnumbers the inliers by far.
Moreover, I understand this is somewhat equivalent to fitting a mixture model with two components: 1) our arbitrary distribution with PDF $P(x \, | \,\theta)$ and 2) a uniform PDF with constant value $\Omega$. In this regard, would it make sense to introduce two more parameters into the optimization problem to model the mixture weights? Or is this unnecesary, given that one of the mixture components has no parameters to optimize.
$$
\mathcal L = \sum_{x \in X} -\log(w_1 \, P(x \, | \,\theta) + w_2 \, \Omega)
\\  s.t. ~~ w_1 + w_2 = 1
$$
In addition, are there other ways to make the fitting robust to outliers in a setup like this?
[1] https://arxiv.org/abs/2303.15440 (see Eq. 7)
Answer: The parameters have no effect on the minimisation. The effect is already regulated with the single parameter $\Omega$
$\qquad \hat{\theta} = \min_\theta  -\mathcal L(\theta)$
$\qquad \hat{\theta} = \min_\theta \sum_{x \in X} -\log(w_1 \, P(x \, | \,\theta) + w_2 \, \Omega)$
using $w_2 = 1-w_1$
$\qquad \hat{\theta} =  \min_\theta \sum_{x \in X} -\log(w_1 \, P(x \, | \,\theta) + (1-w_1) \, \Omega) $
rearranging terms
$\qquad  \hat{\theta} =  \min_\theta  \sum_{x \in X} -\log( \, P(x \, | \,\theta) + \frac{1-w_1}{w_1} \, \Omega) -\log(w_1)$
We can drop the term $\log(w_1)$ which only shifts the likelihood with a constant and has no effect on the minimisation
$\qquad \hat{\theta} = \min_\theta  \sum_{x \in X} -\log( \, P(x \, | \,\theta) + \frac{1-w_1}{w_1} \, \Omega)$
$\frac{1-w_1}{w_1}\Omega$ can be combined into a single constant
$\qquad \hat{\theta} =  \min_\theta \sum_{x \in X} -\log( \, P(x \, | \,\theta) + \Omega^\prime)$

In addition, are there other ways to make the fitting robust to outliers in a setup like this?

With the current method you assume that an outlier is distributed homogeneously. If you know more properties about outliers, and if you know more about the true distribution (e.g. potential correlation between measurements), then you can incorporate this into the likelihood function.
In addition you may have some cost function that you want to minimize, this you may add in a cross validation step to optimize the model hyper-parameters.
Comment: Thanks for your answer. However, note that in the original formulation $\omega$ is not an optimizable parameter, but a fixed hyper-parameter. From your analysis, I take that introducing the optimizable mixture weights while keeping $\omega$ fixed is equivalent to making $\omega$ optimizable. Is that right?
Comment: @DanielLópez Yes, 'making your constant $\Omega$ a variable $\Omega$' versus 'multiplying it with a variable', that has the same effect. To me it would make more sense to do the first and not the second. Why keep this constant when you can combine it with that multiplicative variable?
Comment: I think if you just make $\Omega$ an unbounded variable, it will just blow up to infinity, because you can monotonically reduce the loss by increasing $\Omega$. The mixture weights, which are constrained to $w_1 + w_2 = 1$, introduce a trade-off: you can increase the probability contributed by the uniform component of the mixture, but at the cost of reducing the contribution of the $P(x|\theta)$ component. I think you neglected that trade-off when you dropped the $-log(w_1)$ term. Are you sure you can do that when you are actually also tuning $w_1$?.
Comment: Yes, that is true if you optimize $\Omega$ as a model parameter along with $\theta$ to maximize the likelihood. In that case the step where $-log(w_1)$ is dropped should indeed be skipped. In that case you can drop the $\Omega$ term (set it equal to $\Omega = 1$), and use only a single parameter $w_1$.
Comment: Okay, that makes it clear. Feel free to edit the response to summarize our discussion, which I think is relevant to make the answer more complete. Otherwise I will accept the answer as it is. Thanks a lot!


Render Panels Overridden user profile template

Question: I have overridden the user profile template using Panels module and want to render this overridden user profile in one of my custom module.
Actually I wanted to show "About Author", tab besides the "View" tab of article, which when clicked, will show overridden user profile.
For that I have created menu entry as follows:
function custom_menu() {
   $items = array();

    $items['node/%node/author'] = array(
        'title' => 'About Author',
        'page callback' => 'get_node_author',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

My function is as follows:
function get_node_author($node = NULL) {
    $account = user_load($node->uid);
    $account_view = user_view($account);
    return drupal_render($account_view);
}

But it is loading user profile in normal format and not the one which is customized using panels.
Any suggestion how can I achieve this?
Comment: Never tried, so I don't know. Out of curiosity, why are you doing this from a custom function anyway? Having built a large number of sites with Panels, I find the idea odd, and I'm wondering if you really should be solving this differently.
Comment: I just wanted to create one MENU_LOCAL_TASK (because it must be tab besides view, edit etc.) entry for node that shows customized author profile. Do you have any suggestion ?
Comment: Why not just re-create the user override you now have as a custom page in Panels? You can handle the menu directly from there.
Comment: Ok let me try out.
Comment: Ok, posted as an answer.
Answer: I suggest you don't create a menu hook at all.
Just implement your desired layout in a custom panels page instead, and you can control the menu from there.
Comment: Hey, thanks it is working, one last thing, how can I create tab menu from it.
Comment: Got it, I selected menu tab.
Comment: Well, that was easy ;) Glad I could help. :)


How to reference already existing Azure Portal created storage accounts in an ARM template

Question: I want to create a function app with ARM template such that the ARM template references already existing storage accounts (inputstgdev and outputstgdev) which I have already parameterized. I would like the ARM template to use the inputstgdev storage account as its attached storage account such that it does not have to create a new storage account. The source control of the function app is referenced to a Gitrepo which I have also parameterized in the ARM template. Each time I run the ARM template I get the following error message
##[error]Deployment template validation failed: 'The resource '/subscriptions/bea8ac84-24a4-4e53-9198-e3b0107547d4/resourceGroups/dev-rgp/providers/Microsoft.Web/sites/functionapp/sourcecontrols/web' at line '1' and column '3069' doesn't depend on parent resource '/subscriptions/bea8ac84-24a4-4e53-9198-e3b0107547d4/resourceGroups/dev-rgp/providers/Microsoft.Web/sites/functionapp'. Please add dependency explicitly using the 'dependsOn' syntax. Please see aka.ms/arm-template/#resources for
Any suggestions what the issue might be or possible solutions.
I look forward to your response
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "126.96.36.199",
"parameters": {
    "InputstorageAccount": {
        "defaultValue": "inputstgdev",
        "type": "String"
    },
    "GitrepoBranch": {
       "type": "string",
       "defaultValue": "master",
       "metadata": {
            "description": "Name of the branch to use when deploying (Default = master)."
        }
    },
    "GitrepoURL": {
       "type": "string",
       "defaultValue": "https://github.com/FBoucher/AzUnzipEverything.git",
       "metadata": {
            "description": "URL to repo (Default = master)."
        }
    },
    "InputcontainerName": {
      "type": "string",
      "defaultValue": "inputcontainer",
      "metadata": {
        "description": "Specifies the name of the blob container."
      }
    },
    "OutputstorageAccount": {
        "defaultValue": "outputstgdev",
        "type": "String"
    },
    "OutputcontainerName": {
      "type": "string",
      "defaultValue": "outputcontainer",
      "metadata": {
        "description": "Specifies the name of the blob container."
      }
    }
},
"variables": {},
"resources": [
    {
        "type": "Microsoft.Storage/storageAccounts/blobServices/containers",
        "apiVersion": "2019-06-01",
        "name": "[concat(parameters('InputstorageAccount'), '/default/', parameters('InputcontainerName'))]",
        "properties": {
            "publicAccess": "None"
        }
    },
    {
        "type": "Microsoft.Storage/storageAccounts/blobServices/containers",
        "apiVersion": "2019-06-01",
        "name": "[concat(parameters('OutputstorageAccount'), '/default/', parameters('OutputcontainerName'))]",
        "properties": {
            "publicAccess": "None"
        }
    },
    {
        "name": "serviceplan",
        "type": "Microsoft.Web/serverfarms",
        "apiVersion": "2018-02-01",
        "location": "[resourceGroup().location]",
        "sku": {
            "name": "F1",
            "capacity": 1
        },
        "tags": {
            "displayName": "serviceplan"
        },
        "properties": {
            "name": "serviceplan"
        }
    },
    {
        "name": "functionapp",
        "type": "Microsoft.Web/sites",
        "apiVersion": "2018-11-01",
        "location": "[resourceGroup().location]",
        "kind": "functionapp",
        "dependsOn": [
            "[resourceId('Microsoft.Web/serverfarms', 'serviceplan')]",
            "[resourceId('Microsoft.Storage/storageAccounts', parameters('InputstorageAccount'))]"
        ],
        "properties": {
            "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', 'serviceplan')]",
            "siteConfig": {
                "appSettings": [
                    {
                        "name": "AzureWebJobsDashboard",
                        "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('InputstorageAccount'), ';AccountKey=', listKeys(parameters('InputcontainerName'),'2015-05-01-preview').key1)]"
                    },
                    {
                        "name": "AzureWebJobsStorage",
                        "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('InputstorageAccount'), ';AccountKey=', listKeys(parameters('InputcontainerName'),'2015-05-01-preview').key1)]"
                    },
                    {
                        "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
                        "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('InputstorageAccount'), ';AccountKey=', listKeys(parameters('InputcontainerName'),'2015-05-01-preview').key1)]"
                    },
                    {
                        "name": "WEBSITE_CONTENTSHARE",
                        "value": "[toLower('functionapp')]"
                    },
                    {
                        "name": "FUNCTIONS_EXTENSION_VERSION",
                        "value": "~2"
                    },
                    {
                        "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
                        "value": "[reference(resourceId('microsoft.insights/components/', 'applicationInsightsName'), '2015-05-01').InstrumentationKey]"
                    },
                    {
                        "name": "FUNCTIONS_WORKER_RUNTIME",
                        "value": "dotnet"
                    }
                ]
            }
        },
        "resources":[
            {
                "apiVersion": "2015-08-01",
                "name": "web",
                "type": "sourcecontrols",
                "dependsOn": [
                  "[resourceId('Microsoft.Web/sites/', parameters('InputstorageAccount'))]"
                ],
                "properties": {
                    "RepoUrl": "[parameters('GitrepoURL')]",
                    "branch": "[parameters('GitrepoBranch')]",
                    "publishRunbook": true,
                    "IsManualIntegration": true
                }
            }
        ]

    }
]

}
Comment: If the answer is helpful, please accept it as answer( click on the check mark beside the answer to toggle it from greyed out to filled in). Thank you.
Answer: You encountered this error message due to the wrong dependency.
You should use "[resourceId('Microsoft.Web/sites/', 'functionapp')]" instead of "[resourceId('Microsoft.Web/sites/', parameters('InputstorageAccount'))]".
And you should delete the storage dependency.
"[resourceId('Microsoft.Storage/storageAccounts', parameters('InputstorageAccount'))]"

By the way, as you already have a storage account, you just need to paste your connection string in the value of AzureWebJobsStorage and AzureWebJobsDashboard.
Just like
{
    "name": "AzureWebJobsDashboard",
    "value": "{connectionstring}"
}


Toast Message in ios with multiline

Question: I Am looking for a Toast Message Library such as MBProgressHUD, which contains loading screen with message and without, detail text and only text message.
But MBProgressHUD not have the support for multiline toast message only in showing text message
Can anyone suggest me a Library.
Thanks in advance.
Answer: Please use detailsLabelText property of MBProgressHUD. It supports multiline text.
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeText;
hud.detailsLabelText = @"Your multiline text here ......."
hud.removeFromSuperViewOnHide = YES;
hud.margin = 10.f;
[hud hide:YES afterDelay:2];

Answer: This library does what you need DCToastView allowing you to provide toast messages from the top or bottom side of the screen using auto layout and stackviews it renders as many lines as you need:

You will just need to add the pod
pod 'DCToastView'
Import it where you want to use it.
import DCToastView
And use it
ToastPresenter.shared.show(in: self.view, message: "This is a toast")
You can pass the following properties to the show method:

view: The view in which the toast is going to be presented
message: The message that the toast will show
toastPlace: The place which can be .down or .up
backgroundColor: The background color of the toast; defaults to black
textColor: The text color of the message; defaults to white
timeOut: The amount of seconds for the toast to dismiss if not provided it means that the toast will be sticky (will remain until touched); defaults to nil
roundness: How round the toast will be: .none, .low, .mid, .high; defaults to .mid
Answer: This is something, which was needed by you. Created with lot of Animation Options, screen positions, and duration. Even you can provide your own duration. Check that out below.
AVIToast Link
ToastThis Supports Multiline toasts.
Comment: The link to given library seems not to work. Could you please fix it?
Comment: It is fixed now, Thanks for Informing. Please up vote it.
Answer: I'm able to display multiline messages with MBProgressHUD using this code:
MBProgressHUD *h = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

h.mode = MBProgressHUDModeText;
h.labelText = n.userInfo[@"message"];
h.labelFont = [UIFont boldSystemFontOfSize:12];

[h hide:YES afterDelay:1];

Toast Message in ios with multiline


Manually generate random sample in Gaussian mixture model

Question: I want to generate (manually) a random sample in the Gaussian mixture model:
$$f_{\theta}(x) = \sum_{k = 1}^{K}\pi_k f_{\mathcal N(\mu_k, \sigma^2_k)}(x)$$
Here is my work:
theta = list(pi = c(p1,...,pK), mu = c(m1,...,mK), sigma = c(s1,...,sK))

rnormmix = function(n,theta){
  x = runif(n)

  # find mixed cdf
  pnormmix = function(x,theta){
    cdf = sapply(x, function(y) sum(theta$pi*pnorm(y,theta$mu, theta$sigma)))
    return(cdf)
  }

  # find the root of the equation fmix = F(x) - u
  fmix = function(x,u) pnormmix(x,theta) - u
  my_root = function(x) uniroot(fmix, c(-1000, 1000), tol = 0.0001, u = x)$root

  # generate sample
  return(sapply(x, my_root))
}

My questions are:

Is my work correct? In the uniroot function, I impose the root must be in the interval c(-1000,1000). What happens if the root falls outside this interval?
Are there any better methods?
Answer: In principle, this seems fine, provided there is negligible mass outside of $(-1000,1000)$. It also seems problematic to extend this to a multivariate context.
A common, and more general method is to draw an assignment variable, $y \sim \operatorname{Multinomial}(\pi)$, and condition on it.
In your case this would entail:
Step 1: $y_i \stackrel{iid}{\sim} \operatorname{Multinomial}(\pi)$
Step 2: $x_i | y_i \sim \operatorname{N}(\mu_{y_i}, \sigma^2_{y_i})$
Edit: Example R code
K <- 10
pi_raw <- rexp(K)
theta <- list(pi = pi_raw/sum(pi_raw),
             mu = rnorm(K, 0, 10),
             sigma = abs(rnorm(K, 0, 3)))

rnormmix <- function(n,theta){
  y <-apply(rmultinom(n, size = 1, prob = theta$pi),2,function(col) which(col==1))
  # generate sample
  return(data.frame(x=rnorm(n, theta$mu[y], theta$sigma[y]),y=y))
}

df <- rnormmix(1000, theta)
library(ggplot2)
ggplot(data=df, aes(x=x)) + geom_histogram(aes(y=..density..)) +
  geom_segment(data=data.frame(x=theta$mu, yend=theta$pi),
               aes(x=x,xend=x,y=0,yend=yend), color="red")

Comment: @SiXUlm $\theta$ is fixed in the above example. Does this answer your question?
Comment: Thanks! In case the variable is fixed (like mine), do you have any suggestion?
Answer: Pick $k$ at random according to $\pi$ and simulate the corresponding normal distribution.
rnormix <- function(n, pi, mu, sigma){
  K <- length(pi)
  simulations <- numeric(n)
  for(i in 1:n){
    k <- sample.int(K, 1L, prob=pi)
    simulations[i] <- rnorm(1, mu[k], sigma[k])
  }
  return(simulations)
}

Example:
pi <- c(1/4, 3/4)
mu <- c(0,10)
sigma <- c(1,1)
sims <- rnormix(1000, pi, mu, sigma)
plot(density(sims))

For a better performance:
rnormix <- function(n, pi, mu, sigma){
  K <- length(pi)
  k <- sample.int(K, n, replace=TRUE, prob=pi)
  simulations <- rnorm(n, mu[k], sigma[k])
  return(simulations)
}


Passing referrer to track installs Google Play browser mode

Question: This question is similar to the one asked here
Android (Google Play) Referral Tracking Limitations which hasnt recieved much attention.
I wish to send a deeplink url(as a referrer) and pass the same to the app once its installed.
People who have defaulted the http google play url to playstore on device or select google play app to launch the url forward the referrer but the same is not done if the browser launches the url and the user then selects install.
Is there a workaround for the same.
Answer: It sounds like the App Invites API is exactly what you want.  It allows your users to send links to your application and it tracks referrers and deep link data.  It also works across Android and iOS.


Classical music theory notation for chord inversions (figured bass)

Question: In classical music harmony analysis, we see the chord inversions notated like I6/4, I6, V4/3.
Examples:

What are those numbers? How do they define the inversion? What's the theory behind using those specific numbers?
Answer: Just to expand on Pat's answer, there is a figured bass symbols for all type of inversion including root position.

The picture above shows the complete figured bass symbol and how it will be denoted in analysis. As you can see root position triads and 7th chords have their own complete figured bass symbols, but reduce drastically because how common they are.
The numbers are determined by the interval between the bass note(the lowest note) and the other chord members. So if there was a B in the bass and the chord reduced to a G major in the key of C, the Roman Numeral would be V figured bass would be 6/3 which would reduce to 6 . Only the exact voicing of the bass matters.
The reason why the distinctions are made in analysis is because the bass defines the harmonic progression and different inversions will function differently. For example, a second inversion triad is rather dissonant and has to be approached and resolved correctly in order to sound correct. The figured bass along with the Roman Numeral analysis tells almost everything you need to know about the harmonic progression of a piece.
Answer: They are figured bass numbers, as used under bass lines in (primarily) the Baroque era to indicate harmonic content to be improvised by continuo players such as the harpsichordist. The numbers refer to the diatonic intervals above the bass. Look at your 6/4 example above. The two distinct notes above the bass note are a sixth and a 4th above, hence 6/4. This is true for all of them, although some intervals are left out. For instance, 6/5 (first inversion seventh chord) is technically 6/5/3, but we generally omit the 3rd. 6 (first inversion triad) is technically 6/3, etc.
Comment: The system of notating chords with numbers in figured bass actually predates the idea of giving chords names like C major or C7 or C minor, and predates the idea of referring to a "chord progression" as a sequence of chord names with cadences. Figured bass notation evolved as the Renaissance compositional method of polyphonic music and counterpoint evolved into the Baroque and Classical idea of chord progressions. But the numbers are retained in the study of classical music *theory* because the numbers tell you something about the structure of functional harmony.
Answer: The roman numerals indicate which chord we are using in the scale. If the Roman numerals are written with capital letters then they indicate a Major Chord. If they are written in lower case letters then they indicate a minor chord. A Major chord has a major third and a perfect fifth. A minor chord has a minor third and a Perfect fifth.
I(i) - Tonic
II(ii) - Super Tonic
III(iii) - Mediant
IV(iv) - Sub Dominant
V(v) - Dominant
VI(vi) - Sub Mediant
VII(vii) - Leading Tone
You also sometimes get + and °. The plus sign means we have a augmented chord which means a major third and an augmented fifth. The little degree sign means we have diminished chord whihc implies a minor third and an diminished fifth.
See those two as an accordian going in and out with the augmented chord we have both the third and the fifth going away from the root just like an expanding accordian. With the diminished we have bot the third and the fifth coming closer to the root.
Then lastly we have the inversions. When we talk about inversions we want to know what notes in the chord is at the bottom. The other notes can be arranged differently for specific reasons but inversion tells us what note is on the bottom.
If you have your basic triad you have three notes. Lets say we are in C Major's tonic chord. The notes in our chord would be C-E-G.
If it is in root position the C is at the bottom. If we count from C. We have C(1)d(2)E(3)f(4)G(5) hence the notation of 5/3 for the triad in root position.
If we now go to first inversion we now have the E at the bottom. So we have E(1)f(2)G(3)a(4)b(5)C(6) hence the notate the triad in first inversion as 6/3
The triad in second inversion now has the G at the bottom. So we have the notes G(1)a(2)b(3)C(4)d(5)E(6) hence the notation 6/4
There is also notes with there sevent add. Usually done on the Dominant or Super Tonic chords. So our Triads just get another noted added to them.
So for the seveth chord on the dominant step of C Major we have the notes G-B-D-F
If we are in root position the G is at the bottom So we have the notes G(1)a(2)B(3)c(4)D(5)e(6)F(7) hence the notation of 7/5/3 or more commonly G7
If we are in first inversion of the dominant seventh chord of C Major we now have the notes B(1)c(2)D(3)e(4)F(5)G(6) hence the notations 6/5/3 or more commonly just 6/5
If we are in second inversion of the dominant seventh chord of C Major we have D(1)e(2)F(3)G(4)a(5)B(6) hence the notation 6/4/3 but because our triad in second inversion is called 6/4 we use the notation 4/3 for the dominant seventh chord in second inversion.
Lastly the seventh chord in third inversion here we would have the notes F(1)G(2)a(3)B(4)c(5)D(6) hence the notation of 6/4/2 which we generally call 4/2.
Comment: Can we theoretically have two different inversions result in the same distances from the bass note, and therefore yield the same figured bass notation?
Comment: @MihaiDanila Inspired by your comment, you may be interested in [Can there be a chord with two inversions giving the same figure?](https://music.stackexchange.com/q/124567/70803) — allowing you haven't already found the answer on your own.
Comment: I haven't found the answer (music is a slow-moving hobby for me); thank you for asking that!


Read data from DB and send it as a downloadable zip file

Question: I have a usecase where I want to read data from database and send it to frontend as a downloadable zip file. I am stuck on how to achieve this using node js and express.
For now I was trying to send just a downloadable json file and was confused how to achieve it.
What I have tried so far ->
const data = db.read() // fetch an array of objects.
const myBuffer = Buffer.from(JSON.stringify(data));  //creating a buffer
const readableStream = Readable.from(myBuffer);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=\"my json file.json\"');
readableStream.pipe(res);

trying this from postman gives me json directly. My question is how to create a downloadable zip file of data here and send it to client. I want to make sure I don't use fs to write a file on server and then send it. Any help and guide would be great, Thanks!!
Comment: Take a look at this library and its docs: https://stuk.github.io/jszip/
Comment: @ardritkrasniqi That looks nice but I would prefer not using a library. Was hoping using node's zlib module
Answer: As @ardritkrasniqi suggested to use a third party npm package, I was able to make an in memory zip file and send it to client using npm package archiver.
I created it like this ->
const data = db.read() // fetch an array of objects.
const myBuffer = Buffer.from(JSON.stringify(data));  //creating a buffer
const archive = archiver.create('zip', {});
archive.append(myBuffer, { name: 'test.json'});
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename=\"test.zip\"');
archive.pipe(res);
archive.finalize();

Hope this will be helpful for others who are trying to achieve the same.
PS. I am using express as my backend node framework.


can i say "NO" to "Clone multiply-claimed blocks" in fsck?

Question: I need to know if i can still mount the volume  when i tell fsck "no" in that question.
i dont need to repair all the files in the volume, i just need recover one single file for this event.
the volume got some big files that put fsck stuck for hours if i say "Yes".
    has 753108 multiply-claimed block(s), shared with 3 file(s):
The volume if over LVM and runs a EXT3 Filesistem.
Comment: possible duplicate of [Huge amounts of "multiply-claimed blocks" during fsck](http://serverfault.com/questions/366863/huge-amounts-of-multiply-claimed-blocks-during-fsck)
Answer: Don't repair it. Mount it read only and get your file. When you're done, wipe the drive.
Since you have a superblock error, you can try to mount the filesystem using an alternate superblock. See
http://www.cyberciti.biz/faq/recover-bad-superblock-from-corrupted-partition/
(if someone could edit in the instructions I would appreciate it. I'm on a phone.)
Comment: it told me the there was no superblock
Comment: the damage was done with a buggy hybrid sata raid controller
Comment: See my edit. You can mount read only using an alternate superblock.
Answer: You should be able to mount the filesystem even though it has multiply-claimed blocks.  Do this on an image (I assume you're already working from a bitwise image of the partition, but it never hurts to check).
Multiply claimed blocks will cause corruption for sure if you try to write to them, but you should be able to read from the file you want if this is the only problem (and hopefully fsck can make that so).


Show that $E(S)=\sqrt{\frac{1}{n-1}}\frac{\Gamma(n/2)}{\Gamma[(n-1)/2]}\sigma$

Question: Let $X_1,...,X_n$ be a random sample of size $n$ from the normal distribution with mean $\mu$ and variance $\sigma^2$ and let $S^2=\frac{1}{n-1}\sum^n_{i=1}(X_i-\bar{X})^2$ be the sample variance. Show that $$E(S)=\sqrt{\frac{1}{n-1}}\frac{\Gamma(n/2)}{\Gamma[(n-1)/2]}\sigma$$
Edited:
Below is my trial
$$X_i~N(\mu,\sigma^2)$$
Let $Y_i=(X_i-\bar{X})^2$
$$Y_i=X_i-2X_i E(X_i )+[E(X_i )]^2$$
$$Y_i=X_i^2-2X_i μ+μ^2$$
$$∑_{i=1}^n(X_i^2-2X_i μ+μ^2)=∑_{i=1}^n(X_i^2)-2\mu∑_{i=1}^n(X_i)+n\mu^2$$
Then I not able to continue, because it seem can't simplify further.
Any hint? Because I don't think my steps have the right approach.
Comment: What are your thoughts on the problem? What methods have you attempted already? It appears as if you simply copied a problem to this site. That is not encouraged; rather, we look for questions that include more context about where the problem was encountered, why it is interesting, and what the asker has attempted.
Comment: Sorry about that. I edited the content.
Comment: Are you familiar with Cochran's theorem, which shows that $(n-1)\frac{S^{2}}{\sigma^{2}}$ follows a chi-squared distribution with $n-1$ degrees of freedom? You could use this together with the fact that $x\mapsto\sqrt{x}$ is monotonic on $[0,\infty)$ to calculate $E(S)$.
Answer: To get you started, define a random variable $X$ by
$$X = \frac{(n-1)S^{2}}{\sigma^{2}} \sim \chi_{n-1}^{2}$$
Then
$$S = \sqrt{\frac{\sigma^{2}X}{n-1}}$$
and
$$\mathbb{E}[S] = \mathbb{E}\left[\sqrt{\frac{\sigma^{2}X}{n-1}}\right]= \sqrt{\frac{\sigma^{2}}{n-1}}\mathbb{E}[\sqrt{X}]$$


Find a point (x,y) at a distance 'd' from a given point(a,b) and an angle theta in 2-D.

Question: I am trying to find a point (x,y) that is at a given distance 'd' from a known point(a,b) at an angle theta. it would have been doable if I knew either x or y but both are unknown in this case and the angle (theta) may be clockwise or anti-clockwise in different situations. Also, the point (a,b) does not necessarily lie on the x-axis or the y-axis. this point lies on a given line at some angle from the true North.
Any hints on this problem would be really helpful. I have attached an image for better clarity.(point (c,d) is known).enter image description here
Comment: What do you mean by an angle from a point? An angle can be measured *from* an axis or a specified line or line segment in a defined *sense* (clockwise or counterclockwise). Otherwise, your question is ill-posed.
Comment: Hi @Deepak. thank you. I have made edits to the question.
Answer: Here is the standard process (requiring a number of steps).
Firsr, start with a change of axes from

to

and follow the steps shown. The formula for rotation can be found in many youtube video.


Why are my TextViews null?

Question: I want if the user enters an invalid number, two TextViews should change their texts.
I looked up and checked if I got more than one TextView with the same id and the ruesult was that each id from my  TextViews are unique.
Everytime I force my error with entering an invalid number my app crashes. If i start the app in debug and marked my two "problematic codes". The result was both TextViews were null.
I don't know why this happens because the id's are unique and I don't  change my current layout.
My java code:
public void checkingInput(View view) {
    TextView eKnowledge  = (TextView) findViewById(R.id.enterKnowledge);

    try{
        int inputNumber = Integer.parseInt(eKnowledge.getText().toString());
        _knowledge = KnowledgeLevel.fromUserInput(inputNumber);
        test();
        hideKeyboard(view);
    } catch(NumberFormatException e){
        errorKnowledge();
        hideKeyboard(view);
    }
}

@SuppressLint("SetTextI18n")
public void test() {
    setContentView(R.layout.test);
    TextView test = (TextView) findViewById(R.id.textView_nur_einmal_benutzt_hoff_ich);
    switch(_knowledge) {
        case NOOB:
            test.setText("ENUM = NOOB");
            break;
        case BEGINNER:
            test.setText("ENUM = BEGINNER");
            break;
        case ADVANCED:
            test.setText("ENUM = ADV");
            break;
        case PRO:
            test.setText("ENUM = PRO");
            break;
        case GRANDMASTER:
            test.setText("ENUM = GM");
            break;
        case ERROR:
            errorKnowledge();
            break;
        case FAIL:
            test.setText("FEHLER!");
            break;
    }
}

@SuppressLint("SetTextI18n")
public void errorKnowledge(){
    TextView hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
    TextView tKnowledge = (TextView) findViewById(R.id.testWissenstandText);

    /* da ist der fehler ... einmal mit dem debugger durch zeigt es doch direkt: hKnowledge und tKnowledge sind null, daher die NullPointerException */

    hKnowledge.getResources().getString(R.string.FehlerGefunden);
    hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
    tKnowledge.getResources().getString(R.string.FehlerText1);
    tKnowledge.getResources().getColor(android.R.color.holo_red_light);
}

private enum KnowledgeLevel {
    FAIL, ERROR, NOOB, BEGINNER, ADVANCED, PRO, GRANDMASTER;

    static KnowledgeLevel fromUserInput(final int input)
    {
        if (input >= 11 || input <= -1) {
            return ERROR;
        }
        else if (input == 10) {
            return GRANDMASTER;
        }
        else if (input >= 7) {
            return PRO;
        }
        else if (input >= 4) {
            return ADVANCED;
        }
        else if (input >= 1 ) {
            return BEGINNER;
        }
        else if (input == 0) {
            return NOOB;
        }
        return FAIL;
    }
}

And my XML:
<TextView
    android:id="@+id/testWissenstandHeader"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="8dp"
    android:text="Bla"
    android:textAlignment="center"
    android:textColor="#511613"
    android:textSize="32sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="@+id/kastenKnowledge"
    app:layout_constraintLeft_toLeftOf="@+id/kastenKnowledge"
    app:layout_constraintRight_toRightOf="@+id/kastenKnowledge"
    app:layout_constraintTop_toTopOf="@+id/kastenKnowledge"/>

<TextView
    android:id="@+id/testWissenstandText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text='BlaBla'
    android:textAlignment="center"
    android:textColor="#E0E0E0"
    android:textSize="20sp"
    app:layout_constraintHorizontal_bias="0.512"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/testWissenstandHeader"/>

I researched a bit and the only solution I found on stackoverflow.com was that I need to use setContentView(); but I've got two problems with that:
1. Why should I use that if I don't chnage my layout?
2. I tried it and my app didn't crash BUT my texts didn't change. (setContentView(); were used before setText();" is used)
Here's my whole errorreport (no debug prozess):
08-10 00:14:53.580 2774-2774/com.example.alexander.hashtagnevereverbuggy E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.alexander.hashtagnevereverbuggy, PID: 2774
                                                                                java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:4756)
                                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:4756)
                                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.widget.TextView.getResources()' on a null object reference
                                                                                at com.example.alexander.hashtagnevereverbuggy.MainActivity.errorKnowledge(MainActivity.java:112)
                                                                                at com.example.alexander.hashtagnevereverbuggy.MainActivity.test(MainActivity.java:97)
                                                                                at com.example.alexander.hashtagnevereverbuggy.MainActivity.checkingInput(MainActivity.java:68)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:4756)
                                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

EDIT:
package com.example.alexander.hashtagnevereverbuggy;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

import java.util.Map;

@SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity implements Heroes {

private KnowledgeLevel _knowledge = KnowledgeLevel.NOOB;

private static FragmentManager _fragmentManager;

private enum WerteTextFelder {
    TITLE,TYP, DAMAGE, LADUNG, KUGELN, NACHLADEDAUER, HEILUNG, HEADSHOT, WIRKUNGSDAUER, EXTRAEFFEKT, BESONDERHEIT
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MobileAds.initialize(this, getString(R.string.AppID));

    _fragmentManager = getFragmentManager();

    Button testButtonAnfang = (Button) findViewById(R.id.AnfangsButton);
    testButtonAnfang.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            setContentView(R.layout.testwissenstand);
        }
    });
}

@Override
public void onBackPressed() {
    if(getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    }
    super.onBackPressed();
}

public void checkingInput(View view) {
    TextView eKnowledge  = (TextView) findViewById(R.id.enterKnowledge);

    try{
        int inputNumber = Integer.parseInt(eKnowledge.getText().toString());
        _knowledge = KnowledgeLevel.fromUserInput(inputNumber);
        test();
        hideKeyboard(view);
    } catch(NumberFormatException e){
        errorKnowledge();
        hideKeyboard(view);
    }
}

@SuppressLint("SetTextI18n")
public void test() {
    setContentView(R.layout.test);
    TextView test = (TextView) findViewById(R.id.textView_nur_einmal_benutzt_hoff_ich);
    switch(_knowledge) {
        case NOOB:
            test.setText("ENUM = NOOB");
            break;
        case BEGINNER:
            test.setText("ENUM = BEGINNER");
            break;
        case ADVANCED:
            test.setText("ENUM = ADV");
            break;
        case PRO:
            test.setText("ENUM = PRO");
            break;
        case GRANDMASTER:
            test.setText("ENUM = GM");
            break;
        case ERROR:
            errorKnowledge();
            break;
        case FAIL:
            test.setText("FEHLER!");
            break;
    }
}

@SuppressLint("SetTextI18n")
public void errorKnowledge(){
    TextView hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
    TextView tKnowledge = (TextView) findViewById(R.id.testWissenstandText);

    /* da ist der fehler ... einmal mit dem debugger durch zeigt es doch direkt: hKnowledge und tKnowledge sind null, daher die NullPointerException */

    hKnowledge.getResources().getString(R.string.FehlerGefunden);
    hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
    tKnowledge.getResources().getString(R.string.FehlerText1);
    tKnowledge.getResources().getColor(android.R.color.holo_red_light);
}

private enum KnowledgeLevel {
    FAIL, ERROR, NOOB, BEGINNER, ADVANCED, PRO, GRANDMASTER;

    static KnowledgeLevel fromUserInput(final int input)
    {
        if (input >= 11 || input <= -1) {
            return ERROR;
        }
        else if (input == 10) {
            return GRANDMASTER;
        }
        else if (input >= 7) {
            return PRO;
        }
        else if (input >= 4) {
            return ADVANCED;
        }
        else if (input >= 1 ) {
            return BEGINNER;
        }
        else if (input == 0) {
            return NOOB;
        }
        return FAIL;
    }
}

public static void addTransaction(Fragment fragment, String tag){
    if (_fragmentManager != null) {
        FragmentTransaction fragmentTransaction = _fragmentManager.beginTransaction();
        fragmentTransaction.add(fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }
}

private void hideKeyboard(View view){
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

private class geileListener implements View.OnClickListener{
    private Hero hero;

    private geileListener (Hero hero) {
        this.hero = hero;
    }

    @Override
    public void onClick(View view) {
        setContentView(hero.getHeroLayout());
    }
}

private void advertisment() {
    /*Notwendig um advertisment im showlock darzustellen*/
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}

public void showPreview (Hero hero) {
    setContentView(hero.getPreviewLayout());
    ImageButton button = (ImageButton) findViewById(R.id.imageButton_Preview);
    button.setImageResource(hero.getPreviewImage());
    button.setOnClickListener(new geileListener(hero));
    advertisment();
}

private Map<WerteTextFelder, TextView> getWerteTextFelder() {
    setContentView(R.layout.werte);
    Map<WerteTextFelder, TextView> map  = new HashMap<>();

    TextView Titel = (TextView) findViewById(R.id.textView_Überschrift);
    TextView Typ = (TextView) findViewById(R.id.textView_Werte_0);
    TextView Damage = (TextView) findViewById(R.id.textView_Wert_1);
    TextView Ladung = (TextView) findViewById(R.id.textView_Wert_2);
    TextView Kugeln = (TextView) findViewById(R.id.textView_Wert_3);
    TextView Nachladedauer = (TextView) findViewById(R.id.textView_Wert_4);
    TextView Heilung = (TextView) findViewById(R.id.textView_Wert_5);
    TextView Headshot = (TextView) findViewById(R.id.textView_Wert_6);
    TextView Wirkungsdauer = (TextView) findViewById(R.id.textView_Wert_7);
    TextView ExtraEffekt = (TextView) findViewById(R.id.textView_Wert_8);
    TextView wert9 = (TextView) findViewById(R.id.textView_Wert_9);

    map.put(WerteTextFelder.TITLE, Titel);
    map.put(WerteTextFelder.TYP, Typ);
    map.put(WerteTextFelder.DAMAGE, Damage);
    map.put(WerteTextFelder.LADUNG, Ladung);
    map.put(WerteTextFelder.KUGELN, Kugeln);
    map.put(WerteTextFelder.NACHLADEDAUER, Nachladedauer);
    map.put(WerteTextFelder.HEILUNG, Heilung);
    map.put(WerteTextFelder.HEADSHOT, Headshot);
    map.put(WerteTextFelder.WIRKUNGSDAUER, Wirkungsdauer);
    map.put(WerteTextFelder.EXTRAEFFEKT, ExtraEffekt);
    map.put(WerteTextFelder.BESONDERHEIT, wert9);

    return map;
}

Everything else (abput 4k Lines of code) arent important

Comment: Can you publish the whole class? I'd like to understand when the errorKnowledge method is called, and if you've run a setContentView in the onCreate method.
Comment: from your log it's saying you have a problem on "onClick"
Comment: @instantiator I updated my code. There you go
Comment: @Salman500 Idk why, because I use my `checkingInput` method and my button got this `onClick` method. I don't know why there should be any problem
Comment: What invalid num. are you trying to input?
Comment: @iann -1 or lower, 11 or higher
Answer: In your onCreate(), you have to to call setContentView(R.layout.whateveryourxml). After that, but still tracing back to your onCreate, you may call errorKnowledge(). This should make sure that neither TextView is null.
Comment: I updated my question, I don't think I need to do sth in my `onCreate();` method.
Answer: [Edit: Just to clarify, you do have to call the setContentView method during onCreate, or your TextViews will resolve to null. Assuming you've done that - as in the code you posted - read on!]
These lines of code don't seem right to me. They don't look as if they will do anything:
hKnowledge.getResources().getString(R.string.FehlerGefunden);
hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
tKnowledge.getResources().getString(R.string.FehlerText1);
tKnowledge.getResources().getColor(android.R.color.holo_red_light);

The reason you're seeing no effect is that these are get statements that return some values, but then you don't actually use those values to do anything.
I feel like what you actually want to say is this:
hKnowledge.setText(R.string.FehlerGefunden);
hKnowledge.setTextColor(android.R.color.holo_red_dark);
tKnowledge.setText(R.string.FehlerText1);
tKnowledge.setTextColor(android.R.color.holo_red_dark);

I'd also recommend that you spend some time in your onCreate method doing all the findView work, so that you don't need to do it again and again later. (It's also a little clearer and saves you quite a bit of boilerplate java.)
You can define your various TextView elements (etc.) as private members for the class, so - as an example, just for the 2 TextViews we're already talking about:
private TextView hKnowledge;
private TextView tKnowledge;
...
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
  tKnowledge = (TextView) findViewById(R.id.testWissenstandText);
  ...
}

Having done this, you can then refer to the two TextViews from anywhere else in your class just as their members: hKnowledge and tKnowledge;
Comment: A question to your edit:  My "start" layout is "activity_main" and there is a button which changes the contentView to "testwissenstand". So why do I need to do that in my `onCreate` method?
If I use more than one `setContentView`, I thought it will only use the last one
Comment: It's possible I suppose, although it seems the recommended way to change layouts around dynamically is with Fragments. Fragments have complex lifecycles though so I'd recommend reading up on them.

You could inflate the views manually yourself, and then set your various buttons etc. on the appropriate view, ie. if you create a view `view1 = getLayoutInflater().inflate(R.layout.layout1, null);` then you can find your buttons in it like this `button1 = view1.findViewById(R.id.button_1);` and then you can `setContentView(view1);` (or to any other view) as you prefer.

Why are my TextViews null?


Gap between the words in Key

Question: Let us suppose there is a gap between the words of the key. For example

        Language: {{lang.language}}

        Web Framework: {{lang.Web Framework}}

How to get {{lang.Web Framework}}. I know, i am going wrong there should not be gap between the words, but suppose i get the requirement then how i gonna do it.
Comment: Basic object accessing question. Should have done searching before posting.
Answer: You can use it as
  Web Framework: {{lang["Web Framework"]}}

DEMO

        Language: {{lang.language}}

        Web Framework: {{lang["Web Framework"]}}

Comment: Whoever downvoted! ***** reason
Comment: Yaa, I got it. This was really silly. Thanks for correcting.
Comment: mark if that helped

Gap between the words in Key


Should scales start on 4th natural?

Question: The Pythagorean system of tuning produces, via succeeding 3/2 multiples of a base note (e.g., C), the following set of successive tone ratios:
C to D: 9/8
D to E: 9/8
E to F: 256/243
F to G: 9/8
G to A: 9/8
A to B: 9/8
B to C: 256/243
However, in order to obtain the value for F, one must either drop down a fourth (i.e., multiply C by 2/3) or continue around the circle of fifths for eleven steps.  Would it instead make sense to begin the scale at F or, if it begins at C, to end it on F-sharp?  In other words, would it be better, on a keyboard, to start the scale with four white notes rather than the current three?  If so, the ratios would be as follows:
9/8
9/8
9/8
256/243
9/8
9/8
256/243
This seems to be where the math leads.  Any thoughts are welcome.  Thanks!
-Burch
Comment: @Tim "C>F# is the dreaded tritone, quite dissonant" So is F>B, but nobody has tried to exclude that from a major scale, AFAIK. Anyway, the OP is talking about *Pythagorean* tuning, which makes tritones a different interval from equal temperament. In some temperaments tritones are not dissonant at all!
Comment: @Richard - C>F# is the dreaded tritone, quite dissonant. That's probably a good enough reason in itself to not be the 4th degree of a major scale...  Music seems to work better, and is more listenable when the notes don't jar. Although the aug4 is useful to modulate to the dominant.
Comment: Isn't this essentially the idea presented by George Russell in [The Lydian Chromatic Concept](https://en.wikipedia.org/wiki/Lydian_Chromatic_Concept_of_Tonal_Organization)? I believe he took fifths to be fundamental, and then noted that the Lydian mode can be constructed by stacking fifths.
Comment: The bottom line is that however you slice the math, if you adopt the basic idea of Pythagorean tuning to Just intervals with small integer ratios, somewhere you have to "lose" a factor of 81/80 to close the octave correctly. The "traditional" way to do this is have two different sizes of whole tones, 9/8 and 10/9, not to get rid of the perfect 4ths and 5ths between C and F.
Comment: All, thanks for the helpful feedback! David hit the nail on the head with his reference to Russell's Lydian Chromatic Concept of Tonal Organization, which is new to me. Per the Wikipedia entry: "Russell believed that dominant function was the driving force behind all harmonic motion. Russell focuses on the Lydian mode because it can be built with fifths. For instance, to construct a C lydian scale one could list the first seven tones on the circle of fifths starting with C, the desired Lydian Tonic. This process would yield C, G, D, A, E, B, F♯." Thanks again! -Burch
Comment: As I see it, we have no scientific explanation for why our scale-degree 4 is (in C) F and not F#. I'll be interested to see what answers come up here!
Comment: @Tim Yes, but C to B is also dissonant, and we don't seem to make a fuss about that. I still don't think we have a real *scientific* explanation; "Music seems to work better, and is more listenable when the notes don't jar" unfortunately doesn't meet that requirement.
Comment: "This seems to be where the math leads." - try listening to the result rather than playing with math. You might find that a "major third" of 81/64 sounds pretty rough before you even get to your version of a tritone.
Comment: I wonder if Tim is on to something. F to B is dissonant, but maybe it's not as noticeable as C to F#, because the latter involves the root itself. C to B seems less dissonant too. There might be a scientific explanation lurking somewhere behind what naturally/intuitively sounds good.
Comment: @Burch, I don't see why the math favors F# over F. On the circle of fifths, isn't F only one step away from C, whereas F# is as far away from C as is possible (6 steps away)? Or are you saying it would be more consistent for the notes of C major to require only *clockwise* movement around the circle: | C | G D A E B F# rather than F | C | G D A E B. Couldn't we just as easily say that the math favors notes *closer* on the circle to the root? That would make the preferred scale, in C: Eb Bb F | C | G D A. This cuts out notes like E and B which are farther from C on the circle of fifths.
Comment: Perhaps I'm trying to make the point that you've proposed a value judgment because you selected one mathematical pattern when multiple are available. The math doesn't contain value judgements like "the scale *should* only include clockwise movement around the circle of fifths" or "the scale *should* only include notes closer on the circle to the root." We could come up with other similar mathematical patterns, but saying that one is better than another is a subjective value judgment. It is still a very interesting question though, "why do we prefer F as the fourth over F# in a major scale?"
Answer: What would be the advantage?
F# is the tritone in C, which sounds quite dissonant to most people, so that's a pretty good reason, possibly the primary one.
Keep in mind that you're talking about using the Lydian mode instead of the Ionian mode or major scale, and some pieces do use the Lydian mode. The Ionian mode/major scale is more popular, probably because of the way it sounds.
Personally, I love the fourth scale degree being 5 half steps above the tonic, and I like having a whole step between the fourth and fifth degrees.

Should scales start on 4th natural?


Prove the Countable additivity of Lebesgue Integral.

Question:
Let $E\subset\mathbb{R}$ a measurable subset, $f\in L^1(E)$ and $\{E_n\}$ a disjoint countable union of measurables sets such that $\bigcup E_n=E$. Show that $$ \int_Ef=\sum_{n=1}^\infty\int_{E_n} f$$

MY ATTEMPT (using a hint of the teacher):
Let $f_n=f\chi_{A_n}$, where $A_n=\bigcup_{n=1}^{\infty}E_n$. As, $f\in L^1(E)\Rightarrow|f|\in L^1(E)$. We have that $|f_n|\leq|f|$ and
$$
\lim_{n\rightarrow\infty}f_n=f\lim_{n\rightarrow\infty}\chi_{A_n}=f\chi_E=f
$$
By the Dominated Convergence Theorem (learn more here: http://en.wikipedia.org/wiki/Dominated_convergence_theorem),
$$
\lim_{n\rightarrow\infty}\int_Ef_n=\int_Ef
$$
Now is my doubt
$$
\lim_{n\rightarrow\infty}\int_Ef_n{=}^*\sum_{n=1}^\infty\int_{E_n}f_n
$$
I don't know if I can affirm this last equality. Can someone explain this to me?
Comment: can you please tell how does the way you defined $A_{n} $ in 2 nd line of your attempt makes sense?
Answer: You can affirm that (there is no "n" in the member of the right in your question, makes confusion):
The $E_n$ are disjoint sets, so $$\forall N \in \mathbb{N}, \ \sum_{n=1}^N \int_{E_n} f=\int_{\bigcup\limits_{n=1}^N E_n} f = \int_{A_N}f = \int_E f_N$$
The you take the limit when $N$ goes to $\infty$, and i think you are done!


How do I prove this statement about greatest common divider?

Question: $$2\gcd(a, b) \le \gcd(2a,2b)$$
I'm pretty sure it has something to do with Bezout's lemma or it could use prime factorization, but unsure on how to go exactly about it. Please help!
Full Disclosure: This came up on a midterm and something like this may be on the final so I want to make sure I have it down for next time.
Comment: it does! to some extent, we were never taught the euclidean algorithm properly so I was hoping for something along the lines of bézouts lemma.
Answer: Normally you would prove the equality, as suggested by the link provided in comments. In this case however, you only need to prove one inequality. For this notice $2\gcd(a,b)|2a$ (because $2|2$ and $\gcd(a,b)|a$ by definition) and similarly $2\gcd(a,b)|2b$. So by definition $2\gcd(a,b)|\gcd(2a,2b)$, which implies $2\gcd(a,b)\leq \gcd(2a,2b)$.
Comment: @SamyakJain If LHS divides the RHS, it can not be greater than RHS,..
Comment: i can't quite wrap my head around why " 2gcd(,)|gcd(2,2) implies 2gcd(,)≤gcd(2,2)"
Comment: @SamyakJain Exactly as CiaPan writes, recall the defnition of $m \mid n$, it means $n=km$ (also in your case notice $m,n,k$ are positive)
Answer: It is the special case $\,d = \gcd(a,b)\,$ below.
$$ d\mid a,b\,\Rightarrow\, 2d\mid 2a,2b\,\overset{\!\rm\color{#c00}U}\Rightarrow\, 2d\mid \gcd(2a,2b)\Rightarrow\ 2d\le \gcd(2a,2b)\qquad$$
where we used $\rm\color{#c00}U$ = gcd Universal Property below (provable by Bezout as in the link)
$$ x\mid y,z\!\!\overset{\rm\color{#c00}U\!\!}\iff x\mid \gcd(y,z)\qquad$$
Alternatively employ $\,2\gcd(a,b) = \gcd(2a,2b)\,$ by the gcd Distributive Law.


Mass Continuity Equation for Fluid - Running Into a Problem

Question: I'm running into a problem when trying to show the mass continuity equation for a fluid, which says
$$\frac{\partial \rho}{\partial t} + \left(\nabla \cdot \rho \textbf{u}\right) = 0$$
Where $\rho=\rho(x,y,z,t)$ is the density of the fluid and $\textbf{u} = \textbf{u}(x,y,z,t)$ is the velocity vector of the infinitesimal unit of volume [or mass].
I start by noting that $m=\iiint_V\rho dV$. Differentiating that (with chain rule) gives us
$$\begin{align*}
\frac{\partial m}{\partial t} &= \frac{\partial}{\partial t}\iiint_V \rho dV\\
&= \iiint_V \frac{\partial \rho}{\partial t} dV\\
&= \iiint_V \left(\frac{\partial \rho}{\partial x}x'(t)+\frac{\partial \rho}{\partial y}y'(t)+\frac{\partial \rho}{\partial z}z'(t)+\rho_t\right)dV\\
&=\iiint_V(\nabla \rho \cdot \textbf{u} + \rho_t)dV\\
\end{align*}
$$
And as you can see, that doesn't really match up with the originally stated continuity equation. I have $(\nabla \rho \cdot \textbf{u})$ instead of $(\nabla \cdot \rho \textbf{u})$. Where have I gone wrong? What needs to be corrected?
Comment: You should have terms like $\frac{\partial (\rho x'(t))}{\partial x}$ in your second to last line. The result follows from that in vector form.
Comment: Sorry I cannot write an explicit answer at the moment since I'm on my phone but you are setting up your mass balance incorrectly. The total rate of change inside the volume (your line 1) is set equal to the flux over the surface of the volume. And then an application of Gauss's theorem is used to recover the desired form. See: http://www.nptel.ac.in/courses/Webcourse-contents/IIT-KANPUR/FLUID-MECHANICS/lecture-10/10-4_cont_eqn_int_form.htm
Comment: Ah ok @LuisCosta, I got it. Thanks!
Answer: What we want is $\displaystyle \frac{dm}{dt} = \iiint_V \frac{\partial \rho}{\partial t} dV$. But the integrand here is not equal to the expression in the next line as you've written it; that would be the case if were writing out the complete derivative$\displaystyle \frac{d\rho}{dt}$.
Instead, the instantaneous change in the mass moving into the volume is equal to flow into the closed volume $V$ over its boundary $\partial V$. If $\vec{u}$ is the velocity vector of the fluid, then
$$\frac{dm}{dt} = -\iint_{\partial V} \rho\vec{u}.d\vec{A}$$
There is a negative sign here because we want mass moving in have a positive effect, not a negative effect and the convention with a closed surface is the to have the normal vectors $d\vec{A}$ pointing out.
Applying now Stokes' theorem, this last integral equal to
$$\frac{dm}{dt} = \iiint_V -\nabla(\rho\vec{u}) \ dV $$
Equating now the two expressions for $dm/dt$ we have the desired equation:
$$\frac{\partial \rho}{\partial t} + \nabla(\rho\vec{u}) = 0$$

I've never seen the derivation written down this way, but now that I have, I like it as much as the usual approach using infinitesimal cubes, of size $dx \ dy \ dz$, which in effect rederive Stokes' theorem for this case.


Como fazer um select de um select utilizando o Entity Framework ado.net

Question: Estou desenvolvendo um sistema em ASP.NET MVC que utiliza como padrão o Entity Framework para acesso de dados, porém estou necessitando de um select sobre outro select, e não sei como fazer isto com o Entity.
O código SQL que gostaria utilizar é o seguinte:
select * from pedidos as p
                 inner join agendamentos as a
                 on a.pedidoID = p.pedidoID
                 where a.data = (select max(data) from (select a.data from pedidos as p
                 inner join agendamentos as a
                 on a.pedidoID = p.pedidoID
                 where a.realizado = 0) as dataagendamentos);

Se alguem puder me ajudar, estarei grato!
Comment: Poderia colocar as entidades?
Comment: Poderia explicar qual o intuito desta consulta? Facilitará para a solução do seu problema (pois podem haver outras formas melhores de resolvê-lo).
Comment: A consulta é necessária para listar todos pedidos junto com o último agendamento realizado pelo mesmo.
Comment: @LucasKauer seria um simples
Pedidos 1->n Agendamentos
Answer: Você não deve usar o Entity Framework como SQL porque ele não é SQL. A sentença precisa ser repensada. Deve começar pelos agendamentos incluindo seus pedidos, e não os pedidos incluindo os agendamentos.
Ou seja:
var pedidos = db.Agendamentos
                .Include(a => a.Pedidos)
                .Where(a => a.Realizado == 0)
                .OrderByDescending(a => a.Data)
                .FirstOrDefault()
                .SelectMany(a => a.Pedidos)
                .ToList();

Comment: Pensando no que você fez eu consegui sucesso com o seguinte código:
 `var pedidos = Db.Agendamentos.Where(m => m.Data < DateTime.Now).Where(m => m.Realizado == false).ToList();
Db.Agendamentos.Include("Pedido").ToList();`

Obrigado!
Comment: O campo **Realizado** está na tabela de **agendamentos**, que possui a chave **pedidosID (FK)** e tambem um **Date** que mostra para quando foi agendado. O que eu preciso fazer é Listar todos os pedidos incluindo o ultimo agendamento **já realizado** e que **não foi pago**.
Comment: Você implementou minha resposta? Se sim, qual o resultado apresentado? Além disso, você editou sua pergunta colocando qual o objetivo da seleção, conforme este comentário que fez na minha resposta?


Can a VBO form be integrated with the Commerce Add-to-Cart form to allow adding optional add-on products with checkboxes?

Question: With VBO and Rules I can display a list of Commerce products with checkboxes and a button to add the checked products to the cart (see how).
Is there a way to integrate these checkboxes with the default Add-to-cart form from Commerce? I want to have a single Add-to-Cart form with one button, not two forms.
Alternatives I tried:

The module Commerce Product Add-on allows this, but it doesn't use Views for the list, so I can't customize the appearance (e.g., group the products).
The module Commerce Add to Cart Extras allows this with input fields for the quantitiy, but not with checkboxes. (The patch in Checkboxes instead of quantity doesn't seem to work.)

Is there another way/module?
My goal is to display optional add-on products (with checkboxes) on a primary product page. If the user doesn't select any add-on product, only the primary product is added to the cart; if the user selects add-on products, the primary product and the selected add-on products get added to the cart.
(The question Drupal Commerce - optional extra products on add to cart form seems to have the same goal, but OP seems to be fine with the Commerce Product Add-on module if it would work for him in his case. The question add to cart - multiple products at once seems to be for adding always the full set of products, so without checkboxes.)
Answer: You could do it with Custom Line Item Fields for checkboxes and either just track the add on products using the line item or create a rule that adds the matching product to the cart when an line item is added that has checkbox field values.
PS: If you go with line item fields only approach, you should use pricing rules to change the final price of any line item with those check boxes to add prices to them. If you do that, then you might want this patch that allows line item fields to automatically ajax update the price when something changes:
https://www.drupal.org/node/1541886


Upper and Lower bounds on Normal Operator Norm

Question: The problem comes from Naylor's Linear Operator Theory Section 5.23 Problem 14

Let $T$ be a normal operator on Hilbert space $H$ and let $T = A + iB$ be the Cartesian decomposition of $T$. Show that
  $$\mathrm{max}(\left\lVert A\right\rVert^2,\left\lVert B\right\rVert^2) \leq\left\lVert T\right\rVert^2 \leq \left\lVert A\right\rVert^2+\left\lVert B\right\rVert^2$$

I've shown that Cartesian decomposition of $T$ is unique, $T^*=A-iB$, and that $A$ and $B$ commutes.
For the $\left\lVert T\right\rVert^2 \leq \left\lVert A\right\rVert^2+\left\lVert B\right\rVert^2$ part, I used the fact that $T$ is normal and use that $\left\lVert T\right\rVert^2 =\left\lVert T T^*\right\rVert = \left\lVert T^2 \right\rVert$.
However the $\mathrm{max}(\left\lVert A\right\rVert^2,\left\lVert B\right\rVert^2) \leq\left\lVert T\right\rVert^2$ part is giving me trouble. At first, I made a series of inequalities to build up  to$\left\lVert T\right\rVert^2$, but no luck.
Answer: From the properties of the decomposition, one gets
$$
\|Tx\|^2 =\|Ax\|^2 + \|Bx\|^2,
$$
hence
$$
\max( \|Ax\|^2, \|Bx\|^2 ) \le \|Tx\|^2 \le \|T\|^2 \|x\|^2.
$$
Now take the supremum over $x$ with $\|x\|\le 1$.


enabling users to upload pictures from their harddrive in wysiwyg

Question: I have wysiwyg module with IMCE enabled so I can browse the server of my site is located for pictures I can upload to add to my content. But the idea now is to have users that are bloggers to be able to upload pictures from their harddrive on to the site using a wysiwyg editor (in this case CKEditor).
Anyone experience with that and know how to do that or know of a good tutorial for this. When searching for an answer online I found info that explained how to add CCK fields to my content type but this is not what I want. I want bloggers to be able to choose where they put the pictures in text and how many.
Answer: I have used the WYSIWYG image upload module successfully on my previous D6 sites. It has good documentation and a simple interface to do what you need.
Comment: It's out there! Thanks this totally did the job. Cheers!


Interpenetration of regression coefficient in my case

Question: I run a regression between Gender, age as IVs and cholesterol as a dependent variable. The coefficient of gender is -0.57 (male=1,female=0) and the coefficient of age is 0.4. Now I am wondering how I can explain these coefficients?
Comment: **Interpenetration???**
Answer: The coefficient of gender means:

If I sample two data points from my population, and observe that they have the same age, but different genders, then I expect that, on average, the difference in cholesterol I will observe is -0.57.

The coefficient of age means:

If I sample two data points from my population, and observe that they have the same gender, but one is exactly one year older than another, then I expect that, on average, the difference in cholesterol I will observe is 0.4.

These interpretations are contingent on the regression being a good fit to the data.  I.e., if the actual relationship between age and cholesterol is non-linear (i.e. quadratic, exponential, or something more exotic) then taking these interpretations at face value is not advisable.
Comment: 57% could be appropriate only if your response variable is measured in %. If your response is measured in other units (for example, mg/cm3) then expected cholesterol for me would have 57 units less (or more) than women of the same age.
Comment: Hi, thanks for the comment. Can I say: As age increases by one unit, cholesterol will increase by 0.4 units on average as long as we have the same gender.  2.Men compare to women, have 57% less cholesterol as long as age held constant.?
Comment: Those seem ok, just a bit more informal.
Comment: @ Matthew Drury, so using 57% less is appropriate?


how to hide a button for 10 min with pure js and html

Question: I was using jQuery but I would like to just have JS and HTML hide this button for 10 minuets. jQuery code:

setInterval(function() {}, 100);
setTimeout(function() {
  $(".hide").css("visibility", "visible");
}, 600000);

  <button class="cool_button" onclick="buyMegaMiner()">
    Hire MegaMiner
  </button>

I would like to do the same thing but with pure js and html
Comment: http://youmightnotneedjquery.com/
Answer: replace
$(".hide").css("visibility", "visible");

with
document.getElementsByClassName("hide")[0].style.visibility = "visible";

Comment: I need it to work on 3 buttons using the same class.
Comment: works for three class's using --->    setInterval(function() {}, 100);
    setTimeout(function() {
      document.getElementsByClassName("hide(1)")[0].style.visibility = "visible";
      document.getElementsByClassName("hide(2)")[0].style.visibility = "visible";
      document.getElementsByClassName("hide(3)")[0].style.visibility = "visible";
    }, 600000);


simulate artificial data for regression with a specific P value for y~x

Question: I would like to simulate a dataset to perform simulations with - I would like to set a specific P value a priori and not perse the beta-coefficient, so that I can do follow-up simulations.
So taking the following example of https://stats.stackexchange.com/a/46525/40998
, is it possible somehow to create a random dataset that has P value of 0.01 for y~x1?
> set.seed(666)
> x1 = rnorm(1000)           # some continuous variables
> x2 = rnorm(1000)
> z = 1 + 2*x1 + 3*x2        # linear combination with a bias
> pr = 1/(1+exp(-z))         # pass through an inv-logit function
> y = rbinom(1000,1,pr)      # bernoulli response variable
>
> #now feed it to glm:
> df = data.frame(y=y,x1=x1,x2=x2)
> glm( y~x1+x2,data=df,family="binomial")

Answer: If you had a straight-up linear model, this would just be a question of scaling the residuals. For a binomial model, it's a bit harder. I think your best best will likely be to do rejection sampling. Simulate your model many times and pick out the one that yields a p value closest to what you want. (Simply store the RNG seeds so you can recreate it.)
Note that with $n=1000$ observations and rather strong effects, your p values may well be far lower than the 0.01 you are aiming for, so you might want to reduce either $n$ or the effect size.
n.obs <- 20
n.sims <- 1e4
p.values <- rep(NA,n.sims)

for ( ii in 1:n.sims ) {
    set.seed(ii)
    x1 = rnorm(n.obs)           # some continuous variables
    x2 = rnorm(n.obs)
    z = 1 + 2*x1 + 3*x2        # linear combination with a bias
    pr = 1/(1+exp(-z))         # pass through an inv-logit function
    y = rbinom(n.obs,1,pr)      # bernoulli response variable

    #now feed it to glm:
    df = data.frame(y=y,x1=x1,x2=x2)
    model <- glm( y~x1+x2,data=df,family="binomial")
    p.values[ii] <- summary(model)$coefficients[2,4]
}
hist(p.values,breaks=seq(0,1,by=0.01))

which.min(abs(p.values-0.01))

The big peak at 1 probably comes from those simulations where you got all zeros or all ones. You can now reset the RNG using the output from the last line and resimulate your model:
set.seed(which.min(abs(p.values-0.01)))
x1 = rnorm(n.obs)           # some continuous variables
x2 = rnorm(n.obs)
z = 1 + 2*x1 + 3*x2        # linear combination with a bias
pr = 1/(1+exp(-z))         # pass through an inv-logit function
y = rbinom(n.obs,1,pr)      # bernoulli response variable

#now feed it to glm:
df = data.frame(y=y,x1=x1,x2=x2)
summary(glm( y~x1+x2,data=df,family="binomial"))

The result:
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   1.0701     0.8382   1.277   0.2017
x1            1.7253     0.6888   2.505   0.0122 *
x2            1.1760     0.8392   1.401   0.1611