Unresolved external symbol (singleton class C++)

Question: I already looked up some answers in Stackoverflow for this type of problem, none of which are helping me out. This question describes how to resolve this error, and that I should provide a definition and not just a declaration. I've done that, but I'm still getting the following error:

Error 13  error LNK2019: unresolved external symbol "private: __thiscall NetworkManager::NetworkManager(void)" (??0NetworkManager@@AAE@XZ) referenced in function "public: static class NetworkManager * __cdecl NetworkManager::Instance(void)" (?Instance@NetworkManager@@SAPAV1@XZ)    C:\Users\HIDDEN\Documents\AGK Projects\C++ Libraries\apps\template_windows_vs2013\NetworkManager.obj    Template

Here's the code:
NetworkManager.h
#ifndef _H_NETWORKMANAGER_
#define _H_NETWORKMANAGER_

#include<iostream>
#include<vector>

class NetworkManager
{
private:
    NetworkManager();
    static NetworkManager * netManager;
public:
    int networkID;
    static NetworkManager * Instance();
    int HostNetwork(std::string netName, std::string hostName, int port);
    int JoinNetwork(std::string netName, std::string clientName);
    bool IsNetworkActive(int netID);
};

#endif

NetworkManager.cpp
#include<iostream>
#include "NetworkManager.h"
#include "template.h"

NetworkManager * NetworkManager::netManager = NULL;

NetworkManager * NetworkManager::Instance()
{
    if (!netManager)
        netManager = new NetworkManager;

    return netManager;
}

int NetworkManager::HostNetwork(std::string netName, std::string hostName, int port)
{
    int networdID__;
    const char * netName__ = netName.c_str();
    const char * hostName__ = hostName.c_str();
    networdID__ = agk::HostNetwork(netName__, hostName__, port);
    return networdID__;
}

int NetworkManager::JoinNetwork(std::string netName, std::string clientName)
{
    int networdID__;
    const char * netName__ = netName.c_str();
    const char * clientName__ = clientName.c_str();
    networdID__ = agk::JoinNetwork(netName__, clientName__);
    return networdID__;
}

bool NetworkManager::IsNetworkActive(int netID)
{
    switch (agk::IsNetworkActive(netID))
    {
    case 0: return false; break;
    case 1: return true;  break;
    }
}

Comment: Side note: function `Instance` is not thread-safe.
Answer: You declared NetworkManager::NetworkManager() in the header file but there is no implementation of it in the source file.
Comment: Oh snap! Thanks. I'll vote this as correct answer as soon as I can.


Problem including eigenspace and eigenvalues

Question:
Given $A \in M_n(F)$ and $V_j(A)\ :=N(A^j)$, where $N$ is the nullity.
$(a)$ Prove $V_j\subseteq V_{j+1}, \ \forall j,$ and there exists $l\in \mathbb{N}$ such that for every $j<l: V_j \subset V_{j+1},$ and for all $j \geq l: V_j=V_{j+1}$. That is:
$$\{0\} \subset V_1 \subset V_2 \subset\dots\subset V_l = V_{l+1}=V_{l+2}=\dots$$
$(b)$ Let $\lambda \in F$ be an eigenvalue of $A$ with algebraic multiplicity $k$ and multiple $r$ as root of the minimal polynomial $m_A$.
Let us look at the spaces sequence $V_j(A-\lambda I).$
Prove that in this case, $l=r$ and $\dim V_l(A-\lambda I)=k$

I proved $(a)$, but I'm struggling with $(b)$.
I'm having hard time connecting the line between the minimal polynomial and $N(A^j)$.
I think Jordan might help me here, but not sure how to proceed.
Any help appreciated.
Answer: If you can use Jordan form, then it suffices to note that $\dim(V_j(A - \lambda I)) - \dim(V_{j-1}(A - \lambda I))$ is the number of Jordan blocks associated with the eigenvalue $\lambda$ with size at least $j$.
Comment: I can see that, but I can't see how to proceed. Can you elaborate please?
Comment: From there, note that the algebraic multiplicity is the total of the sizes of the blocks associated with $\lambda$, and $r$ is the size of the largest Jordan block associated with $\lambda$.
Comment: Forgive me, but now I can't understand the note you mentioned in your answer. Mind explaining why is it true? I do know the attributes you mentioned in your comment.
Comment: Look what happens when you take the powers of a Jordan block associated with $\lambda = 0$: whenever $J^k \neq 0$, we have $\dim N(J^{k+1})  = \dim N(J^k) + 1$.   This goes on until we have $J^k = 0$.  Of course, when you take the $k$th power of a block diagonal matrix, you're just taking the $k$th power of each block entry.
Comment: What do you mean by $+1?$
Comment: Oh, excuse me: that should read $\dim(N(J^{k+1})) = \dim(N(J^k)) + 1$
Comment: Okay, I understand that. How does that imply the number of Jordan blocks associated with the eigenvalue $\lambda ?$
Comment: Suppose without loss of generality that $A$ is in Jordan normal form.  Notice that $A - \lambda I$ will now have Jordan blocks associated with zero wherever there was a Jordan block associated with $\lambda$.  If we look at the nullities of the successive powers, then it is precisely the blocks associated with $\lambda$ which cause the changes (if $J$ is a Jordan block not associated with zero, then $\dim N(J^k) = 0$).
Comment: Okay, I understood that. So we have $\dim(V_j(A- \lambda I)) - \dim(V_{j-1}(A- \lambda I)) $ blocks of size at least $j$. How can we get the size of the biggest block out of that ?
Comment: @Itay4 saying that $r$ is the biggest block size is the same as saying that $0 = \dim(V_j(A- \lambda I)) - \dim(V_{j-1}(A- \lambda I))$ is the number of blocks of size at least $j$ for any $j > r$.


Solutions of a second order nonlinear differential equation

Question: I am in trouble solving the following differential equation:
$$\ddot{x}(t)=-\alpha\dot{x}(t)\dfrac{x(t)}{\left(\beta^2+x(t)^2\right)^{\frac{5}{2}}}$$ where $\alpha$ and $\beta$ are constant.
How can I solve it?
Thanks
Comment: Any constant is a solution, so that solves the IVP whenever $x'(0)=0$. Otherwise I doubt you will find a closed form. Try numerics.
Comment: An observation: As long as $\alpha,\beta$ are non-zero, you can introduce appropriate rescalings $x=Ay,$ $t=Bs$ such that the constants disappear i.e. $y''(s)=-\dfrac{y(s)y'(s)}{(1+y(s)^2)^{5/2}}$ for some choice of $A,B$. So the constants really don't matter here.
Answer: It is possible to analytically solve the ODE and express the result on the form of $t(x)$
The huge function found cannot be inverted, so the result is not expressed on the form $x(t)$
Comment: (+1) That implicit form is simultaneously impressive and rather horrifying.
Comment: Hopping that there is no bug in the horrifying calculus ! (Even with some parts made with the help of symbolic maths soft.)
Comment: One thing that would make the computation slightly straighter is to make some substitution $(x,t)=(Ay,Bs)$ for appropriate $A,B$ in such a way that the constants $\alpha,\beta$ need not be explicitly present. Though I don't anticipate that allowing the final form to simplify.


Find mgf from joint pmf

Question: The joint pmf of random variables $ X$ and $ Y$ is given by
$$p_{XY}(x,y)=
\begin{align}
& \frac{e^{-2}}{x! (y-x)!}\quad\text{if}\,\,\,x= 0,1,...y,\ y=0,1,... \\
\end{align}
$$
Find its mgf.
\begin{align}
M(t_{1},t_{2}) &=  E(e^{t_1 x+ t_2 y})\\
&= \sum_{y=0}^{\infty} \sum_{x=0}^{y} e^{t_1 x+t_2 y} \frac{e^{-2}}{x! (y-x)!} \\
&=\sum_{y=0}^{\infty} e^{-2} \frac{e^{t_2 y}}{y!} \sum_{x=0}^y e^{t_1 x} \frac{y!}{x!(y-x)!}\\
&=\sum_{y=0}^{\infty} e^{-2} 2^y \frac{e^{t_2 y}}{y!}  \left(\frac{1+e^{t_1}}{2}\right)^{y}
\end{align}
How do I simplify further?
Comment: Please add the `self-study` tag and detail where you get stuck in the derivation of $M$. Otherwise the question is prone to be voted down.
Answer: This problem is intriguing because it indicates something symmetrical lurks.  One can't help feeling there is a simple, low-computation, insightful solution. Indeed, a little staring at the pmf suggests defining
$$z = y-x.$$
We may assume $z \ge 0$ (because when $z \lt 0$ the $z!$ terms in the denominator have poles, which makes those probabilities zero).  Now, for non-negative integers $x$ and $z$
$$p_{XY}(x,z) = e^{-2}\, \frac{1}{x!}\frac{1}{z!} = \frac{e^{-1}}{x!}\frac{e^{-1}}{z!} $$
is manifestly symmetric under exchanging $x$ and $z.$ It is immediately recognizable as the probability distribution of two independent Poisson$(1)$ variables $X$ and $Z$ where $Z=Y-X.$
Consequently--as you know, or can look up, or can easily compute, its moment generating function is
$$m_{XZ}(s,u) = E[e^{sX + uZ}] = E[e^{sX}]E[e^{uZ}] = \exp(e^s - 1)\exp(e^u-1)=\exp(e^s+e^u-2).$$
This function remains symmetric under an exchange of its arguments $s$ and $u.$ At this point we must break the symmetry to return to the original problem--but the calculations remain simple.  Since $Y=X+Z,$
$$\eqalign{
m_{XY}(s,t) &= E[e^{sX+tY}] = E[e^{sX + t(X+Z)}] = E[e^{(s+t)X+tZ}] = m_{XZ}(s+t, t) \\&= \exp(e^{s+t} + e^t - 2).
}$$
Even if your goal is only to simplify the sums you obtained, this insight into the variables and the underlying symmetric formulation can help guide your work.
Answer: The joint pmf of $(X,Y)$ is of the form
\begin{align}
p(x,y)&=\frac{e^{-2}}{y!}\binom{y}{x}\mathbf1_{x=0,1,\ldots,y\,;\,y=0,1,\ldots}
\\&=\binom{y}{x}\frac{1}{2^y}\mathbf1_{x=0,1,\ldots,y}\,\frac{e^{-2}2^y}{y!}\mathbf1_{y=0,1,\ldots}
\end{align}
This shows that $X\mid Y\sim\mathsf{Bin}\left(Y,\frac{1}{2}\right)$, where $Y\sim\mathsf{Poisson}(2)$.
Using the law of total expectation:
\begin{align}
E\left[e^{t_1X+t_2Y}\right]&=E\left[E\left[e^{t_1X+t_2Y}\mid Y\right]\right]
\\&=E\left[e^{t_2Y}E\left[e^{t_1X}\mid Y\right]\right]
\end{align}
Now recall the MGF and PGF of binomial and poisson distribution respectively.
Edit.
To clarify, my hint above is the same thing as you have done. To finish it off, note that the last sum is just $E(a^Y)$ for some $a=a(t_1,t_2)$, which is just the PGF of $Y$.

Find mgf from joint pmf


Shaded Area of a Symmetrical Figure

Question:
I thought that because no dimensions are given, and because there do not seem to be any perfect squares (only rectangles), I chose K. However, the correct answer is G. Why is this so?
Any help will be greatly appreciated, thanks in advance.
Answer: Let us use similar triangles, and sum their areas in different ways.
 Call $S$ the area of the shaded region, $W$ for the white one.
Call $T_1$ the area of $EFG$, and $T_2$ that of $FGH$. $W=2T_1 = 2T_2$, thus $T_1 = T_2$. And $S=2T_1+4T_2$. So $S/W = \frac{6T_1}{2T_1}$.
Another possibility: remark that the ratio is invariant if you apply an affinity centered on $A$. Compute it in a simple case where you know the lengths, for instance when $ABCD$ is a square.
Answer: Let the length and breadth of the rectangle be $a$ and $b$
In the triangles BAF and CDF , the base and height are $ a/2  $ and $b$ respectively.
In triangles GAE and HED, the base and altitude are $a/2$ and $b/2$ respectively. The total shaded area will be $3ab/4$.
And unshaded area will be  shaded area from total area.
Answer: lazy hint:

Move $\triangle CHD$ to the left of $\triangle ABG$.
Move $\triangle BFG$ below $\triangle AGE$.
Move $\triangle FHC$ below $\triangle EHD$.
Count up your new rhombuses and decide what to do with all the time you saved not doing any algebra.

Shaded Area of a Symmetrical Figure


Add

Question: I am working on a project where the admin wishes to be able to insert a  element into a node's body field.  The site makes use of TinyMCE editor (wysiwyg module) to edit text area fields.
Currently admin is able to add the  element to the body field by switching to source mode of Full HTML text format (by toggling "disable rich-text").  He can then insert the  element and then save node.  In this case the  element will be preserved in the saved markup.
But if the node is edited again the wysiwyg appears to filter out the  element, which means the admin has to re-add it using the method just described.
This unwanted removal of  element also occurs when switching back and forth between the rich-text editor (toggling the "Enable rich-text" or "Disable rich-text" link below the field) after adding the element.
So it seems it is the wysiwyg is filtering this  element out.
Is there a way of preventing this from happening?
Answer: TinyMCE outputs HTML 4.01 Transitional markup by default, and  is not allowed inside  in that (or XHTML) because styles are not block elements.
You can however force TinyMCE to accept [the invalid] style elements inside the body by overriding the valid_children setting.
<code>/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['valid_children'] = '+body[style]';
  }
}
</code>
Thanks to TwoD for supplying the answer.

Add


What is the most appropriate way to test significance of effect difference across two groups?

Question: Here is the question: After running two separate OLS regressions, one for each group (male vs. female), we get coefficient b1 for a specific IV in "male" regression, and coefficient b2 for the same IV in "female" regression. What would be the most appropriate way to test the hypothesis: Ho: b1>b2? As far as I know, Wald is a widely used test, but it only check whether the effect difference is different from zero (Ho: b1-b2=0)
Thanks!
Answer: A one sided test like a $t$-test can be obtained by merging your two separate regressions into one that models both groups. If you are interested in the effect of x on y across groups then add a $x_i D_i$ regressor where $D_i$ is a dummy variable that codes your group:
$y_i = a x_i + b x_i D_i + u_i $
As you can see, your group effects are given by $a$ and $a+b$. Thus your hypothesis test becomes $H_0: b>0 $ and its statistic would be based on a one sided t-statistic
ABOUT COLLINEARITY.
These 2 IV are not going to be collinear as there is no linear combination that makes its sum = 0 under standard conditions (and a OLS, ML estimator). To see why let's only take the sample for which $D_i=0$ and assume the following vector notation:
$y = x a + z b  + u$
where z is a vector with $x_iD_i$components.
Collinearity may airse as the linear combination $c_1x + c_2z$ approaches zero (for $c_j \neq 0 $). But just considering the block of observations where $D_i=0$ automatically leads to a linear combination block equal to $c_1 x\neq 0 $ if $x \neq 0$.
I guess you are thinking in term of standard theory that tells you that higher IV correlation may lead to collinearity, but don't forget that standard theory refers to the IV which in our case are $x_i$  and $z_i(=x_iD_i)$ and not $x_i$ and $D_i$. Moreover, the mathematical issue behind the correlation issue is the fact of having linearly dependent variables, so linear dependence between $x_i$ and $z_i$ must be addressed.
Comment: I agree with JDav.  I think we came up with the same answer at almost the same time. He is really confirming what I happened to get submitted first. I suspect that he was writing his before I finished mine and came up with it independently.  Ihope this will convince you to use this approach rather than work with two spearate regressions.
Comment: Thanks!!The joint model approach sounds rather straightforward and flexible indeed! My only concerns is that, in my dataset, the gender dummy is highly correlated with the IV, and for this reason I was a bit hesitant to pool the two groups together...
Comment: Haha, indeed, almost same answer at almost the same time! I think I am convinced what the best method is:)
Comment: It took me long to write these very few lines and it was certainly almost simultaneous answer. About colinearity, see the edited answer.
Comment: Many thanks for your time, really appreciated!I was stuck with the standard theory as you mentioned;worried about high IV correlation that could cause serious colinearity issues...it sounds clear now!
Answer: Why not do a more conventional thing and do one regression with gender as a covariate?  Then a statistically significant gender effect would indicate that gender is important and more specifically include a gender interaction term with your IV.  If the interaction is statistically significant that indicates that the male and female slopes differ. Make the test one sided and you have your answer.
Comment: Correlation between covariates is not a problem unless it is so high as to create a near multicollinearity.  In fact if you believe one slope is different from the other then the IV interacts with gender and there is necessarily a correlation. Also correlation between a binary variable and and a continuous one is different from correlation between two continuous variables. Certainly a pearson correlation cannot be defined.
Comment: Thanks!!Please see comment above, high correlation between IV and dummy is a point of concern if doing one regression only.
Comment: I see, I was not aware that pearson correlation cannot be defined in case of correlation between binary and continuous variables, many thanks!


How to disable Ctools modal form from running on mobile devices?

Question: I am using Drupal 7 Totem distro (a responsive site). My problem is that the pop-up modal form works fine on large screens but doesn't respond well on mobile devices/smartphones.
How do I disable the modal form from runnning on mobile devices?
Answer: You can hack wonders with a little "@mediaquery" and "!important".
I used this little bit with "modal_forms", not sure if the #id is the same.
<code>@media (max-width: 580px) {
    #modalContent {
      position: fixed !important;
      top: 12% !important;
      bottom: 12% !important;
      right: 4% !important;
      left: 4% !important;
    }
    div.ctools-modal-content {
      width: 100% !important;
      margin: 0 auto;
    }
    div.ctools-modal-content .modal-content {
      width: 100% !important;
    }
}
</code>
Answer: Next code will disable ctools popup appearing, and restore going to URL of link behaviour (tested for Modal forms (with ctools)), so for mobiles, instead of opening modal, it will open URL of link:
<code>if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  $('a.ctools-use-modal-processed', context).unbind('click');
}
</code>


Configurar orphanRemoval=true em Generate Entities of Table - JPA Tools - Eclipse

Question: Estou tendo problema toda vez que preciso usar o Generate Entities of Table do JPA Tools (uso Eclipse Neon.3). Eu gero as entidades com o comando Generate Entities of Table do JPA Tools. No código de uma classe na anotação de um relacionamento adiciono  o codigo orphanRemoval=true e salvo tudo certo. Quando preciso usar novamente o comando Generate Entities of Table, quando vou olhar a mesma classe que inseri o orphanRemoval=true já não existe mais.
Como faço para configurar o JPATools (nas telas de Generate Custom Entities) para inserir o orphanRemoval=true num relacionamento, de modo que esta fique memorizada e toda vez que precisar usar o comando de gerar as entidades de tabelas ele automaticamente insira o orphanRemoval? Assim como vc seleciona cascade na tela Generate Custom Entities e ele mantem memorizada.
Veja o trecho de código do caso abaixo:
Quando gero a entidade com o JPA Tools:
@OneToMany(mappedBy="pessoa", cascade={CascadeType.ALL})
    private Set<PessoaContato> listaPessoaContato;

Insiro manualmente no codigo o orphanRemoval e salvo:
@OneToMany(mappedBy="pessoa", cascade={CascadeType.ALL},orphanRemoval=true)
    private Set<PessoaContato> listaPessoaContato;

Quando preciso regerar novamente, o jpa tools sobreescreve todas as classes apagando tudo que é inserido manualmente, dessa forma o trecho de código volta a ficar:
@OneToMany(mappedBy="pessoa", cascade={CascadeType.ALL})
    private Set<PessoaContato> listaPessoaContato;

Comment: Olá, FredeBr. Bem-vindo ao [pt.so]! Infelizmente eu não sei responder à pergunta (até porque faz anos que não uso mais o Eclipse). No entanto, quero avisar aos que votaram para fechar que a pergunta é perfeitamente clara: o autor da pergunta está usando uma ferramenta de geração de código no editor Eclipse e precisa que o código gerado tenha uma certa característica. Se é ou não possível customizar a ferramenta eu não sei, mas é uma pergunta perfeitamente válida.
Answer: A única referência direta sobre tal opção que encontrei é de muitos anos atrás e basicamente foi dito que não era suportada e não havia planos para isto.
O motivo, creio, é porque a ferramenta de geração de entidades baseadas em tabelas é uma ajuda inicial e não tem pretensão de automatizar a evolução das classes através da regeneração das mesmas em cada mudança do banco.
Fiz uma pesquisa para ver se havia uma forma de ligar tal opção por padrão ou sobrescrever a anotação externamente, independente da anotação do campo, mas não encontrei nenhum resultado.
A melhor solução seria usar a ferramenta apenas para gerar apenas as classes referentes às novas tabelas, sem sobrescrever as existentes.
Uma alternativa seria criar uma ferramenta para processar as classes geradas e adicionar a informação onde for conveniente de forma automática.
Comment: Realmente, o JPA Tools infelizmente não tem esta opção e já tinha visto esta referência que você citou. Achei interessante que nas telas de Generate Custom Entities ele dá opções de você definir o tipo de cascade, o fetch e memoriza esta informações pois se você regerar as entidades nestas telas serão mostradas as configurações que vc definiu anteriormente. Optei pela inserção manual mesmo através do JPA Diagram Editor. Vamos ver se no futuro o pessoal do projeto resolva implementar. Obrigado pelo retorno.


permissions to allow role to edit the posted date

Question: in drupal 7 - I have given a role the permissions to edit, add delete and modify content but he doesn't see the authored date in order to modify it.  how can I give him permissions to modify that ?
Answer: Updated date is set automatically by the system, if you want to edit that you will need to write some custom code.  Your user should be able to see the 'authored date' though.
Alternatively, if you need a date field that the user can edit (say, a publication date), just create a date field on your content and render it appropriately.

[edit based on additional info]:
I went digging in the code and found this in node.pages.inc:
$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

As you can see, access is tied to the 'administer nodes' permission which I'm guessing you haven't, and probably don't want to give to that role.
Luckily this is quite easy to change using hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id), here's the API for that function.
Create a custom module and put this in it:
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id){

    // You may wish to add some logic here to test for a specific role

    $form['author']['#access'] = TRUE;

    // Otherwise this will simply give everyone who can create nodes the
    // ability to change author and date.

}

Comment: Hi, that is the date I want him to see (the authored date) but it's not visible to him (I can see it when I edit as an admin though)
Comment: Updated answer.


Writing a Lebesgue Measurable Set as a Union of a Measure Zero Set and a Countable Union of Compact Sets

Question: I'm trying to showing that using the notion of Lebesgue inner measure, i.e., using the fact that for a measurable set $E$, $m(E)=$Sup$\{m(K): K \;$is compact$\; \land \;K\subseteq E\}$, one can write $E$ as follows: $$E=A\cup\bigcup_{n=1}^{\infty}C_{n}$$ where $m(A)=0$ and each $C_{n}$ is compact.
I've generated a sequence of compact sets $\{K_{n}\}_{n=1}^{\infty}$ with each $K_{n}\subseteq E$ and $m(K_{n}) \to m(E)$ by the definition of the supremum, but I'm stuck at this point.
Answer: Consider $C_n= K_1 \cup \ldots\cup K_n$. Then
$$m(K_n) \le m(C_n) \le m(E)$$
and since $m(K_n) \to m(E)$ we have also $m(C_n) \to m(E)$.  Now, since $C_n$ is an increasing sequence of measurable sets ( compacts) we have
$$m(C_n) \to m(\cup_n C_n) $$
Now, $\cup_n C_n \subset E$ and $m(\cup_n C_n) = m(E)$.
If we have also $m(E)< \infty$ we get $m(E\backslash \cup_n C_n) = 0$, so we can take $A=E\backslash \cup_n C_n$.
Otherwise, write $E= \cup_m E_m$, $E_m$ measurable, of finite measure. For every $m$ consider $L_m$ a finite union of compacts inside $E_m$, such that $m(E_m \backslash L_m) = 0$. Now take $A= E \backslash \cup_m L_m$.


Execução de query após alguns segundos

Question: tenho um script que registra todas as visualizações das páginas do meu site que bolei, e está funcionando muito bem.
Só que agora surgiu alguns problemas no que se trata de visitação do GOOGLE, e tem "muita", mais "muita" visitação dos Robôs do Google e não está legal para ter uma base de visitação do WebSite.
$db->query( "INSERT INTO visitas (ip_address,page_location,date_visitation,visitor_browser,visitor_plataform,visitor_city,visitor_region,visitor_country) VALUES ('$ip','$page_location','$date_visitation','$visitor_browser','$visitor_plataform','$visitor_city','$visitor_region','$visitor_country')" )->fetchAll();

Até onde sei, o robô do google não passa mais do que 5 segundos em uma página do site.
Eu gostaria de fazer este INSERT ser executado após 10 ou 15 segundos. Seria possível? ou teria uma outra solução para esta situação?
Grato pelo apoio.
EDIT 1
Surgiu a necessidade de somente a function  setCounterVisitor() ser executada após 15 segundos, devido meu script ser requerido em outra página.
É importante que para funcionar a function ela venha está na mesma página e não no visitor.php.
<?php
require_once 'app/visitor.php';
setCounterVisitor();
?>

É possível executar o  setCounterVisitor(); após 15 segundos na página carregada?
Comment: coloque o código num arquivo php e chame ele com ajax, nesse ajax faça um `setTimeou`
Comment: Poderia me da um exemplo? o código já está em um arquivo PHP separado. Ele estou chamando em um requere_once.
Comment: Talvez a pergunta seja "como identificar os robôs de Google, Bing etc ?"
Answer: Chame uma função dentro do setTimeout, passando o tempo de delay que ela deve ter (em milisegundos), essa função fará uma chamada assíncrona ao arquivo php que executará o insert
setTimeout(function() {
    httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', 'nomedoarquivo.php');
    httpRequest.send();
}, 15000);

Se já você estiver usando JQuery no seu código pode usar sua função de ajax. Outra opção é a api do fetch

Não tenho certeza se é isso que quer mas você pode passar uma variável pela url e no visitor.php verificar se ela existe, se sim executa a função
No javascript altere a url do xhr:
httpRequest.open('GET', 'visitor.php?exe=true');

No php verifica se existe e chama a função:
if($_GET["exe"]) {
    setCounterVisitor();
}

Comment: Muito bom! Deu certo. Só que agora surgiu uma nova surpresa no meu script. É possível fazer isso para executar uma function em php com esse mesmo método? Tendo em vista que a function que É "setCounterVisitor()" deve ser executada na mesma página e não pegando por meio de um url. Tem possibilidade?
Comment: Pode editar a pergunta com um exemplo? Não entendi muito bem
Comment: Editei, veja por favor !
Comment: Editei a resposta veja se resolve o problema
Comment: Deu o seguinte erro quando executa o $_GET["exe"] do setCounterVisitor(); ----- Fatal error: Uncaught Error: Call to undefined function setCounterVisitor() in C:\AppServ\www\site\header.php:18 Stack trace: #0 C:\AppServ\www\site\paginas\principal.php(16): include() #1 C:\AppServ\www\site\index.php(16): include('C:\\AppServ\\www\\...') #2 {main} thrown in
Comment: A função `setCounterVisitor` não existe no arquivo php chamado no XHR ou está dentro de uma classe, importe a função com o `require` ou instancie a classe e chame a função pela sua instância

Execução de query após alguns segundos


Does absolute pitch always cover the all musical sound range?

Question: There is a question here about the musician who can only identify the pitch of the one single note correctly. Well, this is not completely worthless maybe and could replace a tuning fork.
However I wonder, how often the perfect pitch would not span over all usual sound range? It is always limited at least by the sound range a human is able to hear, but could it be more limited than a typical musical range?
For instance, could anyone have a perfect pitch for just one or two octaves, for instance? Or even more narrow?
Comment: I don't think that's what the questioner meant. They were saying that when they hear a pitch, they can name tunes that start with the pitch. I don't think that "certain" in that question meant a single specific pitch. At any rate, I can't answer definitively, but I will say anecdotally that I've met and worked with many people with perfect pitch, and it was never a small range or only a few specific pitches. Extremely low or high pitches seem to give at least most of them trouble, but I'm talking about notes so extreme that they barely register as pitch anyway.
Comment: Musicians tend to have a much higher accuracy naming notes that are played by their primary instrument. For example, if I were a flutist, it would be easier for me to develop "perfect pitch" naming the flute's notes and/or hearing notes played in the flute's range.
Answer: As someone who has absolute pitch, I can speak from experience: I cannot tell notes apart in the extreme high range. My ability to distinguish notes drops off significantly around 10 kHz or so. Extremely low notes are fine for me (provided they are audible), but I play the bass guitar, for what that's worth; I'm not sure if I've merely had more practice listening in the low range or if those notes are objectively easier to hear.
I discovered that my ability to identify notes was limited when a friend asked me  what pitch a CRT TV makes when it's powered on. I couldn't give him a definite answer.
Despite what many people think, perfect pitch is not perfect. Many people with "perfect" pitch (myself included) sometimes think a note should be a couple hertz sharper/flatter when it is actually in tune.
Comment: Yiu wrote: "Many people with "perfect" pitch (myself included) sometimes think a note should be a couple hertz sharper/flatter when it is actually in tune." I wonder how you define "in tune"? If you, on a violin on the D string, play D-E-F♯ then the F♯ should be intonated rather sharp as a leading note to G in order to sound in tune. But if you play a double stop F♯ on the D string and the open A string then you need to flatten the F♯ in order to play a minor third in tune in just intonation. None of these two might be the same F♯ as the F♯ on a piano, but both of them are in tune.
Comment: I define "in tune" as the standard 12-TET tuning used on modern pianos, since that is the dominant tuning I grew up listening and tuning my instruments to. If you ask me to tune my violin by ear, I'll often tune my A string to 438 or 439 hz instead of 440, because this sounds "in tune" to me without a piano reference.
Answer: I am a Bassist and I have perfect pitch in low frequencies. It starts to weaken in mid frequencies, and weakens more still in high frequencies (though I can still "color hear" in these frequency ranges, just not/no where near as well respectively). I can "color hear" notes on my own instrument (Double Bass and Electric Bass) the best, but the ability does pass over to other low pitched instruments too (such as the Tuba, Bass Trombone, lower regions of a a Piano). I can work out chords, but have a tendency to work them out from the bottom up (I will work out the lowest note using perfect pitch, and the rest of the notes using a mixture of perfect pitch and relative pitch). Beyond that level of perfect pitch/absolute pitch/color hearing I have to resort to relative pitch in order to get by.
The timbre of the instrument that someone plays, and it's pitch range (or in the case of a Keyboardist the main range that they play in) drastically affects any color hearing that a person may develop, so no, absolute pitch does not cover the full sound range.
I personally do not like the term perfect pitch as, let's face it, it's definitely not perfect. There are different levels of it too, from basic color awareness to universal color hearing. It is my belief that very well developed relative pitch is probably superior, but getting to that point takes years of practice.
Answer: My personal experience with my acquisition of absolute pitch is that I indeed initially could only identify the pitch of the one single note correctly - Middle C. That was back in Grade 8. It took me years to learn/index all 12 notes in 12TET by heart with absolute pitch instead of using relative pitch to derive them from the fewer notes I could identify with absolute pitch. So yes, people can indeed have single-note absolute pitch range.
(On a related note, my ability to identify the key of a musical excerpt by ear - also a form of absolute pitch - was also similarly spotty, with me often only being able to identify certain keys for years and needing to use reference pieces of classical music back then - and this time, relative pitch to fill in the rest wasn't much use.)
Comment: Similar experience: I seem to recognize the A (the tuning-fork 440 Hz-ish one) reliably on different instruments; yet I do not have absolute pitch even within one semitone tolerance on my primary instrument. It's almost like all piano notes are sounds, except for A, which says "A" when played.
Answer: I'm pretty sure that a sinousoidal sound wave actually registers as exactly one pitch in the ear. Other periodic functions can be expressed as an infinite sum of sinousoidal functions each of which has a frequency that's a multiple of the frequnency of the periodic function plus a constant function. I heard that the range of frequencies humans can hear goes from 20 to 20,000 Hz. That's probably just approximate for most people. I'm guessing that that range is true only for the sinousoidal tone. If a 10 Hz sinousoidal sound wave is played you probably can't hear it but if 10 Hz of another tone is played, you might hear it and it might sound very wierd because if you express it as an infinite sum of sinousoidal waves, you can't hear the sinousoidal wave that's 10 Hz. I've noticed that I could not sense the relative pitch of very low notes on the piano compared to higher notes. That might be the reason. Maybe the reason is because hair cells in the ear for very low notes register a wider range of frequencies. I think the same might also be true for me about really high notes that I can't sense relative pitch of them. Also, I believe the math shows that for sound whose frequency is more than half the highest frequency sinousoidal wave that you can hear, you can't distinguish between one periodic sound wave of that frequency and another periodic sound wave of the same frequency if the latter sound wave is changed in amplitude to sound the same volume.
I think that for almost all people who have absolute pitch, of the pitches they can sense relative pitch for, if they can sense absolute pitch for one of those pitches, they will be able to figure out how to sense absolute pitch for any of those pitches. I don't know that for sure. If that's so, then maybe people didn't bother inventing a very precise definition of absolute pitch for that reason.
Answer: My daughter has perfect pitch.   She can figure out notes outside the piano range from both ends.   Some people can only hear the instrument of what they play.   Some people can hard all different sounds as notes.  The main advantage for perfect pitch is violin-like instruments and singing.   Piano teachers with perfect pitch is great;  They can hear all the wrong notes, especially the left hand.  Speedy recovery from a wrong note on piano is also the advantage from PP.
Comment: @Karlo - whilst that may be true, just about everyone with relative pitch finds detecting wrong notes immediately simple and useful. The two are not the same, and absolute (perfect) pitch will be helpful in identifying a note's name, in isolation, but relative pitch won't, however, the latter is far more useful in a musician's situation, where a single isolated note isn't often played.
Comment: Perfect pitch doesn't help identifying wrong notes, neither does it help recovering from wrongly played notes.
Comment: @Tim What do you mean? Perfect pitch can be useful to detect wrong notes immediately, where people without perfect pitch might not notice them.


Combinação de uma lista numérica com limitador (Python)

Question: Estou gerando todas as combinações possíveis dentro de uma lista, mas não encontrei nenhum que suprisse todas as minhas necessidades, sendo elas:

Resultado em formato de lista;
Listas com itens repetidos são válidas;
Listas completamente iguais não são válidas;
Deve haver um limitador de tamanho máximo para geração da lista;
O somatório dos itens da lista não pode ser maior que tamax;
O tempo de execução do código é importante;

Fiz o código abaixo, mas gostaria de saber se existe uma forma mais refinada/pythônica de escrever esse mesmo código.
OBS: Usei limitadores para diminuir o número de iterações do gerador, pois eu tinha que fazer combinações com uma lista de 30 números, e sem os limitadores o código nunca terminava de rodar.
import numpy as np
from math import floor
from itertools import product

tamax = 12 #valor máximo da soma dos itens na lista
tamin = tamax * 0.95 #valor mínimo da soma dos itens na lista
tamanhos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = lista para combinações
tamanhos.sort()
limites = [] #armazena os limites para cada número de iterações
iteracoes = [] #armazena o número máximo de iterações que os elementos da lista vão gerar se combinados. É pareado com a lista limites
check = [] #usado como checagem para adicionar itens na lista limites
tamcomb = [] #armazena todas as combinações de tamanhos
comb = () #combinação do gerador aleatório

def sumall(tupla): #retorna o somatório do itens da tupla gerada
  tam = len(tupla)
  lista1 = list(tupla[0:tam])
  return np.sum(lista1)

def cresc(tupla): #transforma a tupla em uma lista em ordem crescente
  tam = len(tupla)
  lista = list(tupla[0:tam])
  lista.sort()
  return lista

for i in tamanhos:
  iteracao = floor(((tamax-i)/min(tamanhos))+1) #retorna o número máximo de iterações que podem ocorrer nas combinações entre os itens da lista
  if iteracao not in iteracoes: #adicionar o número à lista iteracoes
    iteracoes.append(iteracao)
  for j in range(0, (max(iteracoes)+1)): #adiciona na lista limites o tamanho referente ao número de iterações calculado
    if j == iteracao:
      if iteracao not in check:
        limites.append(i)
        check.append(iteracao)
limites.sort(reverse=True)
iteracoes.sort()

print("iteracoes = ", iteracoes)
print("limites = ", limites)

for i in range(1, (max(iteracoes)+1))):
  limite = 0
  for j in iteracoes:
    if i <= j:
      if limites[iteracoes.index(j)] > limite:
        limite = limites[iteracoes.index(j)]
  tamanhos_validos = [tamanho for tamanho in tamanhos if tamanho <= limite] # gera a lista com os tamanhos que serão utilizados de acordo com o número de iterações
  gerador = product(tamanhos_validos, repeat=i) # repeat é utilizado para especificar o numero de item que as combinações irão possuir
  for comb in gerador: #gera as combinações com base no tamax e tamin
    if tamax >= sumall(comb) >= tamin:
      comb = cresc(comb)
      if comb not in tamcomb: #se a combinação ainda não existe em tambcom, é adicionada na lista
        tamcomb.append(comb)
print("combinações validas = "tamcomb)

Output:
iteracoes = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
limites = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
combinações validas = [[2, 10], [3, 9], [4, 8], [5, 7], [6, 6], [1, 1, 10], [1, 2, 9], [1, 3, 8], [1, 4, 7], [1, 5, 6], [2, 2, 8], [2, 3, 7], [2, 4, 6], [2, 5, 5], [3, 3, 6], [3, 4, 5], [4, 4, 4], [1, 1, 1, 9], [1, 1, 2, 8], [1, 1, 3, 7], [1, 1, 4, 6], [1, 1, 5, 5], [1, 2, 2, 7], [1, 2, 3, 6], [1, 2, 4, 5], [1, 3, 3, 5], [1, 3, 4, 4], [2, 2, 2, 6], [2, 2, 3, 5], [2, 2, 4, 4], [2, 3, 3, 4], [3, 3, 3, 3], [1, 1, 1, 1, 8], [1, 1, 1, 2, 7], [1, 1, 1, 3, 6], [1, 1, 1, 4, 5], [1, 1, 2, 2, 6], [1, 1, 2, 3, 5], [1, 1, 2, 4, 4], [1, 1, 3, 3, 4], [1, 2, 2, 2, 5], [1, 2, 2, 3, 4], [1, 2, 3, 3, 3], [2, 2, 2, 2, 4], [2, 2, 2, 3, 3], [1, 1, 1, 1, 1, 7], [1, 1, 1, 1, 2, 6], [1, 1, 1, 1, 3, 5], [1, 1, 1, 1, 4, 4], [1, 1, 1, 2, 2, 5], [1, 1, 1, 2, 3, 4], [1, 1, 1, 3, 3, 3], [1, 1, 2, 2, 2, 4], [1, 1, 2, 2, 3, 3], [1, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 6], [1, 1, 1, 1, 1, 2, 5], [1, 1, 1, 1, 1, 3, 4], [1, 1, 1, 1, 2, 2, 4], [1, 1, 1, 1, 2, 3, 3], [1, 1, 1, 2, 2, 2, 3], [1, 1, 2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 5], [1, 1, 1, 1, 1, 1, 2, 4], [1, 1, 1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 1, 2, 2, 3], [1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

Esse código demorou cerca de 9s para rodar no Google Colab.
Comment: Não sei se entendi exatamente todos os critérios, mas enfim, uma sugestão: https://ideone.com/0NXpxz
Comment: Agradeço a ajuda, atualizei pra tentar explicar melhor, espero ter conseguido. Já atualizei algumas parte de acordo com o que eu vi no seu código, obrigado.
Answer: Dá pra simplificar bastante esse código.
Pelo que entendi, a ideia é buscar todas as combinações, mas a ordem dos elementos parece não importar. Ou seja, se já tiver [2, 10] nos resultados, então não precisa ter [10, 2]. Portanto, uma opção melhor é trocar itertools.product por itertools.combinations_with_replacement.
Só isso já diminui significativamente a quantidade de possibilidades a serem testadas. No caso, sua lista tem 10 elementos (os números de 1 a 10), então product(lista, repeat=n) resulta em 10n elementos diferentes para serem testados. Já combinations_with_replacement(lista, n) resulta em (9 + n)! / n! / 9!. Por exemplo, para n igual a 6, product gera 1 milhão de possibilidades (inclusive as repetidas que não são necessárias, como já mencionado), enquanto combinations_with_replacement gera apenas 5005 combinações (ou seja, quase 200 vezes menos possibilidades). Para n igual a 10, a diferença é maior ainda: 10 bilhões de product versus 92378 de combinations_with_replacement (cerca de 100 mil vezes menos possibilidades).
Com isso você já ganha um bom tempo. E como os valores já estão ordenados, as combinações também estarão (primeiro ele gera de 1 a 10, depois (1, 1), (1, 2), etc, depois (2, 1), (2, 2) e assim por diante). Assim, não precisa ficar ordenando as tuplas, o que significa mais um ganho de tempo.
Enfim, ficaria assim:
from itertools import combinations_with_replacement

valores = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # valores usados nas combinações
valores.sort() # não precisaria nesse caso, pois vc já criou a lista ordenada
tamax = 12 # valor máximo da soma dos itens na lista
tamin = tamax * 0.95 # valor mínimo da soma dos itens na lista

# calcula as iteracoes
iteracoes = []
etc... (confesso que não entendi essa parte, mas usei o seu código, e a mesma lista abaixo)

results = []
for i in range(1, max(iteracoes) + 1):
    for comb in combinations_with_replacement(valores, i):
        if tamin <= sum(comb) <= tamax:
            results.append(list(comb)) # transforma a tupla em lista e adiciona nos resultados

print(results)

Repare que não precisa de uma função para calcular a soma, pois o Python já tem isso pronto: sum recebe qualquer iterável, inclusive uma tupla (não precisa transformá-la em lista, ganhando mais tempo ainda).
E nos resultados, para converter a tupla em lista, basta usar list passando a tupla direto (criar os slices, como você fez com [0:tam], além de gastar mais tempo, é desnecessário nesse caso em que você quer pegar todos os elementos - isso faria sentido se você quisesse pegar apenas um pedaço da tupla). E como agora eu não retorno mais as combinações repetidas, nem preciso verificar se já existe na lista de resultados.
Rodei no Colab e demorou cerca de 0,3 segundos.

Também fiz um teste com o módulo timeit:
def com_permutations():
    # seu código com permutations...

def com_combinations():
    # meu código usando combinations_with_replacement...

from timeit import timeit

# executa 1 vez cada teste
params = { 'number' : 1, 'globals': globals() }
# imprime os tempos em segundos
print(timeit('com_permutations()', **params))
print(timeit('com_combinations()', **params))

Os tempos podem variar de uma máquina para outra, na minha foram (em segundos):
5.775390355000127
0.13096024300102727

Como pode ver, um ganho significativo (de 5,7 para 0,13 segundos, cerca de 40 vezes mais rápido).


How To Solve WP-DBManager Permission issue?

Question: I've installed WordPress on a LEMP stack which is powered by CentOS 6.4. I installed WP-DBManager plugin today and it's showing an error which is mentioned below:
Your backup folder MIGHT be visible to the public

To correct this issue, move the .htaccess file from wp-content/plugins/wp-dbmanager to /var/www/example.com/public_html/wp-content/backup-db

But guys how can I do this as Nginx does not support .htaccess file. Please tell me what permission should I give to backup-db folder that is located in wp-content folder.
The .htaccess file in the folder contains the following code:
<Files ~ ".*\..*">
order allow,deny
deny from all
</Files>

At this time when I directly open that "backup-db" folder, ngnix shows a 403 Forbidden error. But the backups can easily be downloaded if someone has direct URL to the backup zip file located in that folder.
Please help me!
Comment: What is in this .htaccess file?
Comment: @MichaelHampton I've added the .htaccess code. Please check and let me know what to do? Thanks!
Answer: That .htaccess just denies all requests. You can easily do the same in nginx with a second location. For instance this will deny every request in that directory:
location /wp-content/backup-db {
    deny all;
}


Resolution error of specific IP addersses

Question: I have a network with the following topology:
+-----------+       +-----------+
|192.168.1.1+---+--->192.168.1.7|
+-----------+   |   +-----------+
   server       |      windows
                |
                |   +-----------+
                +--->192.168.1.3|
                    +-----------+
                      GNU/Linux

server machine is connected to the internet and acts as a DHCP server for the local network. GNU/Linux machine works fine. windows machine, however, exhibits a strange behavior - it fails to resolve specific internet IP addresses.
I can ping most of the addresses from windows machine:
C:\Users\User>tracert 18.104.22.168

Tracing route to google-public-dns-a.google.com [22.214.171.124]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  192.168.1.1
  2    <1 ms    <1 ms    <1 ms  x.x.x.x
  ....
  7     1 ms     1 ms     1 ms  google-public-dns-a.google.com [18.104.22.168]

Trace complete.

But for some addresses windows machine routs to its local network address:
C:\Users\User>tracert 188.8.131.52

Tracing route to 188.8.131.52 over a maximum of 30 hops

  1  WINDOWS.machine.example.com [192.168.1.7]  reports: Destination host unreachable.

Trace complete.

Same trace from the GNU/Linux machine looks like this:
traceroute to 188.8.131.52 (188.8.131.52), 30 hops max, 60 byte packets
 1  192.168.1.1 (192.168.1.1)  0.322 ms  0.288 ms  0.278 ms
....
14  * * *
15  184.108.40.206 (18.104.22.168)  158.510 ms  158.523 ms  158.505 ms

Windows firewall is turned off, server iptables chains are all set to ACCEPT.
What could cause this behavior?
edit 1
windows machine route tables:
IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
      0.0.0.0          0.0.0.0      192.168.1.1      192.168.1.7     10
    127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
    127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
    192.0.0.0        22.214.171.124         On-link       192.168.1.7    266
  192.168.1.7  255.255.255.255         On-link       192.168.1.7    266
  220.127.116.11  255.255.255.255         On-link       192.168.1.7    266
    184.108.40.206        240.0.0.0         On-link         127.0.0.1    306
    126.96.36.199        240.0.0.0         On-link       192.168.1.7    266
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link       192.168.1.7    266
===========================================================================

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  9    306 ::/0                     On-link
  1    306 ::1/128                  On-link
  9    306 2001::/32                On-link
  9    306 2001:0:9d38:6ab8:3c09:1c95:3f57:fef8/128
                On-link
  5    266 fe80::/64                On-link
  9    306 fe80::/64                On-link
  9    306 fe80::3c09:1c95:3f57:fef8/128
                On-link
  5    266 fe80::9ce4:a7a5:5ab:8512/128
                On-link
  1    306 ff00::/8                 On-link
  5    266 ff00::/8                 On-link
  9    306 ff00::/8                 On-link
===========================================================================

Comment: You'll have to include the routing table from the Windows machine in your question. Otherwise there is not much chance of getting an answer.
Comment: Check the network mask on the Windows host.
Comment: @kasperd added routing table
Answer: You have a bad network mask (220.127.116.11) for your local network that covers the destination address, too.
Put in the correct network mask, and it should work.
Comment: I don't know much about windows networking. Where did this rule come from? Could it be a configuration of the DHCP server?
Comment: Is the Windows host actually configured to use DHCP, or is it manually configured? Someone may have also entered a `route` command. Someone certainly put in a route to the host address `220.127.116.11` to be on-link, and that is almost certainly incorrect.
Comment: @Sergey If both machines are DHCP clients they are supposed to both be getting the mask from the DHCP server. That of course just prompts a new question. How is it possible for the two to get different masks. You can look at the routing table on the Linux machine for comparison as well as what it received through DHCP. On Linux I will usually use `ps -fC dhclient | cat` to find the name of the lease file and then `grep subnet-mask ` to see what mask it received.
Comment: @kasperd I use network manager. Route is `inet4 192.168.1.3/24`. I recall that `windows` machine was previously located somewhere else. Probably got this route there...


Is a complex symmetric matrix with positive definite real part diagonalizable?

Question: Let $M \in \mathbb{C}^{n \times n}$ be a complex-symmetric $n \times n$ matrix. That is, $M$ is equal to its own transpose (without conjugation). If the real part of $M$ is positive-definite, then is $M$ necessarily diagonalizable?
Of course, if we drop the positive-definiteness requirement, then there are examples of non-diagonalizable complex-symmetric matrices. For example,
$$\begin{bmatrix} 1 & i \\ i & -1 \end{bmatrix}$$
is one such example. However, its real part $\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}$ is clearly not positive-definite.
Comment: Adding a positive real multiple of the identity will take care of the positive definite condition, but will not affect diagonalisability. See the answer by Om(nom)${}^3$.
Answer: The answer is no. Based on your example,
$$
\pmatrix{3&i\\i&1}
$$
will not be diagonalizable, but has a positive definite real part.
Comment: Can't believe this didn't occur to me earlier, thanks!
Answer: With symmetric matrices I assume people are talking about  $P^T AP$ rather than $Q^{-1} A Q.$ It does appear that the book Horn and Johnson gives some precedence to using the word "diagonalizable" for  $Q^{-1} A Q.$ On page 215, exercise 15 is exactly the example given in the original question.
From Horn and Johnson, on symmetric complex matrices.  Corollary 4.4.4, if complex matrix $A=A^T$ there exists a unitary $U$ and a real nonnegative diagonal $\Sigma$ such that $$A = U \Sigma U^T.$$ This is called Takagi's factorization.
I also did the example from the earlier answer by the method I had described, $R^T MR,$ as
$$
\left(
\begin{array}{cc}
1 &\sqrt 3 \\
-1 & \sqrt 3
\end{array}
\right)
\left(
\begin{array}{cc}
3 & i \\
i & 1
\end{array}
\right)
\left(
\begin{array}{cc}
1 & -1 \\
\sqrt 3 & \sqrt 3
\end{array}
\right) =
\left(
\begin{array}{cc}
6 + 2i\sqrt 3 & 0 \\
0 & 6 - 2i\sqrt 3
\end{array}
\right)
$$
Comment: You're right, I should have specified that by "diagonalizable" I mean "similar to a diagonal matrix," i.e., $A = PDP^{-1}$. But this Takagi factorization seems very useful, thanks for sharing!
Comment: One reason to prefer **not** using the term "diagonalizable" for the existence of a complex invertible matrix $P$ such that $P^TAP$ is diagonal, is that thus defined is would be _equivalent_ to "symmetric" (in other words the condition is always satisfied in the case you suggest). One can even restrict the diagonal matrix to have diagonal entries $1$ or $0$ only. This is a consequence of the classification of symmetric _blilinear_ forms over$~\Bbb C$.
Answer: Write this as $M = A + iB,$ where both $A,B$ are real and $A$ is positive definite. It follows that $A$ is invertible. From Horn and Johnson, Theorem 4.5.15, page 228 in the first edition, define $C = A^{-1} B.$ If there is a real invertible matrix $R$ with $R^{-1}CR$ diagonal, there is then a nonsingular real matrix $S$ with $SAS^T$ and $SBS^T$ diagonal. It follows that $SMS^T$ is diagonal complex.
Not sure what happens when $A^{-1}B$ has nontrivial Jordan form.
Comment: Not sure whether this is a yes or no answer.
Comment: @MarcvanLeeuwen people do not typically specify whether they want some $P^{-1}AP$ or some $Q^T AQ$ to be diagonal. When $A$ is real symmetric, the second one is the reasonable choice. More in a few minutes, tea ready.


Sample size choice with binary outcome

Question: Our civic association is planning to implement a survey asking our neighborhood one true false question. I would like to make sure that we obtain an adequate sample size.
Let's assume N = 2500 people, and we want to be 90% confident of our results with margin of error no more than 5%.
We would like to know the minimum sample size. Is there a simple formula to apply? If so can you please share it?
If so, is there an easy way to stratify the sample by some categorical variable such as race. For this example let's assume 25% of the neighborhood is part of a minority group. What is the minimum number of minority households that must be included?
Answer: Including a finite correction factor, the margin of error $m$ for binary data is given by $$m = z_{\alpha/2} \sqrt{{p(1-p)} \over {n}} \sqrt{{{N-n} \over {N-1}}},$$ where $N$ is the population size, $n$ is the sample size, $p$ is the success probability (say, the chance of a voter giving a true answer), and $z_{\alpha/2}$ is the appropriate quantile from the standard normal distribution for the desired confidence.
Solving for $n$ we find $$n ={ {z^2_{\alpha/2} \ p (1-p)N} \over {z^2_{\alpha/2} \ p(1-p)+(N-1)m^2} } $$ Now $p$ is unknown, but the worst case is $p={{1} \over {2}},$ so using that we have  $$n ={ {z^2_{\alpha/2} \ N} \over {z^2_{\alpha/2} \ +4(N-1)m^2} } $$
Using your numbers ($z_{\alpha/2}=1.6449$), I get a sample size of $n=244.2,$ so use $n=245.$
Ignoring the finite correction factor would have led to a sample size of $n=272.$
For your second question, I'm not sure what you are asking. The minimum number of minority households to sample may be more of a political issue than statistical.
Comment: With the minority question, Soakley may be alluding to that different groups may have different survey response rates? Eg. if old people oppose some measure (eg. school funding) and respond to surveys at higher rates than young people, you may underestimate support for school funding in the population by looking at survey responses. Anyway, you can get into extremely tricky issues if various covariates (eg. age) are linked with both public opinion and survey response rates.
Comment: To get the desired accuracy on both strata will require much more sampling. With 1875 nonminority households you will need 237 data points, and with the 625 minority households you will need to sample 190. If you have reason to believe the true success probability is much different than 0.5, then you can improve on these using the first formula for $n$ in the answer.
Comment: I am not getting the same result: (1.6449*2500)/(1.6449+4*2499*0.05^2) =154.3933. Clearly I am missing something. Can you see what I did wrong?
Comment: Make sure you square the $z$ factor.

Sample size choice with binary outcome


Echo reduction - large room

Question: I was asked to propose a solution to reduce echos in a large event hall measuring 70 feet long by 60 feet wide with ceiling height 14 feet( I have never done anything of this sort before). The room will be used for seminars & presentations for 100-200 people seated or standing.
The flooring is made of vitrified tiles/ceramic tiles and the 4 walls are made of some kind of highly reflective paint. The ceiling is PoP with  12 feet long concealed ducts for AC .The echo is uncontrollable.
They are running on a very tight budget, so covering the entire floor with carpeting seems very expensive, so is acoustic panels.The ceiling is also off limits due to AC vents & lighting.
For a start i am proposing that tall indoor potted plants be placed in all the 4 corners. Then cover the first 1/3rd of the walls(toward the front ,near the stage area) from top to bottom  with thick velvet curtains, and see if the echo reduces. If it doesn't do much, then repeat towards the back 1/3rd.
Is there any other approach to handle this?
Also I have a choice of proposing either 15-20 in ceiling speakers(bose or QSC) covering the entire area for speech,light music &video / OR 4 point speakers(like bose S1 pro in a single loop) in the 4 corners mounted on 6-8 feet high poles. Which of the 2 solutions will be better for echo reduction? Ill be using a 3-4 wireless MIC setup without any DSP for feedback cancellation. Will it be an issue? or do i have to compulsorily use a DSP?
Comment: I second Laurence's answer. If you are stuck with this start with the curtains in the back, not the front. The back is where the real echoes come from. The front is where early reflections come from which can be annoying but don't seem to be the primary concern in this case.
Comment: This seems like a very constrained situation.  Are you approaching it as a musician or speaker, or as an audio engineer or structural acoustics engineer?  My first suggestion would be to cover the walls in some type of soft carpet like wall covering, someone mentioned curtains.  If the room is full the people will cover the floor so that's not as big a problem.  Is there fixed seating, desks or tables, or would the room be set up different for each event?  That will drive solutions as they can be different for each situation.
Comment: Also ceiling speakers will be better than regular mains for controlling the sound field, but I'm not sure how you would buy, install, and maintain them on a tight budget. If you can afford feedback cancellation, then you should get it. Basically, the budget will control the quality of the system. If you spend less, you're going to get less. If you hire pros and buy quality equipment and have it professionally installed, you'll get a much better system and much better sound. There are no shortcuts and no secret cheap ways to DIY this.
Comment: Maybe you could record the sound of the room as is, and analyze that to check whether there's reverb or echo, and what the problematic frequencies are. This may tell you whether to treat the floor-ceiling or side-side or front-back walls, and whether it needs absorption and/or dispersion.
Comment: @YourUncleBob - you're going to have to do a lot of separate recordings with mics in different locations to ascertain that.
Answer: I don't think the potted plants will make much difference.  The curtains might, but material thick enough to make any difference won't be cheap.
Personally, unless I was an experienced acoustical engineer I'd run a mile from this one.  You're in danger of not only failing to improve the sound but even making it worse.  You might soak up a lot of the high frequencies leaving nasty lf reflections.
The classic approach to amplification in impossibly reverberant spaces is to use lots of small speakers. It can work in a traditional church where there are lots of pillars to put speakers ON.  Not so much use in an open space.
The modern approach might be a line array system.  Sound can be focussed at the audience, not wasted towards the ceiling.   Again, not cheap.
I repeat, unless you're an expert, steer clear of this one!
Comment: Sensible move. Could be chasing rainbows. Would cost way more than budget. +1. Searching for an 'anti-echo chamber'. I've believed for a long time now that there must be a way of producing a 'wall' of anti sound (Such as could be used in open plan offices (what a joke)) and one of those pointed in the right direction/s would do the trick.
Comment: The future might be in 'silent' systems.  Half the audience probably carry personal Bluetooth headphones or earpods already.  We already have standardisation on the 'hearing aid loop'.  This just needs to be extended.
Comment: Yup. +1 My first thought before I even got as far as your answer was "Get a pro." This sounds too big & too much guesswork for a DIY project. It could end up costing several thousand for absolutely no discernible improvement whatsoever. Or you might fix it with a sloped rear stud wall for a couple of hundred… you'll never know without a pro.
Answer: To do this correctly you'll need to do acoustic analysis of the room including reverberation times of the offending frequencies. When you have that information you can design and construct bass traps and diffusers to address the problems discovered in your analysis. It is possible to do this kind of thing if you are given a reasonable budget and are willing to study and learn, but often just coming at the problem with nothing more than your imagination will prove to be a waste of time and money. I'm not trying to discourage you if it's something you want to learn about. There are methods that work quite well, but there are no real easy answers and you will need to know what you're doing. Best of luck.
Answer: Perhaps you could use a combination of diffusers in addition to the sound sound absorbing stuff.  I don't know much about these (I just read enough acoustics to set up a small dance band) as they were only developed during the 1970s.

Echo reduction - large room


Least wasteful use of stamps to achieve a given postage

Question:
You have sheets of $42$-cent stamps and
  $29$-cent stamps, but you need at least
  $\$3.20$ to mail a package.  What is the
  least amount you can make with the $42$-
  and $29$-cent stamps that is sufficient
  to mail the package?

A contest problem such as this is probably most easily solved by tabulating the possible combinations, using $0$ through ceiling(total/greater value) of the greater-value stamp and computing the necessary number of the smaller stamp and the total postage involved.  The particular example above would be solved with a $9$-row table, showing the minimum to be $\$3.23$, made with seven $42$-cent stamps and one $29$-cent stamp.
Is there a better algorithm for solving this kind of problem?  What if you have more than two values of stamps?
Answer: With two stamps, you can do it in linear pseudo-linear time - O(totalCost/costOfLargerStamp) - by simply enumerating every possibility (there is only one possible count of the smaller stamp for each count of the larger stamp).
In general, however, solving this is equivalent to solving a general integer linear programming problem written in standard form, which is NP-complete.
Comment: Please note that the consequences of being NP-complete are [different](http://math.stackexchange.com/questions/742/least-wasteful-use-of-stamps-to-achieve-a-given-postage/755#755) than what many people may understand them to be
Answer: Let t be your target and a and b < a be the values of the stamps you have. Let n = ⌈t/a⌉ be the maximum number of a stamps it makes sense to use.
For each number i from n to 0, consider the cost of the solution with:

i stamps of value a and
j = ⌈(t - i*a) / b⌉ stamps of value b

The cost of each solution would obviously be i*a + j*b.
Your solution is the pair (i, ⌈(t - i*a) / b⌉ ) that minimizes said cost. (Note there's only one unknown in that pair, i.)
An additional optimization would be to stop immediately as soon as a division without rest is performed, either when determining n or j. A division without rest means that we have found a solution that perfectly pays the due amount and cannot thus be improved on. (There may be others like it, but none that is actually better, so there's no need to keep searching).
Comment: __Preemptive "optimization" notice:__ `j*b = ⌈(t - i*a) / b⌉ * b ≠ (t - i*a)`; that's only true in the division without rest scenario.
Answer: It is important to understand that NP-completeness is defined in terms of input size, not in terms of either cost to be paid, C, or the number of types of stamps, S, when we are dealing with integers rather than real numbers.
This algorithm can actually be solved in time CS. We take the first stamp value an mark all multiple of it as obtainable (up to the least number greater than the cost). Then, for each subsequent stamp value, we mark as obtainable all numbers that can be obtained by adding a multiple of its value with an obtainable number (up to the least number greater than the cost). We can keep track of the lowest cost postage amount that we have found so far.
Answer: A similar problem is known in mathematics.  It is called the "Postage-Stamp" problem, and usually asks which postal values can be realized and which cannot.  Dynamic programming is a common but not polynomial-time solution for this.  A polynomial time solution using continued fractions in the case of two stamp denominations exists, and more complex algorithms exist for three or more stamp denominations.  Look up "Frobenius Number" for more technical information.
For the given problem, I would roughly estimate the Frobenius number, and based on the estimate make an easy guess as to a near-solution and then use a dynamic programming/tabular solution, depending on the amount of time I had to solve the problem.
Answer: This is a simple variation of the Knapsack problem. Which is a NP-Complete problem.
Let n to be the target value, it can be solve using knapsack's dynamic programming solutions.
If you have a finite amount of stamps, then you can add them all up, subtract the target value. Run 0-1 knapsack on the stamps with the resulting number. The stamps outside the knapsack is the solution.
If you have a infinite amount of stamps. You can either make them finite: $\lceil \frac{n}{t_i}\rceil$ stamps for stamps with value $t_i$ and run the above process, or you can compute the result by running knapsacks O(log n) times similar to a binary search.
It's no better than a naive backtracking solution when n is large. I assume you are not going to pay $100 for stamps. ;)


How do you build a query to get a series of nodes and their field values filtered by field values?

Question: Hopefully someone with Drupal 7 experience can point me in the right direction.
I'm creating a custom module to query some nodes and group and sort them by their field values.
I tried to use Views but it seems that it's not possible to get the results in the format I need so I've decide to query the database directly and build my own output.
What's the easiest way to query nodes in Drupal 7 as I notice there is a table for every field now which would seem to make any query that I have to write extremely complex?
Are there any methods to query node data and filter/group the results or can it only be done using raw SQL.
If the latter can you show me an example query that includes Drupal 7 Field values?
Answer: I second Jeremy's suggestion of trying harder with views. However, if you absolutely must write your query directly in code, you'll want to use EntityFieldQuery.
For example, to get a count of all nodes with a text field value of 'foo':
// Get field information
$field = field_info_field('field_name');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'NODE TYPE')
  ->fieldCondition($field, 'value', 'foo')
  ->count();

$count = $query->execute();

If you don't want a count, but results instead, you would leave off the count part, and fetch results:
foreach ($query->execute() as $entity_type => $entities) {
  foreach ($entities as $entity_id => $entity) {
  ...
  }
}

The Commerce Guys also have a good blog post detailing a simple use case.
Comment: Great answer, I didn't know about EntityFieldQuery. Thanks.
Comment: Excellent answer, that will save my a lot of headaches!
Answer:
I tried to use Views but it seems that
  it's not possible to get the results
  in the format I need so I've decide to
  query the database directly and build
  my own output.

My first suggestion would be to try harder with views.

What's the easiest way to query nodes
  in Drupal 7 as I notice there is a
  table for every field now which would
  seem to make any query that I have to
  write extremely complex?

Yes it would be, which is why I made the first suggestion.
One tip could be to use a view to do the query but to produce your own output by invoking the view programatically.
A second tip would be to use the query which is generated by views as a starting point.
Fields in drupal 7 are defined via the field api. So you would need to look into that to find out how the fields are stored and help you to define your query. It can be done but it is not straightforward.
Comment: I'm having crazy problems with Views and the Date field in Drupal 7. I think the Date module is broken when using Views 3 and Postgres and views errors with SQL error messages. Also I'm trying to do complex grouping of data and I know Views can only do simple grouping. I don't believe Views is the beginning and the end to all things Drupal. I would love to use Views for this but I'm sure it won't do what I'm trying to do and I'm quite experienced with Views. The question was more for pointers on how to do things like views without using Views module.


UPDATE leftjoin SET +/- problem

Question: I want numbers to be added and subtracted according to one number entered in the table.
Here is my code:
  $uratio =  "

    UPDATE teams
 LEFT JOIN games g1 ON (teams.ID = g1.op1ID)

SET ratio = ratio
    + IF(g1.op1gamescore = 1 , g1.op1score, g1.op1score)
 , ratio = ratio
     - IF(g1.op1gamescore = 0, g1.op1score, g1.op1score)

  WHERE g1.ID = '$_POST[id]'    ;

     ";
      mysql_query($uratio) or die (mysql_error());

     $uratiob =  "

    UPDATE teams
    LEFT JOIN games g2 ON (teams.ID = g2.op2ID)
   SET ratio = ratio
    + IF(g2.op2gamescore = 1, g2.op2score, g2.op2score)
             , ratio = ratio
    - IF(g2.op2gamescore = 0, g2.op2score, g2.op2score)
   WHERE g2.ID = '$_POST[id]'    ;

    ";
      mysql_query($uratiob) or die (mysql_error());

When op2gamescore = 1 it puts op1 with (negative sign) and op2 with (negative sign) op2 is fine but op1 not.
When op1gamescore = 1 it does the same.
It does correct math when op1 or op2 = 0 . But not when it equlas 1.
It does the correct math but op1 always ends with negative sign, why is that? Its like if it executes  - IF  and not + IF... ANY IDEAS?
Comment: You don't understand how IF works. It has 3 parameters, first is the condition, second is the value to return if the condition is true, third is the value to return if the condition is false. You return the same value whether the condition is true or false, so you're essentially just adding the score and subtracting it regardless of the conditions.
Answer: query 1:
UPDATE
  teams
LEFT JOIN
  games
ON
  teams.ID = games.op1ID
SET
  ratio = ratio + IF(games.op1gamescore = 1, games.op1score, -1 * games.op1score)

query 2:
UPDATE
  teams
LEFT JOIN
  games
ON
  teams.ID = games.op2ID
SET
  ratio = ratio + IF(games.op2gamescore = 1, games.op2score, -1 * games.op2score)

Comment: thnks! I stayed with the same code but used the (-1 *) to change the false condition
Comment: OK, but there's no need to set ratio twice in each query. Think it over some.

UPDATE leftjoin SET +/- problem


Sum of series $\sum \limits_{k=1}^{\infty}\frac{\sin^3 3^k}{3^k}$

Question: Calculate the following sum: $$\sum \limits_{k=1}^{\infty}\dfrac{\sin^3 3^k}{3^k}$$
Unfortunately I have no idea how to handle with this problem.
Could anyone show it solution?
Comment: You probably have a reason to hope this can be done in closed form (perhaps it was a contest problem, for example). Otherise, I would never think it could be done.  What, may I ask, is your reason for optimism?
Comment: I am not sure is it a contest problem or not, but i found in one of the papers of problem-solving seminars of my university.
Comment: @FelixMarin I believe I've warned you not to run amok introducing personal stylistic quirks to other people's posts. [`\frac` is the proper way to write fractions, not `\over`.](http://tex.stackexchange.com/q/73822) Question marks are not to be preceded with a space in English, and it's downright ridiculous to add a period afterwards.
Comment: @RFZ: You didn't sign the right answer (until now) ?
Comment: @Khosrotash, You want likes? :) Oh man this sounds awful :)
Answer: Using
$$\sin(3a)=3\sin a-4\sin^3a \to \color{red}{\sin^3(a)=\frac14\Big(3\sin a-\sin(3a)\Big)} $$
so
\begin{eqnarray}
\sum_{k=1}^{\infty}\frac{\sin^3(3^k)}{3^k}
&=&
\frac14\sum_{k=1}^{\infty}\frac{3\sin(3^k)-\sin(3.3^k)}{3^k}\\
&=&
\frac14\sum_{k=1}^{\infty}\frac{\sin(3^k)}{3^{k-1}}-\frac{\sin(3^{k+1})}{3^{k}}\\
&=&
\frac14\sum_{k=1}^{\infty}f(k)-f(k+1)\\
&=&\frac14\Big(\frac{\sin3}{3^{1-1}}-\lim_{n \to \infty}\frac{\sin(3^{n+1})}{3^n}\Big)\\
&=&\frac{\sin(3)}{4}
\end{eqnarray}
Comment: Pov: You unlocked god level. (+1)
Comment: @LaxmiNarayanBhandari: thank you a ton.
Comment: I wonder why your answer didn't get accepted. It is literally the best way to do it.
Answer: An overkill. Let $\mathfrak{M}\left(*,s\right)
 $ the Mellin transform. Using the identity $$\mathfrak{M}\left(\underset{k\geq1}{\sum}\lambda_{k}g\left(\mu_{k}x\right),\, s\right)=\underset{k\geq1}{\sum}\frac{\lambda_{k}}{\mu_{k}^{s}}\mathfrak{M}\left(g\left(x\right),s\right)
 $$ we have $$\mathfrak{M}\left(\underset{k\geq1}{\sum}\frac{\sin^{3}\left(3^{k}x\right)}{3^{k}},\, s\right)=\underset{k\geq1}{\sum}\left(\frac{1}{3^{s+1}}\right)^{k}\mathfrak{M}\left(\sin^{3}\left(x\right),s\right)
 $$ and since $$\mathfrak{M}\left(\sin^{3}\left(x\right),s\right)=\frac{\Gamma\left(s\right)\sin\left(\frac{\pi}{2}s\right)}{4}\left(3-\frac{1}{3^{s}}\right)
 $$ we have for $\textrm{Re}\left(s\right)>-1
 $ $$\mathfrak{M}\left(\underset{k\geq1}{\sum}\frac{\sin^{3}\left(3^{k}x\right)}{3^{k}},\, s\right)=\frac{\Gamma\left(s\right)\sin\left(\frac{\pi}{2}s\right)}{4}\left(3-\frac{1}{3^{s}}\right)\frac{1}{3^{s+1}-1}=\frac{\Gamma\left(s\right)\sin\left(\frac{\pi}{2}s\right)3^{-s}}{4}
 $$ and so inverting we get $$\underset{k\geq1}{\sum}\frac{\sin^{3}\left(3^{k}x\right)}{3^{k}}=\frac{1}{2\pi i}\int_{1/2-i\infty}^{1/2+i\infty}\frac{\Gamma\left(s\right)\sin\left(\frac{\pi}{2}s\right)3^{-s}}{4}x^{-s}ds
 $$ now taking $x=1$ and shifting the complex line to the left we have, from the residue theorem, that we have to evaluate the residues of $$\textrm{Res}_{s=-2n-1} \frac{\Gamma\left(s\right)\sin\left(\frac{\pi}{2}s\right)3^{-s}}{4}=\frac{\left(-1\right)^{k}}{4\left(2k+1\right)!3^{-2n-1}}
 $$ hence $$\sum_{k\geq1}\frac{\sin^{3}\left(3^{k}\right)}{3^{k}}=\frac{1}{4}\sum_{k\geq 0}\frac{\left(-1\right)^{k}}{\left(2k+1\right)!}3^{2k+1}=\color{red}{\frac{\sin\left(3\right)}{4}}.$$
Comment: badass $ (+1) $
Answer: We can use the following identity (leaving for you to prove)
$$
\sin^3 (3^x) = \frac {1}{4} ( 3 \sin(3^x) - \sin (3^{x+1}) )
$$
That is,
$$
\frac {\sin^3( 3) }{3} =  \frac {1}{4} ( \sin (3) - \frac {1}{3} \sin (3^2) )
$$
$$
\frac {\sin^3( 3^2) }{3^2} =  \frac {1}{4} (\frac {1}{3} \sin (3^2) - \frac {1}{3^2} \sin (3^3) )
$$
$$
\frac {\sin^3( 3^3) }{3^3} =  \frac {1}{4} (\frac {1}{3^3} \sin (3^3) - \frac {1}{3^4} \sin (3^4) )
$$
As you can clearly see, all the middle terms cancel out in the sum and we are only left with the first term. So the sum is $$\frac {\sin (3)} {4} $$.
Comment: +1 Pretty fine. The obvious way.


Como posso gerir bilbiotecas JavaScript no meu projecto PHP?

Question: Tenho um projecto em PHP e uso o composer para gerir bibliotecas como por exemplo o PHPMailer para envio de e-mails.
Para poder utilizar as bibliotecas instaladas basta-me incluir o autoload do composer:
require ('vendor/autoload.php');

Recentemente também precisei de usar outras bibliotecas, mas são bibliotecas JavaScript, e fiz o mesmo procedimento acima descrito. O «problema» é que tenho de fazer a inclusão dos ficheiros JS:


Updating Inventory

Question: I am working on a spreadsheet that tracks inventory.  Basically each week the user goes in, sets his inventory to be used that week, compares it to the current stock and tells him when to order more.
The issue I am having is once the inventory for the week has been chosen how can I get it to update the stock permanently when he exits the spreadsheet?
Specifically then user picks the client name from a drop down menu, that in turn uses a VLOOKUP to show the items the customer needs.  From there it COUNTIFs what is needed by all customers and posts it next to the # of each item on hand(refrenced from the "stock" sheet)...I am hunky dory to this step.  I can't seem to make the leap to having the amount in stock update upon completion so that when the next user opens the file (multiple copies cannot be opened at once, already set that up) the sotck is current.
Make sense?
Answer: Your probably going to need to use VBA.
Cant really give you any examples because I cant see the layout of your workbook and it would depend on how you want to update the list.
You could update the stock count, fairly simple to do but not very safe unless you trust all the users to get it right every time.
If you wanted a little more safety, you could have a sort of "transaction" sheet which stores the change to the stock count for each job entered. Allowing you to fix or remove any erroneous entries. This wouldn't update the main stock list so you would want to periodically merge your transaction sheet.
Update
I've had a quick go at making something using VBA. Again, since I don't know how your book is laid out etc I've just played about. It might be helpful, might not.
Example Workbook
The workbook has 3 sheets: Stock, Adjustment, Log.
Stock
A list of products, the quantity on hand and a re-order threshold
Adjustment
Used to 'adjust' the stock... user enters a product name and the requirement.
The worksheet shows the SOH, the adjusted SOH and advises weather a product needs to be reorderd. (depends on the adjusted SOH and threshold set on the stock sheet)
If the adjustment sheet is populated, when a user saves the workbook they are asked to either update the list (which clears the adjustment sheet), not to update the list (saves the adjustment list for later use without updating stock) or to cancel.
If the adjustments are saved, the information for each adjustment is copied to the log sheet along with a timestamp to allow you to track the changes. If an non-stocked (or mistyped) product is found, it is skipped and the user is told at the end.
Answer: OK for a VBA free (sort of) solution you could use a macro. You have in 1 column the current stock, next to it it you have the amount to be deducted from it before exiting the workbook. You will need to add another column that is the amount after deduction. I'm guessing you would know how to set that up if you are using VLOOKUP.
Next step is to record the macro. I'm not sure which version of Excel you are using, but for Excel 2003 you would go to Tools -> Macro -> Record new macro. This will lead to the macro dialog box, chose a name e.g. Update. It would probably be best to  chose a shortcut key e.g. u. click OK to start recording the macro.
Highlight the column with the amount after deduction and use edit -> copy. Highlight the column with the current stock and use edit->paste special and chose values and click ok. Finally click on the stop button on the macro recorder.
If you make a mistake, simply click on stop, and go to Tools -> Macro -> Macros select the macro you have recorded and click delete and then yes. Then start again.
In order to run the macro the user would have to either goto Tools -> Macro -> Macros and click run or press Ctrl + shortcut key e.g. Ctrl+u.
A word of warning, macros are not normally undoable so if the user makes a mistake e.g. running it twice they should exit without saving and start again.

Updating Inventory


ZFS failing on stage during demo. Is this normal behavior?

Question: I'm thinking of migrating my server park to ZFS(not really), but this live demo makes me suspicious.
My question is:

Is what we see here normal behavior for ZFS?

http://www.youtube.com/watch?v=CN6iDzesEs0&feature=player_embedded#t=4m40s
Any way, this is a Kodak moment. The speaker seems not to expect what he see during the first 2 seconds. Hilarious!
Comment: There is a reason why the advise is "Never do live demo's" :-)
Answer: ZFS had it's fair share of issues, but it gets very much attention at Sun. I wouldn't be surprised if the problems at hand are already solved. And drive failure like shown in that case is something every RAID-Controller/Filesystem loathes. I've seen more than one RAID-Controller causing the OS to panic/hang due to drive electronics talking dirty to it (and that was without sledgehammers ;) ).
On the other side I don't think that the question is if "ZFS is any good" but "When will it take over the storage sector".
All the positive things about ZFS (VERY easy block device management, lean provisioning of filesystems, variable block sizes, non-dependency on battery backed write caches for safe operation, snapshots "for free", etc.) are going to be noticed and requested by the customers.
And this is probably why every storage vendor that is not NetApp is slowly becoming nervous these days (they're stuck with their archaic storage designs since a very long time) and Oracle sponsors btrfs development on Linux (though this has become some sort of a moot point since they've vowed to acquire Sun...).
Answer: Yeh, I noticed that too.
I suspect that it is down to the disks being USB attached and the USB controllers not being smart enough to report that the disk has failed. As soon as the usb cable is disconnected the disk subsystem springs back into life.


Enviar confirmação de mensagem recebida UDP

Question: Boa tarde, tenho o código para UDPListen, que faz com que o PC1 envie uma mensagem até ao PC3 através de um interlocutor(PC2) , contudo, depois da mensagem chegar ao PC3, este tem de enviar ao PC1 a confirmar que recebeu a mensagem, contudo não estou a perceber como fazer essa parte. Aqui está o código do UDPListen
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
/*
 Aguarda por datagramas UDP no porto especificado
 Digitar <Ctl><c> para abandonar
 */
#define exit_on_error(s,m) if (s < 0) { perror(m); exit(1); }
#define MAX_BUFFER 512

int main(int argc, char* argv[]){
 int sockfd, size_addr;
 struct sockaddr_in remote_addr;
 struct sockaddr_in local_addr;
 char ip_s[INET_ADDRSTRLEN]; //IP em dotted decimal notation
 int bytes,r,v=1;
 char buf[MAX_BUFFER];

 //verifica argumentos
 if (argc != 2) {
  printf("USAGE: %s <porto>\n",argv[0]);
  exit(1);}

  for(i=0; i < strlen(agrv[1]); i++) //IP argv[1]
  {
   if(!isdigit(argv[1][i])) //IP argv[1]
   {
       printf("<porto> -> Apenas numeros inteiros!\n\n\n");
       exit(1);
   }
  }
  //cria socket UDP
 sockfd = socket(AF_INET,SOCK_DGRAM,0);
 exit_on_error(sockfd,"Error:socket()");
 //permite broadcast
 r=setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &v, sizeof(v));
 exit_on_error(r,"Error:setsockopt()");

 //regista (associa) socket localmente (IP+porto)
 //necessarias permissões de root
 bzero((char *)&local_addr, sizeof(local_addr));//Coloca a zero toda a estrutura
 local_addr.sin_family = AF_INET;
 local_addr.sin_addr.s_addr = htonl(INADDR_ANY); //IP Local
 local_addr.sin_port = htons(atoi(argv[1])); //Porto
 r=bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr));
 exit_on_error(r,"Error:bind()");

 //limpa var remote_addr
 bzero((char *)&remote_addr, sizeof(remote_addr));

 // aguarda por datagrama UDP
 while (1){
  printf("Aguarda UDP no porto %d\n",atoi(argv[1]));
  size_addr=sizeof(remote_addr);
  bytes = recvfrom(sockfd, buf, MAX_BUFFER-1, 0, (struct sockaddr *)&remote_addr, &size_addr);
  // escreve origem e dados recebidos
  inet_ntop(AF_INET,&(remote_addr.sin_addr),ip_s, sizeof ip_s);
  printf("Recebido de: %s\n",ip_s);
  printf("Porto: %d\n",ntohs(remote_addr.sin_port));
  printf("Bytes lidos: %d\n", bytes);
  buf[bytes]=0; //Null terminated string
  printf("Dados: %s\n", buf);
 }
 //fecha socket
 close(sockfd);
}

Código do PC2, UDPgw:
#include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <string.h>
 #define exit_on_error(s,m) if (s < 0) { perror(m); exit(1); }
 #define MAX_BUFFER 512

 int main(int argc, char* argv[])
 {
    int sock, length, fromlen, r, send_sock, sendlen, V = 1, n; //int n declarado
    struct sockaddr_in SERVER_ADDR;
    struct sockaddr_in FROM_ADDR;
    struct sockaddr_in SENDTO_ADDR;
    //struct sockaddr_in LOCALMENTE_addr;
    char buf[MAX_BUFFER];

    //verifica argumentos
    if (argc != 4)
    {
        printf("USAGE: %s <port_2> <ip_broadcast> <port_3/4>\n",argv[0]);
        exit(1);
    }
    //cria socket UDP
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0) printf("SOCKET");
    length = sizeof(SERVER_ADDR);
    bzero(&SERVER_ADDR, length);
    SERVER_ADDR.sin_family = AF_INET;
    SERVER_ADDR.sin_addr.s_addr = INADDR_ANY;
    SERVER_ADDR.sin_port = htons(atoi(argv[1]));

    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &V, sizeof(V));
    sendlen = sizeof(SENDTO_ADDR);
    bzero(&SENDTO_ADDR, sendlen);
    SENDTO_ADDR.sin_family = AF_INET;
    SENDTO_ADDR.sin_addr.s_addr = inet_addr(argv[2]);
    SENDTO_ADDR.sin_port = htons(atoi(argv[3]));

    if(bind(sock, (struct sockaddr *)&SERVER_ADDR,length) < 0) printf("BIND:  ");

    fromlen = sizeof(struct sockaddr_in);

    while(1)
    {
            printf("Wait for the next message...!\n");
            bzero(&buf, MAX_BUFFER);
            n = recvfrom(sock,buf,MAX_BUFFER,0,(struct sockaddr *) &FROM_ADDR, &fromlen);

         if (n < 0) printf("RECVFROM\n");
             printf("Mensagem recebida: [%s], bytes recebidos: [%d]\n",buf,n);

         n = sendto (sock, buf,MAX_BUFFER,0,(struct sockaddr *) &SENDTO_ADDR, sendlen);
             if (n < 0) printf("SENDTO\n");
    }
 }

Alguém me pode ajudar?
Answer: No seu sistema distribuído tanto o nó PC1 como os nós PC2 e PC3 devem ser capazes de enviar e receber pacotes UDP.
Por enquanto, o único nó que é capaz tanto de receber como receber um pacote UDP é o nó PC2, que, creio eu, está rodando o programa UDPbw.
Nesse caso, a solução pra mim é simples: faça uma adaptação do programa que está sendo executado em PC2 para que possa funcionar em PC1 e PC3.
Essa tarefa seria mais fácil de o programa estivesse organizado em funções. O ideal é que não coloque todo o programa na função main. Deve-se modularizar o programa utilizando funções. Criando uma função enviarPacote() e uma função receberPacote(), por exemplo.
Como o programa que roda em PC2 já tem a função de receber e enviar pacotes, basta apenas alterar a ordem e os parâmetros de envio e recebimento adaptando seu funcionamento para os demais nós.
Comment: A minha dúvida é mesmo como fazer o código para ele enviar a confirmação de que recebeu a mensagem. Irei colocar o código do PC2, UDPgw
Comment: É só você alterar a penúltima linha, onde tem n = sendto... para enviar o pacote de volta à origem. Altera o endereço destino.
Comment: Alterar para isto?
n= sendto (sock, buf,MAX_BUFFER,0,(struct sockaddr *) &FROM_ADDR, &fromlen);
Comment: Sim, exatamente.
Answer: Esse código não está muito bem feito.
Apenas o PC2 está a enviar/receber pacotes.
Pelo que percebi a mensagem tem de ser enviada por Unicast e não Broadcast.
Tenho um código semelhante (não é totalmente o que você precisa). Fiz na faculdade enquanto tinha uma cadeira de Redes. Se pretender, envie-me mensagem que eu irei facultar-lhe o código e explicar o que ele faz e o que você deve alterar para ficar o que você pretende.
Fiz UDP com broadcast, mas facilmente dá para alterar para Unicast
Comment: Ficarei à espera de contacto caso ainda pretenda o código
Comment: Muito obrigado.


Finding set of limit points as $ x \rightarrow 0 $

Question: If the function $ f $ is defined as
$$
f(x)
=
\begin{cases}
|x|^{\phi - 1} \sin(1/x), & x \neq 0 \\
0, & x = 0
\end{cases}
$$
where $ \phi > 0 $, how does one find the set of limit points of $ f(x) $ as $ x \rightarrow 0 $, for each $ \phi > 0 $?
Answer: HINT
We need to consider the following cases

$\phi>1$

$$0\le||x|^{\phi - 1} \sin(1/x)|\le |x|^{\phi - 1}\to 0$$

$\phi=1$

$$|x|^{\phi - 1} \sin(1/x)=\sin(1/x)$$

$0<\phi<1$

$$|x|^{\phi - 1} \sin(1/x)=\frac{\sin(1/x)}{|x|^{1-\phi}}$$
Comment: Yes the limit exists only for the first case, for the second we have limsup=$1$ and liminf=$-1$ and for the third limsup=$\infty$ and liminf=$-\infty$
Comment: Just to confirm... in the first case, the only limit point is 0. In the second and third case, there's no limit points?
Answer: So, $\lim_{x \to 0+} x^{\phi - 1}\sin(\frac{1}{x}) = \lim_{x \to 0+} x^{\phi-2} x\sin(\frac{1}{x})$. As $x\sin(\frac{1}{x}) \to 1$ as $x \to 0$ that part has no importance, limit exists where limit $x^{\phi - 2}$ exists and has same value as that limit, and the latter limit is zero when $\phi > 2$, 1 when $\phi = 2$ and doesn't exist when $\phi < 2$


How to delete old Jenkins builds on repository branches

Question: I have used the Blue Ocean plugin to create a Jenkins job that automatically uses the Jenkinsfile (declarative pipeline) to build and report the status back to GitHub. That all works fine.
The issue I have is that I cannot get old builds deleted. The job shows as a repository and I have configured it to keep a maximum of 5 builds. But I noticed that the branches indexed, including the master branch, also have their own configuration. I tried setting up the old builds deletion but there's no save button! I thought this was because the configuration propagates from the repository to the branches, but it has no effect. How can I get this to work?
Answer: Certain job properties are adjusted using directives in Jenkinsfiles and not the configuration in the web UI.  In your Jenkinsfile:
properties([
  // only keep 25 builds to prevent disk usage from growing out of control
  buildDiscarder(
    logRotator(
      artifactDaysToKeepStr: '',
      artifactNumToKeepStr: '',
      daysToKeepStr: '',
      numToKeepStr: '25',
    ),
  ),
])

You may of course adjust the various parameters to suit your needs.
Comment: Now it makes sense that the GUI view is read-only for branches, I see it reflects the properties set in their respective Jenkinsfiles. This is probably an effect of the [multi-branch plugin](https://jenkins.io/doc/pipeline/steps/workflow-multibranch/#-properties-%20set%20job%20properties). I placed the properties snippet above the pipeline directive on the declarative pipeline.
Answer: Unsure which Jenkins version brought the update, but the syntax has changed. Modifying jayhendren's example:
options {
  // only keep 25 builds to prevent disk usage from growing out of control
  buildDiscarder(
    logRotator(
      artifactDaysToKeepStr: '',
      artifactNumToKeepStr: '',
      daysToKeepStr: '',
      numToKeepStr: '25',
    ),
  ),
}

Comment: It appears that both [syntaxes](https://jenkins.io/doc/book/pipeline/syntax/#compare) can be used: jayhendren's as a scripted pipeline and @Bryan's as a declarative one ([How do I set discard old builds for a Multi Branch Pipeline Job? – CloudBees Support](https://support.cloudbees.com/hc/en-us/articles/115000237071-How-do-I-set-discard-old-builds-for-a-Multi-Branch-Pipeline-Job))


Redirecionar url post HTTP para HTTPS no nginx

Question: Tenho uma aplicação que recebo POSTS de retorno do sistema de pagamentos, mas atualmente forçamos o uso do SSL para nosso site, fiz o redirecionamento HTTP para HTTPS, porém recebo erro 404 quando o sistema do POSTBACK envia o POST para a URL http://...., quando meu servidor tenta redirecionar para HTTPS( Ou não tenta ) aparece o erro 404.
Arquivo NGNIX:
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/magicaonline.com.br/before/*;

server {
    listen 80;
    listen [::]:80;
    return 307 https://magicaonline.com.br/$1;
}

server {
    listen 443 http2;
    listen [::]:443 http2;
    server_name .magicaonline.com.br;
    root /home/forge/magicaonline.com.br/public;

    if ($host = 'www.magicaonline.com.br') {
        rewrite ^/(.*)$ https://magicaonline.com.br/$1 permanent;
    }

    #if ($scheme = http) {
    #    return 302 https://$server_name$request_uri;
    #}

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/magicaonline.com.br/132754/server.crt;
    ssl_certificate_key /etc/nginx/ssl/magicaonline.com.br/132754/server.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'xxxxx';
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/magicaonline.com.br/server/*;

    location /lp/ {
        try_files $uri $uri/ @wordpress;
    }

    location @wordpress {
        rewrite /lp/ /lp/index.php;
    }

    location ^/lp/index.php(/.*)?$ {
        fastcgi_split_path_info ^(/lp/index.php)(/.*)$;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO $fastcgi_path_info;
        include fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/magicaonline.com.br-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/magicaonline.com.br/after/*;

Há possibilidades de fazer isso acontecer ?
Preciso dessa solução por que o sistema de pagamentos não aceita modificar a URL do POSTBACK.
Answer: O 302 transforma seu POST num GET, o próprio browser executa esse comportamento.
Seguindo a recomendação do Joao, que está correta, temos um case simples:
http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format compression '$remote_addr - $remote_user [$time_local] '
                           '"$request" - "$request_body" - $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    server {
        listen       8181;
        server_name  localhost;

        access_log /my_path/log/nginx.log;

        location / {
            proxy_pass_header on;
            proxy_pass http://localhost:8080/receive;
        }
    }

    include servers/*;
}

Aqui temos um servidor ouvindo a porta 8181, com escrita de log ativada. Ao realizar um post simples usando curl nessa rota:
curl -X POST -H 'Content-Type: application/json' -d '{"product": "New product", "id": "1"}' http://localhost:81

A requisição será redirecionada para a porta 8080, mantendo os headers. Para testar podemos criar um servidor nodejs ouvindo essa porta:
var express = require('express')
var fs = require('fs')
var url = require('url')
var app = express()

app.post('/receive', function(request, respond) {
    var body = ''

    filePath = __dirname + '/post.txt'
    request.on('data', function(data) {
        body += data
    })

    request.on('end', function (){
        body = body + '\n'
        fs.appendFile(filePath, body, function() {
            respond.end()
        })
    })
})

app.listen(8080)

Para executar o servidor node é só usar os comandos:
npm init
npm install --save express
node index.js

Esse servidor recebe o redirecionamento do nginx e escreve o post num arquivo chamado post.txt.
Ao realizar todo o processo teremos como entrada nesse arquivo:
{"product": "New product", "id": "1"}

Answer: Na verdade, segundo a spec do HTTP, o user-agent 302 não deve redirecionar a request inteira. Acredito que o que aconteça é que a sua request, quando chega o 302, se torna um GET, e isso causa o seu 404 (já que provavelmente o server só está esperando um POST).
Acho que o ideal seria você utilizar uma função de reverse-proxy do Nginx chamad a Proxy Pass.
Atualizar o seu redirecionamento para:
if ($scheme = http) {
  proxy_pass_header on;
  proxy_pass https://$server_name$request_uri;
}

pode resolver seu problema. A primeira linha ativa o envio dos headers, que vão ser necessários pro seu POSTback e vem desabilitados por padrão, e a segunda define a url pro proxy.
Comment: João, primeiramente obrigado pela atenção.
Comment: Infelizmente não conseguir fazer funcionar, pode me dar um exemplo dentro dentro do arquivo que está acima ?