no matches for kind "PrometheusRule" in version "monitoring.coreos.com/v1" when install RabbitMQ HA using helm

Question: When I using helm v3.2.1 to install RabbitMQ HA in kubernetes v1.15.2 cluster follow by this manual:
./helm install stable/rabbitmq-ha --generate-name -n dabai-pro

it give me this tips:
[miao@MeowK8SMaster1 linux-amd64]$ ./helm install stable/rabbitmq-ha --generate-name -n dabai-pro
Error: unable to build kubernetes objects from release manifest: unable to recognize "": no matches for kind "PrometheusRule" in version "monitoring.coreos.com/v1"

should I install some dependencies? what should I do to make it work? This is my helm version detail info:
[miao@MeowK8SMaster1 linux-amd64]$ ./helm version
version.BuildInfo{Version:"v3.2.1", GitCommit:"fe51cd1e31e6a202cba7dead9552a6d418ded79a", GitTreeState:"clean", GoVersion:"go1.13.10"}

and this is the repo I am using now:
[miao@MeowK8SMaster1 linux-amd64]$ ./helm repo list
NAME    URL
stable  https://kubernetes-charts.storage.googleapis.com/

Answer: You can install Prometheus operator in the cluster. RabbitMQ is monitored by Prometheus.After installation verify by running below command
kubectl api-resources | grep prom
prometheuses                                   monitoring.coreos.com          true         Prometheus
prometheusrules                                monitoring.coreos.com          true         PrometheusRule

For different installation options(including helm) of Prometheus check this
Comment: And if I really don't wanna install the Prometheus operator, what do I do to avoid this error?
Answer: It seems like setting prometheus.operator.enabled=false doesn't require Prometheus installation.
I ran this:
helm install --set existingConfigMap=true,prometheus.operator.enabled=false rabbit-ha stable/rabbitmq-ha

And the chart successfully installed.


Why does XDebug remote debugging loses my path mapping (Eclipse) after submit?

Question: I am using XDebug to remote debug an application in Eclipse. I have probably not correctly configured Eclipse.
When I start debugging everything works fine. But as soon as I submit a form, the debugger continues working but Eclipse does not seem to be able to map the server side files to my local files.
Here is the stack trace I see before the submit:
wwwc.example.com [PHP Web Application]
  PHP Application
    Remote Launch (suspended)
      www.example.com/htdocs/toto.inc.php.toto_inc : lineno 12() www.example.com/htdocs/toto.inc.php at line 12
      www.example.com/htdocs/toto.inc.php.include : lineno 23() www.example.com/htdocs/toto.inc.php at line 23
      www.example.com/htdocs/simple.inc.php.include_once : lineno 325() www.example.com/htdocs/simple.inc.php at line 325
      www.example.com/htdocs/index.php.{main} : lineno 106() www.example.com/htdocs/index.php at line 106

After submit
wwc.example.com [PHP Web Application]
  PHP Application
    Remote Launch (stepping)
      /stuff/share/websites/wwwc.example.com/process.php.{main} : lineno 8() /stuff/share/websites/wwwc.example.com/process.php at line 8

Notice that the path after submit (/struff/share/website/wwwc.example.com) is server side while the path before (www.example.com/htdocs) is on my computer. The file and line numbers are correct.
How can I fix this?
Answer: The disk on the server was mounted on a NTFS file system.
There was case error on the action URL (which was not discovererd because NTFS is case insensitive).
Eclipse's mapping strategy is case sensitive which means it did not map the local file to the remote file.
Fixing the case error solved the mapping problem.
Comment: This answer solved the issue for me. I had used a large X: when mapping my samba share. Changing it to a small x: got me passed the next hurdle.


Normalizer of a subset of algebraic group

Question: Let $G$ be a linear algebraic group (I'm thinking of these as subsets of affine space over an algebraically closed field.). Define the normalizer of a subset $H$ to be $\{g \in G: gHg^{-1} \subseteq H\}$. Is this equal to $\{g \in G:gHg^{-1}=H\}$?
Comment: It seems, from ehat you copied of the book («…maps $H$ to a closed subgroup of $G$…») that he is assuming that $H$ is in fact a closed subgroup.
Comment: Yes thank you. I edited my question
Comment: But if $H$ is a closed subgroup, it is in particular an affine subvariety of $G$ and therefore it has a well-defined and well-known notion of dimension as an affine variety.
Comment: Oh right. Now I see what Humphreys is saying
Answer: This holds for any finite group and is not true for infinite groups in general. I'll denote $n(G):=\{g \in G: gHg^{-1} \subseteq H\}$ and $N(G) := \{g \in G: gHg^{-1} = H\}$. Clearly, we always have $N(G) \subseteq n(G)$. Let's show that $n(G)\subseteq N(G)$ holds if $G$ is finite: If $g \in n(G)$, the map
\begin{align}
\varphi_{g} :\; &H \rightarrow H \\
              &h \mapsto ghg^{-1}
\end{align}
is well-defined. It's also easily seen to be injective: $$\varphi_g (h) = \varphi_g(h') \Leftrightarrow ghg^{-1} = gh'g^{-1} \Leftrightarrow hg^{-1} = h'g^{-1} \Leftrightarrow h = h'$$ Because $H$ is a finite set, every injective mapping from $H$ to $H$ is surjective, which shows $\varphi_g(H) = H$ which is equivalent to $g \in N(G)$. If $G$ is infinite, this is no longer true in general, see this question for a counterexample.
Comment: OK but I am restricting to linear algebraic groups so I  excluding the example in the other question.
Comment: @CoffeeBliss how can you exclude it? You can view the set $N$ defined in the question as a subset of $GL_2 (\mathbb{C})$ which is a linear algebraic group (see here http://math.stackexchange.com/questions/169955/gl-nk-general-linear-group-over-a-algebraically-closed-field-as-a-affine-v )
Comment: Oh right. Sorry - I just saw this on the train and replied too quickly.
Answer: The right setup in which you should consider this question is when $H$ is a closed algebraic subset (i.e. Zariski-closed subset of $G$). If there is no algebraic structure on $H$, you won't be able to exploit the algebraic structure of $G$ and end up doing plain group theory where counter-examples can arise for cardinality reasons.
If $H$ is a Zariski-closed subset, write $H = \bigcup_{i=1}^n H_i$ where the $H_i$ are the irreducible components of $H$. If $gHg^{-1} \subseteq H$, we have
$$
gHg^{-1} = \bigcup_{i=1}^n gH_ig^{-1}
$$
and since conjugation by $g$ is an isomorphism of varieties, $gH_ig^{-1} \subseteq H$ is an irreducible subvariety of $H$. Therefore, conjugation simply permutes the irreducible components of $H$ and we conclude that $gHg^{-1} = H$.
Hope that helps,


Expectation of sample variance $E(s^2)=\sigma^2$

Question: Let
$$s^2=\frac{\left(\sum_{i=1}^n y_t^2\right)-n \bar y^2}{n-1}$$
be an estimator of $\sigma^2$. Let
$$E(yAy^T)=Tr(A\Sigma)+\mu^TA\mu$$
be an identity, where $y$ is a random vector, $A$ is a suitable matrix, and $\Sigma$ is a matrix covariance of $y$.
How can be proved $E(s^2)=\sigma^2$ using the above identity?
Comment: Can you write $s^2$ as a quadratic form in $y$?
Comment: $s^2=y^Ty-n(1/ny^Tj)(1/ny^Tj)^T$ where $j$ is a $nx1$  1's vector.
Answer: Proving this result depends on the matrices $A$ and $\Sigma$.  Usually (but not always) an estimator of the variance will use a quadratic form where $A \mu = 0$ for a vector of fixed values $\mu$, so in that case the second term will be zero and $\mathbb{E}(yAy^\text{T}) = \text{tr}(A \Sigma)$.  If you have a look at the form of $A$ that emerges from your estimator formula you will see that it is proportionate to the centering matrix, and it has this property.  It then remains only to derive the matrix $A \Sigma$ and show that its trace is equal to the variance parameter.  To do all this you're going to have to specify $\Sigma$, and then crunch the algebra in the formula.


Nenhum dispositivo aparece para o "run" do AndroidStudio

Question: Estava tudo normal até que fui montar um emulador com a api 21, durante o processo deu erro de disco sem espaço, meu AndroidStudio estava numa partição do hd com pouco espaço, apos o erro o ele começou um processo de indexing, e ficou nisso durante quase meia hora até que eu resolvi fecha-lo e abri-lo novamente, daí quando clico em "run" nem os emuladores aparecem nem meu celular conectado.
Eu já tentei:

Testar com dois celulares diferentes.
Montar uma nova imagem do emular com outra versão do android.
Iniciar o emulador pelo AVD Manager, ele inicia os já criados mas quando clico em "run" não aparece nada.
Já reinstalei o AndroidStudio.
já o instalei em outro lugar e iniciei o novo e mesmo assim não aparece nada e nem dá nenhum erro.

Ele fica apenas assim:
Answer: Você pode tentar voltar o android studio as configurações iniciais.
Vá a pasta de usuário
C:\Users\Seu_usuario

Nesta página, deve ter uma pasta com o nome de .AndroidStudio com sua versão atribuída ao nome da pasta.
Faça um backup desta pasta, e depois apague ela, isso removerar suas configurações.
Caso já tenha tentado isso, tente reinstalar as api.
Vá em Default Settings
Em SDK Plataforms, instale as versões, reinstale as API, e tente outras novas.
Depois, vá em SDK Tools, vá em Show Package Details e certifique-se de marcar as Android SDK Build-Tools nas versões que você escolheu antes.
Answer: O problema estava no processo do adb.exe que estava escutado porém sem fazer nada, para resolver foi simples, só abrir o gerenciar de tarefas e finalizar o processo, então voltar no Android Studio e tentar executar novamente.


Singular Matrix and Identity Matrix

Question:
Let $I$ be an identity matrix.
If $I+A$ is a singular matrix (i.e. $I+A$ has at least one eigenvalue
  being zero), then $\|A\|\geq 1$.

How does a zero eigenvalue of $I+A$ imply $\|A\|\geq 1$?
Comment: @carmichael561 Thanks. Let me edit my question.
Answer: If $I+A$ is singular, then $(I+A)x=0$ for some vector $x$. In other words, $Ax=-x$, and hence $-1$ is an eigenvalue of $A$. This implies $\rho(A) \geq 1$. Since $\Vert A \Vert \geq \rho(A)$ for any norm, the result follows.
Answer: The spectral mapping theorem gives
$$\sigma(I + A) = 1 + \sigma(A) = \{1+\lambda : \lambda \in \sigma(A)\}$$ so if $0 \in \sigma(I + A)$ then $-1 \in \sigma(A)$.
Hence there exists $x \ne 0$ such that $Ax = -x$.
We conclude
$$\|A\| \ge \frac{\|Ax\|}{\|x\|} = \frac{\|-x\|}{\|x\|} = 1$$

Singular Matrix and Identity Matrix


Turn File and Print Sharing on with Windows Firewall Off

Question: I have a Windows 2008 Server R2 that has a fax server on it. This server is NOT on a domain but WORKGROUP. The server has no firewall. The fax server is used for a critical application.
Problem:
I would like to SHARE the FAX server to a couple users on a domain.
I can go to Control Panel | Hardware | Devices and Printers and try to share the fax, but I get an error (0x000006D9). From Microsoft KB I must have the Windows Firewall Service enabled.

Is there a way to share a printer/fax without the Firewall ON? I can
try turning the firewall on and then sharing the fax, and then
turning off the firewall. But not sure what will happen.
Or is there a way to access the fax server remotely without using a
share?

I can not leave the firewall on. There is way to many applications running on it and other servers connecting remotely and probably turn into a huge headache getting everything running again. Which is why my predecessor left the firewall off and not on the domain with windows updates off for the last 2 years... Egads...
Comment: Wait...no windows updates and the firewall service has been disabled for 2 years?  You sure you even want that server running with network connectivity?
Comment: Like Nathan says below - start the service.  Turn off the firewall itself if you must (in the firewall settings), but keep the service running.
Comment: lead support for the application on this server answer for doing the updates was "Microsoft Updates break things"...... lol
Comment: How many times have we all heard "well, the guy here before me just disabled the firewall because they couldn't get it to work"..  UGH  I have industrial machinery that the techs did the same thing.  In talking to Japan and Germany where this equipment was manufactured, they both said this was SOP.    Windows firewall isn't hard to figure out is it? or maybe its just me and not wanting to leave everything unlocked.
Answer: If you must not have the firewall "on", you can work around this by setting it to allow incoming traffic by default instead of blocking.
Windows Firewall is basically embedded in Windows core networking components and needs to be enabled for a majority of things (sharing, for example) to work properly. Either set it to allow all by default or put in a rule to allow all traffic and bypass the block anyway. Either way, you must have it enabled.


Sum of powers of a number divisible by other?

Question: I need to find the probability that $7^m+7^n$ is divisible by $5$ where $m,n\in[1,100]$. I noticed that if the remainder when m and n are divided by 7 differs by two the last digit is zero. So I did $$P=\frac{4*25^2}{100^2}=\frac14$$But I'm now unsure to prove this seemingly correct fact. On a side note I haven't studied Number Theory.
Comment: $7^n$ mod 5 = 2,4,3,1,2,...The ways of making a sum divisible by five are: (4,1),(3,2).
Comment: @daniel how to prove that or present as a solution?
Answer: The first four powers (mod 5) of 7 are $\{2,4,3,1\}.$ After this the sequence repeats. There are 16 ways of pairing these and of those 4 sum to 5: $(2,3),(3,2),(1,4),(4,1).$ So 1/4 of the possible pairings lead to a sum $7^n+7^m =0~ \text{mod}~ 5$
In general there are $(4n)^2$ pairings of which $(2n)^2$ will sum to 0 mod 5. In this case
$$\frac{(2\cdot 25)^2}{(4\cdot 25)^2}= \frac{4\cdot25^2}{16\cdot 25^2} = 1/4. $$

Elementary probability (more than number theory) furnishes an explanation of this. If we have $n$ distinct objects and ask how many pairs can be made from the set, the number, written $nP$2, is
$$\text{Number of pairs} =\frac{n!}{(n-2)!} $$
If in addition we allow cases in which we pair two items that are indistinguishable,for example (4,4) from the set above, the number is
$$\text{Pairs including repetitions} = \frac{n!}{(n-2)!}+n = n(n-1)+ n = n^2. $$
Why do we include these? Because in the problem, we include cases like
$$7^2 +7^6$$
even though both powers are congruent to 4 (mod 5). If the probability of divisibility by 5 (etc.) is defined as
$$P =\frac{\text{number of pairs that sum to 0 (mod 5)}}{\text{number of possible pairs for} ~m,n \leq 100}$$
then this pair should be included. It also explains why the numerator grows proportionally. We treat like congruences associated with different numbers as distinct objects because their sum is still $0$ (mod 5).

The only number theory here is I think modular arithmetic.
Answer: 7=2 (mod 5)
7^m=2^m (mod 5)
 Also,
2^4=1 (mod 5) =>
2^4k=1=7^4k (mod 5)
2^(4k+1)=2=7^(4k+1) (mod 5)
2^(4k+2)=4=7^(4k+2) (mod 5)
2^(4k+3)=3=7^(4k+3) (mod 5)
Thus 5|7^(4k)+ 7^(4k+2) and 5|7^(4k+1)+7^(4k+3)
Further there are 25 integers of each form.Thus, 2*25*25 satisfy case 1 and 2*25*25 satisfy case 2
Thus a total of 4*25*25 are such cases
The rest is as you did
Comment: It would be difficult to prove it without using results from number theory!


Banco de dados externo mobile

Question: Sou novo em programação mobile.
Utilizo o sqllite como banco de dados. Porém o mesmo só consigo criar e usar um banco local. Gostaria de saber se existe um outro banco de dados ou uma opção do sqllite para estar fazendo um CRUD.
Por exemplo, para desenvolvimento Web, existe o MySql, onde você tem um CRUD e qualquer pagina na internet consegue alterar.
Gostaria no app mobile, um jeito de vários smartphones conectarem a um mesmo banco.
Estava dando uma olhada em um tutorial, no qual o desenvolvedor utiliza uma aplicação web, e dispara "get", então insere...
Mas pensando em um cenário onde tenho uma app que eu cadastro meus portfolios, e então a app exibe eles.
Eu vou ter então que ter uma Area feita em web, onde cadastro os portfolios, e então ficar recuperando pela app atravez de json.... O problema que sempre vai precisar de internet...
Ou então a cada novo portfolio preciso lançar uma atualização da app.
Answer: A metodologia atual mais utilizada consiste em duas aplicações: uma aplicação RESTful, vulgarmente API, hospedada num servidor web convencional que acessa um banco de dados convencional (MySQL por exemplo). E um APP que consome dados através dessa API.
Com relação a precisar de internet, não necessariamente, operações que não consomem dados (como criar um novo item) podem ser gravadas antes num banco de dados local e só depois, quando houver internet, serem enviados para a api.
Se você programa em PHP um bom framework RESTful para começar é o http://www.slimframework.com/.

Banco de dados externo mobile


Atomic operation on the circular global buffer in cuda

Question: I am implementing a circular global memory to enable all threads read/write data to the same buffer simultaneously. It is a very simple producer/consumer algorithm in cpu. But i found something wrong in my cuda code.
The circular buffer was defined as follows:
<code>#define BLOCK_NUM 1024
#define THREAD_NUM 64
#define BUFFER_SIZE BLOCK_NUM*THREAD_NUM*10
struct Stack {
    bool bDirty[BUFFER_SIZE];
    unsigned int index;
    unsigned int iStackSize;
}
</code>
The read device is implemented as
<code>__device__ void read(Stack *pStack) {
    unsigned int index = atomicDec(&pStack->index, BUFFER_SIZE-1);
    if(- -index >= BUFFER_SIZE)
        index = BUFFER_SIZE - 1;
    // check
    if(pStack->bDirty[index] == false) {
        printf("no data\n");
        return;
    }
    //set read flag
    pStack->bDirty[index] = false;
    atomicSub(&pStack->iStackSize, 1);
}
</code>
The write device function is:
<code>__device__ void write(Stack *pStack) {
    unsigned int index = atomicInc(&pStack->index, BUFFER_SIZE - 1);
    //check
    if(pStack->bDirty[index] == true) {
        printf("why dirty\n");
        return;
    }
    pStack->bDirty[index] = true;
    atomicAdd(&pStack->iStackSize, 1);
}
</code>
In order to test the read/write function in a more robust way, I write the following kernels:
<code>__global__ void kernelWrite(Stack *pStack) {
    if(threadIdx.x != 0) //make write less than thread number for testing purpose
        write(pStack);
}

__global__ void kernelRead(Stack *pStack) {
    read(pStack);
    __syncthreads();
    if(threadIdx.x % 3 != 0) // make write less than read
        write(pStack);
    __syncthreads();
}
</code>
In the main function, I used a dead loop to test if the read/write is atomic.
<code>int main() {
    Stack *pHostStack = (Stack*)malloc(sizeof(Stack));
    Stack *pStack;
    cudaMalloc(&pStack, sizeof(Stack));
    cudaMemset(pStack, 0, sizeof(Stack));

    while(true) { //dead loop
        kernelWrite<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
        cudaDeviceSynchonize();
        cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
        while(pHost->iStackSize >= BLOCK_NUM*THREAD_NUM) {
             kernelRead<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
                   cudaDeviceSynchonize();
                   cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
         }
    return 0;
}
</code>
When I execute the above code, I got error msg "why dirty" and "no data". What is wrong to the read/write logic?
By the way, I do not map the thread ID to the linear buffer address because in my application maybe only 10% threads write to the buffer, it is unpredictable/random.
Comment: I don't see any code for initializing the contents of `pStack` before you use it. Does it exist? It would be much simpler if you posted a proper [MCVE]
Comment: Sorry, i forgot to memset it because the code was uploaded by my phone but not from the pc.
Comment: @talonmies Yes the memset exsits in my runable programe. This demo is complete except some header includes   and
Answer: The key problem is that the atomic operation is not real atomic because of reading and writing to the same buffer. The weird thing is that when the total thread number is less then 4096, no error message will be shown.


How to retrieve license information with nuget command after version 3.3

Question: I'm trying to find a way to retrieve license information with the available nuget commands. The command Get-package | Select-Object Id, LicenseUrl does not work anymore and the Open-PackagePage command is deprecated and will be removed in the next release. Does anyone know what to use instead after nuget version 3.3?
Comment: What do you mean by "`Get-Package | Select-Object Id, LicenseUrl` does not work"? What is the exact error you are seeing?
Comment: The license url has been added back in NuGet 3.4. There is a [github issue](https://github.com/NuGet/Home/issues/1416) open on NuGet for this.
Comment: No error, but the LicenseUrl object is empty :)
Answer: The license url has been added back in NuGet 3.4.
There is a github issue open on NuGet for this.
Currently NuGet 3.4 is not yet released. There is an RC release which you could try or you can wait for the official final release.
Comment: Thanks a lot for the answer Matt!


Colocar trecho entre parenteses

Question: Tenho este código:
if(isset($params['bedrooms']) && is_numeric($params['bedrooms']) && $params['bedrooms'] > 0){
    $what['bedrooms >= ?']  = $params['bedrooms'];
    $what_or['suites >= ?'] = $params['bedrooms'];
 }

 $where = implode(' AND ',array_keys($what));
 $conditions = array_values($what);
 if (!empty($what_or)) {
   $where .= ' OR ' . implode(' OR ', array_keys($what_or));
   $conditions = array_merge($conditions, array_values($what_or));
 }
 pr($where);
 die();

Que vai me resultar em:
modality_id = ? AND property_type_id = ? AND properties.city_id = ? AND status = ? AND bedrooms >= ? OR suites >= ?
Porém preciso retornar isto com bedrooms >= ? OR suites >= ? entre parenteses, como posso fazer isso?
Ps: sem usar str_replace().
Answer: Coloque a condição do bedrooms na sua array de OR:
$what_or['bedrooms >= ?']  = $params['bedrooms'];
$what_or['suites >= ?'] = $params['bedrooms'];

Depois ajuste a parte que monta o SQL assim:
if (!empty($what_or)) {
   $where .= ' AND (' . implode(' OR ', array_keys($what_or)) . ')';
   $conditions = array_merge($conditions, array_values($what_or));
}

Comment: Obrigado pela resposta! Assim obtive como resultado isto : `modality_id = ? AND property_type_id = ? AND properties.city_id = ? AND status = ? AND garage >= ? AND bedrooms >= ? OR (suites >= ?)` quando preciso que me resulte assim `modality_id = ? AND property_type_id = ? AND properties.city_id = ? AND status = ? AND garage >= ? AND (bedrooms >= ? OR suites >= ?)
`
Comment: Atualizei a resposta @GWER, veja se resolveu.
Comment: Funcionou! Muito Obrigado!

Colocar trecho entre parenteses


Kendoui grid destroy method doesn't refresh grid

Question: I have a kendoui grid (no server-side wrappers). It has several columns displayed and "destroy" (delete) button. Everything works just fine. But it two issues:

When I click "delete" button, then a request to a server is sent (a record is sucessfully deleted on the server). I return a new list of records from the server (after processing a "delete" request). But this new list of records is ignored and not used on the client. And I have to use "requestEnd" grid event to refresh the grid. Hence two HTTP requests are made to the server: "delete a record", "load new list of records". Is it possible to delete a record and return a new list of records from the server usign one single HTTP request?
Also when I click "delete" button the appropriate grid row is immediatelly deleted (user-interface only), then a HTTP request is sent to the server. Is it possible to delete the record from the grid (UI) only after HTTP request is processed?

P.S. Previously when I used Telerik MVC Extensions (before kendoui) it worked fine.
Answer:
Destroy call is executed after the item is removed from the datasource.data() collection, therefore there is no need to return list. If your delete somehow effect other items in the list, call datasource.read form destroy.complete (but yes these are two calls).
At the other hand, nothing is stopping you from returning complex json object as a result of delete, where one of the properties would be your list, unwrapping it on destroy.complete and assigning property with the collection to the datasource, doable. Although consider paging, sorting and other features you will have to deal with if you decide to take it this way.
It is, you can implement custom command and implement the delete process as you wish, using the api.

Examples :
A) pagination and filters down to the server, assuming you enabled server side paging.
<code> parameterMap: function (o, operation) {
                            var output = null;
                            switch (operation) {
                                case "create":
                                    break;
                                case "read":
                                    output = '{ filter: ' + JSON.stringify(o) + '}';
                                    break;
                           }
                          return output;
                        }
                    },
</code>
B) Creating complex json is server side platform specific, in theory you wrap the actual json you are about to return to the client and wrap it into other json, add extra properties and then return it. You can then read it in a following way:
<code>transport: {
         destroy: {
             complete: function (jqXhr, textStatus) {
                       var result = jQuery.parseJSON(jqXhr.responseText);
                       var yourdata = result.yourdata
                       // pass your data to datasource
                      }
               }
           }
</code>
Comment: Thanks. Also my grid has several pages. When I click the "delete" button, the current pge number and size is not passed to the server. How can I make it to send the current grid parameters (such as "page size", "page index", "sorting options", etc?
Comment: Also could you please provide an example of this "returning complex json object as a result of delete, where one of the properties would be your list, unwrapping it on destroy.complete and assigning property with the collection to the datasource"?
Comment: I have updated the answer with some sample code. I think you should follow the kendo way and not to try to get around, alternative is doable but time consuming. (Make sure your model defines id, that could be a reason why the delete is not working). Good luck


passing javascript variable in app.settings (client side variable to server side)

Question:
I want to read the config file in javascript that is the google key
  value. here what i am trying to do is passing a javascript
  variable"keyvalue" that is the keyname in config file but it does not
  work. i just want it so that the js function automatically picks up
  the google key according to site URL whether it may be test or dev or
  qa.abc.com can anyone help me what should i do to read the value form
  config file.

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ReadConfigSettings()" />

    </form>

my config file

<appSettings>
    <add key="GoogleKey_dev" value="ABQIAAAAJ4psDZ8kCtN062-LDcwiXhQ85a215fgrIsfghh547457h1ETJRYlwaBGrrytgytg56g7Mx4QFQ"/>
    <add key="GoogleKey_qa" value="ABQIAAAACoUjxmFCsPtytryhtyty547547Ryt5gVV28BYSHIaU0BRwPyLrf_gf546Jd_5qxcNZ-_b7WZw"/>
    <add key="GoogleKey_test" value="AIzaSyvbghgfyh54654650x2SlGb33KrTtIBc"/>

Comment: [Read Configuration Settings of Web.config using Javascript](http://www.codeproject.com/Tips/77917/Read-Configuration-Settings-of-Web-config-using-Ja)
Comment: thanks for your answer but i want to pass a js variable in ConfigurationManager.AppSettings["Setting"] so simply i want is ConfigurationManager.AppSettings["my js variable"] and my js variable holds my key name.
Answer: Web.Config
</configuration>
    <appSettings>
        <add key="Setting" value="Value"/>
    <appSettings>
</configuration>

In Aspx page take
<asp:HiddenField runat='server' id='hidkey' />

In javascript
 document.getElementById('<%=hidkey.ClientID %>').value = '<%=System.Configuration.ConfigurationManager.AppSettings["Setting"] %>';

Now access in C#
  string key=hidkey.value;//Here u get web.config [Setting] value

Comment: thanks for your answer but i want to pass a js variable in ConfigurationManager.AppSettings["Setting"] so simply i want is ConfigurationManager.AppSettings["my js variable"] and my js variable holds my key name.
Comment: not possible...because AppSettings["Setting"] extract from web.config file.
Comment: yes as you can see above in js i wrote var keyvalue="GoogleKey_"+ first; so i want to pass this variable in AppSettings[] so that it automatically picks up the value from webconfig as per the parameter such as GoogleKey_test or GoogleKey_dev etc
Comment: then take it in hiddenfield and acess on code behind(server side) its simple
Answer: You Can't Mix server side with client side, like this. you need to use AJAX for this kind of functionality


How to specify lifetime bounds for a closure involving references to intermediate local variables?

Question: I'm trying to write a function like the following in Rust:
fn double_and_square<'a, T>(x: &'a T) -> /* whatever the output type of `&t * &t` is */ {
    let t = x + x;
    &t * &t
}

I want it to work on types where T is non-Copy. I need to specify not only that &'a T implements Add (easy), but also that a reference to its output type with the lifetime of local variable t implements Mul.
Attempt #1 (no lifetime specified for the intermediate type):
fn double_and_square<'a, T>(x: &'a T) -> <&<&'a T as Add>::Output as Mul>::Output
where
    &'a T: Add,
    &<&'a T as Add>::Output: Mul,
{
    let t = x + x;
    &t * &t
}

Results in the following compiler error:
error[E0106]: missing lifetime specifier
 --> src/main.rs:6:5
  |
6 |     &<&'a T as Add>::Output: Mul,
  |     ^ expected lifetime parameter

Attempt #2 (alright, I'll add a lifetime specifier):
fn double_and_square<'a, 'b, T>(x: &'a T) -> <&'b <&'a T as Add>::Output as Mul>::Output
where
    &'a T: Add,
    &'b <&'a T as Add>::Output: Mul,
{
    let t = x + x;
    &t * &t
}

Results in the following compiler error:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/main.rs:8:13
  |
8 |     let t = x + x;
  |             ^
  |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the function body at 3:1...
 --> src/main.rs:3:1
  |
3 | / fn double_and_square<'a, 'b, T>(x: &'a T) -> <&'b <&'a T as Add>::Output as Mul>::Output
4 | | where
5 | |     &'a T: Add,
6 | |     &'b <&'a T as Add>::Output: Mul,
... |
9 | |     &t * &t
10| | }
  | |_^
note: ...so that expression is assignable (expected &T, found &'a T)
 --> src/main.rs:8:13
  |
8 |     let t = x + x;
  |             ^
note: but, the lifetime must be valid for the lifetime 'b as defined on the function body at 3:1...
 --> src/main.rs:3:1
  |
3 | / fn double_and_square<'a, 'b, T>(x: &'a T) -> <&'b <&'a T as Add>::Output as Mul>::Output
4 | | where
5 | |     &'a T: Add,
6 | |     &'b <&'a T as Add>::Output: Mul,
... |
9 | |     &t * &t
10| | }
  | |_^
note: ...so that the type `<&T as std::ops::Add<&'a T>>::Output` is not borrowed for too long
 --> src/main.rs:9:10
  |
9 |     &t * &t
  |          ^^

error[E0490]: a value of type `<&T as std::ops::Add<&'a T>>::Output` is borrowed for too long
 --> src/main.rs:9:10
  |
9 |     &t * &t
  |          ^^
  |
note: the type is valid for the lifetime 'b as defined on the function body at 3:1
 --> src/main.rs:3:1
  |
3 | / fn double_and_square<'a, 'b, T>(x: &'a T) -> <&'b <&'a T as Add>::Output as Mul>::Output
4 | | where
5 | |     &'a T: Add,
6 | |     &'b <&'a T as Add>::Output: Mul,
... |
9 | |     &t * &t
10| | }
  | |_^
note: but the borrow lasts for the lifetime 'a as defined on the function body at 3:1
 --> src/main.rs:3:1
  |
3 | / fn double_and_square<'a, 'b, T>(x: &'a T) -> <&'b <&'a T as Add>::Output as Mul>::Output
4 | | where
5 | |     &'a T: Add,
6 | |     &'b <&'a T as Add>::Output: Mul,
... |
9 | |     &t * &t
10| | }
  | |_^

The way that I read the lifetime must be valid for the lifetime 'b as defined on the function body tells me the compiler thinks 'b is supposed to live as long as or longer than the whole function body, whereas I just want it to mean "any lifetime".
Is what I'm trying to do even possible in Rust? If not, are there any proposed changes I should watch that will make it possible?
Answer: Buckle up...
use std::ops::{Add, Mul};

fn double_and_square<'a, T, R>(x: &'a T) -> R
where
    &'a T: Add,
    for<'b> &'b <&'a T as Add>::Output: Mul<Output = R>,
{
    let t = x + x;
    &t * &t
}

Easy enough, right? ;-)
Let's take it step by step...

You wish to take in a reference to a type, but the reference needs to implement Add. where clauses let you write complex types on either side of the :, so we use &'a T: Add.
This will return some value that we take another reference to. However, the caller of double_and_square cannot specify the lifetime, since it only exists inside the function. This means we need to use a higher-ranked trait bound: for <'b>.
We have to use the type of the output of the Add operation, say that it implements Mul, and the output type is the generic R.

I'd recommend not taking references in the original function as it's way easier to understand:
fn double_and_square<T, R>(x: T) -> R
where
    T: Add + Copy,
    for<'a> &'a T::Output: Mul<Output = R>,
{
    let t = x + x;
    &t * &t
}

&Foo is a separate type from Foo and can be passed as the concrete type of T, so this should be able to be used in any place the original was, and probably usable in even more cases.

I want it to work on types where T is non-Copy

Immutable references to types are always Copy, even if the type itself doesn't implement Copy. Thus, you can call this function with e.g. T = i32 or a T = &NonCopy. The original case that only accepted references would only accept the second one.
In an ideal world, you'd be able to avoid the generic type R and just say <...something...>::Output, but as far as I know that's not currently possible.
Comment: Ah, I didn't know "HRTBs" were a thing. They do exactly what I was hoping for; thank you!
Also, is there a name for that `Output = R` syntax? Even in cases where it's not required like this, it'll seriously clean up some of my generic code with complicated return types and I want to read more about it.
Comment: Also, note, the non-reference version requires `T: Copy` but my original requirements explicitly stated I wanted to support non-`Copy` types.
Comment: @JoBates hmm. I think I'd just say that it's "specifying the associated type". The downside of such a syntax is that it's kind of a "lie" in this case. The caller of the function cannot actually pass a second generic type to constrain the call, like you would in a situation like `Iterator::collect`.
Comment: @JoBates that's not a real "requirement" in this case, see my last update. Different generics are happening here.
Comment: oh, of course; you're right. I'm in a different frame of mind because in the code I'm really working on, the argument type (reference or not) is a `SpecificGenericStruct`, not simply `T`. I was just trying to remove extraneous details from the core question.


Planar graph, number of faces, minimum vertex degree 3

Question: In a finite connected planar graph $G$, such that $\delta(G)\geq 3$, show that at least $2$ faces have at most $5$ edges. I have tried writing out degree sum from Handshaking lemma and then substituting in Euler's formula but I am stuck there.
Comment: Shouldn't it be at least 4 faces?
Comment: No, i just checked the exercise, its says what I wrote in question.
Answer: Using the fact $\delta(G)\geq 3$, one could prove each edge is part of a cycle, and therefore bound exactly two faces.
Denote by $e,v,f$ the number of edges, vertices and faces in $G$ respectively.
Intuition
Since the proof is quite technical, I'll try to sum up the proposition I use:

$(f-1)\leq \frac{e}{3}$
$2e\geq 3v$ which implies $v-\frac{2e}{3}\leq 0$
Euler formula $v-e+f=2$

Proof
Now assume by contradiction the statement is false, and therefore at least $f-1$ of the faces have at least $6$ edges.
This implies:
$$2e=\sum\limits_{i=1}^{f} \text{#edges of the face } f_i\geq
6(f-1)\implies \\
2e\geq 6(f-1)\implies (f-1)\leq \frac{e}{3}$$
Using Euler formula $v-e+f = 2$, we get $$ 2 = v-e+f\leq v-e+\frac{e}{3} +1=v-\frac{2e}{3} + 1$$
Since
$$2e = \sum\limits_{u\in V(G)}deg(u) \geq 3v\implies \frac{2e}{3}\geq v$$
and finaly we get a contradiction:
$$v-\frac{2e}{3}\leq 0 \implies v-\frac{2e}{3} + 1 \leq 1$$
and because $$v-e+f \leq v-\frac{2e}{3} + 1 $$
we get
$$2 = v-e+f \leq 1 $$
which is a contradiction.


C++/CLI - Convert System::Object to ContextMenuStrip

Question: I'm working on a piece of legacy code & I'm trying to update some of the interface. I'm not proficient in C++/CLI and the documentation for C++/CLI is sparse at best. I do my best to convert C# documentation to C++/CLI but it doesn't always work.
I want to convert a System::Object to a ContextMenuStrip.
A sample code is:
System::Void Form1::unzoomToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)
{

    System::Windows::Forms::ContextMenuStrip ^menu = sender;
    //a value of type "System::Object ^" cannot be used to initialize and entity of type "System::Windows::Forms::ContextMenuStrip ^"

    //Other code here
}

How is this done in C++/CLI?
Comment: https://msdn.microsoft.com/en-us/library/1bh3t52k.aspx
Comment: You may try the following `auto menu = (System::Windows::Forms::ContextMenuStrip ^)sender;`.
Answer: From the link posted by Hans Passant:

A downcast is a cast from a base class to a class that's derived from the base class. A downcast is safe only if the object that's addressed at runtime is actually addressing a derived class object. Unlike static_cast, safe_cast performs a dynamic check and throws InvalidCastException if the conversion fails.

So you should use:
Windows::Forms::ContextMenuStrip ^menu = safe_cast<Windows::Forms::ContextMenuStrip^>(sender);


Correct form of derivative

Question: In the equations
$$\mathbf{F} = \mathbf{-\mathit{e}(E + v \times B)} = m\frac{d\mathbf{v}}{dt}$$  $$\frac{d^2x}{dt^2}= -\frac{e}{m}\left(E_x + B_z\frac{dy}{dt}- B_y \frac{dz}{dt}\right)$$ $$\frac{d^2y}{dt^2}=-\frac{e}{m}\left(E_y+B_x\frac{dz}{dt}-B_z\frac{dx}{dt}\right)$$
$$\frac{d^2z}{dt^2}=-\frac{e}{m}\left(E_z+B_y\frac{dx}{dt}-B_x\frac{dy}{dt}\right)$$
Is it correct to use $d$ or should I use $\partial$?
(Reference for equations: Liao, Samuel Y. Microwave Devices and Circuits. Englewood Cliffs, NJ: Prentice-Hall, 1980. Print. Page 12.)
Comment: It appears $x,y,z$ are functions of the independent variable $t$ only. In this case $\dfrac{d}{dt}, \dfrac{\partial}{\partial t}$ operate the same. I would say the first is best, since the partial derivative may cause confusion
Answer: Here $x$, $y$ and $z$ appear to be functions of only the one variable $t$ (representing, I suppose, the coordinates of a particle at time $t$).  There is no other variable in sight, and you're certainly not taking derivatives with respect to any other variable.  So $d$ is correct.
Comment: Thank you, that's what I thought, but I wanted to make sure.

Correct form of derivative


Adding value to multi-delta textfield programmatically

Question: I have a phone field in a form, which is just a textfield with its default widget. I'm trying (and failing) to add values to this field programmatically through ajax calls.
I have an ajax call elsewhere on the form, the purpose of which is to add several values to the phone (text) field, and let the user continue to edit them or add more.
My strategy in the ajax callback function has been to take the first textfield delta as a template, and reproduce it to add more. That's not working, because there are too many values to set that have side effects, like ['#delta'] or ['#max_delta']. The modules that manage this even seem to use #id suffixes to control behaviours.
The code below loads the values all right (3 of them show up on the form after the call), but when I press "Add another item", the field collapses from 3 values to 2. A subsequent "Add another item" call then opens up a blank new item, ie starts to behave normally. So something amiss after my ajax operation on the form structure, but gets reset with the first subsequent "Add another item" call. But I haven't been able to isolate what the problem is.
In any case, I think I'm using a bad strategy, and instead need some kind of helper function, or at least a strategy that conforms to Drupal-wide patterns.
So, how do I do this? I need a strategy or an example.
Here's my current ajax callback. The parts other than phone update are working, but the phone part is a mess. The phone part demonstrates what I want to do with updating phones, and the complexity shows why my current strategy isn't working for that phone part.

function rc_business_card_populate_from_staff($form,&$form_state)
{
       // ===============================================
       // THIS PART WORKS
    $selected_staff_id = $form_state['values']['line_item_fields']['field_staff']['und'][0]['profile_id'];
    if (is_null($selected_staff_id)) return $form; // do nothing
    // assemble input fields for data
    $address = &$form['line_item_fields']['field_recipient_address']['und'][0];
    $street_block = &$address['street_block'];
    $locality_block =  &$address['locality_block'];
    $organisation_block =  &$address['organisation_block'];
    $name_block =  &$address['name_block'];
    $values = array(
        // address field:
        'name_line' => &$name_block['name_line']['#value'],// Full Name
        'organisation_name' => &$organisation_block['organisation_name']['#value'], // Company
        'thoroughfare' => &$street_block['thoroughfare']['#value'], // Address 1
        'premise' => &$street_block['premise']['#value'],// Address 2
        'locality' => &$locality_block['locality']['#value'], // City
        'administrative_area' => &$locality_block['administrative_area']['#value'], // Province
        'postal_code' => &$locality_block['postal_code']['#value'],// Postal Code
        // independent fields:
        'field_designation' => &$form['line_item_fields']['field_designation']['und'][0]['value']['#value'], // Designation
        'field_email' => &$form['line_item_fields']['field_email']['und'][0]['email']['#value'],// Email
        'field_website' => &$form['line_item_fields']['field_website']['und'][0]['value']['#value'], // Website
        // phone field, independent:
    );
       // ===============================================
       // THIS PART DOESN'T WORK
    $field_phone = &$form['line_item_fields']['field_phone']['und'];
    $field_phone_template = $form['line_item_fields']['field_phone']['und'][0];
    // assemble input data
    $entities = entity_load('commerce_customer_profile',array($selected_staff_id));
    if (empty($entities)) return $form;
    $entity = reset($entities);
    $source_phones = $entity->field_phone['und'];
    $source_phones[2] = $source_phones[1];
    $source_phones[2]['value'] = 'test'; // ADD A THIRD VALUE FOR TESTING PURPOSES
    $phones = array();
    $length = count($source_phones);
        // HACKING - TRYING TO SET VALUES THAT MAKE THE TEXTFIELD BEHAVE - NOT WORKING
    foreach ($source_phones as $key => $source_phone) {
        $phones[$key] = $field_phone_template;
        $phones[$key]['value']['#value'] = $source_phone['value'];
        $phones[$key]['#delta'] =
        $phones[$key]['#weight'] =
        $phones[$key]['value']['#delta'] =
        $phones[$key]['value']['#weight'] =
        $phones[$key]['_weight']['#default_value'] =
        $phones[$key]['_weight']['#value'] = $key;
        $phones[$key]['_weight']['#delta'] = $length + 1;
        $phones[$key]['value']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-value--' . ($length + 1);
        $phones[$key]['value']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][value]';
        $phones[$key]['_weight']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-weight--' . ($length + 1);
        $phones[$key]['_weight']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][weight]';
        $phones[$key]['#id'] = 'edit-line-item-fields-field-phone-und-' . $key;
    }
        // THIS SUCCESSFULLY LOADS THE DATA FOR PRESENTATION, BUT DOESN'T BEHAVE PROPERLY ON "Add another item"
    if (!empty($phones)) {
        foreach ($phones as $key => $phone) {
            $field_phone[$key] = $phone;
        }
        $form['line_item_fields']['field_phone']['und']['#max_delta'] = $length + 1;
//        $form['line_item_fields']['field_phone']['und']['add_more']['#id'] =
//            'edit-line-item-fields-field-phone-und-add-more--' . ($length + 1);
        $form['line_item_fields']['field_phone']['#id'] = 'edit-line-item-fields-field-phone--' . $length;
    }
       // ===============================================
       // THIS REMAINING PART WORKS
    $source_address = $entity->commerce_customer_address['und'][0];
    $values['name_line'] = $source_address['name_line'];
    $values['organisation_name'] = $source_address['organisation_name'];
    $values['thoroughfare'] = $source_address['thoroughfare']; // Address 1
    $values['premise'] = $source_address['premise'];// Address 2
    $values['locality'] = $source_address['locality']; // City
    $values['administrative_area'] = $source_address['administrative_area']; // Province
    $values['postal_code'] = $source_address['postal_code'];// Postal Code
//    dpm($entity);
    // apply input data to input fields
//    $value = 'something';
//    $form['line_item_fields']['field_designation']['und'][0]['email']['#value'] = $value;
    dpm($form);
    $form['line_item_fields']['#suffix'] = rconnection_get_debug_data();
    return $form;
}
Answer: To answer my own question (it happens):
The critical part for the subsequent behaviour of "Add another item" is to set field_state['items_count'] (yes field state) for the NEXT ajax call from the "Add another item" button.
You can use this as a guide.

Henrik


recovering phase of sine signal from FFT

Question: I have a simple sine function as sin(2*pift+phi). I want to obtain the phase signal phi.
I tried to use FFT to calculate phi. In matlab I do the following
f=200; %frequency of sine wave
overSampRate=30; %oversampling rate
fs=overSampRate*f; %sampling frequency
phase = 3/5*pi; %desired phase shift in radians
nCyl = 5; %to generate five cycles of sine wave

t=0:1/fs:nCyl*1/f; %time base

x=sin(2*pi*f*t+phase); %replace with cos if a cosine wave is desired

NFFT=1024; %NFFT-point DFT
X=fft(x,NFFT); %compute DFT using FFT
XX=2*abs(X(1:NFFT/2+1));
[tt ind]=max(XX);
phase_Estimate=angle(X(ind);

This result makes almost no sense to me. For example, when phi=0.523, phase_Estimate is obtained -0.98.
Answer: Using an non-interpolated FFT result phase only works if the period of sinusoid is exactly an integer submultiple of the FFT length.  In your example, the sine wave isn't integer periodic in aperture.
If not, you will need to interpolate the phase to get a better estimate.  Here's one method to get an better interpolated phase:
First fftshift (rotate by N/2) the data to move the zero phase reference point to the center of the window before doing the FFT.  (This is needed to keep the phase from flipping/alternating between adjacent FFT result bins. * )
Then do the FFT and estimate the frequency of the sinusoid by parabolic or, better yet, Sinc interpolation.
Then use the estimated frequency to linearly interpolate the phase between the nearest two FFT result bin phases.  Update: Or better yet, use Sinc interpolation of the real and imaginary components of the FFT result separately, then use atan2 on the interpolated IQ components to get an interpolated phase.
Then use the estimated frequency and phase at the center of the window to calculate the phase at some other point, such as the beginning of the FFT window.
Also note that the phase of a sine is different from the phase of a cosine wave by pi/2.  atan(im,re) returns the cosine phase.
(* as an alternative to pre-fftshit-ing the data, one could also post-flip the phase of the odd FFT result bins.)
Comment: Thank you. Would you please explain more about how can I interpolate the phase between the nearest two FFT result bin phases?
Answer: This is actually much more difficult question to answer than it first seems.
The answer @hotpaw2 gives is completely correct and spells it out way better than any other resource I found, but it is still only an outline and it took me a few hours to put all the meat to it's bones.
In the hopes that someone else will also find the question relevant (and for future reference for myself), here is a bit more thorough explanation:
Suppose you have a (local) maximum at index ind (as in the case of question).
Step 1: try to interpolate the more precise location of the maximum by using the two surrounding values. This is well explained in many, many places such as https://www.dsprelated.com/freebooks/sasp/Quadratic_Interpolation_Spectral_Peaks.html has a good explanation for how to do that, but TL:DR version is:
delta = 0.5*(X[ind-1]-X[ind+1])/(X[ind-1]-2*X[ind]+X[ind+1])
p0 = ind+delta

with the estimated peak at p0
(If you want a more precise estimate, use log(X[ind-1]) instead, or go full out and use sinc function, but for most purposes, the delta above is sufficient)
Step 2: the tricky part: use that location to interpolate the phase.
The first instinct is to do simple linear interpolation using the delta we just found:
i0 = floor(p0); w = p0-i0; wp = 1-w
ang = wp*angle(X[i0]) + w*angle(X[i0+1])

This WILL NOT WORK for multiple reasons, most of which were outlined by @hotpaw2. The first of them is that this is not how you average angles, as they wrap modulo 2pi so 0 and 2pi should be similar. The more correct approach is to average the normalized complex numbers instead:
ang = angle(wp*X[i0]/abs(X[i0]) + w*X[i0+1]/abs(X[i0+1]))

However, this is still not correct, because if a peak is between i0 and i0+1, the phase flips 180 degrees (pi radians) there, making the average very misleading. To fix this "phase flip", you either have to (a) perform fftshift before fft (yes, in time-domain) or (b) flip the phase of every odd-indexed value of X (achieved by multiplying the complex number with -1) or (in case you are reluctant to touch the FFT as I was), you can also just (c) mock the approach (b) with the following code:
i0 = floor(p0); w = p0-i0; wp = 1-w
if (i0 % 2 == 1) { w*=-1; wp*=-1 } # Flip both if i0 odd
ang = angle(wp*X[i0]/abs(X[i0]) - w*X[i0+1]/abs(X[i0+1])) # Note the "-" here!

This will give you a (mostly) correct phase, but for a cosine and at the center of fft window.
Step 3 (Optional): If you need the phase for sine and from the beginning of the window, you need to add a correction factor:
ang_beg = ang - (2*pi*p0/N)*N/2 + pi*0.5 = ang - pi*(p0 - 0.5)

(0.5*pi converts cos to sin, and -p0*pi translates to beginning of window).
This seemed to work, at least in the Phase Vocoder I needed it in. Hopefully someone else will also find this useful.
As an aside, the phase interpolation is not needed for a pure sine wave, as angle(X[i0]) = angle(-X[i0+1]) so you can just use it directly. With actual signals, there is likely to be some deviation so interpolation adds some robustness which is usually a good idea, although using w and wp and normalizing is likely overkill and angle(sgn*(X[i0]-X[i0+1)) is usually enough.
Any comments to all this are very welcome. I am not a DSP specialist, so I may well be wrong in some details, bu this does seem to work, so hopefully someone else will also find it useful.
Answer: You're trying to get the phase from the power spectrum (XX) when you should be getting it from the FFT (X). Change:
phase_Estimate=angle(XX(ind));

to:
phase_Estimate=angle(X(ind));

Comment: Thank you. I edited my code but still my problem does not solved. My question is that can I obtain phi from the FFT phase ?
Comment: If your frequency of interest does not correspond exactly with a corresponding FFT bin frequency then you will need to do some adjustment to get the phase - search http://dsp.stackexchange.com since this question has already been answered there at least once.
Answer: It maybe late, but I changed Your script a little
f=200; %frequency of sine wave
overSampRate=30; %oversampling rate
fs=overSampRate*f; %sampling frequency
shift = 30
phase = shift*pi/180; %desired phase shift in radians
nCyl = 5; %to generate five cycles of sine wave
t=0:1/fs:nCyl*1/f; %time base
x=cos(2*pi*f*t+phase); %replace with cos if a cosine wave is desired

NFFT=4096; %NFFT-point DFT
X=fft(x,NFFT); %compute DFT using FFT
XX=2*abs(X(1:NFFT/2+1));
[tt, ind]=max(XX);
phase_Estimate = angle(X(ind)) * 360/(2*pi)

It spits out quite close results to what I would expect.
I changed the x vector generation to cosine, calculated degrees in phase_Estimate instead of radians, and made it easy to change input phase shift.


Create entity form as a table

Question: I am looking for a way to create a table entry form for an entity type. We are trying to create an invoice form.  I am currently using a field collection for each invoice line.
Order (node)
  Invoice (node)
    Invoice line (field collection)

I am currently using the field_collection module along with field_collection_table.  I am using entity reference to connect the invoice to the order and invoice line This works great except when we have more than roughly 75 rows.  At that point we are unable to add new rows to the table. Users are getting a 500 AJAX error.
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Internal Server Error
ResponseText:

Originally I received an error about max_imput_vars limit of 1000 when we got to about 50 lines.  I have since changed the limit to 100000.  Now nothing shows up in the server error log or the Drupal recent log messages.  My PHP settings are:
memory_limit = 256M
max_execution_time = 120
max_imput_time = 120
post_max_size = 160M
upload_max_filesize = 128M
max_input_vars = 100000

My thought now is to create a custom entity for invoice line.  The trouble is how to display this entity as a table and allow users to edit multiple items at once.  Some invoices could have 500 rows and I need a way for users to be able to quickly move from line to line.  For non-Drupal forms I have used jQuery to dynamically add new rows to a table.  Not sure how this would work for Drupal since each field in the table has an id that is specific to each row (e.g. edit-field-desc-und-31-value).
Any suggestions?  A separate but important issue is a need to regularly autosave.  Users would not be happy if they added 300 rows and lost power, computer froze, or something else happened.
Comment: Have you looked into Editable Views?
Comment: Thanks Melissa... I just took a look.  Very interesting module however I do not see a way to add new rows.
Comment: You might have to add that functionality on top of it through theming or a custom module. I'd look into an "infinite scroll" pager.
Answer: We ended up going the route of a custom field collection table module combined with batch processing.  The problem was the standard Drupal way of adding rows using ajax.  Instead we created the rows dynamically using Javascript to duplicate the last row and all associated features tied to each field.  We then used a batch process to save the data.  This resolved the issue of the server timing out with lots of rows.

Create entity form as a table


Proof showing that the nonterminating decimal .1348888… represents a rational number. Please verify.

Question: My proof goes like this:
Let $x=0.134888⋯$
$1000x=134.888⋯$
$1000x=134+0.888⋯$
$10000x=10(134+0.888⋯)$
$10000x=1340+8.888⋯)$
$10000x−1000x=1340+8.888⋯−(134+0.888⋯)$
$9000x=1340−134+8.888⋯−0.888⋯$
$9000x=1214$
$$x=\dfrac{1214}{9000}=\dfrac{607}{4500}$$
Then I concluded that this is a rational number. Any feedback is greatly appreciated. Thank you,
Comment: The answer is right, but it needn't have been so elaborate, you could have done it in a smaller number of lines.
Comment: Yes your method Is correct!
Answer: Note that ${1 \over 9} = 0.\bar{1}$, so $0.\bar{8} = {8 \over 9}$.
Then $0.134\bar{8} = {134 \over 1000} + {1 \over 1000} {8 \over 9}$.
Comment: You beat me to it. However, instead of starting with $0.\overline1=\frac19$ I was going to start with the more familiar identity $0.\overline9=1.$


Informal Equivalents of Mathematica "Set" and "SetDelayed"

Question: How would one distinguish between what is meant by Mathematica's "Set" and "SetDelayed" functions in informal mathematical notation? Is there a way to make this distinction any any reasonably standard formal logics? Also, how is informal mathematical notation and formal logic notation related to Mathematica's use of variables like 'x_'?  Here is the relevant part of the Mathematica documentation:
http://reference.wolfram.com/mathematica/howto/CreateDefinitionsForVariablesAndFunctions.html
Answer: Since Mathematica is fundamentally a rewriting system, we can use the concept of a Normal Form to address your question.
We can formalize the behavior of Mathematica this way to get at your question. Consider two sets of rewrite rules, which will store all the rules you enter into Mathematica. In the first set, which we'll call Eager, all the right-hand sides of the rules are rewritten immediately to their respective normal forms. In the second set, however, which we'll call Lazy, no such rewriting takes place. The correspondence with Mathematica is that Eager is the default, including the Set command and the read-eval-print loop; SetDelayed corresponds with Lazy.
Following the example in the Mathematica documentation, entering y = 4 at the prompt puts the rewrite rule $y \rightarrow 4$ into the Eager set:
Eager = $\{y \rightarrow 4\}$,
Lazy = $\{\}$
Entering z := y^2 at the prompt puts the rule $z \rightarrow y^2$ into the Lazy set:
Eager = $\{y \rightarrow 4\}$,
Lazy = $\{z \rightarrow y^2\}$
Entering z at the prompt causes z to be rewritten to its normal form using the union of Eager and Lazy.
$z \Rightarrow 16$
Now if we enter y = 3 at the prompt, the rule that's already there is replaced:
Eager = $\{y \rightarrow 3\}$,
Lazy =  $\{z \rightarrow y^2\}$
So entering z again causes it to be rewritten to its normal form:
$z \Rightarrow 9$
The logic underlying this example is equational, that is, first-order logic with functions and equality. In this setting, rewrite rules are simply equations with a preferred direction.
As for variables like x_, I don't see anything corresponding in rewrite rules to this kind of notation. My guess is that this formalism is designed to inhibit the default Mathematica evaluator, since if we already have x = 3 and type the following into Mathematica....
f[x] := x^2
... we'd get
f[3] := x^2
...which is clearly not what we want. Rewrite systems avoid this problem by not usually making constant bindings like x = 4 into rewrite rules. This is necessary since it's important to be able to rewrite the left-hand sides of rewrite rules into their normal forms, not just the right-hand sides.
Answer: QUESTION 1: How would one distinguish between what is meant by Mathematica's "Set" and "SetDelayed" functions in informal mathematical notation?
Set vs. SetDelayed
f[x_] = Expand[x^2]
x^2
{f[3], f[3.5], f[x + 1]}
{9, 12.25, (x+1)^2}
f[x+1] is not expanded because that was evaluated when f was defined.
Also Set is evaluated once for certain definitions.
r1 = Random[];
{r1, r1, r1}
{0.937245,0.937245,0.937245}
SetDelayed is evaluated each time.
r2 := Random[];
{r2, r2, r2}
{0.687744,0.629629,0.732141}
Clear["`*"]
f[x_] := Expand[x^2]
Notice when you evaluate this expression, there is no output.  That's because the rhs is held until the function f  is evaluated.
{f[24],f[x + 2],f[(h - 4)^3]}
{576, x^2+4 x+4, h^6-24 h^5+240 h^4-1280 h^3+3840 h^2-6144 h+4096}
Now everything works because Expand is evaluated after f gets its input.
QUESTION 3:  Also, how is informal mathematical notation and formal logic notation related to Mathematica's use of variables like 'x_'?
The underscore is what Mathematica uses to show input variables.  It is used with Set and SetDelayed.  Even f[x_] is evaluated without :=.
f[x_]
x_^2
The human mind knows that the x in f(x) is the input.  Computers don't unless you tell them.
QUESTION 2: Is there a way to make this distinction any any reasonably standard formal logics?
I have never seen it.  The human mind would always evaluate like a SetDelayed definition, wouldn't it?
Here's a link to the notebook.  Hope this helps.
Comment: It seems to me that Quine42 already knows this behavior, and is asking about representation or notation of said behavior outside of Mathematica.
Comment: Please, do answer his question, since you seem to understand it better.
Comment: I am not a mathematician.


pairwise.t.test in R returning no value

Question: I am a noob in R, and have been breaking my head for the past three hours over the pairwise.t.test in R. My data frame is structured as given below. My data frame has the age of flight of bees and the duration which they fly for. I want to check the pairwise difference in duration across days.

head(a3)

      age dur.
    1   3  343
    2   2  640
    3   1  333
    4   3  253
    5   3   66
    6   3  686

When I do one-way ANOVA and follow it up with a TukeyHSD, the console prints the values for adjusted p-values.
> an3=with(a3, aov(dur.~factor(age)))
> TukeyHSD(an3)
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = dur. ~ factor(age))

$`factor(age)`
             diff           lwr        upr     p adj
2-1    -16.666667 -1215.7557943 1182.42246 1.0000000
3-1   -105.717444 -1158.4831001  947.04821 1.0000000
4-1   -144.603500 -1198.2056799  908.99868 1.0000000
5-1   -194.405800 -1244.3222876  855.51069 1.0000000
6-1   -223.139535 -1273.5866854  827.30762 1.0000000
7-1   -143.568966 -1190.9244371  903.78651 1.0000000
8-1   -208.927536 -1254.8670531  837.01198 1.0000000
9-1   -255.583333 -1304.7863200  793.61965 0.9999999

I want to carry out pairwise.t.test with the Bonferroni p-value adjustment on the data frame. When I go ahead and do that, I get the following output.

pairwise.t.test(a3$dur.,a3$age,p.adjust.method='bonf')

        Pairwise comparisons using t tests with pooled SD

data:  a3$dur. and a3$age

   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
2  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
3  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
4  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
5  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
6  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
7  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
8  - - - - - - - - - -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
...
P value adjustment method: bonferroni

I do not know why I get blanks for all fields, when in all examples I have seen online, the result is a lower triangular matrix. Has anyone faced similar problems? Are there any solutions for the same?
Cheers
P.S. I have tried the example given in R documentation and it seems to work fine. It's not working for my data set though. I have also ensured that the example data and my data are both data frames.
Comment: @gung, pairwise.t.test performs a t-test between all possible pairs of levels of a factor, not a paired t-test (so no ID variable). It is unclear why that did not work without knowing more about your data. However, you could try testInteractions in the phia package which can do the same thing and may give a more helpful error if it fails. You would use testInteractions(an3, pairwise="age", adjustment="bonf")
Comment: Although asked in the context of R, this is due to a statistical confusion. It isn't really a coding question. IMO, it is on topic here.
Comment: Can you say more about your situation, your data & your goals? What are the variables? How many groups do you have? Etc.
Comment: hi @gung. Thanks for the comment. Could you kindly elaborate on the statistical confusion bit? Sorry if I am being thick
Comment: No problem, can you say more about your situation and your data?
Comment: Hi @gung. I have now updated the info in my text, including my goal and nature of my data. Incidentally, I had initially thought the NA values in my data might have been a problem. After I saw the example in the documentation, I am convinced that it couldn't be the case. the airquality data has multiple NA across all columns.
Comment: I don't see an ID indicator in your dataframe. How many bees do you have? How many measures do you have per bee? How many groups do you have? What is the situation with your NAs, are they censored measurements?
Comment: I don't see any pairing of flight durations in the data frame, so how could a pairwise test be applicable?  Could you explain what things are supposed to be paired and how that pairing is represented in your data?
Comment: Thanks for pointing that out, @tomr. I thought this was about trying to apply a paired t-test. Maybe this is an R coding question after all. I'm not actually sure.
Comment: Thanks all for your inputs. I will definitely try your suggestions later tonight and post the results.
Answer: I ran into the same problem just now, but realized the common issue was that some of your groups only included one value.  For example, the following results in the same - - table as you saw before.
df <- data.frame(x = 1:10,
             group = c("a", "b", "b", "b", "c", "c", "c", "c", "c", "c"))
pairwise.t.test(df$x, df$group)

    Pairwise comparisons using t tests with pooled SD

data:  df$x and df$group

  a b
b - -
c - -

However, when you no longer have categories with only one value, the pairwise.t.test works. (In this case, I changed "b" to "a" so that there are now two values in "a" and two in "b".)
df <- data.frame(x = 1:10,
                 group = c("a", "a", "b", "b", "c", "c", "c", "c", "c", "c"))
pairwise.t.test(df$x, df$group)

Pairwise comparisons using t tests with pooled SD

data:  df$x and df$group

  a      b
b 0.2583 -
c 0.0082 0.0391

pairwise.t.test in R returning no value


Show that $\operatorname{rank} A = 3$

Question:
Matrix $A \in R^{3, 2015}$ is given. It is known that matrix $AA^{T}$ is invertible. Show that $\operatorname{rank} A = 3$.

How to start this? What does the info that $AA^{T}$ is invertible gives us?
Comment: I'm sorry, could you explain me the notation $R^{3, 2015}$? What does it express?
Comment: @Dac0 I assume $R^{3,2015}$ stands for $\mathbb{R}^{3\times 2015}$, the matrices vector space with $3$ rows and $2015$ columns with entries in $\mathbb{R}$.
Comment: ok thanks, for the matrix space I was used to a different notation such as $M^3_{2015}( \mathbb R )$ so it was a bit confusing
Comment: @Dac0 In France, we use a similar notation to yours, namely $\mathcal{M}_{3,2015}(\mathbb{R})$, but it seems $\mathbb{R}^{3\times 2015}$ is the international notation.
Answer: Since $A^\intercal A$ is an invertible matrix of order $3$, one has: $$\textrm{rank}(A^\intercal A)=3.$$
Besides, one has: $$\textrm{rank}(A^\intercal A)\leqslant\min\left(\textrm{rank}(A),\textrm{rank}\left(^\intercal A\right)\right).$$
But, one has: $$\textrm{rank}\left(^\intercal A\right)=\textrm{rank}(A).$$
Therefore, one gets: $$3\leqslant\textrm{rank}(A).$$
Hence the result, since the number of lines of a matrix is greater than its rank.
(Edited)
Remark. Using $\textrm{rank}(AB)\leqslant\min(\textrm{rank}(A),\textrm{rank}(B))$ is overkill, instead you can just use $\textrm{rank}(AB)\leqslant\textrm{rank}(B)$, which is an easier result to prove.

Show that $\operatorname{rank} A = 3$


Using fourier analysis for time series prediction

Question: For data that is known to have seasonal, or daily patterns I'd like to use fourier analysis be used to make predictions. After running fft on time series data, I obtain coefficients. How can I use these coefficients for prediction?
I believe FFT assumes all data it receives constitute one period, then, if I simply regenerate data using ifft, I am also regenerating the continuation of my function, so can I use these values for future values?
Simply put: I run fft for t=0,1,2,..10 then using ifft on coef, can I use regenerated time series for t=11,12,..20 ?
Answer: I'm aware that this question may be not actual for you anymore, but for others that are looking for answers I wrote a very simple example of fourier extrapolation in Python https://gist.github.com/tartakynov/83f3cd8f44208a1856ce
Before you run the script make sure that you have all dependencies installed (numpy, matplotlib). Feel free to experiment with it.

P.S. Locally Stationary Wavelet may be better than fourier extrapolation. LSW is commonly used in predicting time series. The main disadvantage of fourier extrapolation is that it just repeats your series with period N, where N - length of your time series.
Comment: This good visual example demonstrates the weakness pointed out in the other posts: the frequency domain, by its nature, produces fixed cycles in the time domain. The red line extrapolation above is simpy a copy of the beginning segment of the blue (observed) line, albeit de-noised slightly. Therefore, to do any meaningful short-term prediction over horizon *h* time units, where *h* ≪ the number of historical observations, only the most significant **high** frequency coefficients should be used in the extrapolation. A "high" frequency threshold can be arbitrarily defined in relation to *h*.
Comment: To further clarify my previous comment, the extrapolated red hump at time ~350 is just a copy of the blue hump at ~50. If the historical period had instead been initiated right before the hump at 50, then the very first predicted units would have that hump copy, which seems a bit silly and arbitrary. Thus, by either eliminating and down-weighting the lower frequency components, we can reduce the arbitrariness induced by the historical data starting point.
Comment: So, sorry just making sure I understand.  x (blue line) is the observed data?  extrapolation (red line) is the prediction?
Comment: @jeffery_the_wind Yes, the red line is the prediction and blue is observed data. Obviously there is overfitting in this example, to avoid that you can adjust the number of harmonics in the model.
Comment: I'm a bit confused by this script, mainly the line that reads `for i in indexes[:1 + n_harm * 2]:` you sort the indices by frequency value before doing this, guaranteeing that you get the `n_harm` lowest frequencies. Would you not want the `n_harm` frequencies associated with the highest peaks instead? Should the indices not be sorted by absolute value of `x_freqdom `? Maybe I misunderstand but that seems to be the best way to denoise.
Comment: @Mike you're right, I wanted to extract lowest frequencies as I suggested that they're best describe cycles and periods in the data, while highest frequencies usually are noise. And of course, this suggestion may be wrong in your case
Answer: It sounds like you want a combination of extrapolation and denoising.
You say you want to repeat the observed data over multiple periods. Well, then just repeat the observed data. No need for Fourier analysis.
But you also want to find "patterns". I assume that means finding the dominant frequency components in the observed data. Then yes, take the Fourier transform, preserve the largest coefficients, and eliminate the rest.
X = scipy.fft(x)
Y = scipy.zeros(len(X))
Y[important frequencies] = X[important frequencies]

As for periodic repetition: Let z = [x, x], i.e., two periods of the signal x. Then Z[2k] = X[k] for all k in {0, 1, ..., N-1}, and zeros otherwise.
Z = scipy.zeros(2*len(X))
Z[::2] = X

Comment: So you are repeating most important coefficients in Z (twice in the above example), and if use ifft to regenerate my time series, this new series will be longer than the original and by definition will have predictions in it.
Comment: I guess by denoising you mean picking the most important coefficients.
Comment: `Z = [X[0], 0, X[1], 0, X[2], 0, ..., X[N-1], 0]`. If that's what you mean, then yes. And yes, preserving the most important coefficients will have a "smoothing" or "blurring" or "denoising" effect on the signal.
Comment: I just realized I can keep calling Y[ctr] * (np.cos(x*ctr*2*pi/N) + 1j*np.sin(x*ctr*2*pi/N)) where x is new values and Y is coefficients, and ctr is coef indexes, and add this up; this will essentially forecast. What do you think?
Comment: Yes, that is basically isolating a single complex sinusoid in the time domain. But the answer will be complex. You also need the component `Y[N-ctr]` in order to get a real signal. (`x` is a real signal iff `X` has conjugate symmetry, i.e., `X[k] = X*[-k]`.)
Answer: When you run an FFT on time series data, you transform it into the frequency domain.  The coefficients multiply the terms in the series (sines and cosines or complex exponentials), each with a different frequency.
Extrapolation is always a dangerous thing, but you're welcome to try it.  You're using past information to predict the future when you do this: "Predict tomorrow's weather by looking at today."  Just be aware of the risks.
I'd recommend reading "Black Swan".
Comment: I read Black Swan. I am not talking about stock prices necessarily. Let's say .. harvesting data, which is very seasonal, or the famous sunspots data. So I am talking about something predictable.
Comment: +1. Extrapolation is dangerous, yes. Usually, people make models, and assume that the future will behave like the model says. Models depends on parameters, which are estimated with present or past observations. So you don't "predict" anything, you only fit a model.
Comment: @Alexandra C: I am talking about data that is known to repeat itself.
Comment: Let me clarify little further: Let's say I pinpointed a frequency that is pretty dominant in the data. How do I tie this back to points in the time domain data, so I can jump ahead and in the future and do prediction.
Comment: @user: this is a very difficult and probably too broad question.
Answer: you can use the library that @tartakynov posted and, to not repeat exactly the same time series in the forcast (overfitting), you can add a new parameter to the function called n_param and fix a lower bound h for the amplitudes of the frequencies.
def fourierExtrapolation(x, n_predict,n_param):

usually you will find that, in a signal, there are some frequencies that have significantly higher amplitude than others, so, if you select this frequencies you will be able to isolate the periodic nature of the signal
you can add this two lines who are determinated by certain number n_param
h=np.sort(x_freqdom)[-n_param]
x_freqdom=[ x_freqdom[i] if np.absolute(x_freqdom[i])>=h else 0 for i in range(len(x_freqdom)) ]

just adding this you will be able to forecast nice and smooth
another useful article about FFt:
forecast FFt in R
Comment: @DhivyaNarayanasamy fixed ;)
Comment: Hi the link you have provided is broken. Can you please post again if possible or If you have? Thank you.
Comment: Very interesting but wouldn't you want to bias the prediction with more weight on the last half (more recent) values given?   That is try this with data that is a flat line for the first half but a slopped line for the other half.  The sloped line should have more emphasis that the flat part.


How to access my error fetch data with JavaScript - [[PromiseValue]]]:Object

Question: I am trying to access an error message in my code. This is how it looks like this
const status = response => {
const status = response => {
            if (response.status >= 200 && response.status < 300) {

                return Promise.resolve(response)

            }

            return Promise.reject(new Error(response.statusText))

        }

               fetch('/url hast been omitted', {

                   method: 'POST',

                   headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                   },

                   body: JSON.stringify({
                        email: email.value,
                        name:  name.value,
                        message:  message.value
                   })

               }).then(status).then(res => {

                 const response = res.json();// i did this so i can console.log the value, which i did

                  return  response;

               }).then( data => {

                 console.log('data :'+ data.errors);

               }).catch(err=>{

                 console.log(err);

               });

And this is my browser information when I console.log the response:
And when I log data to the console, it looks like this:
   data :[object Object],[object Object]

I don't know how to access the errors array message. It is in this  [[PromiseValue]]].
What is wrong here, how can I access this?
Comment: Use `console.log('data:', data.errors);` (you forced an object into a string, which produces `[object Object]`)
Comment: try using console.dir(data, { depth: null });
Comment: You don't need to do `return Prmise.resolve` or `Promise.reject` inside the callback function `status` for then, just simply do `return response` or simply reject with a new `error`.
Comment: .It worked. thank you.
Answer:

}).then( data => {

  console.log('data :'+ data.errors); // Change this!
  console.log(data.errors); // to this
  // Now the object is converted to a String.

}).catch(err=>{
Comment: Thanks. I already did that. have pushed it to my landing page.


how to search and replace "-" character with "\0" in a string without sed and tr command in korn shell

Question: I am working in korn shell, here one variable "date" has some date value. I want to remove "-" character or replace "-" with null, from the date without using sed and tr command.
I tried the following but it is not working:
# echo $date
2014-10-16
# replace='\0'
# echo $replace

# echo ${ date//\-/$replace }
/bin/sh: : bad substitution

Answer: You can use tr:
date='2014-10-16'
echo "$date" | tr -d '-'
20141016

Or you can use sed:
echo "$date" | sed 's/-//g'
20141016

Or use built-in string function:
echo "${date//-/}"
20141016

Or using a variable:
replace=$'\0'
echo "${date//-/$replace}"
20141016

Comment: Why /bin/sh??? You wrote it is **korn shell**. First change your shell to `ksh` by typing `ksh` and then run these commands.
Comment: following is also not working:
echo "${date//-/}"
/bin/sh: : bad substitution
Comment: # replace=$'\0'
# echo "${date//-/$replace}"
/bin/sh: : bad substitution
Comment: echo $date
2014-10-16
# echo "${date//-/}"
ksh: : bad substitution
# replace=$'\0'
# echo "${date//-/$replace}"
ksh: : bad substitution
Comment: Don't know what old ksh you may have. Any way you can use `BASH` or `sed` instead?


ARRAYFORMULA with COUNTIF in Google Sheets

Question: We have a Google Form using which users will submit their survey. It may so happen that same user might submit the survey multiple times, at which point we only want to consider the latest response and ignore all the previous responses. The sheet has two key columns (timestamp and email) and we have created an additional column "Accepted" which is expected to have two values "0" or "1" where responses with "0" are not accepted and responses with "1" are accepted (as this is the latest submitted response).
Timestamp | Email | Accepted
2020/06/01 00:05:22 | email@example.com | 0
2020/06/01 00:35:06 | email@example.com | 1
2020/06/01 01:45:51 | firstname.lastname@example.com | 1
2020/06/01 02:03:40 | email@example.com | 0
2020/06/01 03:44:01 | firstname.lastname@example.com | 1

The first row of the Google Sheet has headers. So, the formula entered in C2 is:
=IF(COUNTIF($B$1:B2,B2)=COUNTIF($B$1:B,B2),1,0)

which works perfectly when dragged to all the rows. However, since we want to update the Column C to each new response, tried using the ARRAYFORMULA as below:
=ARRAYFORMULA(IF(COUNTIF($B$1:B2,B2:B)=COUNTIF($B$1:B,B2:B),1,0))

which returns 0 to all rows. Link to the sample Google Sheet is below:
https://docs.google.com/spreadsheets/d/1qAdOIV_ZioBw41UR_WEBR_Ean5tQ0Yd_f6oLRi83fOk/edit?usp=sharing
Please help. Thanks in advance :)
Comment: Would you be willing to have an Apps Script custom formula for this? Also, considering that you want certain actions to be done when a Form is submitted, it would be appropriate to have an [onFormSubmit trigger](https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onFormSubmit()). What do you think about that?
Comment: Have no idea about onFormSubmit trigger. Haven't used any of those so far :)
Answer: You can accomplish this via a custom function created in Google Apps Script. To achieve this, follow these steps:

In your spreadsheet, select Tools > Script editor to open a script bound to your file.
Copy this function in the script editor, and save the project:

function GETLAST(input) {
  input = input.filter(row => row[1] !== ""); // Remove empty elements
  return input.map(row => { // Iterate through rows
    const responderRows = input.filter(el => el[1] === row[1]); // Filter by email address
    const isLast = responderRows.every(el => el[0] <= row[0]); // Check if it's last email
    return isLast ? 1 : 0
  });
}

Now, if you go back to your spreadsheet, you can use this function like any in-built one. You just have to provide the appropriate range (in this case it would be A2:B), as you can see here:

Note:

This function is using the submission time (column A) in order to find the last submission for each email address. Row order does not matter.

Reference:

Custom Functions in Google Sheets


Block FaceTime/Whatsapp video

Question: I want to avoid video calls in my network, mainly from whatsapp and FaceTime.
Ideally, the phone shouldn't even receive the ring, but it might not be possible as the ring is certainly sent differently than the rest. 2nd choice is simply: No video.
According to doc found online, (i.e.:
https://support.apple.com/en-us/HT202078) I know which ports are used but not which for which usage. If it's possible, how can I determine that?
Comment: If the user device, can or use LTE, you already lost the control over that. The only control you have is to block your users to bring their own devices.
Comment: @yagmoth555-GoFundMeMonica  [other comment](https://serverfault.com/questions/993148/block-facetime-whatsapp-video/993152#comment1292113_993152)
Comment: My comment was more, if any user use LTE or his mobile coverage network, he bypass anything you set inside your router.
Comment: It won't be an issue, as long as it's not in our network. We want users using our network not being able to use video calls. If they're using LTE, it's fine, they will video call freely and outside our network
Answer: Since Facetime and What app is encrypted traffic, It would not be possible to block
video unless the apps use a different URL for text messages and video. Knowing the port numbers does not help because you cannot just block a port without disrupting other services. From my experience, you are fighting a losing battle. Unless you own the devices connecting to your network, you can not easily control what is done on those devices.
Comment: I understand that ports are not "service" specific here. Even if I owned the device, is there a way to block video calls?
Comment: For IOS devices, you can control what apps are allowed to be installed See: https://www.apple.com/business/it/ You could block the facetime app which would solve your problem. For WhatsApp, I am not sure what your options are but you could completely block that app too.
Comment: the issue isn't the app, I would like our users too be able to use WhatsApp, FaceTime, iMessage for text and audio calls, just not for video
Comment: Unless the developers have created the ability to block video via the apple configuration utility, then there is no way to do this. While you can try and figure out what url and ports facetime uses, chances are you will either break something else or the ports and urls will change.
Comment: I'm convinced (by your answer) that ports aren't used specifically for video or calls. I'm just answering to others about my needs, but I understood it's not feasible
Answer: The best way to determine what ports FaceTime uses would be to start capturing packets on the network, start a FaceTime call, and look at the ports used.
However based off Apple's listed ports, and knowing that FaceTime uses STUN (Session Traversal Utilities for NAT) protocol, blocking UDP ports 3478-3497 should suffice.
Keep in mind that STUN is widely used in VoIP applications, and blocking its ports will most likely cause issues for other VoIP traffic.

Block FaceTime/Whatsapp video


drupal 7, paths and urls are not working properly

Question: I'm developing a website on my localhost. I have a problem with urls.
for a url like this
http://localhost:81/my_website/library

I should output image src this way :
<img src="<?php print $directory; ?>/image/header/headerR.png"/>

but when the above url is changed to this
http://localhost:81/my_website/library/

I should output image src this way :
<img src="../<?php print $directory; ?>/image/header/headerR.png"/>

I mean it should refer to the parent. my website has also contextual filter which must be inserted after library/ .is there any general solution for handling such thing?
Comment: Why don't you use these global variables: $base_path or $base_url for your stuff.
Comment: I tested $base_path and the same problem happened
Comment: Do you remove the comment of this line `$base_url = 'http://www.example.com'` in **settings.php** and change the `www.example.com` by your domain. It should be like  `$base_url = 'http://localhost:81/my_website';` in your **settings.php** file
Answer: Use the global variables for resolving the issue of path of files as below:

Use base_path if your fine with domain name not to be included:
It will return path respect to the drupal root.
Eg:  "/" for drupal root(http://localhost:81/my_website), and
"/images/header" for http://localhost:81/my_website/image/header/header
Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_path; /* will return "/" for http://localhost:81/my_website*/
$image_path = $base_path . 'image/header/headerR.png';

Note: Don't use trailing slash / for adding path of files with $base_path as it adds a "/" to the beginning and end of the returned path.
Use base_url if you want to get the full path: It will return
base URL of the Drupal installation.
Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_url; /* will return http://localhost:81/my_website in you case*/
$image_path = $base_url . '/image/header/headerR.png';


Need a theoretical textbook for calculus, proof based

Question: The course descriptions is :
A theoretical course in calculus; emphasizing proofs and techniques. Trigonometric identities. Limits and continuity; least upper bounds, intermediate and extreme value theorems. Derivatives, mean value and inverse function theorems. Integrals; fundamental theorem; elementary transcendental functions. Techniques of integration. Taylor's theorem; sequences and series; uniform convergence and power series.
This course is using Spivak's calculus, but I'm also looking for another proof based book accompany with Spivak, thx
Comment: I have used four different books for analysis including Spivak's Calculus on Manifolds. My recommendation would be to use Kosmala's A Friendly Introduction to Analysis. It is almost purely epsilon-delta based, whereas Spivak will be using open balls.
Comment: Does it have plenty of exercise? How is its difficulty comparing to spivak?
Comment: Yes, there are many exercises and examples. I have never read Spivak's Calculus, only Calculus on Manifolds, so I can't compare. However, I do believe Spivak is an authority when it comes to calculus. I know manifolds wasn't an easy read.
Comment: One or more of the books listed [here](http://math.stackexchange.com/questions/731087/joseph-kitchens-calculus-reference) might be useful.
Answer: The Theory of The Calculus is called Mathematical Analysis ...Elementary Analysis for the R to R functions....so any of the very many books on Analysis should serve your purpose.
Comment: More advanced Analysis is usually approached "Topologically" Spivak's Calculus on Manifolds tries to do that...shame he does not know where to put apostrophies!
Answer: You might try the standards:

Apostol - Calculus Vol I
Hardy - A Course of Pure Mathematics
Piskunov - Differential and Integral Calculus

You might also try Rosenlicht's "Introduction to Analysis". It's a cheap, awesome Dover book that presents basic analysis at a good level. Not exactly parallel to Spivak, but you might find the presentation enlightening paired with Spivak.


How to find the quaternion representing the rotation between two 3-D vectors?

Question: I have two 3-D vectors:
$$
V_1 =
\left[
\begin{array}{r}
 -0.9597 \\ -0.9597 \\ 8.8703
\end{array}
\right]
$$
and
$$
V_2 =
\left[ \begin{array}{r}
-0.9568 \\ -0.9368 \\ 8.8432
\end{array} \right]
$$
How would I find the quaternion matrix to represent the rotation between $V_1$ and $V_2$? Specifically, what algorithm would I have to utilize to find it? MatLab code would be of great use!
Thanks in advance.
Comment: There are multiple rotations that will take $V_1$ to $V_2$, you will need to choose one first. I.e. you will need to decide on the axis and angle of the rotation you want to apply.
Comment: Welcome to Mathematics StackExchange! This short guide can help expand your MathJax knowledge: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: First find the axis ${\bf n}$ and angle $\theta$ for the rotation and then create the quaternion as $$q = (\cos \frac{ \theta}{2}, {\bf n} \sin \frac{ \theta}{2})$$
The axis is simply  perpendicular both vectors.
$$ {\bf n} = \frac{ {\bf v}_1 \times {\bf v}_2 }{\| {\bf v}_1 \times {\bf v}_2  \|} $$
The angle is
$$ \theta = \tan^{-1} \left( \frac{\| {\bf v}_1 \times {\bf v}_2  \|}{{\bf v}_1 \cdot {\bf v}_2} \right) $$
NOTE: $$ {\bf v}_1 \cdot {\bf v}_2 = \| {\bf v}_1 \| \| {\bf v}_2 \| \cos \theta$$ and  $$\| {\bf v}_1 \times {\bf v}_2 \| = \| {\bf v}_1 \| \| {\bf v}_2 \| \sin \theta$$
Comment: Great answer! I have a question about finding $\theta$. Why did you use $\tan^{-1}$ instead of $\cos^{-1}$ or $\sin^{-1}$ on the dot and cross products respectively?
Comment: Divide the cross product and the dot product and they will equal $\tan \theta$.  [But there are better ways](https://possiblywrong.wordpress.com/2020/07/17/computing-the-angle-between-two-vectors/) also to compute angles between vectors.
Answer: If you have access to Simulink, there is a function called vrrotvec which returns an angle-axis representation of the rotation between two 3d vectors ( see : https://www.mathworks.com/help/sl3d/vrrotvec.html ). Otherwise, you can get the axis by using the cross product of $V_1$ with $V_2$ and the angle by a dot product.
You can convert to a quaternion by using $q = \cos(\theta/2) + (u_x \hat{i} + u_y \hat{j} + u_z \hat{k}) \sin (\theta/2)$, where $u_x$, $u_y$ and $u_z$ are the components of the rotation axis, $\theta$ is the rotation angle and $\hat{i}$, $\hat{j}$ and $\hat{k}$ are the components of the quaternion. See the wiki page on quaternions (https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation).
Comment: How this function work? What formalism lay in this function?


Why transformer in deep learning is called transformer?

Question: Where does the name "transformer" come from in deep learning? I want to know more about the correlation between its name and its working principle.
Comment: Someone thought it would be a fun name...
Comment: Yeah, +1 to Tim. It's marketing.
Comment: Probably because transformer architectures use series of (non)linear transformations, i.e., recall Q, V, K matrices. That might be the reason. @Tim yes fun name, if we associate with Transformers franchise. Interesting that name is not disputed by Hasbro.
Comment: But those matrix multiplications are exactly linear. There is only softmax function applied on the top of scalar products of K and Q and then again linearly multiplied by V.
Answer: Transformer,  becuase it uses the attention mechanism with softmax transformation after  that using the feedforward with nonlinear transformation. In short it uses different transformations(activation functions) to transform the input from intial representation into final representation if  we would explain that in very simple words.
Comment: ...kinda like every other machine learning or even mathematical model


Forwarding variadic template parameter to printf-like function

Question: I have the following log function:
template<typename... Arguments>
void Log(const char* file, const int line, int level, const char* fmt, Arguments... args)
{
   std::string formattedFile;

   if (file)
   {
      boost::filesystem::path p(file);
      formattedFile = p.filename().string();
   }

   std::string message{boost::str(boost::format("%1%:%2% [%3%] - %s") % formattedFile % line % m_uxid % fmt)};
   __android_log_print(level, m_tag.c_str(), message.c_str(), args...);
}

This application is run on Android using NDK, so this is the logging system for that platform. The problem is that __android_log_print() fails to compile with:
error: format not a string literal and no format arguments [-Werror=format-security]
          __android_log_print(level, m_tag.c_str(), message.c_str(), std::forward<Arguments>(args)...);
                                                                                ^

I'm not sure what this means. Am I not using the variadic template argument correctly?
Comment: Quite plain: You asked your implementation to enforce format-string-correctness by passing `-Werror=formant-security` (maybe using something more inclusive), and it is not able to guarantee that the passed format-string is safe.
Comment: It doesn't make much sense to `std::forward` stuff to a C-style variadic function, and even less sense to do it when you are not taking the arguments by universal reference.
Comment: @T.C. I disagree. It makes perfect sense to do so when that C-style function is a variant of `printf`, because you can't easily rewrite `printf` by yourself as a variadic template, and variadic templates are more powerful than C-style variadics (for example, you can forward with an additional argument added at the end, try doing that with a `va_list`). Also it's okay to take the arguments by value because `printf` does.
Comment: @Brian I'm talking about the use of `std::forward` in particular, not the concept of forwarding.
Comment: @T.C. Whoops, my bad. Gotcha.
Comment: `format not a string literal` is exactly what it says on the tin - you need to pass the format as a literal. See `-Wformat-nonliteral` here [here](https://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Warning-Options.html)for why that's a problem
Comment: @T.C. What do you mean by "universal reference", I had trouble understanding what `std::forward` actually does, but I found that in a sample online so I used it. Can you explain?
Comment: http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers
Comment: Thanks @T.C., now that I have read about universal references it doesn't make sense to not use `Arguments&&...`. But if I don't use it, is it taking all of those parameters by value as if I had typed them out by hand?
Answer: Untrusted input into printf can be a security problem. Enforcing the format by using a string literal is one way of improving security
Turning warnings into errors will cause the build to fail so you are forced to address the warning.
GCC's warning options have this to say
-Werror:
Make all warnings into errors.
-Wformat-security:
Warn about uses of format functions that represent possible security problems.
At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments
This may be a security hole if the format string came from untrusted input and contains %n.
What is generally advised is to create a std::string in your function and pass this with a %s format string literal to your logging function
__android_log_print(level, m_tag.c_str(), "%s", message.c_str());

Where message is built from processing args..., typically using something like boost::format or a std::stringstream.
If you want to use your provided fmt string and the variadic args, you can parse the arguments using a custom printf style function which produces a std::string
std::string va_string_printf(const char* format, va_list ap)
{
    char stack_buf[256];

    char* buf = stack_buf;
    int buf_size = sizeof(stack_buf);

    std::string out_str;

    while(true)
    {
        va_list ap1;
        va_copy(ap1, ap);
        int min_buf_size = vsnprintf(buf, buf_size, format, ap1) + 1;
        va_end(ap1);

        if (min_buf_size > buf_size)
        {
            if (buf != stack_buf) // allocate a bigger buffer
                delete[] buf;

            buf = new char[min_buf_size];
            buf_size = min_buf_size;
            continue;
        }

        out_str = buf;
        break;
    }

    if (buf != stack_buf)
        delete[] buf;

    return out_str;
}

std::string string_printf(const char* format, ...)
{
    va_list ap;
    va_start(ap, format);
    std::string str = va_string_printf(format, ap);
    va_end(ap);

    return str;
}