Feedback suppression pedal?

Question: Is there an effect pedal (preferably nano) that its purpose is to locate, capture, and eliminate feedback for acoustic instruments for live-stage performance?
I've been using the Fishman Aura Spectrum DI, that had an anti-feedback system that automatically locates and squelches the troublesome frequencies, but it was stolen from me, and besides it's too bulky. I'm looking for a smaller pedal.
Comment: Jimi would be very sad to lose all feedback :-)
Answer: There is no 'pedal' you speak of. I beleive this is because the solution you are looking for is a digital one. Feedback is a physical phenomenon caused by your pickups literally hearing the speaker and then the speaker amplifying itself repeatedly. The 'fix' is to lower the gain stage (volume), or put more damping between the pickups and the speaker. Most onstage artists do this by facing toward the cab for more feedback and away for less. Your body is a good damping tool.
There are digital feedback eliminators out there like the Behringer Shark. These detect a spiking feedback loops and specifically bring down only that frequency, but they won't come in pedal format simply because they have to work continuously to actually tell if they are hearing feedback or say a whistling instrument.
Comment: FWIW active analog circuits can be designed to do frequency/gain tracking so it doesn't absolutely have to be digital.  Digital is "easier" .  But see the famous (??)  Burwen adaptive box for hiss removal.   https://patents.google.com/patent/US3678416A/en    and  some of the commercial products   https://thea.com/Vintage-Pro-Audio-Equipment-Dynamic-Noise-Filter/
Comment: Why would "digital" and "pedal" be a contradiction? There are lots of digital pedals, and many of them are continuously on but merely use the pedal to switch between different modes.
Comment: Behringer Shark is good but it's too bulky and is rather accustomed for studio, not for live performance, which is what I'm looking for. Thanks for your nice answer anyway.
Answer: The problem isn't with the gain of the instruments as such; it's the gain of the instruments, plus the gain of the PA, plus the EQ of the PA versus the room that you're playing in, adding in the position of the instrument and artist.
The solution, then, is not simple, and it isn't an instrument pedal. You need a decent sound engineer :p
Failing that, there are Feedback Suppressors (usually rackmounted) that can listen for feedback and notch out that frequency using a built-in parametric graphic equalizer. These work OK for voice and some guitar work, but their failing is that they sometimes incorrectly hear a long keyboard note (or sustained singing note). When this happens, they think the system is going into feedback, and they notch out that note. It can ruin a song...
The other (best) solution is to ring out the room your playing in. Once you've done it a few times, it becomes a quick process before sound check. But you do need some equipment to do it. Basically, you attempt to identify the frequencies in the room that will cause issues, and you notch them out on EQ.
Comment: I've updated my question.
Answer: You might like the LR Baggs Session DI pedal. It has a notch filter that is pretty easy to use. You set up on stage, let the guitar start feeding back, and then sweep the knob until the feedback stops.
Comment: It can only suppress a single freq, doesn't it?
Comment: Yes, it just reduces the gain for a single narrow frequency band. It works great for me.
Comment: What if you have several troublesome tones?
Comment: For an acoustic, the biggest problems I typically have is some low to mid-low frequency causing the whole guitar to resonate and feedback. So it's not like the "microphonic" feedback you might get with a distorted electric guitar. This just notches out the offending frequency and you are good. You could pair it with a multi band EQ pedal if you want to cut other frequencies.
Comment: It always depends on the pickup. Every pickup has its own troublesome frequencie**s**.
Answer: TC Electronic BodyRez Acoustic pickup enhancer might do it for you

Feedback suppression pedal?


Complex power series exponential

Question: How do we evaluate $\sum _{n=0}$ $\frac{8^n}{(3n)!} $?
We know that $e^z$= $\sum _{n=0}$ $\frac{z^n}{(n)!} $
So can we say that $\sum _{n=0}$ $\frac{8^n}{(3n)!} $ = $\frac{e^8}{3}$ ? Obviously the denominator is wrong. (How?)
Where do we put the $3$ then?
Also, $\sum _{n=0}$ $\frac{27^n}{(3n+1)!} $ $=?$ $\frac{e^{27}}{3n+1}$
Comment: A [related](http://math.stackexchange.com/questions/610526) question.
Answer: You can evaluate this using a differential equation, but it's not very elegant. Define
$$f(x)=\sum_{n=0}^\infty\frac{x^{3n}}{(3n)!}$$
and observe that this satisfies
$$f''+f'+f=e^x,\\
f(0)=1,\quad f'(0)=0$$ Assuming you know how to solve a second-order linear differential equation, I'll spare you the details in showing that the general solution to $f''+f'+f=e^x$ is
$$f(x)=\frac13e^x+e^{-x/2}(A\cos\tfrac{\sqrt3}2x+B\sin\tfrac{\sqrt3}2x)$$
You can use the initial data to show $A=\frac23$ and $B=0$. Hence
$$\sum_{n=0}^\infty\frac{8^n}{(3n)!}=f(2)=\frac13e^2+\frac2{3e}\cos\sqrt3$$
Comment: Alternatively, by differentiating the equation and equating them to $e^x$, you get $f''+f'+f=f'''+f''+f'\implies f^{(3)}=f$, which may be easier to solve if homogeneous equations can be solved
Answer: Let's solve the more general case of $\sum\limits_{n=0}^\infty\frac{z^{an+b}}{(an+b)!}, b<a$. Through repeated differentiation, it can be seen that it satisfies the differential equation $$y=y^{(a)}, y^{(b)}(0)=1, y^{(k)}(0)=0, k<a, k\neq b$$
If we try the first sum of yours ($a=3,b=0$), we have
$$y=y^{(3)},y(0)=1, y'(0)=0, y''(0)=0$$
which implies that
$$\sum_{n=0}^\infty\frac{x^{3n}}{(3n)!}=\frac13\,{{\rm e}^{x}}+\frac23\,{{\rm e}^{-\frac12\,x}}\cos \left( \frac12\,\sqrt {3}x
 \right)
$$
Plugging in $x=2$ gets us
$$\sum_{n=0}^\infty\frac{2^{3n}}{(3n)!}=\sum_{n=0}^\infty\frac{8^{n}}{(3n)!}=\frac13e^2+\frac2{3e}\cos(\sqrt3)$$
As for your second question we can solve the differential equation for $a=3,b=1$ to get (it turns out to be the second derivative of the first function)
$$\sum_{n=0}^\infty\frac{x^{3n+1}}{(3n+1)!}=\frac13\,{{\rm e}^{x}}-\frac13\,{{\rm e}^{-\frac12\,x}}\cos \left( \frac12\,\sqrt {3}x
 \right)+\frac1{\sqrt3}\,{{\rm e}^{-\frac12\,x}}\sin \left( \frac12\,\sqrt {3}x
 \right)$$
Plugging in $x=3$ and dividing by 3 we get
$$\frac13\sum_{n=0}^\infty\frac{3^{3n+1}}{(3n+1)!}=\sum_{n=0}^\infty\frac{27^{n}}{(3n+1)!}=\frac19\,{{\rm e}^{3}}-\frac19\,{{\rm e}^{-\frac32}}\cos \left( \frac32\,\sqrt {3}
 \right)+\frac1{3\sqrt3}\,{{\rm e}^{-\frac32}}\sin \left( \frac32\,\sqrt {3}
 \right)$$

Complex power series exponential


Doubt (or more likely, my misunderstanding) in wikipedia's Pigeonhole principle proof of Dirichlet's approximation theorem

Question: https://en.wikipedia.org/wiki/Dirichlet%27s_approximation_theorem
I will call the following the Lemma of Dirichlet's Approximation theorem:

For a given irrational α, the inequality
$ 0<\left|\alpha -{\frac {p}{q}}\right|<{\frac {1}{q^{2}}}$ is
satisfied by infinitely many integers $p$ and $q$.

If I were to summarise wikipedia's proof of this Lemma, it would be this:
Let $\ \alpha\ $ be an irrational number and let $\ n\ $ be an integer. Then there exists $\ p\in\mathbb{Z},\ q \in \{ 1,\ldots, n\}\ $ such that $\ \left\lvert \alpha - \frac{p}{q} \right\rvert < \frac{1}{q^2}.\ $ Here, by $\ q\ $ I mean, $\ q:= j-i.$
But as far as I can see, this doesn't prove the Lemma, because for each $\ n,\ q\ $ could be any number between $\ 0\ $ and $\ n\ $, so $\ q\ $ doesn't necessarily tend to infinity as $n$ tends to infinity.
What is wrong with my understanding of the proof?
Edit: When wikipedia says, "Dividing both sides by $j-i$ will result in:
$\left|\alpha -{\frac {m_{j}-m_{i}}{j-i}}\right|<{\frac {1}{(j-i)n}}\leq {\frac {1}{\left(j-i\right)^{2}}}$"
Is it saying that this bit proves the Lemma? Or is the proof in wikipedia just proving the original theorem only?
Answer: You're right that this step needs explanation. In fact, the version you quoted isn't quite strong enough to prove "infinitely many", as you've noticed. We need to go back to the slightly stronger version:
Let $\alpha$ be irrational and let $n$ be a positive integer. Then there exists integers $p$ and $q\in\{1,\dots,n\}$ such that $\bigl| \alpha-\frac pq \bigr| < \frac1{qn}$.
Note that any such $\frac pq$ automatically satisfies $\bigl| \alpha-\frac pq \bigr| < \frac1{qn} \le \frac1{q^2}$. However, this stronger form shows that we don't just get the same $\frac pq$ over and over: for any fixed $\frac pq$, the quantity $\bigl| \alpha-\frac pq \bigr|$ is positive (this is where we use the fact that $\alpha$ is irrational!), and so it exceeds $\frac1{qn}$ when $n$ is sufficiently large. Thus we must get a new fraction $\frac{p_2}{q_2}$, which can only survive for so long, and so on and so on.


Incorporating features that are always 0 given the value of another feature into a decision tree?

Question: If I'm building a decision tree model, what is the best way to incorporate features that are always 0 given the value of another feature?
For example, imagine I'm predicting whether or not someone has high blood pressure, and two of the many features I have are gender and whether or not the person has uterine cancer.  Clearly if gender is male, then uterine cancer has to be 0 because men cannot get uterine cancer.  I'm fairly positive this can be done with interaction terms, but decision trees cannot utilize them.
Answer: Technically speaking, your Gender and Cancer factors are neither crossed nor nested. If they were nested, then you could just specify the interaction term, but I am not sure whether it will work correctly in this case.
Therefore, I think the best way to avoid confusion is to introduce a new factor Gender_Cancer with 3 levels: "M_No", "F_Yes", "F_No". Then in order to test the effect of gender, you specify the contrast as "M_No vs F_No". To test the effect of Cancer, the contrast is: "F_Yes vs F_No".
Comment: (+1) This is a good answer because it takes advantage of an intrinsic ability of decision trees to study interactions. Besides, it's one less feature to try splits, so might speed up calculations a bit. Also, it's useful because splits on sex variables might not be near the root node.
Answer: Decision trees (e.g. CART) should not be affected.
In the male branch of the tree, the cancer variable would be always 0. Therefore, it has 0 statistical power. And the tree will not learn any splits based on the cancer variable.
Comment: No splits in the male branch, or no splits in both the male and the female branch?
Comment: Hey @BrandonSherman, just the male branch. The cancer variable has predictive power in the female branch, so there will be a split on the cancer variable if your max depth allows it.
Comment: Ah okay.  So it does the split automatically, so there's no need to manually create an interaction.


Is the definition of Hazard Ratio strict?

Question: Is it always (even if only by convention) hazard rate in intervention group divided by hazard rate in control group?
Comment: What, in your opinion, is a lax definition of the hazard rate, and what is a strict definition? What you are writing doesn't seem at all like _any_ definition of hazard rate that I have ever seen.
Comment: Apologies, error in question corrected. Wikipedia states "In survival analysis, the hazard ratio (HR) is the ratio of the hazard rates corresponding to the conditions described by two levels of an explanatory variable."
Answer: Hazard ratios apply to many more situations than control/intervention groups. If you have a continuous predictor like age or blood pressure, the hazard ratio in a Cox regression would be the change in hazard per unit change in age or pressure. If you have a categorical predictor (say, multiple subtypes of a disease as in breast cancer, or gender) then you arbitrarily choose one category as a reference against which to compare the others.
In the control/intervention context it's certainly usual to choose the control as the reference group. I am, however, aware of no law requiring that. In some contexts you might choose to switch reference groups or the direction of a continuous variable (e.g., hazard per year decrease rather than per year increase in age). For example, when you examine a plot of the relative entries of predictors as the penalty changes in a LASSO model it's most convenient (at least for me) for the predictors to have either all HR >1 or all <1, obtained with appropriate choices of reference levels or directions, so that all the curves start by pointing all up or all down when they leave the horizontal axis.
If you are reading, pay careful attention to the authors' choice of reference level. If you are writing, choose reference levels that make it easiest to explain to your audience.
Comment: That's what I mean. Especially when a treatment can result both in improving or degrading conditions for patients, then the HR can be > 1 even if the conventional treatment is the reference.


Is the inverse of $(x+y, zw+z+w, y^2)\subset Q[x,y,z,w]$ under inclusion $g: Z[x,y,z,w]\to Q[x,y,zw]$ in $Z[x,y,z,w]$ still be $(x+y, zw+z+w, y^2)$?

Question: In general, suppose
$g: Z[x,y,z,w] \to Q[x,y,z,w]$
is the canonical inclusion, and $I=(f_1,...,f_n)\subset Q[x,y,z,w]$ be an ideal such that for each $f_i$, its coefficients are 1, and for each two generators $f_i, f_j$, their terms are different with each other.
My questions is whether the inverse image of $I$ under the inclusion $g$, for which is the ideal of $Z[x,y,z,w]$, i.e. $Z[x,y,z,w]\cap I$, still has the form $I=(f_1,...,f_n)$?
If the coefficients are not 1 and two polynomials have common terms, there has counterexample, for example
$I=(x-y, x+y)\subset Q[x,y,z,w]$, it is clear that $x\in I$, however, $x$ is not in$Z[x,y,z,w]\cap I=(x-y, x+y)\subset Z[x,y,z,w]$.
Especially I am interested in the following two ideals:
$I_1:=(x+y,zw+z+w,y^2)$
$I_2:=(x+y+z+w+xy+xz+xw+yz+yw+zw, xyz+xyw+yzw+xzw+xyzw)$
I want to ask if the inverse image of these two ideals in $Z[x,y,z,w]$ still keep the form?
Comment: It seems like you answer the question from the first paragraph in the second paragraph - you know that the answer is no.  Therefore, it may be better to clarify your question (and start with the question of interest).
Comment: If I'm understanding this correctly, a generalized version of this question is "Let $\phi:R_1\rightarrow R_2$ be a map of commutative rings with identity, and let $\phi':R_1[x_1,\dots,x_n]\rightarrow R_2[x_1,\dots,x_n]$ be the corresponding map.  Let $I=(f_1,\dots,f_m)$ be an ideal in $R_1[x_1,\dots,x_n]$.  Under what conditions does $\phi'^{-1}(\phi'(f_1),\dots,\phi'(f_k))=(f_1,\dots,f_k)$?"
Comment: Hi, thanks for you comment. For your first comment, in my first paragraph, I add some conditions, I require all of the coefficients should be $1$, but in my second paragraph, $x-y$ has $-1$ as coefficient; Moreover, my second assumption is that the terms should be different with each other, but the polynomials $f_1=x+y$, $f_2=x-y$ has the common term $x$ and $y$ .
Comment: For you second comment, yes this is a more general version, but I am not sure there are answers for this version. So in my question, I restrict $R_1=Z$ and $R_2=Q$ and $\phi$ be an embedding.
Answer: Let $I=(f_1,\dots,f_n)$ be an ideal of $\mathbb{Z}[x_1,\dots,x_n]$ and $J$ the corresponding ideal in $\mathbb{Q}[x_1,\dots,x_n]$.  In other words, $J=I\otimes_{\mathbb{Z}}\mathbb{Q}$.
Let $G$ be a (strong and reduced) Groebner basis for $I$.  Note that $G$ is a Groebner basis for $J$ as well: Let $g\in J$, then $g=\sum h_i f_i$ where $h_i\in\mathbb{Q}[x_1,\dots,x_n]$.  For a large enough $N\in\mathbb{Z}$, $Ng = \sum (Nh_i)f_i$ is in $I$ since $Nh_i\in \mathbb{Z}[x_1,\dots,x_n]$.  Thus, the leading monomials of both $I$ and $J$ are the same.
If any $f\in G$ has nontrivial content (that is, the $\gcd$ of the leading coefficients), then $J\cap\mathbb{Z}[x_1,\dots,x_n]\not=I$, by dividing through by the content.  On the other hand, if all the leading coefficients of elements of $G$ are $1$'s, then $J\cap\mathbb{Z}[x_1,\dots,x_n]=I$.  In particular, the division algorithm will never produce a fractional coefficient and the algorithm will be identical in both $I$ and $J$.
In your examples, graded-reverse-lex Groebner bases (as computed by Macaulay2) have Groebner bases with every leading coefficient $1$, so the intersection is an equality.
Note: In the case where the Groebner basis elements have leading coefficient not equal to $1$, but are content free, the situation is more complicated: $(2x+y)$ has the desired property, but $(2x+y,3y+2z)$ does not have the desired property.  There are content-free Groebner bases for both ideals, but the leading coefficients are not $1$ in this case.
Comment: Thanks for your answer. I want to ask whether your answer use the the condition: every term should be different? Because if there has common term, for example, considering the ideal $I=(x+y,x+z,y+z)$, in $Q[x,y,z]$, $x\in I$, but $x$ is not in the inverse image.
Comment: And by the way, is there still has a definition of Groebner bases over $Z[x_1,x_2,...x_n]$?
Comment: The Groebner basis for the $I$ you mention has $2z$ in it, so the distinctness of terms is captured by these conditions (in this case).
Comment: Strong Groebner bases are for polynomial rings over Euclidean domains.  See this open access [paper](https://projecteuclid.org/journals/illinois-journal-of-mathematics/volume-56/issue-1/Effective-computation-of-strong-Gr%C3%B6bner-bases-over-Euclidean-domains/10.1215/ijm/1380287466.full) for references.
Comment: Thanks for your reply. So in this question, we first need to use the Macaulay 2 to compute the Groebner base of of ideal in $Z[x,y,z,w]$, if the coefficients are all $1$, then we can say the inverse image keeps the form right? In Macaulay 2, we use the following function: g=gb I,  gens g. Is my understand correct?
Comment: Any order should work in Macaulay2.  You don't need all the coefficients to be $1$, just the leading coefficient.
Comment: For Macaulay2 code, you can be a bit fancy, the following code computes and prints out the leading terms of the Groebner basis.  "ZZ[x,y,z,w];I=ideal(x+y,x+z,y+z); netList first entries leadTerm gens gb I"
Comment: What do you mean "any order"? Is the total order we give for the polynomial ring? By the way, the second ideal I interested, which I denote it $I_2$, is also keep the form? Because I use the Macaulay 2 to compute the Groebner base, and the coefficient has 2
Comment: Any monomial order should give you information, I'm not sure if one will work better than another.  As for $I_2$, I get that the leading terms (using grevlex) are $x^2y^2z$, $xw$, and $y^2zw$, all of which have coefficient $1$.
Comment: Thank you, it seems like a magic! I also have an extra question, can we use the Macaualy 2 to tell an ideal $I$ in $Z[x,y,z,w]$ is prime or integral closed? I only know we can do it over $Q$ or $F_p$.
Comment: I'd suggest contacting the [Macaulay2 google group](https://groups.google.com/g/macaulay2) for additional questions.  There are many people (including myself) there who can help with specific Macaulay2 questions.


How to monitor SQL Server backups with Nagios?

Question: How can I set up Nagios to monitor the health of SQL Server (SQL Agent) backups?
Answer: Check out nagios exchange.
The plug-in check_mssql_health will probably do what you want.  i.e. database-backup-age
Otherwise it's up to you to write your own probe, which shouldn't be too hard.


Rollback em tabela específica Laravel 4

Question: Estou manipulando um banco MySQL com Laravel 4. Quero saber se existe alguma forma de fazer um rollback em apenas uma das tabelas do banco. Por exemplo, a minha migration incluiu as tabelas x, y e z. Quero fazer um rollback apenas na tabela y. É possível?
Comment: Olá @Amanda Lima, sua pergunta não seria sobre truncate? porque a resposta para essa pergunta foi sobre truncate. Se for o caso gostaria de editar sua pergunta. Quando você executa um Rollback ele desfaz apenas a ação executada no momenta, já o truncate limpa a tabela inteira.
Comment: Realmente @MiguelBatista. Não sei se ela está se referindo ao método `down`, presente nas classes de migração do `Laravel`.  Mas, se for para analisar pela resposta data, acho que não tem nada a ver com rollback. Mas lembrando, se estiver falando do método `down` do migrations, então tá certo.
Answer: Sim é possível:
Para deletar os dados da tabela:
DB::table('tabela_y')->delete();

Truncating em uma tabela:
DB::table('tabela_y')->truncate();

Link da documentação.
Comment: Bem você pode tentar dar um `php artisan tinker` e colocar o comando que postei. Acho que não tem um comando direto para isso.
Comment: Obrigada, não tinha pensado dessa forma! Tem alguma maneira de fazer isso pelo artisan?
Comment: Mais uma vez obrigada!
Comment: "Deletar a tabela" ou "Deletar os dados da tabela"?
Comment: Deletar os dados da tabela, corrigi a resposta.

Rollback em tabela específica Laravel 4


Visual Studio 2005, posso substituir?

Question: Tenho uma maquina na empresa que tem uma versão do Visual Studio 2005, para um tipo de sistema web.
A máquina precisou passar por uma formatação e na rede não a uma cópia VS2005.
Posso substituir o Visual Studio 2005 por alguma versão, talvez o Visual Studio Community?
Minha preocupação geral é com relação a algum tipo de incompatibilidade
Answer: As versões do Visual Studio 2002, 2003, 2005 e 2008 geram projetos independentes, ou seja quando você abre na versão mais avançada ele converte para a nova versão. A partir da versão 2010, os projetos são compátiveis, você pode abrir no 2012 e depois abrir no 2010 e assim por diante.
Quanto ao framework .Net ele vai manter a compatibilidade com o projeto, porém alguns componentes terão que ser atualizados como o ReportServer e CrystalReports, e outros se você estiver usando.
Sim, você pode substituir, terá que fazer pequenas adaptações, mas nada muito trabalhoso.
Recomendo fazer uma cópia antes caso precise ou deseje voltar.
Comment: Obrigado, vou analisar para tomar esse rumo.
Answer: Existe alguma incompatibilidade, mas é pequena, certamente terá que fazer algumas adaptações, tem até conversor nele para os arquivos de projeto que mudaram (acho que roda automático).
Agora, muita coisa não é bem incompatibilidade, é jeito diferente de fazer. Como está acostumado com uma coisa, a mudança pode assustar, pode parecer que tem problemas e na verdade é só falta de conhecimento. Você terá que decidir se começa usar versões mais recentes do compilador e .Net, o que aconselho fortemente, ou se vai configurar tudo para trabalhar com versões antigas.
Algumas coisas que ossa ter feito no projeto pode ser mais incompatível que outras, mas duvido que encontre grandes problemas, é raro alguém fazer algo muito diferente. Claro que pode ser seu caso.
Extensões do VS podem não ser compatíveis, pode ter que pegar uma versão mais nova ou não existir uma versão nova compatível.
Eu poderia lhe dizer que ficar no 2005 é mais seguro, mas na prática é o posto, ficar com um software tão antigo e até onde sei não mais suportado é que não é seguro. Vá para o 2015 já e pague o preço de ter que adaptar. Se tivesse feito as atualizações ao longo do tempo seria menos traumático. Mas não espere nada trágico. Você deve ser um desenvolvedor, então deve achar soluções. Se tiver dificuldades específicas poste aqui.
Não é algo que é só instalar e vai funcionar, mas é perfeitamente factível. Na pior das hipóteses se não der certo mesmo você poderia tentar voltar para o VS 2005, o que não aconselho de forma alguma.
Comment: Obrigado pela resposta. A questão de não atualizar com o tempo, não foi viável, por que eu ingressei em uma empresa a pouco tempo, e isso já tem anos, queria migrar para versão mais recente justamente por isso.
Comment: @Marzine dê uma olhada no [tour] e entenda a melhor forma de dizer obrigado. Você pode aceitar uma só resposta em pergunta que fez. Marque quando achar que deve a que mais lhe ajudou. Você pode votar em tudo no site que achar útil, não só aqui.

Visual Studio 2005, posso substituir?


Is $f$ differentiable at $(0, 0)$?

Question: I asked a question earlier relating to the equation:
Let $f : \mathbb{R^2} \rightarrow \mathbb{R}$ be given by
$$f(x, y) =
\cases{
    \frac{xy}{x+y}& if $x+y\neq0$  \\
    0 & if $x+y=0$}$$
I have another question relating to this equation which goes as follows:
Is $f$ differentiable at $(0, 0)$?
Im really not sure how to find if its differentiable or not so any help will be appreciated
Answer: The partial derivatives of $f$ at $(0,0)$ exist. They are equal to
$$ \partial f/\partial x(0,0) = 0, \ \ \ \partial f/ \partial y (0,0) = 0,$$
Therefore, if $f$ is to be differentiable at $(0,0)$, the derivative cannot be anything other than the linear transformation $ \mathbb R^2 \to \mathbb R$ represented by the matrix $[0 \ 0 ]$.
Let's test to see if the linear transformation $[0 \ 0]$ really is a derivative for $f$ at $(0,0)$. If $[0 \ 0]$ is the derivative, then, for any $\epsilon > 0$, there would need to exist a $\delta > 0$ such that
$$ \sqrt{h_1^2 + h_2^2} < \delta \implies \left|f(h_1, h_2) - f(0,0) - \left[0 \ 0\right] \left[ \begin{array}{c} h_1 \\ h_2\end{array}\right] \right| < \epsilon \sqrt{h_1^2 + h_2^2}$$
i.e. for any $\epsilon > 0$, there would need to exist a $\delta > 0$ such that
$$ h < \delta \implies \begin{cases}\left| h \frac{\cos \theta \sin \theta}{\cos \theta + \sin \theta} \right| < \epsilon h & {\rm  \ if \ } \theta \neq \frac {3\pi} 4,  \frac {7\pi}4 \\ 0 < \epsilon h & {\rm  \ if \ } \theta = \frac {3\pi} 4,  \frac {7\pi}4 \end{cases}$$
Here I introduced polar coordinates for $(h_1, h_2)$:
$$ h_1 = h \cos \theta, \ \ \ h_2 = h \sin \theta.$$
The problem is that, as $\theta$ approaches $ \frac {3\pi }4$ or $\frac {7\pi}4$, the expression $(\cos \theta \sin \theta)/(\cos \theta + \sin \theta)$ tends towards plus or minus infinity. (You can see this best if you draw a graph.) So for a given $ \epsilon$, the inequality
$$ \left| \frac{\cos \theta \sin \theta}{\cos \theta + \sin\theta} \right| < \epsilon$$
cannot be satisfied for all $\theta \in [0, 2\pi) \backslash \{ \frac {3\pi} 4,  \frac{7\pi }4 \}$.
Therefore, there exists no $\delta > 0$ such that
$$ h < \delta \implies \left| h \frac{\cos \theta \sin \theta}{\cos \theta + \sin \theta} \right| < \epsilon h {\rm \ \ \ for \ all \ \  } \theta \in [0, 2\pi) \backslash \{ \tfrac {3\pi} 4,  \tfrac{7\pi } 4 \}.$$
The conclusion is that $f$ is not differentiable at $(0,0)$.

Alternative argument: If $f$ is differentiable at $(0,0)$, then its directional derivative at $(0,0)$ in the direction of the vector $(\lambda_1, \lambda_2)$ must be
$$ df/dt = \lambda_1 \partial f/\partial x + \lambda_2 \partial f/\partial y .$$
This is zero, since both partial derivatives vanish.
Now let's compute the directional derivative explicitly. Consider a straight path parametrised by $(x,y) = (\lambda_1 t , \lambda_2 t)$. Then
$$ f(t) = t \frac{\lambda_1 \lambda_2}{\lambda_1 + \lambda_2}$$
along this path (assuming that $\lambda_1 \neq \lambda_2$), so
$$ df/dt = \frac{\lambda_1 \lambda_2}{\lambda_1 + \lambda_2},$$
which in general is NOT zero. This shows that $f$ is not differentiable at $(0,0)$.

Is $f$ differentiable at $(0, 0)$?


Por que o hibernate está deletando antes do saveOrUpdate()?

Question: Eu tenho a uma relação m:n entre Coluna e Elemento. A entidade dona da relação é Coluna. porém quando eu estou salvando um mapa de Colunas,  acontece o seguinte cenário:
1) Na primeira iteração, o Hibernate:
1.1) salva o primeiro elemento Coluna
1.2) insere os dois elementos na tabela coluna_elemento
segue console:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into coluna (COLUNA_ALIAS_OPERACAO, COLUNA_CLAUSULA, COLUNA_DATA_DOIS, COLUNA_DATA_UM, COLUNA_EXIBE_FILTRO, COLUNA_EXIBE_NO_RELATORIO, COLUNA_EXIBE_TOTALIZADOR, COLUNA_INDEX, COLUNA_LABEL, COLUNA_NOME, COLUNA_OPERACAO, COLUNA_OPERACAO_REFERNCIANDO_ALIAS, RELATORIO_ID, COLUNA_TEMPO_DOIS, COLUNA_TEMPO_UM, COLUNA_TIPO_CLAUSULA_TEXTO, COLUNA_TIPO_EXIBICAO, COLUNA_TIPO_FILTRO, COLUNA_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into coluna_elemento (COLUNA_ID, ELEMENTO_DOMINIO_ID) values (?, ?)
Hibernate: insert into coluna_elemento (COLUNA_ID, ELEMENTO_DOMINIO_ID) values (?, ?)

Neste momento a tabela coluna_elemento do meu banco está assim:
coluna_id | elemento_id
    988        860
    988        861

Até aqui está tudo ocorrendo conforme o esperado.
2) Na segunda iteração, o Hibernate:
2.1) salva o segundo elemento coluna
2.2) deleta da tabela coluna_elemento o elemento salvo anteriormente
2.3)insere os dois elementos na tabela coluna_elemento
Como mostra a saída do console a seguir:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into coluna (COLUNA_ALIAS_OPERACAO, COLUNA_CLAUSULA, COLUNA_DATA_DOIS, COLUNA_DATA_UM, COLUNA_EXIBE_FILTRO, COLUNA_EXIBE_NO_RELATORIO, COLUNA_EXIBE_TOTALIZADOR, COLUNA_INDEX, COLUNA_LABEL, COLUNA_NOME, COLUNA_OPERACAO, COLUNA_OPERACAO_REFERNCIANDO_ALIAS, RELATORIO_ID, COLUNA_TEMPO_DOIS, COLUNA_TEMPO_UM, COLUNA_TIPO_CLAUSULA_TEXTO, COLUNA_TIPO_EXIBICAO, COLUNA_TIPO_FILTRO, COLUNA_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: delete from coluna_elemento where COLUNA_ID=?
Hibernate: insert into coluna_elemento (COLUNA_ID, ELEMENTO_DOMINIO_ID) values (?, ?)
Hibernate: insert into coluna_elemento (COLUNA_ID, ELEMENTO_DOMINIO_ID) values (?, ?)

E então, a tabela coluna_elemento no banco está assim:
coluna_id  |  elemento_id
   989           860
   989           861

Quando o que eu esperava era o seguinte:
coluna_id | elemento_id
  988          860
  988          861
  989          860
  989          861

O que estou fazendo de errado?
O código onde eu salvo o mapa de colunas é o seguinte:
private void salvaColunas() {
    for (Map.Entry<Integer, Coluna> entry : mapaColunas.entrySet()){
        Coluna coluna = entry.getValue();
        coluna.setRelatorio(relatorio);
        colunaDao.saveOrUpdate(coluna);
    }
}

A o método saveOrUpdate da minha classe Dao é o seguinte:
public void saveOrUpdate(T obj) {
    Session session;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }catch (HibernateException ex) {
        session = HibernateUtil.getSessionFactory().openSession();
    }
    try{
        tx = session.beginTransaction();
        session.saveOrUpdate(obj);
        tx.commit();
      } catch (RuntimeException e) {
          e.printStackTrace();
      } finally {
          if(session.isOpen()) {
              session.close();
          }
      }
 }

O mapeamento na classe coluna (já com os metodos equals e hashCode implementados) está assim :
@ManyToMany(fetch= FetchType.LAZY, cascade= {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
@JoinTable(name="coluna_elemento",  joinColumns={
        @JoinColumn(name="COLUNA_ID", nullable=false, updatable=false )},
        inverseJoinColumns = {@JoinColumn(name = "ELEMENTO_DOMINIO_ID", nullable=false, updatable = false)  })
private Set<ElementoDominio> elementosDoDominio;

public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((label == null) ? 0 : label.hashCode());
    result = prime * result + ((nome == null) ? 0 : nome.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Coluna other = (Coluna) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    if (label == null) {
        if (other.label != null)
            return false;
    } else if (!label.equals(other.label))
        return false;
    if (nome == null) {
        if (other.nome != null)
            return false;
    } else if (!nome.equals(other.nome))
        return false;
    return true;
}

E minha classe Elemento (que também tem os métodos equals e hashCode implementados) está assim:
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "elementosDoDominio")
private Set<Coluna> colunas;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((label == null) ? 0 : label.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    ElementoDominio other = (ElementoDominio) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    if (label == null) {
        if (other.label != null)
            return false;
    } else if (!label.equals(other.label))
        return false;
    return true;
}

Ambas as classes Coluna quanto Elemento tem mais atributos, inclusive o id que é gerado pelo Hibernate. Todos com getters e setters.
Alguém pod eme ajudar?
Obrigada
Comment: Faz o seguinte, coloca o updatable pra true no elementosDoDominio. Eu acho que ele deve estar tentando atualizar o objeto ao invés de inserir um novo. Só um palpite..
Comment: Tentei inserir as colunas num hashMap antes de salvar em cada interação e vi que ao invés do hash conter as duas colunas, ele está contendo uma só . O que me leva a crer que o meu método equals está retornando que as duas colunas são iguais.. mas não são!!!
Comment: Hmm, mas quando é no hash vc tem que implementar o hashCode, ele não usa o equals. Como ele está implementado?
Comment: gerei pelo eclipse
Comment: Coloca o método aqui.
Comment: pronto, coloquei!
Comment: Não dá pra ter ideia só olhando isso, sugiro que você debugue, coloque um breakpoint no método hashCode e veja se de fato ele está retornando true na segunda interação e por isso ele substitui o objeto anterior.
Comment: já fiz isso. Ele retorna false... portanto, não são iguais
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/73594/discussion-between-giuliana-bezerra-and-tathiana-ianelli).
Comment: eu uso um set e não um list..não preciso do @OrderColumn
Answer: bom, ao invés do set, eu usei um list e ele fez o que eu esperava (o oposto do que está sendo sugerido em Otimização inserts hibernate quando há relacionamento @ManyToMany ).
coloquei na classe Coluna:
private List<ElementoDominio> elementosDoDominio;// ao inves do Set

e na classe Elemento mudei para:
private List<Coluna> colunas; // tb mudei para list

nãos sei o motivo, mas funcionou... se alguém puder explicar, ganha um voto!


Should I set up outbound email server for each app server, or one central one?

Question: My web application has to send emails, and it's hosted on multiple physical servers.  Using a third-party service is not an option, so I'm installing postfix (or maybe sendmail).
Is it more common in this case to install postfix on a central server, or to install it on each app server?  I'd imagine the latter would be easier, requiring less networking/security configuration (and I'd use chef or something to deploy it to all machines at once).  Are there disadvantages to this approach?
One potential problem that crossed my mind is whether it'd make it more likely for the message to get flagged as spam, but AFAICT I could set up a reverse DNS for each server and alleviate that problem?  Anything else I'm not considering?
Comment: `Using a third-party service is not an option` - Why not? Is it a cost issue? If so, most email relay providers offer a free tier.
Comment: @joeqwerty We are currently using mandrill.  It doesn't work with MMS to e.g. firstname.lastname@example.com or whatever.  Mobile carriers ignore it.  We've tried other third-party services and they all have the same problem.  We transferred to gmail, which works, but then we hit rate limits.  So now manual seems to be the only option left.  We'll continue to use mandrill for regular email.
Comment: @joeqwerty (Though if you want to ask why not send MMS via twilio...I'm not sure, that's probably way smarter and more reliable anyway).
Answer: You don't want each server sending out its own mail. Relay through a central server - you'll have a single point to refer to for logging, a single point of configuration with regards to relay ACLs, and a single point to install/configure spam detection/prevention if necessary in the future.
Answer: I would recommend you installing local MTA on each server, accepting only connections on localhost, not necessarily demanding auth. These servers then rely to central server, properly configured (PTR, dkim, etc...).
PROS:
1. identical config on every app server
2. no need to change revdns and so when adding machines
3. faster mail sendout from application point of view
4. keeping queue in case of central server outage
Answer: My best recommendation is to use 3rd party email delivery system through the application (e.g. SendGrid) - having to configure postfix manually would be pain (possible with puppet/chef/etc but unnecessary pain) especially when all you care about is guaranteed transactional emails from the app.
And as mentioned by other fellow members, central SMTP server is the way to go when 3rd party service is out of question.
Comment: configuration management is what you need. Then setting up postifx is painless. Having a central relay server is the way to go here.


Inverse function theorem example question

Question: I try to understand the inverse function theorem by trying learn what will happen if one of conditions isn't satisfy. I try to find if it's possible to find an example such that
a function $f:[a,b] \to [a,b]$ is bijective,
$f$ is infinitely differentiable,
$f$ has some continuous inverse function $g$,
but $g$ is not differentiable at some point of $[a,b]$
I don't think there is an example satisfy all of above, but I'm not so sure about that.
Comment: $x^2$ on the interval $[0,1]$.
Comment: may I have a question ? from your example $g(x)= \sqrt {x}$ which is defined on $[0,1]$, but how is it not differentiable on that interval? Maybe this is a stupid question, but I forget alot about calculus and really want to regain my knowledge.
Comment: It's not differentiable at zero, since it has a vertical tangent line there.
Comment: oh, I see , thank you very much.
Answer: Whenever the derivative of $f$ has a zero, the inverse function $g$ will not be differentiable. Thus, a function such as $x^2$ on $[0,1]$ or $x^3$ on $[-1,1]$ will give examples of non-differentiable inverse functions.


Volume of a Solid of Revolution problem

Question: I'm stuck on a problem from my Calc 2 class and I would appreciate some help with it.
My object is bounded by $y=\sqrt{x}$, $y=0$, and $x=3$ and rotated about the y-axis. Here is what I have setup:
$$v=\pi\int_0^{\sqrt{3}}{y^2}^2 dy$$
$$v=\frac{\pi9\sqrt{3}}{5}$$
The book says it is $$v=\frac{\pi36\sqrt{3}}{5}$$
Thanks in advance
Answer: I intended to make a comment but I made a typo and it came too long, so...
You're integrating over the wrong area. Do a drawing, you want to revolve around the $y$-axis the area between the graph of $x= y^2$ and $x=3$, and you're doing the area between $x=0$ and $x=y^2$ !
The expression representing the volume of revolution should be
$$\pi\int\limits_0^{\sqrt 3}(9-y^4)dy=9\sqrt 3\,\pi-\pi\int\limits_0^{\sqrt 3}y^4\,dx=9\sqrt 3\,\pi-\left.\frac{\pi}{5}y^5\right|_0^{\sqrt 3}=9\sqrt 3\,\pi-\frac{3^{5/2}\pi}{5}=\frac{36\sqrt 3\pi}{5}$$
Comment: Thank you so much, I wouldn't have done that if it was x values :)
Comment: I know, it may be confusing. Drawing the graph of the gang of functions involved and reading carefully what area the questions asks to be revolved helps a lot.
Answer: In this case, it may be easier to use the method that is often called the Method oc Cylindrical Shells. Take a thin vertical strip between $x$ and $x+dx$. Its area is roughly $\sqrt{x}\,dx$. When rotated about the $y$-axis, it sweeps out a shell of volume approximately $(2\pi x)x^{1/2}\,dx$. "Add up" (integrate) from $0$ to $3$. So we want
$$\int_0^3 2\pi x^{3/2}\,dx.$$
The integral is $(2\pi)\frac{2}{5}3^{5/2}$.
Comment: Yes but I was required to use the disk method for this section +1 though
Comment: @David: "Holes" like the one we get by disk/washer method sometimes cause students trouble. That's why I pointed at the shells method, which sidesteps that issue.

Volume of a Solid of Revolution problem


call mp3player field (CCK Field) in a page

Question: I Use MP3 Player module to play audio files. I'm looking for a PHP code to call MP3 Player from a specific node. (e.g. node 4) how can I do that ?
this code doesn't work:
<?php
$node = node_load(4);
print $node->field_audio[0];
?>

this is the result of print_r($node) in node 4.
stdClass Object (
[nid] => 4
[type] => story
[language] => en
[uid] => 1
[status] => 1
[created] => 1343931282
[changed] => 1343931282
[comment] => 2
[promote] => 1
[moderate] => 0
[sticky] => 0
[tnid] => 0
[translate] => 0
[vid] => 4
[revision_uid] => 1
[title] => 5455
[body] =>
[teaser] =>
[log] =>
[revision_timestamp] => 1343931282
[format] => 1
[name] => admin
[picture] =>
[data] => a:0:{}

[field_audio] => Array (
[0] => Array (
[fid] => 7
[uid] => 1
[filename] => audio.mp3
[filepath] => sites/default/files/audio.mp3
[filemime] => audio/mpeg
[filesize] => 3663455 [status] => 1
[timestamp] => 1343931251
[list] => 1
[data] =>
)
)

[last_comment_timestamp] => 1343931282
[last_comment_name] =>
[comment_count] => 0
[taxonomy] => Array ( )
)

Answer: From the readme.txt file of that module.

Pop this code anywhere to insert an audio player:

if (module_exists('mp3player')) {
  print theme('mp3player', 'Default', $audio_file_url, $audio_title, $audio_artist, $description);
}

Comment: Thanks, I tried this before but It didn't work, I made some changes and now everything is ok: `field_audio[0]['filepath'], 'Static title'); ?>`


How to wait until a web page is loaded with javascript?

Question: I want to change between two pages in html with javascript, but when I change with window.location, the code that is after this sentence continues executing.
So when I do, for example, a call to getElementById() it doesn't recognize the element because the page is still loading.
function myFun(){

    // ...

    window.location = 'page.html';

    // ... wait until page.html is loaded

}

How can I wait until the page is loaded to avoid this problem?
Answer: When you do
window.location = 'page.html';

you replace the page in the browser, the one containing the code of myFun, by a new page. There is no way for the code following this instruction to be executed.
If you want to execute it, and only after that change page (but I don't see the point), then you might do
document.onload = function(){ window.location = 'page.html'; };

Comment: but `myFun` is placed in a separate .js file.
Comment: If it's imported in your html file, it's exactly as if it was directly in the page. Its execution stops when you replace the page.
Comment: ok thanks, as you told me that it's impossible I've changed the logic of the program to fix that! :)
Answer: You can use jQuery document.ready or you can create custom bind like this one. In case you use jQuery.
   $(document).ready(function() {
        window.location = 'page.html';
    });

Answer: You can't execute code in your own page after doing window.location = 'page.html';.  Your page will be replaced by the new page and the code in the current page will no longer be there.
The only ways to execute some code after page.html is loaded into the current window are as follows:

Load it in an iframe or another window and monitor for when the iframe or window has finished loading.  In this way, your current code stays around and is not replaced.
Have some code in page.html that monitors when it finishes loading and trigger your desired action from there.


Why printf show false value of an hex number

Question: Code
char a;
a = 0xf1;
printf("%x\n", a);

Output
fffffff1

printf() show 4 bytes, that exactly we have one byte in a.
What is the reason of this misbehavior?
How can i correct it?
Comment: A `char` would be promoted to `int` by virtue of the integer promotions anyway....
Comment: `char a;` --> `unsigned char a;`
Comment: @EsmaeelE There is no requirement in standard C that ASCII be the character set used. Consider that C also runs on machines using EBCDIC.
Comment: wrong format. Try `int a`
Comment: It casted to an integer, which extended the sign
Comment: @EsmaeelE I assume you're programming for a Unix system, since you're using a Unix programming language, so a Unix manual might be a good place to start! [Here's one](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdarg.h.html)... Pay careful attention to the parts about *integer promotion*!
Comment: @EsmaeelE You can't safely learn C by trial and error! It has undefined behaviours which you must learn to avoid unless you want to risk being sued for losses caused by serious bugs (e.g. the heartbleed SSL bug). Fortunately the technology you're using comes with manuals which you can read... so read them *BEFORE* you resort to guessing! Perhaps your guessing might lead you to some flawed conclusion which works for your system, then gets you in trouble because it doesn't for some other... at least the manual would be your defense in court.
Comment: @Jean-FrançoisFabre  `printf("%zu", sizeof(int));` show 4 byte, i want only one byte.
Comment: @DavidBowling its true David. but consider `int` have 4 byte length, and `char` have only one byte, try `sizeof`. i know any characters in C cast to appropriate ASCII.
Comment: @EsmaeelE You can try `sizeof`, but by the time you finish writing a `printf`-like function in order to test the `sizeof` its argument, you could have just read the manual... In fact, you *should* read the manual.
Comment: @EsmaeelE The comments section is for requesting and providing clarification for the question you asked. Please don't diverge so much from the original topic. I'm not your research hound. You can find that information.
Comment: @EsmaeelE-- if you just google [EBCDIC](https://en.wikipedia.org/wiki/EBCDIC) you would get the Wikipedia page I just linked to.
Comment: @Seb about first your comment,  I must read which manual instead of use `sizeof`?
Comment: @EsmaeelE [Here's one about a common compiler/standard library](http://www.gnu.org/software/libc/manual/html_node/Calling-Variadics.html) which says "objects of type char or short int (whether signed or not) are promoted to either int or unsigned int" and "if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int)."
Comment: @Seb how to seperate, bytes with `printf()` ff_ff_ff_ff
Comment: @EsmaeelE The comments section here is not the right place to ask a new question. Nonetheless, *before* you ask that new question you should conduct adequate research or else you'll end up with a *closed, unanswered* question... Which research have you conducted? I recall learning about division in primary school; perhaps you should do some research into that (and its related friend, modulo)...
Answer: printf is a variable argument function, so the compiler does its best but cannot check strict compliance between format specifier and argument type.
Here you're passing a char with a %x (integer, hex) format specifier.
So the value is promoted to a signed integer (because > 127: negative char and char is signed on most systems, on yours that's for sure)
Either:

change a to int (simplest)
change a to unsigned char (as suggested by BLUEPIXY) that takes care of the sign in the promotion
change format to %hhx as stated in the various docs (note that on my gcc 6.2.1 compiler hhx is not recognized, even if hx is)

note that the compiler warns you before reaching printf that you have a problem:
gcc -Wall -Wpedantic test.c
test.c: In function 'main':
test.c:6:5: warning: overflow in implicit constant conversion [-Woverflow]
 a = 0xf1;

Comment: my advice: keep it like `-Wall -Wextra` (sometimes `-Wpedantic` is a little too much)
Comment: some compilers do this check anyway. gcc will produce the warning, and cast char to int in this case
Comment: @PeterJ not on my version (which is a branch of 6.2.1), but thanks, I have used max warning options and got a warning _before_. gcc probably casts char to int silently, but I don't see any warning (I get warning for wrong number of parameters)
Comment: @EsmaeelE add `-Wextra` too and `-Woverflow`...
Comment: which gcc version do you have? gcc has improved since 2.95. time to upgrade. The price is cheap :)
Comment: yes: `-Woverflow` is the one.
Comment: @Jean-FrançoisFabre thanks for advice. `gcc -Wall -Wextra` not generate any message in this case. only `-Wpedantic` show that thing. and `-Woverflow` not catch.
Answer:
What is the reason of this misbehavior?

This question looks strangely similar to another I have answered; it even contains a similar value (0xfffffff1). In that answer, I provide some information required to understand what conversion happens when you pass a small value (such as a char) to a variadic function such as printf. There's no point repeating that information here.
If you inspect CHAR_MIN and CHAR_MAX from <limits.h>, you're likely to find that your char type is signed, and so 0xf1 does not fit as an integer value inside of a char.
Instead, it ends up being converted in an implementation-defined manner, which for the majority of us means it's likely to end up with one of the high-order bits becoming the sign bit. When these values are promoted to int (in order to pass to printf), sign extension occurs to preserve the value (that is, a char that has a value of -1 should be converted to an int that has a value of -1 as an int, so too is the underlying representation for your example likely to be transformed from 0xf1 to 0xfffffff1).
printf("CHAR_MIN .. CHAR_MAX: %d .. %d\n", CHAR_MIN, CHAR_MAX);
printf("Does %d fit? %s\n", '\xFF', '\xFF' >= CHAR_MIN && '\xFF' <= CHAR_MAX ? "Yes!"
                                                                             : "No!");

printf("%d %X\n", (char) -1, (char) -1); // Both of these get converted to int
printf("%d %X\n", -1, -1);               // ... and so are equivalent to these

How can i correct it?

Declare a with a type that can fit the value 0xf1, for example int or unsigned char.
Answer: You should use int a instead of char a because char is unsigned and can store only 1 byte from 0 to 255.
And hex number need many storage to store it, and also int storage size is 2 or 4 bytes. So it's good to use int here to store hex number.
Comment: Plain `char` may be `signed` or `unsigned`; this is implementation-dependent.
Comment: on the OP's platform char specifically is *signed*; that's why they see this behaviour.
Comment: @EsmaeelE-- check for wrap-around of negative numbers: `char x = -1;  printf("%s\n", x < 0 ? "signed char" : "unsigned char");`.
Comment: It's promoted when code is being compiled?
Comment: `0xf1` requires only one byte, so `unsigned char` would be sufficient.
Comment: how to find out in my machine `char` is `signed` or `unsigned`?


Will training a classifier on data where one class is more present than another going to mess everything up?

Question: Let's say I have a dataset where we have examples belonging to either class A or class B but we have more examples belonging to class B than A.
If I train a classifier on this data will it be useless?
Comment: [Some argue that class imbalance is no issue at all and that "correcting" for it is a poor strategy.](https://stats.stackexchange.com/questions/357466/are-unbalanced-datasets-problematic-and-how-does-oversampling-purport-to-he) I tend to find myself in this camp.
Answer: Training a classifier on data in which there is a large class imbalance can lead to problematic behaviour from the classifier.  For example, using the popular classification rule of $p<0.5 \implies 0$ else 1 in logistic regression for an imbalanced classification can lead to all the classifications being 0/1 (depending on which class is most prevalent).
In this case, it might be better to estimate the probability that each observation belongs to each class.  This gives you the added flexibility of creating your own cutoff should you want it, or better yet using the probability directly in any downstream decisions.
Comment: Some people consider the thresholding step to be a category error: [Classification probability threshold](https://stats.stackexchange.com/q/312119/1352)
Comment: @Stephan I agree, as evidenced by my post history. Nevertheless, it is an option for OP


Select com inner join com CakePHP

Question: Estou com um probleminha a algum tempo referente a um projeto que estou desenvolvendo em cakephp, minha view não consegue ler um select com inner join da tabela.
Controller:
           public function initialize()
       {

           $posts = $this->Posts->find("all",array(
              "joins" => array(
                  array(
                    "table" => "users",
                    "alias" => "User",
                    "type" => "INNER",
                    "conditions" => array("Post.user_id = User.id "),
                    "fields" => array('Post.*', 'User.username')
                   )
               )
            )
         );

model;
      public function initialize(array $config) {
          $this->addBehavior('Timestamp');
          $this->displayField('title');

         //join
         $this->belongsTo('User');
}

View
<?= $post->username ?>

Código SQL
SELECT posts.*,
       users.username
FROM   posts
       INNER JOIN users
               ON ( posts.user_id = users.id )

Explicando melhor, essa consulta está buscando o "username" da tabela A para a tabela B, sendo que essa tabela B minha view consegue fazer a leitura normalmente. Com esse select meu banco traz a consulta exatamente que eu preciso, mas minha view não mostra o resultado e retorna nulo. Ou diz se eu tentar fazer a view assim:     $post->users->username, retorna um erro que não encontra o objeto users.
Comment: Como você está passando os dados para a view?
Comment: username ?> é minha view
Answer: Com JOIN's o CakePHP coloca os valores dentro dos seus respectivos objetos.
Provavelmente o seu username está dentro do objecto User:
$post->user->username

Dê um pr() no seu objeto $post para que ele exiba todos os atributos.
Em vez de fazer sql puro, você poderia usar as propriedades belongsTo(), hasMany() e hasOne() do CakePHP.

Você precisa fazer a consulta no seu controller e setar a variável para que ela exista em sua view.
Controller
$posts = $this->loadModel('Posts');
$all = $posts->find('all');

$this->set('posts', $all);

Model Posts - Usando o belongsTo()
class PostsTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Users');
    }

}

Caso você não tenha criado as suas models, verifique esse link
Comment: Sim Jeferson, esta dentro do obj User. Pode me dar um exemplo de como usar o pr() ?
Comment: a função `pr()` do cake, nada mais é que um `print_r()`, você pode usar da seguinte forma: `pr($post)`, se a minha resposta estiver correta, marque ela para que possa ajudar outras pessoas que tenha o mesmo problema.
Comment: Usando dessa forma, a coluna "username" esta retornando vários arrays, como por exemplo: [_accessible:protected] => Array e [_properties:protected] => Array
Comment: Usando o `pr()` ele vai exibir tudo do objeto, porém chamando `$post->user->username` ele te retorna somente o valor
Comment: me retorna o erro "Trying to get property of non-object"
Comment: tenta dessa forma `$post->User->username`
Comment: Mesmo erro, não preciso setar nada no controller?
Comment: Posta o código que esta no método da sua controller
Comment: Postei como resposta a minha pergunta.
Comment: Edita sua pergunta e coloque nela, no seu código da controller você não faz nenhuma consulta referente à posts, somente a parte do `AuthComponent`
Comment: Editei. Como eu poderia fazer essa consulta?
Comment: Editei minha respostas, pelo que entendi você não esta utilizando as models para fazer a consulta e esta tentando chamar posts na view sem setar
Comment: fiz as inclusões conforme você orientou, mas na view, minha coluna "username" continua retornando NULL, se eu fizer, por exemplo $post->user_id (que é uma coluna criada na tabela "post"), puxa certinho os Id, mas se eu fizer $post->username (username que é uma coluna da tabela Users) considerando o inner join que eu fiz, retorna null.
Comment: Porque o `usename` esta dentro do objeto User (ou user), tenta `$post->user->username` ou `$post->User->username`
Comment: Editei a pergunta com algumas alterações
Answer: Caso alguém precise da resolução, consegue faze-la adicionando esse código no PostsController.
           public function index()
               {
           $posts = $this->Posts->find('all', [
              'conditions' => ['Posts.online !=' => -1]])->order(['Posts.publication' => 'DESC'])->contain(['Users']);
           $this->set(compact(['posts']));
               }

Model
        public function initialize(array $config) {
            //funcao para trazer username do inner join
            $this->addBehavior('Timestamp');
            $this->displayField('title');
            $this->belongsTo('Users', [
                'foreignKey' => 'user_id',
                'joinType' => 'INNER',
            ]);
       }

Select com inner join com CakePHP


Submitting a SPARQL query with variable binding to GraphDB REST API

Question: I am trying to submit a SPARQL query to a local repository on Ontotext GraphDB via its REST API. According to the documentation, one of the query params is also $<varname> which specifies variable bindings.
Suppose we have a repository called testrepo that contains customers, each of whom has a unique customerID. Submitting the following query:
PREFIX : <http://www.example.com/>
SELECT * WHERE {
    ?customer a :Customer ;
           :hasID ?customerID .
}

as a GET request with the respective variable binding customerID = "123" unfortunately retrieves all the customers and not the specific one.
Here is the request:
http://localhost:7200/repositories/testrepo?query=PREFIX%20%3A%20%3Chttp%3A%2F%2Fwww.example.com%2F%3E%0ASELECT%20*%20WHERE%20%7B%0A%09%3Fcustomer%20a%20%3ACustomer%20%3B%0A%20%20%20%20%20%20%20%20%20%20%20%3AhasID%20%3FcustomerID%20.%0A%7D%20&customerID="123"

So, what am I doing wrong?
Comment: *"one of the query params is also $ which specifies variable bindings."* As @UninformedUser mentioned, you'd probably need `&$customerId="123"` for this to work.  Otherwise, it'd be impossible to bind a value for a variable called `query`, since `?query=...` is already used for the query itself.
Comment: did you try with a leading `$` char to indicate that the HTTP param is a query variable?
Comment: Note that you could also use a `values` block within the query: `select ... where { ... values ?customerId { "123" } }`.
Comment: Duh, both of you are absolutely correct, I needed to add a `$` in front of the param name. Many thanks!
Answer: SOLVED: As specified by UninformedUser and Joshua Taylor, I should have added a $ in front of the param name.
The correct request is the following:
http://localhost:7200/repositories/testrepo?query=PREFIX%20%3A%20%3Chttp%3A%2F%2Fwww.example.com%2F%3E%0ASELECT%20*%20WHERE%20%7B%0A%09%3Fcustomer%20a%20%3ACustomer%20%3B%0A%20%20%20%20%20%20%20%20%20%20%20%3AhasID%20%3FcustomerID%20.%0A%7D%20&$customerID="123"


Php: array_filter changes data format

Question: In the code below I would expect
t2: [{"value":"".....}, {}, {}]

but instead I get
t2: {"0":{"value":"",.. , "1":{}, .. }

even casting
json_encode( (array) $t2);

doesn't make it work
thx
function filter($var) {
    return($var->id < 4);
}

$t1=json_decode('[{"value":"","id":"0","key":"algo"},{"value":"0.8","id":"-1","key":"cout"},{"value":"2012-07-21","id":"3","key":"date"},{"value":"","id":"0","key":"europe"},{"value":"","id":"0","key":"inria"},{"value":"1","id":"4","key":"ndOfRates"},{"value":"part","id":"0","key":"offre"},{"value":"","id":"0","key":"paris"},{"value":"Ut enim quisque sibi plurimum confidit et ut quisque maxime virtute et sapientia sic munitus est, ut nullo egeat suaque omnia in se ipso posita iudicet, ita in amicitiis expetendis colendisque maxime excellit. Quid enim? Africanus indigens mei? Minime hercule! ac ne ego quidem illius; sed ego admiratione quadam virtutis eius, ille vicissim opinione fortasse non nulla, quam de meis moribus habebat, me dilexit; auxit benevolentiam consuetudo. Sed quamquam utilitates multae et magnae consecutae sunt, non sunt tamen ab earum spe causae diligendi profectae. Hae duae provinciae bello quondam piratico catervis mixtae praedonum a Servilio pro consule missae sub iugum factae sunt vectigales. et hae quidem regiones velut in prominenti terrarum lingua positae ob orbe eoo monte Amano disparantur. Ultima Syriarum est Palaestina per intervalla magna protenta, cultis abundans terris et nitidis et civitates habens quasdam egregias, nullam nulli cedentem sed sibi vicissim velut ad perpendiculum aemulas: Caesaream, quam ad honorem Octaviani principis exaedificavit Herodes, et Eleutheropolim et Neapolim itidemque Ascalonem Gazam aevo superiore exstructas. Post hoc impie perpetratum quod in aliis quoque iam timebatur, tamquam licentia crudelitati indulta per suspicionum nebulas aestimati quidam noxii damnabantur. quorum pars necati, alii puniti bonorum multatione actique laribus suis extorres nullo sibi relicto praeter querelas et lacrimas, stipe conlaticia victitabant, et civili iustoque imperio ad voluntatem converso cruentam, claudebantur opulentae domus et clarae. Et quoniam apud eos ut in capite mundi morborum acerbitates celsius dominantur, ad quos vel sedandos omnis professio medendi torpescit, excogitatum est adminiculum sospitale nequi amicum perferentem similia videat, additumque est cautionibus paucis remedium aliud satis validum, ut famulos percontatum missos quem ad modum valeant noti hac aegritudine colligati, non ante recipiant domum quam lavacro purgaverint corpus. ita etiam alienis oculis visa metuitur labes.","id":"4","key":"text"},{"value":"on","id":"0","key":"type"}]');

$t2 = array_filter($t1, "filter");

echo 't2: '.json_encode($t2);

Comment: json_encode(array_values($t2)) seems good
Comment: dose the json_encode($t1) give the same problem? and how about json_encode(array_values($t2))?
Comment: no t1: [{"value":"","id":"0","key":"algo"},{"value":"0.8","id":"-1","key":"cout"},{"value":"2012-07-21","id":"3","key":"date"},{"value":"","id":"0","key":"europe"},{"value":"","id":"0","key":"inria"},{"value":"1","id":"4","key":"ndOfRates"},{"value":"part","id":"0","key":"off.......  that's why this is strange
Answer: In PHP, there is no difference between associative and numeric arrays. Therefore, when converting to JSON, json_encode has to infer from the array's keys whether it should be encoded as an array or an object. It does this by testing to see if (a) the keys are numeric and (b) if they are sequential, starting with 0; if both tests pass, it will be encoded as an array.
When you use array_filter, you remove some of the keys. The others are not renumbered, so the keys are no longer sequential.  This means that json_encode infers that this should be an object rather than an array when encoded in JSON.
You can correct this by renumbering the keys. Use array_values to do this:
echo 't2: '.json_encode(array_values($t2));

Php: array_filter changes data format


How to smoothly change between vastly different melodies

Question: I'm starting a Concerto(Piano) and all of the problems I have come across are A: regarding the orchestration(this is my first orchestral piece) and B: the 2 subjects of the first sonata movement are very different in terms of tempo(The concerto starts in 120 bpm, the first subject is just four whole notes, the second is syncopated quarter and 8th notes) so when I attempt the modulation from the slow opening with the first subject(diatonic with chromatic harmony) to the faster 2nd subject(chromatic with less chromatic harmony) it seems sudden and abrupt. I have tried everything I could think of to lighten the modulation to the 2nd subject, but no matter what I do, it is always abrupt and does not work. How do you create transitions between very different subjects?
Comment: It's your concerto, so you have to decide how you want to solve issues like that.  Without seeing what you have, I can't comment much, but I'd probably do the modulation slow, end on a fermata, and then let 'er rip for the 2nd.  Be like Beethoven-- make the abruptness a feature.
Comment: There are hundreds of concerti out there, written by the famous names and more. Listen to lots and copy what you like.
Answer: There's no 'answer' to your question.  But let me throw some ideas at you.
If your second subject doesn't grow organically out of the first subject it might be the wrong one for THIS sonata.  But 'sudden and abrupt' is good too.  Just try to choose two themes that are in the same ballpark - that CAN follow one another in the same musical flow.
(Maybe what you've written so far is a slow introduction and a first subject?)
'Just four whole notes'.  That might describe the thematic germ of the first subject, in the same way as 'just an appeggio plus a twiddle' describes the germ of Beethoven's Piano Sonata op.2 no.1 (and if you're attempting a sonata-form movement and haven't studied that piece, drop everything and do it NOW!)   But you've got to turn that into at least a couple of pages of music if it's going to be worth the musicians turning up!  And it can't ALL be whole notes.


How do you show that branch cuts result in a single valued function for logarithmic branch points?

Question: I know the way that basically everywhere says to do it, but I'm having trouble putting it into equations that make sense for logarithmic branch points.
Everywhere says to trace a path around the branch points, with the angles $\theta_1$ and $\theta_2$ corresponding to the angles between each branch point and any given point on the path. As a circle is traced around the first branch point, $\theta_1$ gets incremented by $2\pi$, then the path is followed along the cut to the next branch point with the angles remaining the same. Then a circle is traced around the second branch point, with $\theta_2$ getting incremented by $2\pi$. Then you follow the cut back to the initial point, again with no change in angle.
If the function is single valued, you should arrive back at the same value for $f(z)$ after tracing this path. This is easy to show for something like $((z-1)(z+1))^{1/2}$ :
$$
(r_1e^{i\theta_1} \cdot r_2e^{i\theta_2})^{1/2}=r_1r_2e^{i(\frac{\theta_1+\theta_2}{2})} \\
$$
$$
\begin{align*}
(r_1e^{i(\theta_1+2\pi)} \cdot r_2e^{i(\theta_2+2\pi)})^{1/2}& =r_1r_2e^{i(\frac{\theta_1+\theta_2}{2}+2\pi)}
\\
&=r_1r_2e^{i(\frac{\theta_1+\theta_2}{2})}e^{i(2\pi)}
\\
&=r_1r_2e^{i(\frac{\theta_1+\theta_2}{2})}(1)
\\
&=r_1r_2e^{i(\frac{\theta_1+\theta_2}{2})}
\end{align*}
$$
But throw in a logarithm with infinite sheets and it doesn't seem to add up, like: $\log((z-1)(z+1))$
$$
\log(r_1e^{i\theta_1} \cdot r_2e^{i\theta_2}) = \ln(r_1r_2) + i(\theta_1+\theta_2)
$$
$$
\log(r_1e^{i(\theta_1+2\pi)} \cdot r_2e^{i(\theta_2+2\pi)}) = \ln(r_1r_2) + i(\theta_1+\theta_2 +4\pi)
$$
It's no longer periodic so multiples of $2\pi$ no longer cancel out automatically.
If you set $0\leq\theta_1<2\pi$ and $-\pi\leq \theta_2 < \pi$ which i believe it is supposed to be with the additional branch point at infinity, seemingly the only way to stay single valued going from $\theta_1=0 $  to  $\theta_1=2\pi$   and simultaneously from $\theta_2=-\pi $  to  $\theta_2=\pi$ is for the trace to cross over the branch cut.
$$
\begin{align*}
\log(r_1e^{i(0)} \cdot r_2e^{i(-\pi)})& = \ln(r_1r_2) + i(-\pi) \\
\log(r_1e^{i(0+2\pi)} \cdot r_2e^{i(-\pi+2\pi)}) &= \ln(r_1r_2) + i(3\pi) &\text{ (not the same value)}\\
\end{align*}
$$
$$
\begin{align*}
\\
\log(r_1e^{i(0)} \cdot r_2e^{i(\pi)})& = \ln(r_1r_2) + i(\pi) \\
\log(r_1e^{i(0+2\pi)} \cdot r_2e^{i(\pi-2\pi)}) &= \ln(r_1r_2) + i(\pi) &\text{ (same value)}\\
\end{align*}
$$
Basically it seems like one of the branch points has to be traced around the wrong direction, from  the maximum angle to the minimum angle, which corresponds to the trace crossing over the branch cut before going around the point. If you treat infinity as a single point on the Reimann sphere, tracing around the cut means both points should be gone around either clockwise or both counterclockwise, but that seems to result in extra $i\pi$'s in the value of the function.
What is going on here? I'm clearly missing something because I know this works, just every explanation I have seen is lacking some kind of information needed to describe the full idea of what they are trying to do here.
Since there seems to be some confusion, this is the method for testing a branch cut I was referring to earlier:
Branch cut
Associated graphic
Comment: Perhaps you're confusing branch points with branch cuts? (see https://functions.wolfram.com/ElementaryFunctions/Log/04/04/ and https://functions.wolfram.com/ElementaryFunctions/Log/04/05/)
Comment: the difference between the two functions is that infinity is a pole (not a branch point) for the square root one but still a branch point for the logarithmic one so one needs a cut there too in that case
Comment: I am specifically talking about the branch cuts you create using the branch points. The whole purpose is to make a multi-valued function single-valued, but how do you show that the chosen branch cut renders a single valued function? And I know infinity is a branch point, i mentioned it in the post and have the cut passing from -1 through infinity to 1.
Comment: Your question is confused. Do you know that if $U$ is simply connected and doesn't contain any branch point then any branch of $f$ extends analytically to the whole of $U$?
Comment: @reuns I am specifically talking about multi-valued functions with multiple branch points, as I specified in my original post. What is confusing?
Comment: The very first sentence is "Everywhere says to trace a path around the branch points, with the angles θ1
 and θ2
 corresponding to the angles between each branch point and any given point on the path." What are the angles of the path? What are angles between points? In the next sentence those angles are increased, so they were not numbers but... something. That is confusing. I stopped reading there.
Comment: One has to be cautious with the terminology here. "Function" means single-valued. If someone just refers to a function, it will be a "single-valued function". "Multi-valued functions" are not truly functions. Cauchy's theorem and integral formula, and the result that reuns quoted which follows from them, are all about functions, not multi-valued functions. If you restrict a multi-valued function to a simply-connected domain, and choose a particular value for it at one point in that domain, it automatically uniquely determines the value everywhere in that domain, making it single-valued.
Answer: Maybe we can actually draw some pictures and clear up your confusion.
$f(z) = \log(z^2-1)$ has three branch points where it is not analytic: $z=1, z=-1, z=\infty$.
In order to make $f$ single-valued, we need to restrict it to a simply-connected domain on the Riemann sphere. We can do that by connecting the three branch points by a simple curve, and discarding that curve from the domain of $f$. While any simple curve would work, it is almost always easiest to use lines:

In this example, $1$ is connected to $-1$, and $-1$ is further connected to $\infty$. The domain $U$ consisting of all the Riemann sphere outside this curve is simply-connected. We can choose a particular value for $f$ at some point not on $(-\infty, 1]$, say $f(\sqrt{e + 1}) = 1$. Then take the Taylor series of $f$ about this point, having the selected value as constant term, and arrive at a single-valued function within the radius of convergence. Then per the result reuns quoted, extend that function to the entirety of $U$, on which by Cauchy's theorem it will be single-valued, since $f'$ is analytic everywhere in $U$ and thus will integrate to $0$ around any closed loop.
Now, let's add your path description:

I hope you can see why that didn't work. The whole point of cut lines is that they are removed from the domain of the function. You cannot cross them. When you cross the cut, the value of the function jumps discontinuously, which you ignored.
If you want examine it properly, you have to also draw a circle around the third branch point, $\infty$. When projected into the plane, a small counter-clockwise circle about $\infty$ becomes a large clockwise circle about $0$, which encircles both of the other branch points.


How do you defend against the BlackHat 2009 null-character SSL exploit?

Question: The details are here:
http://hackaday.com/2009/07/29/black-hat-2009-breaking-ssl-with-null-characters/
One recommendation per post please.
Comment: Maybe this should be a wiki?
Answer: Use FireFox 3.5 which is apparently1 not vulnerable.
(In  the end, all SSL clients will need to update to ignore null for null characters when checking the host name of the certificate matches.)
1 According to this article on The Register (final paragraph).
Comment: null-terminated strings are a fixture of C, and possibly other languages.
Answer: This is not really a solution and more of a discussion kick-off.
It can be mitigated by reducing the reliance on SSL. What I means is that we should not rely on SSL only and assuming that all SSL connections are secure. The hack essentially allows MITM attacks from being detected by the user.
Maybe, the way to work around it is by avoiding any transmission of sensitive information through the connection.
Eg.
Instead of transmitting login passwords through SSL, have the password hashed at the client and with some sort of salt issued by a challenge and then transmit that through SSL. Also, using some sort of OTP generator like some banks use, is a good idea.


Why is "ps" output not resolving the uid of my process?

Question: Context: on an ubuntu Linux 2.6.24-22-xen #1 SMP x86_64 GNU/Linux
I am starting a daemon via an init.d script but in the "ps" output, it is displaying the daemon's user in numeric form. e.g.
1000  17560  1  1 11:04 ?  00:00:09 /usr/lib/jvm/java-6-sun/bin/java -server
        -jar /home/superduperadmin/server/daemon.jar

1000 is the mapped to superduperadmin in /etc/passwd.
Why is this ? Is it because superduperadmin is too long ?
Comment: ok, beside that, what is it that you are encountering problems with?
Comment: It is not exactly a problem yet. I'm just wondering why some processes's userids are resolved to their textual counterparts while my daemon is not.
Answer: Yes, it's because it's too long...
from the ps(1) man page...

euser  EUSER  effective user name. This will be the textual user ID,
              if it can be obtained and the field width permits, or
              a decimal representation otherwise. The n option can be
              used to force the decimal representation.
Comment: IIRC the limit for ps is 8 characters and it can't be changed, no matter how wide your terminal is. \o/
Comment: I'd been wondering this myself, if perhaps it had something to do with LDAP users, but no. Thanks.
Answer: The username is too long to display - more than 8 characters.
If you want a ps listing with longer names, you have to set the allowed maximum length yourself:
$ ps -e -o "pid,user:16,command"

Answer:
rename user 'superduperadmin' to 'sda'.
renaming the home dir to match is optional, but you do need to edit any scripts, config files, etc that reference that username (or the dir if you DO rename the home dir).

give yourself a whack on the back of the head for creating a user account that requires Too Much Typing to remind yourself not to do it again :)


Puppet - Possible to use software design patterns in modules?

Question: As I work with puppet, I find myself wanting to automate more complex setups, for example vhosts for X number of websites. As my puppet manifests get more complex I find it difficult to apply the DRY (don't repeat yourself) principle. Below is a simplified snippet of what I am after, but doesn't work because puppet throws various errors depending up whether I use classes or defines. I'd like to get some feed back from some seasoned puppetmasters on how they might approach this solution.
# site.pp
import 'nodes'

# nodes.pp
node nodes_dev {
    $service_env = 'dev'
}

node nodes_prod {
    $service_env = 'prod'
}

import 'nodes/dev'
import 'nodes/prod'

# nodes/dev.pp
node 'service1.ownij.lan' inherits nodes_dev {
    httpd::vhost::package::site { 'foo': }
    httpd::vhost::package::site { 'bar': }
}

# modules/vhost/package.pp
class httpd::vhost::package {

    class manage($port) {

        # More complex stuff goes here like ensuring that conf paths and uris exist
        # As well as log files, which is I why I want to do the work once and use many

        notify { $service_env: }
        notify { $port: }
    }

    define site {

        case $name {

            'foo': {

                class 'httpd::vhost::package::manage':
                    port => 20000
                }
            }

            'bar': {

                class 'httpd::vhost::package::manage':
                    port => 20001
                }
            }
        }
    }
}

That code snippet gives me a Duplicate declaration: Class[Httpd::Vhost::Package::Manage] error, and if I switch the manage class to a define, and attempt to access a global or pass in a variable common to both foo and bar, I get a Duplicate declaration: Notify[dev] error.
Any suggestions how I can implement the DRY principle and still get puppet to work?
-- UPDATE --
I'm still having a problem trying to ensure that some of my vhosts, which may share a parent directory, are setup correctly. Something like this:
node 'service1.ownij.lan' inherits nodes_dev {
    httpd::vhost::package::site { 'foo_sitea': }
    httpd::vhost::package::site { 'foo_siteb': }
    httpd::vhost::package::site { 'bar': }
}

What I need to happen is that sitea and siteb have the same parent "foo" folder. The problem I am having is when I call a define to ensure the "foo" folder exists. Below is the site define as I have it, hopefully it will make sense what I am trying to accomplish.
class httpd::vhost::package {

    File {
        owner   => root,
        group   => root,
        mode    => 0660
    }

    define site() {

        $app_parts = split($name, '[_]')

        $app_primary = $app_parts[0]

        if ($app_parts[1] == '') {
            $tpl_path_partial_app = "${app_primary}"
            $app_sub = ''
        } else {
            $tpl_path_partial_app = "${app_primary}/${app_parts[1]}"
            $app_sub = $app_parts[1]
        }

        include httpd::vhost::log::base

        httpd::vhost::log::app { $name:
            app_primary => $app_primary,
            app_sub     => $app_sub
        }
    }
}

class httpd::vhost::log {

    class base {

        $paths = [ '/tmp', '/tmp/var', '/tmp/var/log', '/tmp/var/log/httpd', "/tmp/var/log/httpd/${service_env}" ]

        file { $paths:
            ensure  => directory
        }
    }

    define app($app_primary, $app_sub) {

        $paths = [ "/tmp/var/log/httpd/${service_env}/${app_primary}", "/tmp/var/log/httpd/${service_env}/${app_primary}/${app_sub}" ]

        file { $paths:
            ensure  => directory
        }
    }
}

The include httpd::vhost::log::base works fine, because it is "included", which means it is only implemented once, even though site is called multiple times. The error I am getting is: Duplicate declaration: File[/tmp/var/log/httpd/dev/foo]. I looked into using exec, but not sure this is the correct route, surely others have had to deal with this before and any insight is appreciated as I have been grappling with this for a few weeks. Thanks.
Comment: `Notify[dev]` - where's `dev` come from?
Comment: @ShaneMadden: Updated code snippet to answer your question.
Answer: First off - you should definitely be using define for httpd::vhost::package::manage, not class, since it's going to be defined multiple times for the same node.
notify { $service_env: } will always blow things up, since $service_env is dev for both calls of the define.  You can't ever declare the same resource a second time with the same name.
You can fix this by changing over to something like notify { "${service_env}-${port}": }, but you'll likely run into other issues if this wasn't built properly to handle being set up as a defined type.
The class structure getting all the way out to httpd::vhost::package::manage is strange - I'd recommend really slimming things down to a class structure that'll simplify things and allow you to have only the resources that're needed.
httpd (init.pp - have it include the install, config, service classes)
httpd::install (install.pp - have it define Package[httpd] to install)
httpd::service (service.pp - have it define Service[httpd]; the vhost defines can
                notify this to update)
httpd::config (config.pp - any configuration, such as handling of httpd.conf,
               that won't be per-vhost)
httpd::vhost (vhost.pp - the defined type that can be used multiple times.  Have
              it include httpd so that the base classes are handled, and
              notify httpd::service from your vhost config file resources)

A simple example of vhost management is actually the example for defined types in the documentation - let me know if you need any other clarification on how to set this up to be a nice reusable bit of config!
Edit:
Update for the shared parent directories problem.
Managing a file from two separate places is a pain in Puppet, and it's given me problems before too.  Especially frustrating when there's no conflict between the two resource declarations like in your current conundrum.
You're right that an exec resource is likely your best answer.
define app($app_primary, $app_sub) {
    exec { "mkdir_${service_env}_${app_primary}_${app_sub}":
        command  => "/bin/mkdir -p /tmp/var/log/httpd/${service_env}/${app_primary}/${app_sub}",
        creates  => "/tmp/var/log/httpd/${service_env}/${app_primary}/${app_sub}",
        require  => Class["httpd::vhost::log::base"],
    }
}

This works for both cases (with and without a subdirectory) because you're setting $app_sub to an empty string if it's not in use.
I'd argue that it's probably a lot cleaner to just not share a directory tree (use log/httpd/foo_sitea as the log dir instead of log/httpd/foo/sitea), but this should do the trick.  Splitting the string and behaving differently based on that, and all these separate defines when this can really just live in the site class.. make sure to keep it simple!
Comment: You can use `if ! defined(File[$paths]) { file { $paths: ensure  => directory  } }` to declare a parent multiple times. If the resource has not been declared, it gets declared; else, nothing happens.
Comment: @MikePurcell I've updated my answer for your new question.
Comment: Thanks for the additional info. It's unfortunate that puppet has this type of restriction, where it's not easy to ensure that a parent directory is available to multiple, shared child directories. Never liked using apis that dictated implementation. However it's far better than having to write shell scripts to do the same.


Korolyuk's theorem and a set theoretical proof

Question: I am looking at Stochastic Processes by Ross. In the middle of proving the Korolyuk's theorem, he said that (the successive symbols mean the intersection, and the bar means the complement):
$$A_k \overline{B_n} = \bigcup_{j=0}^{n-1} C_{nkj} \overline{B_n},$$ where

$A_k=\{N(1) > k\}$,
$B_{nj} = \{ N(\frac{j+1}{n}) - N(\frac{j}{n}) \geq 2\}$,
$B_n = \bigcup_{j=0}^{n-1} B_{nj}$,
$C_{nkj} = \{ N(\frac{j+1}{n}) - N(\frac{j}{n}) \geq 1, N(1) - N(\frac{j+1}{n}) = k \}$;

$\{N(t), t \leq 0 \}$ is a counting process.
But, I can't understand how we can say the equality of $A_k \overline{B_n} = \bigcup_{j=0}^{n-1} C_{nkj} \overline{B_n}$. It is hard for me to deal with something like these large sets.
Could you please explain this? Thanks!
Comment: What is $B_n$? You only seem to define $B_{nj}$?
Comment: @martini Sorry. I added the definition of $B_n$.
Comment: You mean $t\ge 0$, right? And do we have $N(0) = 0$ a. s.?
Answer: The event $\overline{B_n}$ means that between points $k/n$, there are no jumps greater than $1$; in other words, all jumps are equal to $1$. Now look at the first jump, occurring between $j/n$ and $(j+1)/n$, say. Then $N(j/n) = 0$, $N((j+1)/n) = 1$, so $N(1)>k$ is equivalent to $N(1) - N((j+1)/n)\ge k$, which, combined with $N(j/n) = 0$ and $N((j+1)/n) = 1$ is exactly $C_{nkj}$.


One-to-many table setup

Question: I have a table where I have to relate groups of primary keys to one another. There is no information about these groups other than that they exist. Specifically, I am storing groups of Editions of Books together, so I can know that a certain set of books are editions of each other.
I currently have a setup where I have an Edition_Group_ISBN column, where one of the ISBN's is arbitrarily chosen to group a set of Editions together.
The typical approach for this problem is to have a separate table like Book_Editions, where I would have an autoincrementing integer primary key like "Edition_Group_ID" linking ISBNs together. I have been told this method is preferable.
However, the problem with implementing that system relates to the loading in of data. How am I to dynamically load in Edition Groups? One solution might be to lock the table and do a transaction on the next ID in the autoincrement. I imagine this would be slower and more cumbersome than my current method, though.
Given the difficulty of inserting data under that system, what is the optimal system to address this problem?
Comment: How (and when in your process) do you determine which books are related to one another?
Comment: Whenever a user searches for books (either by ISBN, Title, author, or some other way)
Answer: You load in Edition Groups by having an ISBN table foreign key in your Edition Groups table, and then inner-joining your two tables together in your query, using the Primary Key of your ISBN Books table, and the Foreign Key of your Edition Groups table in the join.
ISBN Table
    ISBN_ID                                    // Auto-incrementing Primary Key
    ISBN
    Book_Title
    .etc

EDITIONS Table
    Edition_ID
    FIRST_EDITION_ISBN_ID
    ASSOCIATED_ISBN_ID                         // Foreign Key to ISBN table

Most database systems have a way to return the Primary Key ID of a newly inserted record, so:
NEW_ID = INSERT INTO ISBN (ISBN, BOOK_TITLE)
         VALUES (12345678, "The Frog Prince");
         SELECT SCOPE_IDENTITY();              // Returns new ID from ISBN table.

INSERT INTO EDITIONS (FIRST_EDITION_ISBN_ID, ASSOCIATED_ISBN_ID)
    VALUES (12345678, NEW_ID);

Comment: Can you give an example of the INSERT query?
Comment: In MySQL, the equivelant of SCOPE_IDENTITY() is LAST_INSERT_ID().  Would that function work to dynamically add data?  Would I need to lock the table so no new ID's are isnerted between queries? Not sure how to setup the query...
Comment: Also, one question about your table setup.  Why is Edition_ID necessary?  Why not just make  (FIRST_EDITION_ISBN_ID and    ASSOCIATED_ISBN_ID) the primary key?
Comment: Edition_ID is there because it's good practice to put a Primary Key in every table, and I dislike composite primary keys (how do you join them to other tables?).  But, to each his own.
Comment: You don't need to lock any tables; you just need a reliable way to get the new ID into a variable, so that it is stable (`LAST_INSERT_ID()` sounds like the correct way to do it in MySQL).  Your MySQL documentation will tell you how to do this safely.  Once you have that, you can run the second INSERT.

One-to-many table setup


Storing user data securely in Flutter and Dart

Question: Suppose I have a notes app where I need to store user's notes securely. Can I store the notes in a plaintext format in an sqlite database? Or should they be encrypted locally as well?
Also should I encrypt it before I send it to the Firestore database? I've looked into the encrypt package but it's difficult to understand. Are there any good tutorials for this?
If I should encrypt, what type of encryption should I use?
Answer: Consider the usage of hive, which is a very popular NoSQL database for Dart and Flutter which automatically does a strong encryption of the data.
It's also used by the hydrated_bloc for example and other packages.

In general, you shouldn't implement encryption/decryption logic by yourself. Use well-known libraries (such as hive) which just does the work for you.
Comment: If you mean "secure = encrypted" then no, sqlite databases are not automatically encrypted. You still need to entrypt data by yourself
Comment: Hi I'm wondering about data being sent off device for example to Firestore
Comment: You don't need to send encrypted notes via Firestore since it's already a secure HTTPS connection. It's already encrypted by construction. You shouldn't store passwords in clear so sending encrypted passwords is generally the best thing to do. Ok, Firestore "is safe" but still you shouldn't store sensible data in clear.
Comment: That's good to know! I'm not sending any passwords. And other than Hive are sqlite databases generally secure?
Comment: Is it necessary to encrypt non sensitive data stored in sqlite databases?
Comment: Yes. With SQLite you should use something to encrypt your passwords (MD5, SHA-1...) but you have to look for a reliable one.
Comment: So even non sensitive information stored in an sqlite database should be secured with a password?
Comment: It depends on you, there is not a general rule. Passwords for sure shouldn't be in clear but the rest, it depends
Comment: Where would I store the encryption key for the hive, isn't that just moving the problem? With the key and the hive storage dumped the data is accessible. I know data is stored securely by apps out there so it should be possible but I'm not sure how that is
Answer: I dont think you need to encrpyt before you send it to firestore.. As long as you set your firestore rules well it would be ok
Comment: But I can see their data as the admin...isn't that unsafe?
Comment: you can block everyone including yourself
Comment: Oh wow, I didn't know that! And do I need to encrypt the data stored in sqlite databases on device?
Comment: yh its pretty easy should i give you a link where you can learn more about rules
Comment: https://fireship.io/snippets/firestore-rules-recipes/
Comment: Thanks! And do I need to encrypt the data stored in sqlite databases on device?
Comment: please can you upvote my answer.. Well i dont think so .. You can just put an extra layer of security. Like a password page.. Which is really easier
Comment: thanks if you need help with a password page i can help
Comment: Thanks, I have a password page
Answer: I guess including encryption depends on the type of data you're storing. Whether it is sensitive etc. same yada yada rules apply even in flutter. Like you should encrypt passwords etc.
I you're going for encryption I highly suggest to encrypt the data even using dart before sending it to firebase or as some http request/response.
Check out this package-
flutter_string_encryption
xxtea


Joint and conditional distributions of multiple variables

Question: If I have three random variables $X, Y$ and  $Z$ where $Y$ and $Z$ are independent. Is it true that $P(X,Y,Z)=P(X,Y)P(X,Z)$? What about $P(X\vert Y,Z)=P(X\vert Y)P(X\vert Z)$?
Answer: No. Just consider $X$ independent from both $Y$ and $Z$, then
$$P(X,Y,Z) = P(X)P(Y)P(Z)$$
$$P(X,Y)P(X,Z) = P(X)^2P(Y)P(Z).$$
These are only equal if $X$ is constant.
For the second question, still considering independent $X$,
$$P(X|Y,Z) = P(X)$$
$$P(X|Y)P(X|Z) = P(X)^2,$$
which, as before, are only equal if $X$ is constant.
The inference that you can make from your assumptions is
$$P(X,Y,Z) = P(Y,Z)P(X|Y,Z) = P(Y)P(Z)P(X|Y,Z).$$
Comment: Hi Filipos, thanks for your answer. But what is it like if X is not independent to both Y and Z?
Comment: Consider $X = (Y, Z)$. We get $P(X)\delta_{X, (Y, Z)}$ versus $P(X)^2\delta_{X, (Y, Z)}$ in the first questions and $\delta_{X, (Y, Z)}$ versus $P(X)\delta_{X, (Y, Z)}$ in the second one.


Drupal update domain whitelist

Question: I'm working on a Drupal project that will live on a locked-down webserver. The internet access on that box is constrained by a domain whitelist so I need to be able to provide a complete list of the domains that are needed for Drupal to update itself and its modules.
We're using Acquia-Drupal so we'll certainly the following to be able to update Drupal itself:
git.acquia.com

I ran a drush update while listening with netstat -t -u -c to try and get a feel for which domains are needed. This raised the following:
*.drupal.org  (obviously)
ec2-174-129-202-133

The latter seems to be an AWS domain.
I realise it may depend on the modules to some extent, but is there a definitive (and unchanging) list of domains that are required to update Drupal's modules?
I'm particularly concerned that if I start getting into AWS domains, they will change down the line, breaking our update path!
Comment: @kiamlaluno Why edit out my thanks to people for taking the time to read (and hopefully answer) my question?! Stack Exchange sites are all about their communities and speaking in a friendly and approachable way makes everyone's time here more pleasant.
Answer: The whitelist that we used (which seems to work fine) is as follows:
master.drupal.org
master2.drupal.org
ftp.drupal.org
ftp-osl.osuosl.org
git.acquia.com  <-- we are using this repo for Drupal core, you may not need it

They may not all be needed, ftp-osl.osuosl.org in particular may be required by another part of our stack, but this represents a working list of required domains.

Drupal update domain whitelist


How to give boolean value in @Container in spring data cosmos?

Question: In the below code, I am not able to set autoScale from the configuration property. I am getting errors as "expected boolean but the string is supplied".
@Container(containerName = "${dynamic.container.name}"
        , autoScale = "${dynamic.container.autoScale}", ru = "400")
public class FruitsContainer(){
.....
}

Kindly let me know how can I achieve this?
Answer: Simple entities are defined in Cosmos DB as items. And we can do so by adding the @Container annotation and specifying properties related to the container, like container name, request units (RUs), time to live, auto scale and so on.

Annotation  @Container(containerName="myContainer")  specifies container name in Azure Cosmos DB.

And by default request units (RUs) assigned to newly created containers is 400. But we can change it to customize it according to our need.

Lastly, annotation autoScale field describes that container to be created with autoscale throughput when set to true. Check this Microsoft Document for more information on autoscale.

If you check Creating Containers with autoscale throughput, you will find that you can achieve what you want using the following snippet-
@Container(containerName = "${dynamic.container.name}"
        , autoScale = true, ru = "400")
public class FruitsContainer(){
.....
}

Comment: Yes... Thank you, But how can change autoscale value based on environmental configuration?
Comment: `autoScale` field in the @Container only takes **Boolean Values**. By default it is **false**, which means containers are created with **manual throughput**.
Comment: yes, I want to control that per environment. ie in one environment I need to have autoscale enabled and in another, it should be manual.