Showing derivative operator is self-adjoint

Question: Consider the Hilbert space $L^2(\mathbb{R})$, and unbounded operator $Au:=iu'$ with domain
$$D(A)= \{u \in L^2(\mathbb{R}) | u \text{ is absolutely continuous and } u' \in L^2(\mathbb{R})\} $$
I'm showing that it's self-adjoint. It's not hard to show that it's symmetric, and suffice to show that $D(A^*) \subseteq D(A)$, which I don't know how to deal with.
Any help will be appreciated.
Comment: Isn't $u'\in L^2(\mathbb{R})$ enough to ensure absolute continuity of $u$? Why is that a separate assumption?
Answer: Let $u\in D(A^\ast)$. For all $\phi\in C_c^\infty(\mathbb{R})$ we have
$$
\langle A^\ast u,\phi\rangle=\langle u,A\phi\rangle=-i\int u\phi'=i\langle u',\phi\rangle,
$$
where $u'$ is the distributional derivative of $u$.
Thus
$$
|\langle u',\phi\rangle|=|\langle A^\ast u,\phi\rangle|\leq \|A^\ast u\|_2\|\phi\|_2.
$$
Hence $u'\in L^2(\mathbb{R})$ by the Riesz representation theorem.
Now let
$$
\tilde u(x)=\int_0^x u'(y)\,dy.
$$
This function is absolutely continuous and has weak derivative $u'$. It follows that there exists a constant $C\in\mathbb{R}$ such that $u=\tilde u+C$ a.e. as explained here.
Comment: I have one more question, $u=u^~+C$ doesn't mean $u$ is square integrable if $C$ is arbitrary, does it?
Comment: In this part I only showed that if the weak derivative of $u$ is square-integrable, then $u$ is absolutely continuous. But the domain of $A^\ast$ is by definition contained in $L^2$, so $u$ must be square-integrable.
Comment: Got it! Thanks you!
Answer: On the Hermite Function basis, $A$ is a tri-diagonal matrix
$$const \times
\begin{bmatrix}
0 & -i\sqrt{1} & 0 & 0 & 0 & \cdots \\
i\sqrt{1} & 0 & -i\sqrt{2} & 0 & 0 & \cdots \\
0 & i\sqrt{2} & 0 & -i\sqrt{3} & 0 & \cdots \\
0 & 0 & i\sqrt{3} & 0 & -i\sqrt{4} & \cdots\\
\vdots & \vdots & \vdots & \vdots & \vdots & \ddots \\
\end{bmatrix}$$
(Wikipedia).
Since the off-diagonal elements are  $\mathscr O(\sqrt n)$,
by Carleman's test $A$ is essentially self-adjoint on the span of the Hermite Functions. Since the Hermite Functions are complete, $A$ is essentially self-adjoint on the larger domain.
Comment: I'm not so familiar with quantum mechanics, but thanks your work!
Comment: I also need to prove that A on your domain is closed or maximal symmetric.
Comment: @milkysausage The tri-diagonal form of the matrix comes from the three-term recurrence relation for the  Hermite Functions. No QM needed!
Answer: Suppose $v\in\mathcal{D}(A^*)$. Then there exists $w\in L^2(\mathbb{R})$ such that, for all $u\in\mathcal{D}(A)$, one has
$$
           \int_{-\infty}^{\infty} (Au)vdx=\int_{-\infty}^{\infty}uwdx.
$$
Information about $w$ is obtained by choosing specific $u \in \mathcal{D}(A)$. For example, let
$$
         u_{a,b,\epsilon,\delta}=\int_{-\infty}^{x}\frac{1}{\epsilon}\chi_{[a-\epsilon,a]}(t)-\frac{1}{\epsilon}\chi_{[b,b+\delta]}(t)dt.
$$
This function is $0$ for $x < a-\epsilon$ and $0$ for $x > b+\delta$. It is $1$ in $[a,b]$, and it is linear on $[a-\epsilon,a]$ and on $[b,b+\delta]$. $u_{a,b,\epsilon,\delta}\in\mathcal{D}(A)$. So, the first equation applied with $u=u_{a,b,\epsilon}$ gives
$$
       \frac{1}{\epsilon}\int_{a-\epsilon}^{a}vdx-\frac{1}{\epsilon}\int_{b}^{b+\delta}vdx=\int_{-\infty}^{\infty}u_{a,b,\epsilon,\delta}wdx
$$
The limit as $\epsilon\downarrow 0$ exists, because it exists on the right. Similarly the limit as $\delta\downarrow 0$ exists. It follows that the following holds for almost all $a,b\in\mathbb{R}$:
$$
              v(a)-v(b)=\int_{a}^{b}w(x)dx
$$
Therefore, $v$ is equal a.e. to an absolutely continuous function that is in $L^2$ with a derivative $v'=w\in L^2$. So $v\in\mathcal{D}(A)$. In other words $\mathcal{D}(A^*)\subseteq\mathcal{D}(A)$. The opposite inclusion follows directly using the symmetry of $A$.


Let $f($z$)= \sum _{n=0}^{\infty } a_nz^n$ be the power series expansion of f about $0$. Prove that $|a_n| \le (n+1)(1+1/n)^{n} < e(n+1)$

Question: Suppose that $f$ is analytic in the unit disc D = {$z \in \mathbb{C}$ : |$z$| < 1} and $|$f($z$)$| \le 1/(1-|$z$|)$ for all $z\in D$.
Let $f($z$)= \sum _{n=0}^{\infty } a_nz^n$ be the power series expansion of f about $0$.
Prove that $$|a_n| \le (n+1)(1+1/n)^{n} < e(n+1)$$
Comment: I've been working on this problem for a while now, but can't seem to get anywhere.  I've tried expressing 1/(1-$|$z$|$ as the geometric series $\sum _{n=0}^{\infty} |z|^n$ and writing $|f($z$)|= \sum _{n=0}^{\infty } |a_n||z|^n$ $\le$ $\sum _{n=0}^{\infty} |z|^n$
Comment: Also, I know that $$e=\lim_{n \to \infty} (1 + 1/n)^n.$$ My approach was to prove the $\le$ inequality first and then use this fact to show the last inequality
Comment: Please avoid using `$$` in titles.
Comment: k, thanks. sorry!
Comment: The second inequality is really easy, use $(1+\frac{1}{n})^n <e<(1+\frac{1}{n})^{n+1}$
Comment: @matt No reason to apologize. It is just a matter of not making some questions pop "off" in main.
Answer: Here are some hints.

Cauchy's theorem can help you recover $a_n$ from $f$.
Use the inequality $|\int f| \leq \int |f|$
What is the minimum of $\frac{1}{z^{n+1}(1-z)}$ when $z\in (0,1)$?
Answer: Recall that Cauchy integral formula gives us
$$
a_n=
\frac{1}{2\pi i}\int\limits_{\partial B(0,r)}\frac{f(z)}{z^{n+1}}dz
\frac{1}{2\pi i}\int\limits_{0}^{2\pi}\frac{f(r e^{it})}{(re^{it})^{n+1}}d(r e^{it})=
\frac{1}{2\pi}\int\limits_{0}^{2\pi}\frac{f(r e^{it})}{r^n e^{int}}dt
$$
hence
$$
|a_n|\leq
\frac{1}{2\pi}\int\limits_{0}^{2\pi}\frac{|f(r e^{it})|}{r^n |e^{int}|}dt\leq
\frac{1}{2\pi}\int\limits_{0}^{2\pi}\frac{dt}{r^n (1-|r e^{it}|)}=
\frac{1}{r^n (1-r)}
$$
As the consequence
$$
a_n\leq\min\limits_{r\in(0,1)}\frac{1}{r^n (1-r)}=(n+1)\left(1+\frac{1}{n}\right)^n
$$
I suggest you to fill the gaps.
Comment: sorry, i'm still not sure how you get the equality on the right hand side of $$a_n\leq\min\limits_{r\in(0,1)}\frac{1}{r^n (1-r)}=(n+1)\left(1+\frac{1}{n}\right)^n$$
Comment: use calculus to find point of minimum. Find derivative, find stationary points, substitute into the function


Need function for 2D sigmoid-shaped monotonic Surface

Question: I am looking for a 2D function, $f(x, y)$ which increases monotonically over the range $(0,0)$ to $(1,1)$.  In other words, it will be $0$ at $(0,0)$ and $1$ at $(1,1)$.  It will also evaluate to $0$ whenever $x = 0$ or $y = 0$.  It's monotonic in the sense that the value at $(0.5,0.6)$ will be greater than at $(0.5, 0.5)$.  The closest guess that I have to the function that I am looking for is:
<code>Plot3D[1/((1+e^(-x*y))),{x,0,1},{y,0,1}]
</code>
But I would also like to be able to "bias" or make the function rise faster with $x$ relative to $y$ or vice-versa.  Ideally, I would like to specify the surface with 2 variables.  One that controls / scales how $f(x,y)$ rises relative to $x$, and another that controls / scales how $f(x,y)$ rises relative to $y$.
Edit:
I am looking for a sigmoid-shaped curve.  The function does not need to be exactly equal to 1 at $z(1,1)$. However, $z(1,1)$ needs to be higher than any other $z(x,y)$ across the space $x[0:1], y[0:1]$.  A closer function than the one above is:
$$z=1/\left(1+e^{-(x^a*y^b)}\right),$$
where $a$ and $b$ are used to "bias" or change the slope of the curve with respect to $x$ vs. $y$.  However, that curve is close to 1 at $z(2,2)$ instead of $z(1,1)$.  So $x$ and $y$ need to be scaled.  Those scaling factors will be a function of $a$ and $b$.  They cannot be computed directly since the exponent needs to be 0 to satisfy the equation exactly.   However, if the exponent evaluates to a sufficiently small number, such as $0.01$, that should be close enough for my purposes.
Answer: Here's a simple example: $f(x,y)=xy$.  You can change the powers of $x$ and $y$ to 'bias' one of $x$ or $y$.
Here's another function that is "sigmoid-shaped" and is close to your required values, as per your comments:
$$f(x,y)=\left( \frac{1}{1+e^{-100x+50}}\right)\left( \frac{1}{1+e^{-100y+50}}\right)$$
This is approximately $0$ at $(0,0)$ and $1$ and $(1,1)$, and is sigmoid-shaped in the sense that when either $x=1$ or $y=1$ the resulting slice of the 3D-plot is a sigmoid, as seen here:

Theoretically, you could also make this exactly equal to $1$ at $(1,1)$ and $0$ at $(0,0)$ by multiplying by a constant and changing the values of $50$ in the exponents appropriately to ensure that the function went through the points $(0,0,0)$ and $(1,1,1)$.
Comment: That fits my original requirements, but is there another function that also fits the requirements, but has more of a sigmoid shape?  For example, z=1/(1+e^(-x^a*y^b)) might be the function that I am looking for, but how do I make it == 1 when x = 1, y = 1?  The multiplier constant should be a function of a and b, but not sure how to compute it.
Comment: Your function won't ever be able to equal to 1 when $x=y=1$ because $e^w$ is never zero, which would be necessary for you to have $z(1,1)=1$.  You should add that you want a "sigmoid-shaped curve" to your question.  You won't ever be able to get anything that is truly sigmoid-shaped that satisfies the other properties, simply because the horizontal asymptotes $y=0,1$ make this impossible.  However, I can give you something "close" if you want.
Comment: I should have mentioned that it does not have to exactly equal 1 at z(1,1).  But I would like z(1,1) to be higher than any other z(x,y) across the space x[0:1], y[0:1].  The function that I mentioned above, z=1/(1+e^(-x^a*y^b)), for example with a = 2 and b = 0.9 is approximately equal to 1 at x = 2, y = 2.  So z=1/(1+e^(-(x*2)^a*(y*2)^b)) is close enough to 1 at x = 1, y = 1 for a = 2 and b = 0.9.  The problem is that the x and y multiplers (which are both 2 in this case) change as a function of a and b.  What function did you have in mind that is "close"?
Comment: @PentiumPro200 I think that you should put in your question exactly what you want.
Comment: @PentiumPro200 see updated answer.
Comment: Thanks Hayden for your help.  That function suits my needs for now.
Answer: The following function may fit your need:
$$
\frac{1}{1+e^{-(x+y-1)*(a+b*(x-y)^2)}}
$$
when $a = 4, b = 16$, the function looks like this:

The following is its contour plot:

When $x=y, a=1$, the function degenerates to a simple sigmoid function
$\frac{1}{1+e^{-(x+y-1)}}$, which provides the basic required property of the function, such as $f(0, 0) \approx 0$, $f(1,1) \approx 1$.
Adding the term $a+b*(x-y)^2$ is to provide some control to the shape of the function to achieve $f(0, y) \approx 0$, $f(x,0) \approx 0$, $f(1, y) \approx 1$, $f(x,1) \approx 1$ etc.


Blocking traffic from specific TCP ports to other specific TCP ports using iptables

Question: I have a Linux system where I have multiple processes communicating with a master process via TCP ports. I need to create a scenario where I block all traffic from all ports of one particular process to the ports used by master process for communicating with that process.
Example:

PROCESS A master ports = 1012, 1013 ... 1015
PROCESS A ports = 2012, 2013 .. 2015

The rule I want to put in is traffic from all ports of PROCESS A (which I can find using netstat etc) destined towards Master process ports is blocked using iptables.
I looked around and found ways of dropping traffic destined to particular ports, but no luck in specifying the source ports.
Answer: It's pretty much the same as with destinations ports. If you used --dport for destination ports, you must also specify --sport for source port(s)
man iptables-extensions

   tcp
   These extensions can be used if  `--protocol  tcp'  is  specified.  It  provides  the  following
   options:

   [!] --source-port,--sport port[:port]
          Source port or port range specification. This can either be a service name or a port num‐
          ber. An inclusive range can also be specified, using the format first:last.  If the first
          port  is  omitted,  "0"  is  assumed; if the last is omitted, "65535" is assumed.  If the
          first port is greater than the second one they will be swapped.  The flag  --sport  is  a
          convenient alias for this option.

   ...

Comment: Thanks, however I could not solve the problem as the process that I blocked ports for, opened up new ports to the master process. I am looking to block all traffic from a particular process, up till kernel 2.6 they provided --pid-owner so that we can block out the traffic using pid, but they dont support that on newer kernels. Any ideas about that ? thanks.


AlarmManager triggering after 5 minutes and not at the desired time

Question: I am using an alarm manager to trigger an intent service every 40 seconds. The below code is how I am triggering the alarm and starting the service. I know that the alarm is not always triggered after 40 seconds exactly and may vary.
But I got a case where the alarm varied a lot and stayed constantly triggering EXACTLY every 5 minutes.
starting the alarm:
<code>Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long interval = 40000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
</code>
alarm receiver:
<code>@Override
public void onReceive(Context arg0, Intent arg1)
{
     globalVariables.DebugLogging("IsSignedIn: "+GlobalVariables.IsSignedIn+" -DownloadServiceCanStart:- "+GlobalVariables.DownloadServiceCanStart);
     if(GlobalVariables.IsSignedIn)
     {
          if (GlobalVariables.DownloadServiceCanStart)
          {
               GlobalVariables.DownloadServiceCanStart=false;
               Intent intent = new Intent(arg0, DownloadService.class);
               context.startService(intent);
          }
     }
}
</code>
Comment: anyone can help me with this?
Comment: It's an Android bug. I assume you have a Samsung device. A lot of this is manufacturer-dependent and Samsung seems to like to use 5 minute repeats. See https://code.google.com/p/android/issues/detail?id=211988&thanks=211988&ts=1464886635
Answer: The AlarmManager is not very precise.
As the official documentation states:

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS
  will shift alarms in order to minimize wakeups and battery use. There
  are new APIs to support applications which need strict delivery
  guarantees; see setWindow(int, long, long, PendingIntent) and
  setExact(int, long, PendingIntent). Applications whose
  targetSdkVersion is earlier than API 19 will continue to see the
  previous behavior in which all alarms are delivered exactly when
  requested.

There is also a minimum interval of 60 seconds. So your 40 second interval would be expanded to 60 seconds.
If you want to run something every 40 seconds exactly, you could investigate this answer:
https://stackoverflow.com/a/9539579/503508
Comment: ok thanks ill look into that, i know its not precise but it went to 5 minutes and then precisely every 5 minutes which i found strange.
Comment: This is a bug. See https://code.google.com/p/android/issues/detail?id=211988&thanks=211988&ts=1464886635
Comment: Also, the official documentation is WRONG. Even if you target API < 19, on most Android 5 and all Android 6 devices you don't get the specified behaviour. And it is very manufacturer-specific.


Ao clicar na paginação chama sempre a primeira div

Question: Tenho dois section na mesma página. Dentro de cada section tenho uma div, mas quando clico na paginação da segunda div retorna me sempre para a primeira div.
código:
<?php
require("conexao.php");

$itens_por_pagina = 10;

$itens_por_pagina1 = 10;

// pegar a pagina atual
$pagina = intval($_GET['pagina']);
if (!$pagina) {
$pc = "0";
} else {
$pc = $pagina;
}
$inicio = $pc - 0;
$inicio = $inicio * $itens_por_pagina;

$pagina1 = intval($_GET['pagina1']);
if (!$pagina1) {
$pc1 = "0";
} else {
$pc1 = $pagina1;
}
$inicio1 = $pc1 - 0;
$inicio1 = $inicio1 * $itens_por_pagina1;

$query = "SELECT Id, De, Assunto, Conteudo, Prioridade, TIME_FORMAT(Recebido,'%h:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador'
ORDER BY Recebido Desc LIMIT $inicio, $itens_por_pagina";

$query1 = "SELECT Id, De, Assunto, Conteudo, Prioridade, TIME_FORMAT(Recebido,'%h:%i') AS Hora, DATE(Recebido) AS Data,
 Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE Tipo = 'Geral' AND raddb.Alertas.Para = '$colaborador'  ORDER BY Recebido Desc LIMIT $inicio1, $itens_por_pagina1";

$result = $conn->query($query) or die($conn->error);
$result1 = $conn->query($query1) or die($conn->error);

$produto = $result->fetch_assoc();
$produto1 = $result1->fetch_assoc();

$num = $result->num_rows;
$num1 = $result1->num_rows;

$num_total = $conn->query("SELECT Id, De, Assunto, Conteudo, Prioridade, TIME_FORMAT(Recebido,'%h:%i') AS Hora, DATE(Recebido) AS Data,
Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE raddb.Alertas.Para = '$colaborador'
ORDER BY Recebido Desc")->num_rows;

$num_total1 = $conn->query("SELECT Id, De, Assunto, Conteudo, Prioridade, TIME_FORMAT(Recebido,'%h:%i') AS Hora, DATE(Recebido) AS Data,
 Email, Tipo, raddb.Alertas.Para, Status FROM raddb.Alertas LEFT OUTER JOIN raddb.ValAlertas
ON raddb.ValAlertas.IdSMS = raddb.Alertas.Id AND raddb.ValAlertas.Para = raddb.Alertas.Para
WHERE Tipo = 'Geral' AND raddb.Alertas.Para = '$colaborador'  ORDER BY Recebido Desc")->num_rows;

$num_paginas = ceil($num_total/$itens_por_pagina);

$num_paginas1 = ceil($num_total1/$itens_por_pagina1);

Agora as section e as div dentro da section:

Alerta Recebido

<?php if($num > 0){ ?>

            De
            Assunto
            Prioridade
            Recebido

    <?php

        do{

         if($nomede != $produto["De"]){
    ?>
        Recebido: <?php echo $produto["Data"]; ?>
    <?php
        $nomede = $produto["De"];
        }
   ?>

        <?php echo $produto["De"]; ?>
        <td class="td-info view_data apagar" id="<?php echo $produto["Id"]; ?>,<?php echo $produto["Para"]; ?>" data-toggle="modal" href="#dataModal" width="20%" <?php echo $produto["Status"] != '0'?' style="font-weight:bold; font-size: 90%" ':' style="font-weight:normal; font-size: 90%" '?>><?php echo $produto["Assunto"]; ?>
        <?php echo $produto["Prioridade"]; ?>
        <?php echo $produto["Hora"]; ?>

<?php } while($produto = $result->fetch_assoc()); ?>

«

<?php
for($i=0;$i<$num_paginas;$i++){
$estilo = "";
if($pc == $i)
$estilo = "class=\"active\"";
?>
<li <?php echo $estilo; ?> ><a href="?pagina=<?php echo $i; ?>"><?php echo $i+1; ?>

<?php } ?>

<a href="?pagina=<?php echo $num_paginas-1; ?>" aria-label="Next">
»

<?php } ?>

Alerta Geral

<?php if($num1 > 0){ ?>

            De
            Assunto
            Prioridade
            Recebido

    <?php
        do{

         if($nomede != $produto1["De"]){
    ?>
        Recebido: <?php echo $produto1["Data"]; ?>
    <?php
        $nomede = $produto1["De"];
        }
   ?>

            <?php echo $produto1["De"]; ?>
            <td class="td-info view_data1 apagar" id="<?php echo $produto1["Id"]; ?>,<?php echo $produto1["Para"]; ?>" data-toggle="modal" href="#dataModal1" width="20%" <?php echo $produto1["Status"] != '0'?' style="font-weight:bold; font-size: 90%" ':' style="font-weight:normal; font-size: 90%" '?>><?php echo $produto1["Assunto"]; ?>
            <?php echo $produto1["Prioridade"]; ?>
            <?php echo $produto1["Hora"]; ?>

<?php } while($produto1 = $result1->fetch_assoc()); ?>

«

<?php
for($i=0;$i<$num_paginas1;$i++){
$estilo = "";
if($pc1 == $i)
$estilo = "class=\"active\"";
?>
<li <?php echo $estilo; ?> ><a href="?pagina1=<?php echo $i; ?>"><?php echo $i+1; ?>

<?php } ?>

<a href="?pagina1=<?php echo $num_paginas1-1; ?>" aria-label="Next">
»

<?php } ?>

O problema estará no caminho onde faço Next ou Previous dentro de cada div.O problema está em atualizar sempre a página ao mudar de paginação, mas não estou a conseguir resolver
Só esqueci de mencionar uma coisa, eu troco de div com esse menu, será por causa disso que sempre que troco de paginação atualiza a página?

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-11" aria-expanded="false" style="float: left">
        Toggle navigation

      </button>

Alertas

              Caixa de entrada

Recebidas

Geral

Comment: Aqui , aparentemente aparece a numeração correta devido ao $i+1, e em "?pagina=" não há contagem+1, não seria isso?
Answer: Altera:
<li <?php echo $estilo; ?> ><a href="?pagina=<?php echo $i; ?>"><?php echo $i+1; ?>

Para:
<li <?php echo $estilo; ?> ><a href="?pagina=<?php echo $i+1; ?>"><?php echo $i+1; ?>

Pois a numeração do link não acompanha a numeração do número expresso na div.
Comment: apliquei a solução que apresentou mas continua com o mesmo resultado
Comment: o problema é que quando mude de paginação atualização a página e não devia, só devia de atualizar a div
Comment: https://chat.stackexchange.com/rooms/93700/paginacao


Random URLs return error code 500 instead of 404

Question: In my urls.py file, I've got the following :
def error_404(request): return render(request, 'shop/errors/404.html')
def error_500(request): return render(request, 'shop/errors/500.html')

handler404 = error_404
handler500 = error_500

However, when I enter random urls, like "mysite.com/lhazeglazd", a 500 error page is returned.
What is causing 500 errors from overriding my 404 errors ?
Answer: Your logs or the admin error email should give the reason for the 500 server error.
Note that you don't need custom 404 and 500 handlers in this case. The default handlers look for 404.html and 500.html by default, so you just need to move your templates up a couple of directories.
If you must have a custom 500 handler, note that it's not recommended to pass the request to render - if there's a problem with a context processor the error will reoccur when trying to render the 500 template.
Comment: You were right ! I removed the handlers and placed my `404.html` and `500.html` directly in `projectname/static/templates`, and things are working properly now !


Powershell: undelete messages removed by recipient policy

Question: A specific recipient policy was mistakenly applied to all mailboxes in our company.  I have changed the recipient policy to the correct one. I now need to restore (from delete items) all messages that that were affected by that recipient policy.
These users have many subfolders and I don't want to open outlook and use "recover deleted items" on each folder.
How can I recover deleted messages from all folders in a given mailbox?  Can I constrain it by date deleted?
Answer: Use the Search-Mailbox cmdlet to search for items deleted today, and copy them back.
NOTE: I haven't tested this yet, so please follow all three steps and make sure it acts as expected!
Perform a search on a Test Mailbox and review the output:
Get-Mailbox "Test Mailbox" | Search-Mailbox -SearchQuery 'modified:(today)' -SearchDumpsterOnly -EstimateResultOnly

Perform a search again on a Test Mailbox and verify that messages deleted today were moved back
Get-Mailbox "Test Mailbox" | Search-Mailbox -SearchQuery 'modified:(today)' -SearchDumpsterOnly

Perform the search on all mailboxes and emjoy!
Get-Mailbox | Search-Mailbox -SearchQuery 'modified:(today)' -SearchDumpsterOnly

I hope this helps :-)
Comment: Search-Mailbox does not support the modified property unfortunately


Define a relation on $Z$ by a~b if and only if $a=b(mod2)$ and $a=b(mod5)$. Show that ~ is an equivalence relation.

Question: The if and only if is throwing me off.  Would the first direction be to prove the two modular conditions hold if the relation is an equivalence relation? Furthermore, I'm having difficulty proving reflexivity, symmetry and transitivity with the modular arithmetic. Help?
Comment: It is a **definition** - you **can't prove it**.
Comment: @AnalysisStudent0414 Yes. You **define** a *relation*, then you have to prove that it is an **equivalence** relation.
Comment: ^what? You define the relation, then you have to prove the three equivalence properties
Comment: ...yes. And that's what OP is asking, apparently
Answer: It seems that there might be some confusion about what you're actually trying to prove; there are two parts here: The first is the definition of $\sim$, and the second is a claim about the properties of $\sim$. So by definition, we write
$$a \sim b$$
if $a \equiv b \mod 2$ and $a \equiv b \mod 5$, and we don't write $\sim$ in any other case.
Now the claim about $\sim$ is that it's an equivalence relation; there are three things to check in the definition of an equivalence relation:

Show that $a \sim a$ by noticing that $a \equiv a \mod 2$ and $a \equiv a \mod 5$.
Show that if $a \sim b$, then $b \sim a$; again, this is immediate from studying congruences.
Show that if $a \sim b$, then $b \sim c$. That is, assume that $a \equiv b$ both modulo $2$ and $5$, and that $b \equiv c$ both modulo $2$ and $5$, and try concluding that $a \equiv c \mod 2$ and $a \equiv c \mod 5$.
Comment: +1 The answer is fine and does not deserve the downvotes (probably part of the [recent massive serial downvoting)](http://meta.math.stackexchange.com/q/13756/242)
Answer: Hint: the relation can be viewed as $a=b \pmod{10}$
In fact $a=5z + b$, $a=2y + b$ implies $5z=2y$, so $z=2w$ (i.e. $z$ is even, they're integers) and so $a=10w+b$.
Answer: What you want to show is that ~ is reflexive, symmetric and transitive.
For reflexive, this amounts to showing that for any integer x, x~x i.e. $x=x$ (mod 2) and $x=x$ (mod 5). But this is clear, since any number is congruent to itself (mod 2) and (mod 5).
Symmetric: You need to show that for any integers x and y, that if x~y then y~x. That is, if $x = y$ (mod 2) and $x=y$ (mod 5), then $y=x$ (mod 2) and $y=x$ (mod 5). You should use the definition of modular equivalence here.
Transitive: You need to show that for any integers x, y, and z, that if x~y and y~z then x~z.


Errors coming after creating a new project in drools ECLIPSE IDE

Question: I added drools engine plugin into eclipse Kepler IDE.I set all preferences but it's giving errors in project folder.Please respond to me as soon as possible.
This is my exception
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    KnowledgeBase cannot be resolved to a type
    The method readKnowledgeBase() from the type DroolsTest refers to the missing type KnowledgeBase
    StatefulKnowledgeSession cannot be resolved to a type
    KnowledgeRuntimeLogger cannot be resolved to a type
    KnowledgeRuntimeLoggerFactory cannot be resolved
Comment: possible duplicate of [Errors coming after creating a new project in drools ECLIPSE IDE](http://stackoverflow.com/questions/23267760/errors-coming-after-creating-a-new-project-in-drools-eclipse-ide)
Answer: You need to download the Drools jars from http://drools.jboss.org/downloads.html. Download Drools Expert (first one in the list), unzip to a folder and add the jars to the project.
Alternatively, convert the project to Maven and add drools dependencies - http://mvnrepository.com/artifact/org.drools. You will probably only need drools-core to get started.
Answer: You need to add the downloaded jar (knowledge-api-5.3.0.Final.jar) to your project. it is worked for me. please see the below image to where to add jar in your project. Hope it will be helpfull for beginners.
Thansks
Screenshot of adding jar to drools project


Como posso refatorar essa mutation vuex?

Question: Eu tenho o seguinte cenário: eu estou manipulando o objeto namespaced questions, dentro dele existe list e news, quero criar um mutation que adicione um par chave valor nas questions dentro desses dois arrays.
Quero uma função genérica que saiba em qual dos dois arrays está, e altere aquela question específica.
const SET_TYPING_COMMENT = (state, question) => {
    state.list = [
        ...state.list.map(_question => {
            if (_question.id == question.id) {
                _question = { ..._question, typing: true };
            }
            return _question;
        })
    ];

    state.news = [
        ...state.news.map(_question => {
            if (_question.id == question.id) {
                _question = { ..._question, typing: true };
            }
            return _question;
        })
    ];
};

Answer: Podes fazer isso assim:
const changeQuestionState = (state, type, {id}, typing) => {
  return state[type].map(_question => {
    return {
      ..._question,
      typing: _question.id == id ? Boolean(typing): _question.typing
    };
  });
}

const SET_TYPING_COMMENT = (state, question) => {
  ['list', 'news'].forEach(type => {
    state[type] = changeQuestionState(state, type, question, true);
  });
};

A ideia é criar uma função que receba tudo o que precisa para retornar o array com o novo estado.
Podes também fazer o state.list = mais DRY com ['list', 'news'].forEach(type => {
Nota: Quando usas o .map() não precisas do operador spread, o .map() não muda a array original.

Se quiseres colocar essa nova função dentro do action não precisas de tantos argumentos...
const SET_TYPING_COMMENT = (state, question) => {
  ['list', 'news'].forEach(type => {
    state[type] = state[type].map(_question => {
      return {
        ..._question,
        typing: _question.id == question.id ? Boolean(typing) : _question.typing
      };
    });
  });
};


Showing that, for $|a|>3$ and $n\geq1$, the function $f(z)=e^z-az^n$ has exactly $n$ roots (all simple and different) in the open unit disc

Question:
Let $|a|>3$, $n\geq1$, $n\in\mathbb{N}$,
  then the function $$f(z)=e^z-az^n$$
  has exactly $n$ roots in the disc $\{z\mid|z|<1\}$, and that they are all simple.
Hint: look at $f(z)-f'(z)$

I am not sure how do I even approach proving existence of roots, rather then proving maybe that the function is not vanishing (and then it has logarithm, and root, but how do I show existence of n roots?)
I thought also of maybe using somehow Rouche's Theorem, since:
$$f(z)-f'(z)=az^{n-1}\cdot(n-z)$$
and from there, that showing that $f$ has $n$ roots in the disk.
Thank you!
Comment: Possible duplicate of [Show that if $a>e$, the equation $az^n=e^z$ admit $n$ roots in the unit disk - Rouché theorem](https://math.stackexchange.com/questions/1734959/show-that-if-ae-the-equation-azn-ez-admit-n-roots-in-the-unit-disk-r)
Answer: Proving existence of roots by using Rouché's Theorem is a good idea. Let $g(z)=az^n$ then for $|z|=1$,
$$|g(z)|=|a|>3>|e^z|=e^{\cos(t)}=|f(z)-g(z)|$$
where $t\in [0,2\pi)$.
What may we conclude?
Moreover if $|w|<1$ and $f(w)=e^w-aw^n=0$ then $w$ is NOT simple iff
$$0=f'(w)=e^w-anw^{n-1}=aw^{n-1}(w-n)$$
which holds iff $w=0$ which is not a root because $f(w)=1$. So $w$ is simple.
Answer: The fast way is with Rouche's Theorem.
Alternatively, set $f_t(z)=az^n-te^z$.
Observe that, $f_t(z)\ne 0$, for $|z|=1$, and $t\in [0,1]$, and that the
$$
g(t)=\frac{1}{2\pi i}\int_{|z|=1}\frac{f_t'(z)\,dz}{f_t(z)}=\text{number of roots of $f$ is $\{|z|<1\}$} \in \mathbb Z
$$
Meanwhile, $g$ is continuous on $[0,1]$, and hence constant. Thus
$$
\text{number of roots of $f$ is $\{|z|<1\}$}=\frac{1}{2\pi i}\int_{|z|=1}\frac{f'(z)\,dz}{f(z)}=g(1) \\=g(0)=\frac{1}{2\pi i}\int_{|z|=1}\frac{nz^{n-1}\,dz}{z^n}=n.
$$
Comment: Zeros and roots is the same thing, in Complex Analysis.
Comment: @user3708158 : If there is made a distinction, zeros are the zero-value points of a function, while roots are the solutions of an equation. In the arabic original the words for "(square, cubic,...) roots" and "solution" had the same abbreviation, and so Fibonacci in "Liber abaci" translated them the same, which is since traditional.
Comment: Why is $g(t)$ is the number of roots of f?
From the argument principle, g(t) is the number of zeros of f minus the number of poles in f (including their order). why is it equal to the number of roots?
Comment: Clearly, $f_t$ DOES NOT have any poles or other singularities in the disk, as it is entire analytic.
Comment: Yes, in this case it is equal to the number of zeros with their order. why is it the number of roots? (I know, I am confused with the definitions)


Erro ao usar MapPath 'http:/..is not a valid virtual path.'

Question: Estou tentando abrir um aquivo no page_load através de uma função RetornaCaminho() que retorna a URL do arquivo.
<code>reEditorContrato.Open(MapPath(RetornaCaminho(CodigoArquivo)))
</code>
obs: reEditorContrato é um controle ASPxRichEdit da DevExpress
A função me retorna  a string "http://localhost:51696/exemplo/contratos/Contrato.docx", mas no momento que ele vai abrir pelo MapPath ele me retorna um erro.
'http:/localhost:51696/exemplo/contratos/Contrato.docx' is not a valid virtual path.
Percebi que nessa parte http:/ ele retira uma barra e creio eu que é por esse motivo que o caminho da sempre inválido.
Alguma solução?
Comment: O erro deve estar em usar `MapPath`, retire ele. Deixe assim: `reEditorContrato.Open(RetornaCaminho(CodigoArquivo))`.
Comment: Já tentei dessa maneira, o método open não suporta esse tipo de formato "http...".
Answer: Bom, como pode ver neste link, o método MapPath só aceita caminhos físicos do servidor (o tal do virtual path na mensagem de erro). Neste caso, creio que você teria que passar seu caminho desta forma para a função: "/exemplo/contratos/Contrato.docx", ou seja, sem a parte do "http://...", isso explicaria o tratamento que ele faz removendo uma das barras do "http://".
Espero ter ajudado.
Qualquer dúvida estou a disposição!


Uso de STI(Single Table Inheritance) no Rails

Question:
Supondo um projeto no rails com os modelos Pecuária, Agricultura,
Piscicultura e Benfeitoria.
Sendo que estes herdam as propriedades de um modelo chamado Atividade
e são considerados tipos de Atividade.
Os modelos não precisão herdar métodos ou comportamentos específicos,
no caso apenas os de acesso as propriedades herdadas
Porém alguns modelos possuem propriedades além das herdadas e outros
não, por exemplo Agricultura , além das herdadas, possui as
propriedades GrupoAgricola e TipoDeAgricultura.

Tendo isto em mente vem minhas dúvidas:
 1ª É um cenário propício para o uso da técnica STI(Single Table Inheritance)?
 2ª No caso dos modelos que possuem apenas as propriedades herdadas, ha como evitar a criação de uma nova  tabela ou modelo de persistência?.
Comment: Já experimentou modelar com composição ao invés de Herança?
Answer: Se os modelos vão herdar um número considerável de atributos e vão implementar comportamento comum, sim, é uma boa opção.
Usando postgres 9.4 com rails 4.2 dá pra fazer de forma bem transparente.
Recomendo a leitura destes posts para uma idéia de como implementar:
https://netguru.co/blog/renewed-life-for-sti-with-postgresql-json-type
http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails
Comment: Não, nao é criadas tabelas para XA nem XB, todos modelos usam a mesma tabela.
Comment: Leia os links que passei na minha resposta, lá ensina a gravar os campos "extras" em uma campo json.
Comment: porém o fato de eu querer evitar que alguns tipos de atividades sejam persistidos, como devo fazer?, apenas não criar o Model correspondente mas incluir na lista de tipos, por exemplo 'def Atividade.tipos %w{Tipo1 Tipo2 Tipo3}' porém não criar o arquivo tipo3.rb?
Comment: Não entendi, pq não seriam persistidos?
Comment: Porque pelo oque eu entendi usando STI todas propriedades herdadas do 'Base' são salvas na tabela referente á base ex: o modelo X possui as propriedades x1, x2 e x3 os modelos XA e XB estendem X porém o modelo XA também possui as propriedades xa1, xa2 e xa3, e XB não possui nenhuma além. Contudo são criados 3 tabelas a tabela x com os campos (id, x1, x2 , x3, created_at e modified_at) a tabela xa com os campos (id, xa1, xa2 , xa3, reated_at e modified_at) e a tabela xb s com os campos (id, reated_at e modified_at). Porém não vejo a necessidade de criar xb


Otimizar a colisão entre as partículas

Question: Preciso otimizar ao máximo o algoritmo que faz a colisão entre as partículas, tem algo que possa ser feito para isso? E também pretendo adicionar uma imagem de background, é possível?
Segue código canvas.cpp:
canvas::canvas(QWidget *parent) :
QWidget(parent)
{
m_particulas.resize(20);

int n = m_particulas.size();
for(int i = 0 ; i<n ; ++i)
{
    m_particulas[i].init();
}

startTimer(10);
}

void canvas::paintEvent(QPaintEvent * event)
{
(void) event;

QPainter painter(this);
painter.setWindow(0,0,1000,1000);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap));
painter.setBrush(QBrush(Qt::darkCyan, Qt::SolidPattern));

int n = m_particulas.size();
for(int i = 0 ; i<n ; ++i)
{
    double x = m_particulas[i].x();
    double y = m_particulas[i].y();
    double L = m_particulas[i].r();
    painter.drawEllipse(QPointF(x, y), L, L);
}
}

void canvas::timerEvent(QTimerEvent *event)
{
(void) event;

int n = m_particulas.size();

for(int i = 0 ; i<n ; ++i)
{
    m_particulas[i].andar();
    Particula &pi = m_particulas[i];

    for(int j = 0 ; j < n ; ++j)
    {
        if (i == j) continue;

        Particula &pj = m_particulas[j];

        if (pi.testa_colisao(pj))
        {
            pi.calcula_colisao(pj);
        }
    }
pi.andar();
}
update();
}

particulas.cpp:
Particula::Particula()
{

}

void Particula::init()
{
m_r = 20;

m_x = 900.0*rand()/RAND_MAX + 50;
m_y = 900.0*rand()/RAND_MAX + 50;

m_vx = 2.0 * rand()/RAND_MAX - 1;
m_vy = 2.0 * rand()/RAND_MAX - 1;

double norma = sqrt(m_vx*m_vx + m_vy*m_vy);
m_vx /= norma;
m_vy /= norma;

}

void Particula::normaliza(double &vx, double &vy)
{
double norma = sqrt(vx*vx + vy*vy);
if (norma > 0)
{
    vx /= norma;
    vy /= norma;
}
}

bool Particula::testa_colisao (Particula &p)
{
    double dx = x() - p.x();
    double dy = y() - p.y();
    double dist = sqrt(dx*dx + dy*dy);
    return dist <= r() + p.r();
}

void Particula::calcula_colisao(Particula &p)
{
    double vx = p.x() - x();
    double vy = p.y() - y();
    normaliza(vx,vy);

    p.m_vx += vx;
    p.m_vy += vy;
    normaliza(p.m_vx,p.m_vy);

    m_vx -= vx;
    m_vy -= vy;
    normaliza(m_vx, m_vy);

    while (testa_colisao(p))
    {
        andar();
        p.andar();
    }
}

double Particula::x() const
{
return m_x;
}

double Particula::y() const
{
return m_y;
}

double Particula::r() const
{
return m_r;
}

void Particula::andar()
{
m_x += m_vx;
m_y += m_vy;

if(m_x > 1000-m_r) m_vx *= -1; //inferior - multiplicado por -1 para inverter a direção...
if(m_y > 1000-m_r) m_vy *= -1; //direita
if(m_x < 0+m_r) m_vx *= -1; //esquerda
if(m_y < 0+m_r) m_vy *= -1; //superior
}

Answer: Para uma otimização simples que não demande muita mudança no código, eu tenho três sugestões:

Você está testando todas as partículas contra todas as outras duas vezes (i.e. i de [0,n] vs j de [0,n]). Teste-as apenas uma vez:
for(int i = 0 ; i<n ; ++i)
{
    m_particulas[i].andar();
    Particula &pi = m_particulas[i];

    for(int j = i+1 ; j < n ; ++j)
    {
        //if (i == j) continue;

        Particula &pj = m_particulas[j];

Para isso ser possível, não faça a partícula andar depois de testar pela colisão. Em vez disso, mova todas as partículas primeiro, depois comece os testes (P.S. por que você está movendo cada partícula duas vezes?):
// Primeiro move
for (int i = 0 ; i < n ; i++ )
    m_particulas[i].andar();

// Depois testa
for(int i = 0 ; i<n ; ++i)
{
    Particula &pi = m_particulas[i];

    for(int j = i+1 ; j < n ; ++j) ...

O cálculo da raiz quadrada é muito mais lento que a multiplicação. Eleve a equação da distância inteira ao quadrado de modo a evitar esse cálculo:
bool Particula::testa_colisao (Particula &p)
{
    double dx = x() - p.x();
    double dy = y() - p.y();
    double dist2 = dx*dx + dy*dy;
    double somaRaios = r() + p.r()
    return dist2 <= somaRaios * somaRaios;
}

No calcula_colisao, faça a partícula andar pelo menos uma vez antes de testar de novo se há colisões (pois da primeira vez que executar, sempre retornará true):
...
normaliza(m_vx, m_vy);

do
{
    andar();
    p.andar();
} while (testa_colisao(p));

Isso deve evitar todo trabalho desnecessário no código atual. Com base nisso, podemos passar pras otimizações mais complexas, que envolvem refatorar o programa como um todo. Essa pergunta no SOen dá algumas sugestões promissoras:

Divida seu espaço em áreas menores, e faça o cálculo separadamente para cada uma dessas áreas. Por exemplo, se seu cenário é um quadrado de 100x100, crie 9 quadrados de 40x40 (com alguma interseção entre os quadrados, de modo que uma partícula muito perto da fronteira não deixe de ser testada contra o quadrado adjacente) e coloque cada partícula em um ou mais quadrados. Atualize isso a cada movimento (deve ser rápido, pois é só uma questão de comparar posições x e y - e se o número de sub-áreas for grande, pode-se fazer uma busca binária). Ao testar por colisões, considere somente as partículas que estão no mesmo quadrado.

Bônus: esse é um bom candidato para paralelização - crie um processo/thread separado para lidar com cada quadrado. Apenas tome cuidado para o overhead da gestão da concorrência não anular o benefício, essa técnica só vale a pena se o número de partículas for bastante grande.

Em vez de buscar por colisões a cada quadro da simulação, guarde em outra estrutura de dados as distâncias entre cada par de partículas dividido pela soma de suas velocidades. Esse valor corresponde ao número mínimo de quadros necessário para que exista uma chance dessas partículas colidirem. Se na hora de testar pela colisão esse valor for maior ou igual a 1, decremente-o e não faça o teste - pois com certeza retornará falso. Se for menor, faça o teste e atualize a previsão de colisão (que pode ter aumentado, diminuido, ou permanecido a mesma, dependendo das direções do movimento).

Nota: se seus quadros não têm duração fixa, adaptações podem ser necessárias.

Toda vez que uma partícula colidir com qualquer outra, sua velocidade pode aumentar. Você poderia recalcular essa matriz de previsões inteira [para essa partícula] sempre que isso acontecesse, mas imagino que seria por demais custoso. Uma aproximação razoável poderia ser simplesmente reduzir todos os valores proporcionalmente (ex.: a velocidade aumentou de 2 pra 3, divida todas as previsões de colisão em 1.5).

Essas técnicas podem ser combinadas (i.e. divida seu espaço em áreas menores, e faça a matriz de previsões para cada sub-área), e há outras mais sofisticadas a se considerar. Apenas tome o cuidado de pesar as vantagens/desvantagens de cada uma delas segundo o seu caso particular. Exemplos:

Se há muitas partículas em relação ao espaço, de modo que as colisões serão frequentes e localizadas, a estratégia 1 é mais interessante e a 2 desnecessária; divida seu espaço em bastantes sub-áreas, pois será raro uma partícula mover-se de uma área pra outra.
Se há poucas partículas em relação ao espaço, e elas se movem bastante rápido, a estratégia 1 é inútil (pois toda hora uma partícula mudará de sub-área) e a 2 mais interessante; mantenha a matriz de previsões ordenada, de modo que você não precise percorrê-la toda ao testar cada partícula.
Outros casos particulares vão ter diferentes impactos na melhor estratégia.

Otimizar a colisão entre as partículas


usando CAST no INNER

Question: Bom dia
estou tentando fazer um join mas da erro.

<code> string Query = "Select rec.chvbfj, rec.doc, vndB.chvvnd, vndB.chvps, ps.chvps, ps.Dsc " +
               "From (( " +
               "rec " +
               "inner join vndB " +
               "on vndB.chvvnda = cast(rec.doc as int)) " +
               "inner join ps " +
               "on ps.chvps = vndB.chvps)";
</code>
da o erro:

Falha de IErrorInfo.GetDescription com E_FAIL(0x80004005).'

rec.chvbfj numero
rec.doc texto
vndB.chvvnda numero
vndB.chvps numero
ps.chvps numero
ps.Dsc texto
Vou listar rec.chvbfj (3), resultado seria 3(3,4,5), formato texto, procuro na tabela vndB.chvnda(3,4,5), formato numerico, do campo chvps o resultado tem que sair da tabela ps campo Dsc o nome.
Comment: Tente utilizar ou a função CInt ou a CStr do Microsoft Access.
Comment: Tente remover os parenteses: Os dois depois do `From`, o segundo depois do `cast`, e o que está no fim da query e tente novamente.
Comment: Antes de usar verifique se é seu caso: [Suporte da Microsoft Hotfix E_FAIL(0x80004005)](https://support.microsoft.com/pt-br/help/921292/fix-you-may-receive-a-0x80004005-e-fail-error-message-when-you-use-a-r)
Answer: Com base no que você forneceu consegui fazer algo que talvez você precise!
obs: ignore as tabelas temporária!
<code>declare @rec table(chvbfj int, doc varchar(20))
insert into @rec values(1,'1')
insert into @rec values(2,'2')
insert into @rec values(3,'3')
insert into @rec values(3,'4')
insert into @rec values(3,'5')
insert into @rec values(4,'6')

declare @vndB table(chvvnda int, chvps int)
insert into @vndB values(3,1)
insert into @vndB values(4,1)
insert into @vndB values(5,2)

declare @ps table(chvps int, Descc text)
insert into @ps values(1,'escova')
insert into @ps values(1,'escova')
insert into @ps values(2,'lixa')

declare @rec_temp table(chvbfj int, doc int)
insert into @rec_temp(chvbfj,doc)
select * from @rec where doc in (3,4,5)

Select a.chvbfj, a.doc, b.chvvnda, b.chvps, c.chvps, c.Descc
               From
               @rec_temp A
               inner join @vndB B
               on b.chvvnda = a.doc
               inner join @ps C
               on c.chvps = b.chvps
</code>

usando CAST no INNER


Block with the same function as page of Taxonomy term view

Question: Is there any way to replicate as block which displays all nodes associated with the end of the url, like page view ( Taxonomy term view -A view to emulate Drupal core's handling of taxonomy/term.)  but in a block.
Example in url news/term1 the block should be able to show all nodes with the term term1.
Thank
Answer:
Set up a new view of type "node"
Give the view a "block" display (not a page)
In the "advanced" section of the view (on the right) create a relationship to "taxonomy term"
you can set up a "contextual filter" based on "taxonomy term".
The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
Go to admin->blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/* (this will work even though your term is aliased).
Comment: Works great, thank you for answering. Thank you very much.


Singular Values and Matrix Rank

Question: I came across this problem and I'm not sure if the proof I have found is OK. Any suggestions or confirmation of correctness would be appreciated.
The Problem:
Show that the number of non-zero singular values of a matrix $A$ coincides with its rank
My Approach:
We have an arbitrary matrix $A_{m\times n}$. For every eigenvector $v_i$ of the modulus $|A|$ of $A$ (where $|A|^2=A^*A$, $|A|$ being $n\times n$), and its corresponding eigenvalue $\lambda_i$ ($\forall i=1,\,2,\,...,\,n$), we have $(|A|-\lambda_i \mathbb{I}_n)v_i=0$. For every singular value $\sigma_i$ of $A$ equal to zero, the corresponding eigenvalue $\lambda_i$ of $|A|$ is also zero. Therefore, from the previous expression, for every $\sigma_i=0$, we have:
$$|A|v_i=0$$
So the problem comes down to solving this homogeneous system. Because $|A|$ is self-adjoint, there always exists a basis of eigenvectors of $|A|$, which means that the geometric multiplicity of any eigenvalue of $|A|$ is always equal to its algebraic multiplicity. Therefore, $ \dim Ker|A| = n-r$, where $r$ is the number of non-zero eigenvalues of $|A|$, and therefore also the number of non-zero singular values of $A$.
Using the well known equality, $\dim Ker|A|=n-\text{rank}|A|$, and the previous result, we have:
$$n-r=n-\text{rank}|A|\rightarrow r=\text{rank}|A|$$
From the definition of $|A|$, for any $x \in \mathbb{C}^n$:
$$\mid \mid |A|x \mid \mid^2 =(|A|x,\,|A|x)=(|A|^*|A|x,\,x)=(|A|^2x,\,x)=(A^*Ax,\,x)=(Ax,\,Ax)=\mid \mid Ax \mid \mid^2 \rightarrow$$
$$\rightarrow\mid \mid |A|x \mid \mid=\mid \mid Ax \mid \mid$$
This means $|A|x=0\Leftrightarrow Ax =0$, $\forall x \in \mathbb{C}^n$, so $KerA=Ker|A|$. Then:
$$\text{rank}A=n-\dim KerA=n-\dim Ker|A|=n-(n-\text{rank}|A|)=\text{rank}|A|$$
Therefore, as $\text{rank}|A|=\text{rank}A$, we have:
$$r=\text{rank}|A|=\text{rank}A$$
Therefore, the number of non-zero singular values of an arbitrary matrix $A_{m\times n}$ is equal to the rank of such matrix.
Comment: this is much too long.  Simply write $A=U \Sigma V^*$,  where $U$ and $V$ are chosen to be square (and hence invertible). Then $\text{rank}\big(A\big)= \text{rank}\big(U \Sigma V^*\big) = \text{rank}\big(\Sigma\big)$  and the rank of a (not necessarily square) diagonal matrix is given by its number of non-zero pivots -- the number of non-zero singular values.
Comment: Yes.  There are many ways to verify this. I happen to like inequalities.   If you know $\text{rank}\Big(BA\Big)\leq \text{rank}\Big(B\Big)$ then for invertible $A$, you have $\text{rank}\Big(B\Big) = \text{rank}\Big(BAA^{-1}\Big) \leq \text{rank}\Big(BA\Big)\leq \text{rank}\Big(B\Big)$ so right multiplication by an invertible matrix preserves rank.  As for left multiplication by an invertible matrix-- you can easily verify that an injective map preserves rank or note that row rank = col rank, then work with the transpose and re-run the above argument.
Comment: OK @user8675309 that looks much more doable. Thanks! Just one thing, the step $\text{rank}(U\Sigma V^*)=\text{rank}(\Sigma)$ comes from the fact that $U$ and $V^*$ are full rank, right? Then the only matrix that affects the rank of $A$ is $\Sigma$.
Comment: @user8675309 Thanks, that's exactly what I was after!
Answer: As mentioned by @user8675309, this is another possible approach:
The matrix $A$ can be decomposed with SVD in order to obtain $A=W \Sigma V^*$, with $W$ and $V^*$ being two square invertible matrices and $\Sigma$ being diagonal (with the singular values of $A$ in the diagonal), although not necessarily square. Then, $\text{rank}(A)=\text{rank}(W \Sigma V^*)=\text{rank}( \Sigma )$.
To prove $\text{rank}(W \Sigma V^*)=\text{rank}( \Sigma )$, we consider the case of two matrices $A$ and $B$, where $A$ is square invertible. Then, $\text{rank}(BA)\leq \text{rank}(B)$. Also, $\text{rank}(B)=\text{rank}(BAA^{-1})\leq \text{rank}(BA)\leq \text{rank}(B)$. Therefore, we have the expression:
$$\text{rank}(B)\leq \text{rank}(BA)\leq \text{rank}(B)$$
This means $\text{rank}(B)= \text{rank}(BA)$, so right multiplication by a square invertible matrix preserves rank. For left multiplication by square invertible matrices, we can take the transpose, because column rank is equal to row rank. We have:
$$\text{rank}(AB)=\text{rank}((AB)^T)=\text{rank}(B^TA^T)\leq \text{rank}(B^T)=\text{rank}(B)$$
Also, $$\text{rank}(B)=\text{rank}(B^T)=\text{rank}(B^TA^T(A^T)^{-1})\leq \text{rank}(B^TA^T)=\text{rank}((B^TA^T)^T)=\text{rank}(AB)\leq \text{rank}(B)$$
Therefore:
$$\text{rank}(B)\leq \text{rank}(AB)\leq \text{rank}(B)$$
This means $\text{rank}(B)= \text{rank}(AB)$, so left multiplication by a square invertible matrix also preserves rank.
The two previous results combined prove $\text{rank}(A)=\text{rank}(W \Sigma V^*)=\text{rank}( \Sigma )$.
Because the rank of $\Sigma$ is just the number $r$ of its nonzero rows (because it is diagonal), and $r$ coincides with the number of nonzero singular values, we can see that:
$$r=\text{rank}(A), \text{ where } r \text{ is the number of nonzero singular values of }A.$$

Singular Values and Matrix Rank


How to get application root path in Symfony 4 Console Command

Question: I have a simple Symfony 4 Console application.
In execute() method i need to print application root path.
This $this->getContainer()->get('kernel')->getRootDir() - don't work.
This $this->get('kernel')->getRootDir(); - don't work.
This $this->get('parameter_bag')->get('kernel.project_dir'); - don't work.
How can i get application root path?
Comment: what about passing it explicitly to the console command using https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service
Comment: `$this->get('kernel')->getProjectDir()` ?
Answer: I suggest not injecting container to the command but passing the param explicitly in service definition
src/Command
class YourCommand extends Command
{
    private $path;

    public function __construct(string $path)
    {
         $this->path = $path;
    }

    public function (InputInterface $input, OutputInterface $output)
    {
       echo $this->path;
    }
}

config/services.yaml
services:
    # ...

    App\Command\YourCommand:
        arguments:
            $path: '%kernel.project_dir%'

Comment: 1. The code is more readable, by looking at the dependencies you +- what the class do
2. The class is testable, you can mock the dependencies instead of mokcing whole container
3. Injecting Container is considered as bad practice
4. You'll be notifed about missing dependencies when container is complied.
5. Easier type hinting when you do $container->get('mailer') IDE has no idea what it is unless you use `@var Mailer` etc.

There are a lot more "for" using direct dependencies
Comment: why you suggest not injecting container to the symfony command?
Comment: `You probably forgot to call the parent constructor.`


MuMIn dredge gam error using default na.omit

Question: I have a global model I'm trying to dredge, but I keep getting the error "Error in dredge(myglobalmod, evaluate = TRUE, trace = 2) :
'global.model' uses 'na.action' = "na.omit"
I tried running the global model with na.action="na.omit" within the gam() call and leaving it out (since it's the default).
myglobalmod <- gam(response~ s(x1) + s(x2) + s(x3) + offset(x4), data=mydata, family="tw", na.action="na.omit")

options(na.action=na.omit)
mydredge <- dredge(myglobalmod, evaluate=TRUE, trace=2)

When I didn't include na.action="na.omit" within the gam, I got a similar error.
I then tried with a subset of the data that has all the NA rows removed, but same error.
I've gotten dredge to work before so I'm not sure why it doesn't like the na.omit now, I'm using the same code.
Comment: Unless this dredged model is going to be used for prediction, I would suggest instead using `gam(...., select = TRUE, method = "REML")` to do the model selection (for many reasons). Also, jus confirming that `x4` is already on the log scale? The link function for the Tweedie is `log()` so the offset needs to be on that scale too, i.e. `offset(log(x4))` assuming `x4` is in units of "effort".
Answer: MuMIn insists that you use na.action = na.fail, in order to ensure that the same data set is used for every model (if NA values were left in the data set, different subsets could be used for different models depending on which variables were used). You can use na.omit(mydata) or mydata[complete.cases(mydata), ] to get rid of NA values before you start (assuming that the NA values in your data set occur only in variables you will be using for the full model).
> library(MuMIn)
> m1 <- lm(mpg ~ ., data = mtcars)
> d0 <- dredge(m1)

Error in dredge(m1) :
'global.model''s 'na.action' argument is not set and options('na.action') is "na.omit"

> m1 <- lm(mpg ~ ., data = mtcars, na.action = na.fail)
> d1 <- dredge(m1)
Fixed term is "(Intercept)"


Content Types with field "clusters". Possible or is there a different solution?

Question: My dilemma is this. At the moment I have a content type called "equipment" that I want to have a taxonomy term that will give a type of equipment, based on the selected type I want a new "cluster" of fields and/or taxonomy terms to pop up.
There is likely a different/better way of organizing the data.  Creating a new content type for each type of equipment doesn't seem very elegant, especially if I want to create a view for all of the equipment.
Any leads on where I can find a solution to this? My brain has problems with decorator patterns in SQL as well.
Comment: If "elegant" is important factor, then there can't be objective answer to this question. Views shouldn't really be a problem.
Comment: It's not that important to me.  I am basically asking if there is any kind of standard for this.  As someone who is not yet working in software, I want to understand "best practices" when they are available.  Thanks!
Comment: See http://drupal.stackexchange.com/q/78364/16495
Answer: Probably the easiest solution is to have a single content type, add all fields that you need in any possible situation, and use Conditional Fields to hide/show fields based on the chosen equipment type taxonomy term.


big O for an algorithm

Question: I have a question about this algorithm, I am having hard time in understanding the complexity
    While(input) {
            ...
            array to check
            ...
           for (int i=0; i< arraysize; i++) {
                creation first subarray;
                creation second subarray;
           }

           for (int i=0; i < firstsubarraysize; i++) {
                 addinput to array;
                for( int j = 0; j < secondsubarraysize; j++) {
                   calculate array[j] * input;
             }
           }
   }// endwhile

So, considering input a M variable and the array is N, the big O would be O(m(nlogn)) or O(n2)?
The sub arrays are not always n\2.
I apologize If I'm not very clear.
Comment: What does "creation first subarray" do? We can't analyze the runtime without knowing this.
Comment: It creates a subarray with all numbers close to input (10 numbers before and after input). The second array is other numbers. That for is used to discard numbers that are not used. So both sub arrays are always smaller than the first one.
Answer: Generally, for each nested loop, you will have one N in the big O for time complexity.
Here assume the outer most loop while run M times, then there are two nested for inside of it. So the total is O(M N^2).
Comment: Important to keep in mind that big O targets the worst scenario, so if it can be worse, it is.
Comment: So, it does not matter if the two nested loops are running in less than N times (they are sub arrays always smaller than the original)?
Comment: OK, thank you. I thought it was n log n because of the sub arrays.
Comment: @JamX well, it could be n log n if there was more details about sub arrays suggesting that this a log based complexity. Otherwise, I assume that N times is a possibility.
Comment: The subarrays are 1) numbers close to input 2) numbers very smaller than input. There are always numbers discarded from the first array, building the sub arrays. The original array is not in order.
Comment: it is hard to guess in your case. but if the elements are not sorted, i would assume it is not log N
Comment: @CSPei The elements are not sorted in the original array. Thank you anyways, I know it's a bit unusual.

big O for an algorithm


Permutations where no partial sum is divisible by 3 (contest question)

Question:
A permutation of the integers $1901,1902\dots 2000$ is a sequence in which each of those integers appears exactly once. Given such a permutation, we form the sequence of partial sums
$$s_1 = a_1,\;\;s_2 = a_1 + a_2,\;\;s_3 = a_1 + a_2 +
a_3, \; \ldots\;, \; s_{100} = a_1 + a_2 + \cdots + a_{100}.
$$
  How many of these permutations will have no terms of the sequence
  divisible by three?

This problem is taken from the 2000 Canada National Olympiad.

Ignoring numbers divisible by $3$, in modulo $3$ the sequence must follow one of the following two patterns in order to skip all threes:

$1,1,2,1,2,\ldots$
$2,2,1,2,1,\ldots$

Doing a count of the various residues modulo $3$ in the set $\{1901,1902,1903,\ldots,2000\}$, we have:
$$N(0)=N(1)=33;N(2)=34$$
Hence, our sequence of non-zero residues must be $$2,2,1,\ldots,2,1 \tag{1}$$
There must be no numbers divisible by $3$ to the left of the first term in (1).
The number of independent ways of permuting the numbers in all residue classes is given by $$33!\,33!\,34!$$
but I am unsure of how to count the number of distinct patterns given by (1) once residue $0$ terms are admitted.
Comment: Does noticing that $|N(2)| = |N(1)| + 1$ help? This excludes some cases for you.
Comment: Wait, are the numbers all from the set $\{1901,1902\dots 2000\}$?
Comment: Yes. Each integer appears as exactly one $a_i$ in the permutation, as your solution assumes.
Comment: Yeah, thanks. Although in the first version I had assumed the numbers where $1,2,3\dots 100$.
Comment: @dREaM - My apologies. I don't know how the $1901,1902,\ldots,2000$ was lost. It was certainly in the original document I pasted from.
Comment: It's ok, it didn't change the problem much from how I had it initially.
Answer: First choose the positions for the multiples of $3$, the multiples of $3$ can be placed anywhere we want and they do not affect anything else, all that matters is the first position is not occupied by a multiple of $3$.
So we select the $\binom{99}{33}$ multiples of $3$ and permute them in $33!$ ways.
After this the real problem starts.
We have $34$ numbers that are $2\bmod 3$ and $33$ numbers that are $1\bmod 3$ and we must place them in a line (we can forget about the multiples of $3$).
We start by placing a $1$ or a $2$ (two options).
If we place a $1$ the next must be a $1$, and then a $2$ and then a $1$ and then a $2$ and so on... we get the sequence $1,1,2,1,2,1,2\dots$. This sequence always has more ones than $2$, so when we reach the $67$'th term we will have $34$ ones and $33$ twos, this is impossible.
If we start with a $2$ however, the next must be $2$, then $1$, then $2$ and so on.. so the sequence is $2,2,1,2,1,2\dots$. We must place $33$ ones and $34$ twos, this one is possible.
Hence there is only one way to select the places for the numbers $\bmod 3$.
So the only thing we can choose is how we permute the $1$'s and $2$'s internally. There are $33!\cdot 34!$ ways to do so.
Hence there are $\binom{99}{33}\cdot33!\cdot34!\cdot 33!$ ways in total.
Comment: Thanks. Of course, there are 99 positions in which the 33 multiples can be placed.
Comment: @dREaM Nope! Looks good to me :)
Comment: This is incorrect, well, sort of. At least based on the start of his solution's assumption :P
Comment: yeah, He hadn't said the numbers are $1901,1902\dots 2000$. I took them to be $1,2\dots 100$. I changed it accordingly. Or did you mean something else is wrong?


User registration form: Give username "username n+1" value, if and when n is already used

Question: I'm using the first & last name in the user registration form to generate the username for the new user:
<code>$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
if ($results_number == 0) {
    $form_state['values']['name'] = $username;
}
else {
    $i = 1;
    $username = $firstname.''.$lastname.''.$i;
    while ($results_number > 0) {
        $result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
        $results_number = $result->rowCount();
        $i++;
        $username = $firstname.''.$lastname.''.$i;
        $form_state['values']['name'] = $username;
    }
}
</code>
But I get an infinite loop. There is a problem with that while loop, any suggestions on the best way to fix that?
Comment: `rowCount()` wont work with `SELECT COUNT(*)`. And Drupal user name is unique. With out `LIKE` statement if you are fetching value with user name, always you will get Row Count value is 1.
Comment: the count part I understand, I must have missed it in some terrible way - the 2nd part should work though, $i is increased every time the number of results is > 0, no?
Answer: So here is what I used to increment the username's suffix by 1 if the initial value is not found:
<code>function increment_string($str, $separator, $first = 1) {
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

$username = $firstname . ' ' . $lastname;
$result = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
    if ($results_number == 0) {
        $form_state['values']['name'] = $username;
    }
    else {
    while ($results_number >= 1) {
        $username = increment_string($username_to_store, ' ');
        $result = db_query('SELECT uid FROM {users} WHERE name LIKE :name_pattern', array(':name_pattern' => db_like($username)));
        $results_number = $result->rowCount();
    }
    $form_state['values']['name'] = $username;
    }
</code>
Answer: Try below solution.
<code>$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT uid FROM {users} WHERE name like '$username%'");
$results_number = $result->rowCount();
if($results_number == 0){
  $form_state['values']['name'] = $username;
}else{
  $form_state['values']['name'] = $username.$results_number;
}
</code>
Comment: This solution fails when at least one user gets deleted from the system. e.g. we have username_1 and username_2 and username_3 and username_2 is deleted. Then the above fails.
Comment: `db_like()` should be instead used.


Do Organizational culture and social power bases interact to determine follower outcomes or should I study a moderation effect?

Question: I am writing my dissertation on the "Effects of Social Power Bases within Varying Organizational Culture."  I keep writing that I am looking at how organizational culture and social power bases will interact to determine follower outcomes of compliance and commitment.  However, I am confused as to whether I should actually be studying whether organizational culture is a moderator of the relationship between the power bases and the follower outcomes, which relationships have been widely studied in the literature.  Any advice you can give would be greatly appreciated.
Comment: While this is phrased in a way that looks like it's asking for an opinion about what you should study (which would be opinion based and thereby off-topic), at heart this turns out to be a question about explaining the connection between moderators and interaction - which is on-topic. [It would be useful if you could edit your question in a way that didn't appear to be calling for opinion on what you should study, but instead more directly asked a question about statistical issues.]
Answer: The statements
"$A$ is a moderator of the relationship between $B$ and $y$"
and
"There's an interaction between $A$ and $B$ in their relationship with $y$"
are effectively synonymous.
For example, see the second sentence in the Wikipedia article on moderation:

The effect of a moderating variable is characterized statistically as an interaction

The notion of moderation shouldn't be limited to simple linear interaction, but in practice that's almost always exactly how it's assessed.
So doing what you're doing is also studying whether organizational culture is a moderator of the relationship between the power bases and the follower outcomes.


how to replace string (with special characters) to normal string in vim

Question: Hi i am trying to replace a string with special character at the end with new string. For Example, I want to replace
qwerty_CRS_abc\

to
qwerty_CRS_abc

I tried with this:
:%s/qwerty_CRS_abc\/qwerty_CRS_abc/g

but I'm getting this error:
Pattern not found: padring_CRS_CAN\/padring_CRS_CAN\g

Basically, I just want to remove that backslash in whole file. It should be just
qwerty_CRS_abc

Comment: have you tried `:%s|qwerty_CRS_abc\\|qwerty_CRS_abc|g`
Answer: Use:
:%s/qwerty_CRS_abc\\/qwerty_CRS_abc/g
Certain characters such as  /&!.^*$\? carry a special significance to the search process and must be escaped using the \ character when they are used in a search. Hence the \\ used to escape the backslash in your example.


Associate Elastic IP to Interface or Instance?

Question: What advantages are there to pairing an Elastic IP (EIP) to an interface as opposed to the instance itself?
I see the point of the network interfaces - you can associate and disassociate them from/to instances on-demand without losing configuration. However, you could just as easily do the same for an Elastic IP without any kind of hindrance by disassociating it with the instance and associating it with the new one.
Answer: Network interfaces are exposed for many service you spin up within your VPC, this includes things like load balancers, databases along with normal EC2 instances.
Network interfaces can be considered the same as standalone Ethernet card in the real world.  When you move a network interface between machines it can keep its public, private and mac address.
Under normal circumstances assigning an EIP to an instance, is actually just assigning an EIP to that instances primary interface.  A primary interface is created automatically when creating an instance. [AWS Docs]
This does get a little more complicated when you include 'ec2-classic' mode, as these instances don't have the concept of network interfaces, as they are pre-vpc.  In this mode, EIP's are attached to the instance, not the interface. More details on the differences between the 3 'vpc modes'.
One other thing to note is that you can assign multiple interfaces to the same instance, so there will be some situations where you will need to explicitly search by interface, and not instance.
Comment: I think that's a mixture of two things.  Firstly, the search for which interface belongs to what instance, is somewhat difficult to use. Most people don't care about the interface only the instance.  Also AWS still supports 'ec2-classic', which is now mostly redundant.  When using AWS in 'ec2-classic' mode, there are no network interfaces, only instances.  The only time you will likely really need to use the 'network interface' option is when you attach multiple interfaces to a single instance.
Comment: When associating the Elastic IP, it asks you to choose the instance or the interface to attach to. I figure that AWS has designed it this way on purpose, for some benefit or another. If this were the case, wouldn't AWS just strictly offer you the ability to assign it to interfaces only?


Minimizing the length of a pipeline between cities

Question: I have been trying to minimize piping going to two different cities.  City A is located at $(0,4)$ and city B is located at $(6,3)$.  The cities must connect to the $x$-axis (the main pipe line.)  It is allowed to connect the piping from both cities to a middle point $M$ and then connect that point to the $x$-axis.
I've been able to set up a function giving length of the pipelines $f(x,y)$ using pythagorean theorem and adding up the three individual pipe lengths, and then minimizing numerically.  I've found trying to minimize exactly with derivatives yields high-powered polynomials, and I don't believe there's a general way to solve it.  Is there a more elegant way to find the minimum?
I have a friend who used a triangle center, I forget which one, to find the point, but he was not able to give me the coordinates this way.
Thanks for your help!
Answer: You are looking for the Fermat point, $M(x)$, of the triangle whose vertices are $A=(6,3)$, $B=(0,4)$, and $C=(x,0)$, and trying to minimize the value
$$d(x)=|AM|+|BM|+|CM|$$
According to this calculation, the acute angles between $\overline{AM},\overline{BM},$ and $\overline{CM}$ are all $\frac{2\pi}{3}$.  Appealing to intuition, we see that $d(x)$ will be minimized when $M(x)=(x,y)$, that is, when $M$ sits directly above $C=(x,0)$.  Using these two facts, we see that the Fermat point $M$ minimizing $d$ will be the intersection of the following two lines:
$$y=-\frac{x}{\sqrt{3}}+4\\y=\frac{x-6}{\sqrt{3}}+3$$
This is because these lines pass through the known points $A$ and $B$, and intersect each other and any vertical line at acute angles of $\frac{2\pi}{3}$.  Their intersection occurs at $M=(3+\frac{\sqrt{3}}{2},\frac{7}{2}-\sqrt{3})$.  Hence $C=(3+\frac{\sqrt{3}}{2},0)$, and a calculation shows that the minimum length of piping required is then
$$d(3+\frac{\sqrt{3}}{2})=\frac{7}{2}+3\sqrt{3}$$
Here is a picture illustrating our triangle, and the two lines given above, intersecting at the Fermat point:
$\hspace{1.75in}$
This problem is related to the Motorway problem, which can be solved using soap bubbles, as is discussed in this entertaining video.
Answer: Let the pipelines be $AM$, $BM$ and $MX$. Then the choice of $M$ and $X$ are such that $|AM|+|BM|+|MX|$ is minimized. So, by $M$ being the optimal choice, it must be the Fermat point of $ABX$, and since $X$ is the optimal choice on the $x$-axis, $MX$ must be vertical. So, then we get $\angle AMB = \angle BMX = \angle XMA = 120^\circ$ and $M$ and $X$ have the same $x$ coordinate. This is enough to find the points $M$ and $X$, as in Jared's answer.


Evaluate $\int _0^{\infty}d\lambda \left(\lambda ^2 + 2b\lambda + c\right)^{-\frac{\epsilon}{2}}$

Question: Evaluate $\int _0^{\infty}d\lambda \left(\lambda ^2 + 2\lambda b + c\right)^{-\frac{\epsilon}{2}}$ with $b<0,\epsilon>0$ and $\epsilon$ is very small $\epsilon\to 0$.
I see this in the book Heavy Quark Physics(the book, it is on Page.79).
The original integration is
$$-\left(\frac{4}{3}\right)g^2\mu^{\epsilon}\int \frac{d^nq}{(2\pi)^n}\frac{1}{(q^2-m^2)v\cdot (q+p)}$$
Where $q$ and $p$ are in Minkowski space that $q=(q_0,q_1,q_2,q_3),q^2=q_0^2-q_1^2-q_2^2-q_3^2$. After combine the denominator, Wick rotation and then use dimensional regularization,
$$n=4-\epsilon, \int\frac{d^n q}{(2\pi)^n}\to q^{3-\epsilon}\frac{2\pi^{\frac{4-\epsilon}{2}}}{\Gamma (\frac{4-\epsilon}{2})}\int d q$$
and some other calculations, finally, it becomes
$$-\left(\frac{8}{3}\right)g^2 \mu^{\epsilon}\int _0^{\infty}d\lambda \frac{i}{(4\pi)^{2-\frac{\epsilon}{2}}}\Gamma (\frac{\epsilon}{2})\left(\lambda ^2 - 2\lambda v\cdot p + m^2\right)^{-\frac{\epsilon}{2}}$$
In the book, it says, define
$$I(a,b,c)\equiv \int _0^{\infty} d\lambda \left(\lambda ^2 +2 b\lambda +c\right)^a=\frac{1}{1+2a}\left(\left(\lambda ^2 +2b\lambda +c\right)^a\left(\lambda +b\right)\left.\right|_{0}^{\infty}+2a(c-b^2)I(a-1,b,c)\right)$$
And
$$\int _0^{\infty}d\lambda \left(\lambda ^2 + 2\lambda b + c\right)^{-\frac{\epsilon}{2}}=\frac{1}{1-\epsilon}\left(\color{blue}{c^{-\frac{\epsilon}{2}}b}-\epsilon (c-b^2)\int _0^{\infty}d\lambda \left(\lambda ^2 + 2\lambda b + c\right)^{-1-\frac{\epsilon}{2}}\right)$$
I'm stucked by the first term, it says in dimensional regulation, as long as $z$ depends on $\epsilon$ in a way that allow one to analytically continue $z$ to negative values
$$\lim _{\substack{\lambda \to \infty}}\lambda ^z = 0$$
I really don't understand what does this mean.
In fact, I know some other method to evaluate the original integration, I just want to understand and learn the trick to evaluate $\int _0^{\infty}d\lambda \left(\lambda ^2 + 2b\lambda  + c\right)^{-\frac{\epsilon}{2}}$ here. I need help. Thanks for reading!
Comment: As far as I know the integral you want is non-elementary for non-integer values of $\epsilon$
Answer: It is answered here: https://physics.stackexchange.com/questions/239690/detail-of-a-trick-evaluating-hqet-self-energy/239970#239970 For those who are interested I also post the answer here. It turns out that I have a misunderstanding about the dimensional regulation(DR). DR does not mean to set the dimension $n$ to a number close to the real dimension $4$. Which means it is not necessary to require $\epsilon \to 0$ in $n=4-\epsilon$ when integral. It is only required at last. So one can use $\epsilon > 1$ to integral and vanish the $\lim _{\lambda\to\infty}\lambda ^z$ term, and then use $\epsilon \to 0$ in the final result.


How to get all the Test Case ID using User Story ID of Rally using API request

Question: Hi all I am creating a code where on entering a user story ID it will pass or fail all the TC's of the same using Java. But I cannot quite figure out how to approach and how to get the list of TC ID's from User Story ID. Any help will be much appreciated.
Answer: it sounds like you want to be using the Rally REST Toolkit for Java. Take a look at the ReadMe, you'll find links to the user guide, javadocs and examples there. Find an example that looks similar to what you want to achieve and start working on a solution.
At a high level, you'll want to first load the user story that fits the ID. Then from there you'll be able to load the collection of Test Cases associated with it. The Rally Web Services API will help you understand the story to test case relationship for querying.


Stratified sampling with replacement of participants in R

Question: I am wondering whether in R, there is a possibility to draw a stratified sample with replacement of participants. Often, in surveys, we need each group to have certain size. Hence if one respondent in group is not reachable, there are few other "replacements" to reach while keeping the "stratification" in mind.
So for example, if we need 10 people with attribute X and we know that the response rate is ~50%, we'd need another 5 respondents with attribute X as a backup.
EDIT
To clarify, by replacement of participants I mean to have large enough sample in each stratum when non responses are taken into account.
NOT the usual meaning of sampling with/without replacement.
Comment: Could you clarify your language a bit? Are you interested in sampling with replacement as opposed to sampling without replacement, or in drawing large enough of an initial sample to end up with enough respondents in each stratum taking into account nonresponse rate? These are different things. "Sampling with replacement" has a very specific meaning, and it does not mean "backup." It means roughly that after you select your first element, you replace it (put it back in the sampling frame), so that it has the same probability of being selected again.
Comment: I modified my question. Hope its clear now. I know it is somewhat confusing, but I don't know the official term used for this kind of sampling.
Comment: Great, now it's clear. I'm not sure it's a question about R per se, or at least that it's a different question from just "how to take a stratified sample." I also don't know of an "official term" for this kind of sampling, but I think that's because it's not a different kind of sampling. I'm pretty sure it's just a matter of taking some things into account. I'll add an answer with what I think your best option is.
Answer: I don't think this is a different kind of sampling, so when you ask how to do it in R, I don't have a different answer for you than "same as you would take a stratified sample if there were no nonresponse." Taking nonresponse into account is a practical question, and it's independent of its implementation in statistical software. And, because survey methodology is not an exact science, you'll have to make some decisions that are inevitably subjective and based on what you as the author of a survey believe is the best choice.
You're interested in preserving stratification while taking into account the nonresponse rate. This may be possible only through sampling, but likely you may need to combine sampling design with some method of poststratification in order to preserve strata sizes. This depends on how close your expected response rate (prior to actually doing the survey) is to your actual response rate once you've finished the survey. Due to the nature of sampling, even if you know from previously sampling the same population that on average 50% of people respond, in any particular survey you can get a lower or higher number, like 48% or 55%. So if you really want to preserve exact strata sizes, you will probably need to adjust this in post-stratification.
In the planning stage, I don't think you have any better choice than contacting a larger sample than you need (backup, as you suggest). Survey Monkey mentions this approach. The total number of elements you need to contact (call it $c$) in order to obtain a desired number of respondents ($n$) is inversely proportional to your expected response rate expressed as a fraction ($r$): $c = (1/r)*n$. To take your example, if you need 10 respondents and the response rate is 50%, you need to contact $(1/0.5)*10=20$ people. This makes sense intuitively, too. If you are targeting 10 people and expect only 5 of them to respond, you need another 10 people as a backup because, if they are drawn from the same population, the backup people ALSO have a response rate of 50%.
Combining this with stratification, you have two choices. If you believe the non-response rate is the same across all strata (i.e. it's uncorrelated with the stratification variable), you would simply double all allocated strata sizes. Say, if you need a sample of 100 allocated across four strata (let's label them A, B, C, D) thus: A = 10, B = 20, C = 30, D = 40, and the response rate in all strata is 50%, you would draw a sample of A = 20, B = 40, C = 60, D = 80, for a total of 200 people to contact. If you think the response rates are different across strata (A = 50%, B = 75%, C = 90%, D = 60%), then you would draw: A = 20, B = ~27, C = ~33, D = ~67 for a total of 147 people to contact.
In R, you can do this with the stratsample() function in the 'survey' package, or with the strata() function in the 'sampling' package (make sure to read the details section to order your data correctly).
How you treat these larger strata sizes then is a matter of choice. You can contact all and see what you get. You can contact them in some order (or no particular order) until you get the desired sample size. You can split your larger sample into a "primary" and "backup" sub-sample in each stratum (for example by drawing a sub-sample of primary elements, and treating the remainder as backup), contact the primary sub-sample first, and then draw from the backup sub-sample; you could even match elements in the primary and backup sub-samples by some variables you think matter, so that when person i from the primary sub-sample does not respond, you have an exact person i-backup (or a couple of them) in the backup sub-sample to contact instead (I've done this in a survey of farm households: I had four strata of size 30 each, but I drew 40 from the sampling frame. When a cattle farmer with less than 10 cows would fail to respond, I would replace them with another cattle  farmer with less than 10 cows).
So much for sampling. You can deal with nonresponse further in post-stratification. In R, you can use the nonresponse() function from the 'survey' package to adjust weights for nonresponse across strata.
I hope this helps you.


Upload a TSV file into Google Drive via the API and remove qualifying quotes around each cell

Question: I'm trying to upload TSV file to Google Drive and have its contents converted to a spreadsheet by using the ?convert=true flag when sending the file. Everything seems to be working well, except when the file is converted none of the quotes are being removed from around each cell of data. The result looks like this:

I have the same problem when uploading via the UI in Google Docs, unless manually set the "Separator character" to be "Tab". In the UI, this fixes the problem and the quotes are automatically removed from the import.
My question is: can I manually specify a separator character when importing a file into Google Drive via the API? Or can I format my file in some way that specifying a separator character is not necessary? I have to keep the quotes in place because some of my content contains new line characters. Without the quotes the importer can't tell that the content is part of the same cell.
I'm already transferring the file with the mimeType set to "text/tab-separated-values". I've also tried formatting with commas and uploading as a "text/csv", but that had even worse results with all the cells jammed into the first column.
Answer: Drive API doesnt support a custom separator character. We're not keeping the feature parity between the UI and the API in this case, we're considering it as an enhancement.
Comment: I made an internal feature request to provide a separator param, fyi.
Comment: Hi, thanks the response Burcu! What about alternatives? Is there any way to get a CSV/TSV into Google Drive that maintains new line characters properly? As of right now I'm left only with stripping out newlines and tab characters in the data and replacing them with spaces.
Comment: I marked this accepted, but it seems like there's no way to do what I've requested: import data that contains new lines. Doh. Here's hoping the API gets this ability eventually.


Programmatically validate a node?

Question: I am programmatically creating many nodes. Obviously they have to be valid before storing them. Such $node objects have CCK fields mixed with custom fields.
Because the validators only set a form_set_error() and hardly ever return the validation-result, I have to go trough the form-api in order to know if a node is valid, or so it seems.
I call node_validate(), then form_get_errors() (which, in turn calls form_set_error()).
There appear to be several problems with this approach:

form_set_error() sets a message with drupal_set_message(); for stuff like cron (a session-less user), this adds orphaned persistent error-messages to the database (they will never be printed, hence never deleted).
the returning array of errors is created to be used in a multidimensional form array. Especially with CCK-fields, I have to dig quite deep in order to find the actual error.
I just want to store a node, so I am not interested in a user-faced form; using the form API just feels wrong.

Is there a simpler, more elegant method?
Comment: Is the problem that your data source that you are using may have invalid data in it, or just that you are trying to validate your own code?
Comment: I just want to avoid storing nodes that are "invalid", according to whatever defines if they are valid. If, say, an image is required, one can assume that the theme will be able to render that image, regardless. If my importers start saving nodes without these images, the theme will print broken image-links.
Answer: There aren't any other ways, as the hooks that the modules need to implement to validate a node are hook_validate() (if the module implements a content type) and hook_nodeapi('validate') (for all the other modules). Those hooks get a $form parameter, and are supposed to call form_set_error() in the case there is a validation error.
The easier way to find if there are errors set for a form is to use form_get_errors(), which returns the array with all the errors set with form_set_error(), the function that is also called from form_error().
In the case more than one node is validated, you would need to call form_set_error(NULL, '', TRUE) before node_validate(), and then get from form_get_errors() the array containing the error messages; if this is empty, there are no error messages.
form_set_error(NULL, '', TRUE);

// node_validate() call.

$errors = form_get_errors();

if (!empty($errors)) {
  // Some module reported an error.
}

Alternatively, you can use the following snippet to verify no module reported an error, after you call node_validate():
if (!empty($_SESSION['messages']['error'])) {
  // Some module reported an error.
}

Before calling node_validate() from the cron task, you would need to set $_SESSION['messages']['error'] to an empty array; in that way, you are sure the errors reported in the array are caused by the node validation hooks.
$_SESSION['messages'] is the variable used from drupal_set_message() to store the messages passed to the function.
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
  if ($message) {
    if (!isset($_SESSION['messages'])) {
      $_SESSION['messages'] = array();
    }

    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();
    }
    // …
  }
  // …
}

Comment: is this work on drupal 7 ?
Comment: The question is for Drupal 6; you need to slightly change the code for Drupal 7.
Comment: can you just give a direction how to do in drupal 7

Programmatically validate a node?


Melhor Tipo Mysql para contabilizar os acessos

Question: Tenho uma base de dados onde contém arquivos PDF, só que estou querendo contabilizar quantas visualizações teve esse arquivo. A estrutura de contabilizar está pronta, pois foi feita em PHP/Mysql, só que estou com uma dúvida. Normalmente coloco o Tipo Varchar(255), mas para esse tipo é ideal para fazer essa contagem? A cada acesso, irei usar o UPDATE.
Comment: A pessoa que negativou, poderia ao menos dizer o motivo? Afinal é uma dúvida que se refere a programação.
Comment: Se vc quer calcular (soma / subtração e etc) um valor, o mesmo deve estar numa coluna numérica e não numa `VARCHAR`, como mencionado pelo @rLinhares o certo é `bigint`, `Integer` ou alguma na mesma linha.
Comment: Se entendi bem você quer armazenar o total de visualizações, ou seja, um número. Por que a coluna não seria `bigint`?
Comment: Pergunta um "bocado" forçada, talvez seria melhor acrescentar/perguntar as desvantagens na utilização de um`varchar` em vez de um `int`
Comment: Olá rLinhares. Certo. Ela aceitaria a soma de cada acesso? Ou seja. A cada acesso, eu teria que somar com + 1, pois nunca usei esse Tipo.
Comment: Certo. Vou seguir a dica de vocês. Obrigado a todos.
Comment: Sim, é um campo numérico, não teria problema
Answer: Contagem é numérico, e são valores inteiros e positivos.
O tipo adequado para isso, portanto, é INTEGER UNSIGNED (inteiro SEM sinal). Nesta família, temos estas possibilidades:
TIPO        BYTES   SIGNED                        UNSIGNED
=========== ======= ============================= =====================
TINYINT     1       de -128 a 127                 de 0 a 255
SMALLINT    2       de -32768 a 32767             de 0 a 65535
MEDIUMINT   3       de -8388608 a 8388607         de 0 a 16777215
INT         4       de -2147483648 a 2147483647   de 0 a 4294967295
BIGINT      8       de -2^63 a 2^63-1             de 0 a 2^64-1

Escolha o tipo que melhor atender o seu caso, prevendo o número máximo que pretende armazenar.

Mais detalhes no manual:

https://dev.mysql.com/doc/refman/5.7/en/integer-types.html


I gave a slightly different strong induction proof to $3^{2n+1}+2^{n-1}$, is it correct?

Question: I would like to know whether the following proof is correct and whether I also use correct notation.
We have the following formula: $A(n)=3^{2n+1}+2^{n-1}$. We want to know the whether $A(n)$ is divisible by 7 for all $n \geq 1$.
Here follows my proof:
Base case:
$$3^{2(1)+1}+2^{1-1}=28$$
$\frac{28}{7}=4$ so the base case holds true.
We assume:
$$A(k)=3^{2k+1}+2^{k-1}  \space \text{so that}  \space\space 7|A(k)\space \space\forall k \in \mathbb{N}, \space k \gt 1$$
Therefore:$$A(k+1)=3^{2(k+1)+1}+2^{(k+1)-1}$$
$$\dots$$
$$=9(3^{2k+1}+2^{k-1}) - 7(2^{k-1})$$
So: $\space\space 7|A(k)\space \space\forall k \in \mathbb{N}, \space k \gt 1$

My primary concern is with correctness of notation and whether my conclusion in the induction step   ($\space \space9(3^{2k+1}+2^{k-1}) - 7(2^{k-1})\space\space$) is an ok solution. I noticed that I could've just factored $7(3^{2k+1})$ out and that might have been better but I wonder whether it matters for anything other than aesthetics.
Comment: "the best possible solution". Nonsense.
Comment: @arugula changed it for ya ;)
Answer: As a variant, write $$A_n=3\times 9^n+\frac 12 \times 2^n$$
Since $9,2$ are roots of the quadratic $$(x-9)(x-2)=x^2-11x+18$$ we deduce that we can define the $A_n$ recursively as $$A_1=28,\;A_2=245\quad \&\quad A_n=11A_{n-1}-18A_{n-2}$$
Since $7$ divides both $A_1,A_2$ it is clear (inductively) that $7\,|\,A_n$ for all $n\in \mathbb N$.
Note:  It was clear without computation that there was such a two step recursion with integer coefficients, so even at the start all we had to do was to check the first two values.  The argument doesn't depend on the exact values of the coefficients, just on the fact that they are integers.
Comment: This kind of argument explains why the persistence of divisibility occurs in these problems, and also shows how to construct as many such examples as required eg for practice on induction.
Comment: @MarkBennet thank you. I can now construct examples on my own thanks to this answer. I will give him the tick mark.
Answer: That's how I would have done it, except that after writing that $$A(k+1)=9(3^{2k+1}+2^{k-1}) - 7(2^{k-1}),$$I would have added that this is $9A(k)-7(2^{k-2})$ and therefore, by the induction hypothesis, this number is a multiple of $7$.
Answer: Non-induction alternative: write $A(n)$ as:
$$
3(9^n-2^n)+7\cdot 2^{n-1}
$$


RepeaterCommandEventArgs is incorrect after changing repeater items onpostback

Question: I am struggling to word this correctly as I am not really sure what the issue is but I will give it a try.
I have a list of events in a repeater. I have a checkbox above this list which does a postback and displays expired events.
When it posts back, it has the right information in the repeater, but when I click Edit (ItemCommand) it has the wrong event id (instead it shows the id of the event before postback).
I am not sure if there is some kind of id mapping going on with repeaters which is beyond my knowledge.
Here is some of my code to hopefully make things a bit clearer:
<code>    protected void chkShowExpired_CheckedChanged(object sender, EventArgs e)
    {
        rptEvents.DataSource = Events.GetFiltered(null, null, chkShowExpired.Checked, null, null, null, null, "");
        rptEvents.DataBind();
    }

    protected void rptEvents_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "DeleteEvent":
                ...
            break;

            case "EditEvent":
                ...
            break;
        }
    }
</code>
Answer: Well the check box event going to fire before the on index changed event. So in the check box event, you can't directly use the control to get the row/selected index. You would have to wait until the selected index repeater event fires.
HOwever, I drop buttons, checkboxes and all kinds of controls into that repeator.
What I do, is not even bother with the repeater event model.
just do this in your check box event, or button event, or whatever
<code>protected void cmdUpdate_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;

RepeaterItem rItem = (RepeaterItem)btn.Parent;

TextBox tBox = (Textbox)rItem.FindControl("txtHotelName");

response.Write("hotel name = " + tBox.Text);
}
</code>
In ohter words, just pluck out the sender. Now, this becomes plain jane asp.net code and buttions. You don't have to care about using the repeater event mode, and triggering say the on indexed changed event of the repeater.
Also, one more cool trick.
When you drop in a check box, drop downllist, button?
Well, since it is inside of the repeater, then we can't do that all wonderful bring up the property sheet or EVEN more simple is say double click on the control that jumps to code behind.
But, you CAN do this cool trick - just use intel-sense:
eg this:
Just type in the event name in the markup, and when you hit "=" sign, then intel-sense will give you a option to create the event like this:

So, you can now click on create new event - it SEEMS like nothing occured, but if you now go to code behind, you see the buttion event (in this example).
So, by picking up sender, and then sender.parent (which is the repeater item), then we really don't care about having the Repeater event model "index change" event fire - you really don't care since you get/have/see full use of the repeater row item by using the .parent of the sender.
The end result?
You kind of just code those controls and their events like any other control outside of a repeater.
And once you have your hands on that repeater item (row), then you quite much home free to do whatever  you want.


How to calculate the fourier series coefficients of $(f(x))^m?$ knowing the Fourier series of $f$?

Question: For sake of simplicity $f$ is assumed to be $2π-$periodic function on $\Bbb R$.  Given the fourier series of $f$, which coefficients  are
$$\widehat{f}(k)= \frac{1}{2π}\int_0^{2π}f(t)e^{-ikt}dt,~~~~~~k\in \Bbb Z. $$
how to calculate the fourier series coefficients of $(f(x))^m?$

If I know the fourier series expansion of a function $f(x)$  is it possible to express the fourier series coefficients of $(f(x))^m$ as functions of fourier series coefficients of $f(x)?$
Is there any general algorithm to calculate this?

I think by a recursive formula it suffices to find the result for $m=2$. Does anyone has an idea?
Comment: it could be great to explain your down vote it will help for sure. may be my question is too obvious
Answer: If $$f(x)=\sum_{m=-\infty}^\infty \hat f(m)e^{imx}$$ then $$f(x)^2=\sum_{m,n=-\infty}^\infty\hat f(m)\hat f(n)e^{i(m+n)x}$$
  Letting $m=M-n$ gives $$\sum_{M,n=-\infty}^\infty\hat f(M-n)\hat f(n)e^{iMx}$$ so $$\widehat{f^2}(M)=\sum_{n=-\infty}^\infty \hat f(M-n)\hat f(n)=\hat f\ast \hat f,$$ where $\ast$ denotes the convolution of two sequences.  In general, $\widehat {f^m}=\hat f\ast \hat f\ast\cdots\ast \hat f$ $m$ times.