Automatic Cast to Reference?

Question: I have the following code:
#include <iostream>

template<typename T>
void gaga(T * a){
    std::cout << "gaga(T * a)";
}

template<typename T> class A{};

template<typename T>
void gaga(A<T> & a){
    std::cout << "gaga(A<T> & a)\n";
}

template<typename T>
class B {
public:

    T * p;

    operator T*() const{
        std::cout << "Cast called" <<std::endl;
        return p;
    }
};

int main()
{
    B< A<int> > b;
    gaga(*b); /// WHAT IS GOING ON HERE? WHY is void gaga(A<T> & a) CALLED?

    A<int> * p;
    gaga(p); /// WHEN THE ABOVE calls void gaga(A<T> & a) WHY  is here
             /// void gaga(T * a) CALLED???
}

And I am really puzzled why the gaga(A<T> & a) is called when I call it with *b which obviously results by the conversion operator in A<T> * but why?? ---> *b is a dereference operator not even defined!??  why can that be handed even to gaga(A<T> & a)?
Thanks for an explanation!
Comment: @Gabriel Read [this](https://stackoverflow.com/questions/4421706/operator-overloading). The part relevant to your question is [this](https://stackoverflow.com/a/16615725/241631) answer ... `operator T*()` is not the deference operator but a user defined conversion operator to implicitly convert a `B` to `A *`
Comment: sorry edited the stuff, AA should be A
Comment: Do you know what the `operator T*() const` line does?
Comment: I really don't understand your confusion here. This is doing exactly what I'd expect it to do. Are you expecting `gaga(A& a)` to get called on a pointer? I'm also not sure what you mean by "cast to reference". You don't cast to a reference, you just create a reference to something, or pass something by reference to get one.
Comment: obviously i dont know what `operator T*()` const does
Comment: So your question is ... why is the compiler doing exactly what I asked it to?
Comment: No I dont understand what the compiler does here
Answer: well, b is a of type B b which can be cast to a T*, because of the conversion operator you added, meaning it can be cast to a A*.
when calling the dereference operator, you see that *b become A, so it is quite obvious that the second gaga is called, as it has a reference as parameter.
in the second case, it's even more obvious. You have a pointer to A, it will be matched with the only gaga function that takes a pointer as an argument, the first one.

Automatic Cast to Reference?


The value attribute of  inside  is not added through the $.each jQuery function

Question: I get a JSON response as follows.
{
   "stateTables":[
      {
         "stateId":15,
         "stateName":"kkkkkkkk"
      },
      {
         "stateId":34,
         "stateName":"qwqw"
      },
      {
         "stateId":61,
         "stateName":"xx"
      },
      {
         "stateId":66,
         "stateName":"aaa"
      }
   ]
}

The JavaScript function that receives this response is as follows.
var timeout;
var request;

function poplateStateListe(id)
{
    if(!request)
    {
        if(id===null||id===""||id===undefined||isNaN(id))
        {
            var options = $("#state");
            options.find('option').remove().end();
            options.append($("<option/>").val("").text("Select"));

            alert("Please select an appropriate option.");
            return;
        }

        request = $.ajax({
            datatype:"json",
            type: "GET",
            contentType: "application/json; charset=utf-8",
            data: {"id": id},
            url: "PopulateStateList.action",
            success: function(response)
            {
                var list = response.stateTables;
                var options = $("#state");

                options.find('option').remove().end();
                options.append($("<option/>").val("").text("Select"));

                $.each(list, function() {
                    options.append($("<option/>").val(this.stateId).text(this.stateName));
                });
            },
            complete: function()
            {
                timeout = request = null;
            },
            error: function(request, status, error)
            {
                if(status!=="timeout"&&status!=="abort")
                {
                    alert(status+" : "+error);
                }
            }
        });
        timeout = setTimeout(function() {
            if(request)
            {
                request.abort();
                alert("The request has been timed out.");
            }
        }, 30000);
    }
}

I write this response to a <select> list. I however, generate this list as follows.
<select name="entity.stateId" id="state">
    <option>Select</option>
    <option>kkkkkkkk</option>
    <option>qwqw</option>
    <option>xx</option>
    <option>aaa</option>
</select>

The value attribute of <option> is not added. The actual list should have been.
<select name="entity.stateId" id="state">
    <option value="">Select</option>
    <option value="15">kkkkkkkk</option>
    <option value="34">qwqw</option>
    <option value="61">xx</option>
    <option value="66">aaa</option>
</select>

Why is not the value attribute added through the $.each function
$.each(list, function() {
    options.append($("<option/>").val(this.stateId).text(this.stateName));
});

inside the success handler of the given JavaScript function? I'm missing something obvious here.
Answer: Try with using .attr() instead of .val()
$.each(list, function() {
    options.append($("<option/>").attr('value', this.stateId).text(this.stateName));
});

Answer: Another possible syntax is :
$.each(list, function() {
    options.append($("<option/>", {value: this.stateId}).text(this.stateName));
});

Hope it helps.


Differential equations having different solutions near different points (according to wolfram)

Question:
So, I know this differential equation is homogenous and I tried solving it by using the homogenous substitution $ y=xt$ , However in one of the steps I had to integrate something with a cubic in denominator
$$\int \frac{ u^2 +1}{-u^3 - u^2 - u + 1} du$$
So this integral comes up and I don't know how to solve it. What exactly could be wrong? why does this solution look so convuluted and having different 'solutions' near different points?
Edit:
Unsolvable Differential Equation?
I found this which is similar, however I don't think the solution which was given to this is quite right
Comment: Really similar.
Answer: Given homogenius ODE is
$$\dfrac{\mathrm dx}{\mathrm dy} = \dfrac{x^2+y^2}{x^2-y^2}.$$
Can be applied substitution
$$x= (u+1)y,\tag1$$
$$y\dfrac{\mathrm du}{\mathrm dy} = -u-1+\dfrac{(u+1)^2+1}{(u+1)^2-1},$$
$$y\dfrac{\mathrm du}{\mathrm dy}=-u+\dfrac{2}{(u+1)^2-1},$$
$$\dfrac{\mathrm dy}{y}=-\dfrac{u^2+2u}{u^3+2u^2-2}{\mathrm du}.\tag2$$
Since the denominator of RHS(2) has a root
$$r=\dfrac13\left(\sqrt[3]{19+\sqrt{297}}+\sqrt[3]{19-\sqrt{297}}-2\right)\approx 0.83928\,67552\,14161,\tag3$$
\begin{align}
&27(r^3+2r^2-2) = (3r+2)^3 - 12(3r+2) - 38\\
&=  \left(\sqrt[3]{19+\sqrt{297}\,}\,+\sqrt[3]{19-\sqrt{297}\,}\,\right)^3
-12\left(\sqrt[3]{19+\sqrt{297}}+\sqrt[3]{19-\sqrt{297}}\right)-38\\
&= \left(3\sqrt[3]{19+\sqrt{297}\,}\,\sqrt[3]{19-\sqrt{297}\,}-12\right)\left(\sqrt[3]{19+\sqrt{297}\,}\,+\sqrt[3]{19-\sqrt{297}\,}\,\right)\\
&= \left(3\sqrt[3]{64}-12\right)\left(\sqrt[3]{19+\sqrt{297}\,}\,+\sqrt[3]{19-\sqrt{297}\,}\,\right) = 0,
\end{align}
then
$$u^3+2u^2-2 = (u-r)(u^2+(r+2)u+r^2+2r),$$
$$R(u)=\dfrac{u^2+2u}{u^3+2u^2-2}=\dfrac A{u-r}+\dfrac{B(2u+r+2)}{u^2+(r+2)u+r^2+2r}
+\dfrac{C}{u^2+(r+2)u+r^2+2r},$$
where
$$A = \lim_{u\to r}(u-r)R(u) = \dfrac{r^2+2r}{3r^2+4r} = \dfrac{r+2}{3r+4},$$
$$A+2B = \lim_{u\to \infty}uR(u) = 1,\quad B=\dfrac{r+1}{3r+4},$$
$$\dfrac {B-A}r+\dfrac C{r^2+2r} = R(0)=0,\quad C=\dfrac{r+2}{3r+4},$$
$$u^2+(r+2)u+r^2+2r = \left(u+\dfrac{r+2}2\right)^2+\dfrac{(r+2)(3r-2)}4.$$
Then from $(2)$ should
$$(3r+4)\ln \mathrm{const}|y| = (r+2)\ln|u-r|+(r+1)\ln|u^2+(r+2)u+r^2+2r|\\
+2\sqrt{\dfrac{r+2}{3r-2}}\arctan\dfrac{2u+r+2}{\sqrt{(r+2)(3r-2)}},$$
$$\color{green}{\mathbf{\small C_1|y|^{3r+4}|u-r||u^3+2u^2-2|^{r+1} = \exp\left(2\sqrt{\dfrac{r+2}{3r-2}}\arctan\dfrac{2u+r+2}{\sqrt{(r+2)(3r-2)}}\right)}},\tag4$$
where $C_1$ is the arbitrary constant.
Formulas $(1),(3),(4)$ present the common solution of the given ODE.
Comment: I have one question, why does wolf ram give me different solutions neear different points?
Comment: @DDD4C4U It looks as WA used the intervals method to avoid the function |a|.
Comment: what happens at |a|
Comment: what is |a| , i couldnt figure from your solution
Comment: @DDD4C4U I've meant the absolute value.   But I shoud think once more.
Comment: @DDD4C4U There is the fractions expansion over the complex roots $r_i.$ And then WA uses the antiderivatives for $\frac1{u-r_i}.$
Comment: I see, from what I know the fraction decomposistion changes in the complex plane, is this related to that?
Comment: @DDD4C4U There are three terms. Every term uses the root for the antiderivative and at the same time - for the coefficient evaluating.
Comment: why did you put  $ x= (u+1)y$
Comment: @DDD4C4U To simplify the denominator.


ASP.Net Application keeps prompting for cedentials

Question: We have an MVC application hosted on IIS  6 web server. It uses integrated authentication. It's been hosted there since last 5 years. Recently our IT department had installed some patches on the server. After the patch installation, suddenly our application started prompting for credentials. When user enters his credentials, it again prompts for credentials. It keeps on repeating and user will not be able to get into the application. When user cancels the credentials window, it gives the below error:

401 - Unauthorized: Access is denied due to invalid credentials.

Can somebody, please guide me to understand why it might have occurred and how to fix this?
Comment: Maybe wrong credentials?
Comment: Windows 2003 (and by extension IIS6) is out of support and has been for several years...why has the server not been upgraded?
Answer: We actually ran into this about 8 months ago. It brought down our entire environment for 3 days. At that time we came to find that it was a Microsoft patch that was applied to our web servers in regards to NTLM authentication. I will look and see if I can find the documentation on exactly what KB it was. Our solution was (at the time) to temporarily roll back the patch. Long story short is the underlying cause turned out to be that the patch that was installed had specific dependencies on other patches being installed on the web server AND our domain controllers. I will follow up and edit my answer when I get into the office, but I recommend checking the server to see what patches got installed and take note of if any in regards to NTLM.
Try remoting into the server. Then while you are in, minimize your screen and try hitting the website again. I bet I will work and authenticate. If that is the case, then you are seeing the exact same thing we were. I will follow up in a little bit with more specifics.


problem with routes with node-oidc-provider

Question: I'm just starting with oidc-provider and I can't get express to recognize routes once I include oidc-provider.
In the simple setup below, I get a "unrecognized route on '/'. The well known url for setup does work, and the auth endpoint looks like it does as well.
const express = require('express');
const Provider = require('oidc-provider').Provider;

const app = express();

const configuration = {
  // ... see /docs for available configuration
  clients: [{
    client_id: 'foo',
    client_secret: 'bar',
    redirect_uris: ['http://192.168.128.128:3000/oidc/cb'],
    // ... other client properties
  }],
};

const oidc = new Provider('http://localhost:3000', configuration);

app.use('/oidc', oidc.callback());

app.get('/', function(req, res) {
        res.send('hello world');
});

oidc.listen(3000, () => {
  console.log('oidc-provider listening on port 3000, check http://localhost:3000/.well-known/openid-configuration');
});

I don't understand the whole "mount" notion though I suspect it has something to do with my route problem. Why is this happening? What is the solution?
Answer: This is because you are doing:
oidc.listen(...)

And by doing that, you are ignoring all the routes added to app.
What you should do instead is to make the express app to listen, instead of the oidc provider:
app.listen(...)


Can't access my website

Question: I can't access my website. I guess it has been hacked. Some drupaldev user is already been created and is in admin list. I have blocked that user multiple times, but it reappears again and again in my admin panel list.
My site has also faced spamming, which i stopped by disabling registration module. But i believe its too late now.
How can i prevent letting this user access my website? What have i missed in my security constraints? Please help.
Drupal Version : 7.17
Comment: "What have i missed in my security constraints?" No way to tell what you're missing, unless you tell us what tehy are. Also: What versions are you running, what contrib have you installed, and are you running any custom modules?
Comment: I wish i could answer that question, then certainly i would have started fixing them instead of wasting time in here to put that question. Yes i am using 2 custom modules to meet some of my requirements. There are many contrib modules installed which are successfully running on thousands of sites.
Comment: If you can guide me, what could i have done possibly wrong keeping in mind your experience, and security breaches you have seen..that will be helpful..
Answer:
What have i missed in my security constraints?

I looks like you're running an outdated version of Drupal (ver. 7.17) with many severe security issues including the one known as "Drupageddon" (fixed in ver. 7.32).
First, you must start reading up on the Drupal Security advisories, in particular SA-CORE-2014-005 - Drupal core - SQL injection, PSA-2014-003 and FAQ on SA-CORE-2014-005 - they will tell you what you've missed regarding Drupageddon. This flowchart is a great resource.
To get back the control over your site, you should simply delete it, and start recreating it from scratch on a different server, since the attacker may have a root kit on your present server.  Change the password of the db-user that Drupal uses, and the passwords of all privileged accounts. If you want to keep your content, roll it back from a backup created before Oct. 15 (you have backups, don't you?).
If you don't have backups, there are some tools (including a Drush command named Drupalgeddon) that may be use for forensics and part clean-up of an compromised site.  I do not recommend that you use these tools, as there is no guarantee that they'll able to find all infected areas on your site and web server. But they're the last resort, if scrapping the site and starting over is not an option.
You should also start reading up an all Drupal SAs.  Or even better, subscribe to them: Log in on Drupal.org, go to your user profile page and subscribe to the Drupal security newsletter on the Edit » My newsletters tab.
Contributed modules frequently have security flaws.  These are eventually fixed, but the fix also tells all the bad guys how to exploit unfixed sites.  That means that to keep your site secure, you must make sure you install security updates in a timely manner.  That's why subscribing to the security newsletter is so important.
Custom modules made by inexperienced programmers is a huge risk.  If you use custom modules, make sure you have their code reviewed by someone experienced in security.
Comment: Yes there it is. My site encountered the same security issue. Bad news for me is i can't roll it back to Oct 15th back up, there has been lot of things done after this date. lots of enhancements, user engagements etc.
I understand the security risk, but yes i missed newsletter part and this is what i have to pay for it now.
For applying this patches i need to put my site down, which is a problem. Wondering what could be the best possible solution for me now.
Comment: My website is probably dead now. I believe all user data is stolen for sure.

Can't access my website


Linear Dependence of n vectors

Question: We have vectors $$ v_{0}, v_{1}, ... v_{n}$$ in $$\ R^{m}$$ which are said to be affinely independent if with scalars $$c_{0},c_{1}...c_{n}$$ we have, $$\sum_{i=0}^{n}c_{i}v_{i}=0$$ and $$\sum_{i=0}^{n}c_{i}=0 \implies c_{i} = 0 \forall i = 0,1,...,n$$
If such is a case then which of the following is an implication
1) $$v_{0}, v_{1}, ... v_{n}$$ are linearly independent.
2) $$v_{1}-v_{0}, v_{2}-v_{0}, ..., v_{n}-v_{0}$$ are linearly independent.
3) $$n\leq m$$
The answer is given as , Only 2 and 3 are true.
Now, my doubt is, why doesn't statement 1 hold? Is it because if m = 2 (say) and the $$v_{i}$$ vectors have dimension 3 then they may not be linearly independent.
Also, does that imply linear dependence because if that happens then statement 2 is true
And finally, statement 3, how can we just say that $$n\leq m$$ just like that?
Please suggest a way. Thank you.
Comment: If the answer given is that only 1 and 2 are true, why are asking "why doesn't statement 1 hold", and why are asking "why is statement 3 true"? I'm a bit confused.
Comment: I am sorry I made an error while typing. It was given that only 2 and 3 are true. I have corrected it.
Comment: $n\leq m$ because by 2 you have $n$ linearly independent vectors in $\mathbb{R}^m$.
Answer: To see why statement 1) is not true, you can consider $m=n=2$ and
$$
v_0=\begin{pmatrix}1\\1\end{pmatrix},~v_1=\begin{pmatrix}1\\0\end{pmatrix},~v_2=\begin{pmatrix}2\\0\end{pmatrix}.
$$
From $c_0v_0+c_1v_1+c_2v_2=0$ we get
$$
c_1+2c_2=0\\c_0=0.
$$
From $c_0+c_1+c_2=0$ we conclude $c_1=-(c_0+c_2)=-c_2$ since $c_0=0$. This yields
$$
c_1+2c_2=0\Leftrightarrow -c_2+2c_2=0\Leftrightarrow c_2=0.
$$
Finally we get $c_1=0$.
Therefore $v_0,v_1,v_2$ are affinely linear independent, but not lineare independent since $v_2=2v_1$.
For statement 2) you have to consider
\begin{align}
\sum_{i=0}^nc_i=0~\wedge~\sum_{i=0}^nc_iv_i=0
&\Leftrightarrow
c_0=-\sum_{i=1}^nc_i~\wedge~c_0v_0+\sum_{i=1}^nc_iv_i=0
\\&\Leftrightarrow c_0=-\sum_{i=1}^nc_i~\wedge~-\sum_{i=1}^nc_iv_0+\sum_{i=1}^nc_iv_i=0
\\&\Leftrightarrow c_0=-\sum_{i=1}^nc_i~\wedge~\sum_{i=1}^nc_i(v_i-v_0)=0.
\end{align}
Since we have
$$
\sum_{i=0}^nc_i=0~\wedge~\sum_{i=0}^nc_iv_i=0 \Rightarrow c_0=\ldots=c_n=0,
$$
we get
$$
\sum_{i=1}^nc_i(v_i-v_0)=0 \Rightarrow c_1=\ldots=c_n=0.
$$
Therefore $v_1-v_0,\ldots,v_n-v_0$ are linear independent.
The third statement follows directly from the second. If $n>m$ then $v_1-v_0,\ldots,v_n-v_0$ can't be lineare indepentent in $\mathbb{R}^m$, which contradicts statement 2.
Comment: Oh wow. That's, awesome. Thank you :)

Linear Dependence of n vectors


Prove the inequality $(1+x^2)(1+y^2)(1+z^2) \ge 64$ if $xy + yz + zx = 9$

Question: Given non-negative reals $x, y, z$ satisfying $xy + yz + zx = 9$, we're supposed to prove the inequality $(1+x^2)(1+y^2)(1+z^2) \ge 64$. My first approach was something like C-S or Hölder, since we're multiplying sums together. Another approach was to realize that $(1+x^2)(1+y^2) \ge (x+y)^2$, so it would suffice to prove $(x+y)^2(z^2+1) \ge 64$, but from here I couldn't make much progress. An "obvious" observation I made was $x^2 + y^2 + z^2 \ge xy + yz + zx \implies (x+y+z)^2 \ge 27$, but again I am stuck. Any help would be much appreciated.
Comment: Hint: 1/ $ (1+x^2)(1+y^2) \geq (x+y)^2$. 2/ $x+y+z \geq 3\sqrt{3} $.
Comment: @Calvin Lin Yes, I already found these two, but couldn't find the next step...
Comment: So you want to relate $ (x+y)(y+z)(z+x)$ to a combination of $xy+yz+zx $ and $x+y+z$. Know of any inequality that does that?
Comment: @CalvinLin not sure here... if I just do AM-GM, I get $(x+y)(y+z)(z+x) \ge 8xyz$ but I don't think that'll help...
Comment: You have no control over $xyz$ (other than the trivial $ \geq 0 $ bound), so that's not helpful. Please involve $ xy+yz+zx$ and $x+y+z$.
Comment: Hölder or Cauchy Schwarz?
Comment: Ah, I misspoke. Unfortunately we can't use $ 1/ (1+x^2)(1+y^2) \geq (x+y)^2$ because equality doesn't hold at $ x = y = \sqrt{3}$. I thought all-variables equal could work out, but it didn't when I pushed through. $\quad$ FWIW The inequality I was thinking of was $(x+y)(y+z)(z+x) \geq 8/9 (x+y+z)(xy+yz+zx)$.
Answer: Just another way, using CS inequality:
$$(1+x^2)(1+y^2)(1+z^2)=\left((x+y)^2+(xy-1)^2 \right)(z^2+1) \\ \geqslant \left((x+y)z+(xy-1)\right)^2=64$$
Note, here we need an estimate tighter than $(1+x^2)(1+y^2)\geqslant (x+y)^2$, motivating the expression $(x+y)^2+(xy-1)^2$.
Comment: In fact, using $(a^2+b^2)(c^2+d^2) = (ac+bd)^2+(ad-bc)^2$ (similar to the "estimate tigher than CS"), we get $(1+x^2)(1+y^2)(1+z^2) = [( x+y)^2 +(xy-1)^2[(1+z^2)] = (xz+yz+xy-1)^2 + (x+y+z-xyz)^2 $.
Comment: Thats true - it's essentially the usual proof of the CS inequality in its simplest form, also giving the equality condition.
Answer: Here is the $pqr$-technique based proof. First, we homogenize the inequality:
$$\prod(1+x^2)\ge64$$
$$\prod(9+9x^2)\ge64\cdot9^3$$
$$\prod(9x^2+xy+yz+zx)\ge64(xy+yz+zx)^3.$$
After expanding we get:
$$\sum\left( x^4y^2+x^2y^4+2x^4yz+2x^3y^3\right)+42x^2y^2z^2\ge 10\sum \left(x^3y^2z+x^3yz^2\right).$$
Let $p=x+y+z$ and $r=xyz$ ($q$ is equal to $9$). Then the inequality turns into:
$$81p^2-2\cdot9^3-2p^3r+36pr-3r^2+2p^3r-54pr+6r^2+\\+2\cdot9^3-54pr+6r^2+42r^2\ge 90pr-30r^2.$$
After simplifying we get: $$81p^2+81r^2\ge162pr.$$
The last inequality is obviously true.
Comment: @Aig I think homogenization is not good for pqr method which involves more calculation. Just: We have $$(1 + x^2)(1 + y^2)(1 + z^2) = x^2y^2z^2+x^2y^2+y^2z^2+z^2x^2+x^2+y^2+z^2+1 $$ $$= r^2 + (q^2 - 2pr) + (p^2 - 2q) + 1 = r^2 + p^2 - 2pr + 64 = (p - r)^2 + 64.$$
Comment: Note: That is the expression $(1+x^2)(1+y^2)(1+z^2) = (xyz-x-y-z)^2 + (xy+yz+zx - 1 )^2$, which sets up this inequality.  Once known, it is easy to verify by expansion. It could be derived using complex numbers, or product of sums of 2 squares.
Comment: I am not too familiar with the $pqr$-method, but I've heard of it sometime. Is this method generally as much brute force as something like BW?
Comment: @MartinWestin It usually implies extensive calculations. Some inequalities (like this, for example) are auto-solved by it without any meaningful mind effort. But sometimes it can be quite hard. The technique is very powerful and allows to prove many inequalities where no "nice" proof is available.
Comment: I was surprised when I couldn't find any "nice" proofs to this problem, since it looked very simple indeed. But if pqr doesn't involve heavy calculations in this case, it might not be so bad...
Comment: @MartinWestin Well, it did involve quite heavy calculations in this case. Like expanding the products from the third inequality in my solution. I did it with Wolfram Alpha, of course.
Comment: @RiverLi You are absolutely right.
Answer: To prove the inequality ((1+x^2)(1+y^2)(1+z^2) >= 64) given that (xy+yz+zx=9), we can use the AM-GM (Arithmetic Mean-Geometric Mean) inequality.
First, let's simplify the left-hand side:
((1+x^2)(1+y^2)(1+z^2) = (1+x^2+y^2+z^2+x^2y^2+y^2z^2+z^2x^2+x^2y^2z^2))
Now, we need to find a relationship between (x^2 + y^2 + z^2) and (x^2y^2 + y^2z^2 + z^2x^2).
Using the given condition (xy + yz + zx = 9), we can square both sides:
((xy + yz + zx)^2 = 81)
(x^2y^2 + y^2z^2 + z^2x^2 + 2xyz(x + y + z) = 81)
Now, we know that (x^2 + y^2 + z^2 = (x + y + z)^2 - 2(xy + yz + zx)), so:
[x^2 + y^2 + z^2 = (x + y + z)^2 - 2(9)]
[x^2 + y^2 + z^2 = (x + y + z)^2 - 18]
Now, we can rewrite the left-hand side of the inequality in terms of (x + y + z) and (x^2 + y^2 + z^2):
((1 + x^2)(1 + y^2)(1 + z^2) = (1 + x^2 + y^2 + z^2 + x^2y^2 + y^2z^2 + z^2x^2 + x^2y^2z^2))
[= [(x + y + z)^2 - 18 + x^2 + y^2 + z^2 + x^2y^2 + y^2z^2 + z^2x^2 + x^2y^2z^2]]
Now, let's denote (x + y + z) as (S):
[= [S^2 - 18 + S^2 - 18 + x^2y^2 + y^2z^2 + z^2x^2 + x^2y^2z^2]]
Using AM-GM inequality on the terms (S^2 - 18) and (S^2 - 18), we have:
[\frac{(S^2 - 18) + (S^2 - 18)}{2} \geq \sqrt{(S^2 - 18)(S^2 - 18)}]
[S^2 - 18 \geq \sqrt{(S^2 - 18)^2}]
[S^2 - 18 \geq |S^2 - 18|]
Since (S^2 - 18) is always positive, we can replace (|S^2 - 18|) with (S^2 - 18):
[S^2 - 18 + S^2 - 18 \geq 2\sqrt{(S^2 - 18)^2}]
[2S^2 - 36 \geq 2(S^2 - 18)]
[2S^2 - 36 \geq 2S^2 - 36]
[0 \geq 0]
This inequality is always true, and the equality occurs when (S^2 - 18 = 0), which implies (S = \sqrt{18}).
Therefore, the minimum value of ((1 + x^2)(1 + y^2)(1 + z^2)) occurs when (x + y + z = \sqrt{18}) or (xy + yz + zx = 9). By AM-GM inequality, the minimum value is (64), which is achieved when (x = y = z = \sqrt{3}). Thus, the inequality is proven.
Comment: I cannot make out how you reach the conclusion $x+y+z=\sqrt{18}$ for equality, but that clearly contradicts with your last line $x=y=z=\sqrt 3$.  Taking the AM-GM of $S^2-18$ with itself seems irrelevant as well.  The difficulty with your approach is to find a lower bound for $x^2y^2z^2$ which is in the LHS, just AM-GM wont help with that. Things may be clearer as to what you're trying to do if you enclose most of the math/latex within $ signs, so that it renders properly.
Comment: Note that $x^2 + y^2 + z^2 \ge xy + yz + zx = 9 \implies (x+y+z)^2 \ge 27$, which makes $x + y + z = \sqrt{18}$ impossible...


Where to get Sql server 2019 32 bit

Question: I am trying to install Sql Server 2019 on my 32 bit windows 10. But I am unable to do so because on the download page of Sql server there is only 64 bit installer available.
Please advise from where can I download 32 bit installer for Sql Server 2019.
Thanks.
Comment: You don't, it doesn't exist. 32-bit versions were [discontinued with SQL Server 2016](https://learn.microsoft.com/en-us/sql/database-engine/discontinued-database-engine-functionality-in-sql-server?view=sql-server-ver15#discontinued-features-in--1).
Answer: SQL Server 2014 is the last version available on x86/IA32 architecture
Source: https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server

Where to get Sql server 2019 32 bit


Find roots of polynomial in a finite field

Question: I need to build a field $L$ of 121 elements and find how many roots polynomial $g=x^9-1$ has in $L$. Then to find all these roots.
So, $121=11^2$ this is power of prime. We can build finite field of 121 elements by finding normal irreducible polynomial of of power 2. We can see that $x^9-1 = (x-1)(x^2+x+1)(x^6+x^3+1)$, lets take $h=x^2+x+1$ as irreducible since it does not have natural roots in $Z_{11}$. We can build the field $L=\{k\alpha+b + h(\alpha), k,b \in Z_{11}\}$ Instantly we can see that 1 is the root of $g$ because of $(x-1)$.
Am I right so far? How can I find other roots of $g$ or at least find their conunt?
Comment: So far mostly good. Presumably $\alpha$ is the coset $x+\langle h(x)\rangle$. Therefore you can simply state that $L=\{k\alpha+b, k,b\in\Bbb{Z}_{11}\}$. Irreducibility of $h(x)$ is all you need to get this far. Observe that $h(\alpha)=0$ so there is no need to add that term. Seeing that $1,\alpha$ and $\alpha^2$ are the only zeros of $g$ in $L$ is a bit more involved. I endorse lhf's method. Had I been awake when you posted this question I would have given the same answer :-)
Answer: To construct a field with $121$ elements we just need an irreducible quadratic polynomial over $\mathbb{F}_{11}$.
For instance, since $\left(\frac{2}{11}\right)=-1$ ($2$ is not a quadratic residue $\!\!\pmod{11}$, since $11\equiv 3\pmod{8}$)
we have:
$$ \mathbb{F}_{121}\simeq \mathbb{F}_{11}[z]/(z^2-2) \tag{1}$$
In general, the roots of $x^9-1$ are the ninth roots of unity, i.e. $1$, the primitive third roots of unity and the primitive ninth roots of unity:
$$ x^9-1 = (x-1)\cdot \Phi_{3}(x)\cdot\Phi_9(x) \tag{2}$$
$\mathbb{F}_{121}^*$ is a cyclic group with $120$ elements, hence $x^3-1$ splits as a product of linear factors over $\mathbb{F}_{121}$, but no root of $\Phi_9(x)$ (i.e. no primitive ninth root of unity) lies in $\mathbb{F}_{121}$, since $9\nmid 120$.
We may notice that by defining $\mathbb{F}_{121}$ as in $(1)$ we have:
$$ (z+5)^3 = (z+5)(z^2+10z+25) = (z+5)(2-z+3)=25-z^2=1 \tag{3} $$
hence $1,z+5$ and $(z+5)^2 = 5-z$ are the third roots of unity in $\mathbb{F}_{121}$.
Here I got $z+5$ by computing $(z+a)^3$ for $a=1,2,3,4$ then finally being lucky, but there is no need for trial and error. In general we have $\omega=\frac{-1+\sqrt{-3}}{2}$, but in $\mathbb{F}_{11}$ we have $-3=8$, hence $$\omega = \frac{-1+2\sqrt{2}}{2} = z+5$$ since $z=\sqrt{2}$, roughly speaking.
Comment: Where did you get $(z+5)^3$ from?
Comment: @Levitan: by trial and error. I computed $(z+a)^3$ for $a=1,2,3,4$ and finally got lucky.
Comment: @Levitan: anyway, there is a way that avoids trial and error. In general we have $\omega=\frac{-1+\sqrt{-3}}{2}$, but in $\mathbb{F}_{11}$ we have $-3=8$, hence $$\omega = \frac{-1+2\sqrt{2}}{2} = z+5$$ since $z=\sqrt{2}$, roughly speaking. Answer updated with this explanation.
Comment: $\sqrt{2} \notin Z_{11}$
Comment: @Levitan: I know that, but $z$ in $\mathbb{F}_{11}[z]/(z^2-2)$ is still a root of $z^2=2$. So we may say that $\sqrt{2}\not\in\mathbb{F}_{11}$, but $\sqrt{2}\in\mathbb{F}_{121}$.
Answer: Once you have constructed $L$, note that the multiplicative group $L^\times$ has order $120$ and so the solutions of $x^9=1$ are the same as the solutions of $x^3=1$ because $\gcd(120,9)=3$. There are exactly $3$ roots because $L^\times$ is cyclic. These roots are $1, u^{40}, u^{80}$, where $u$ is a generator of $L^\times$.
Comment: could you please point me to the theory which gives "$x^9=1$  equal to $x^3=1$ because of $gcd(120,9)=3$"? This statement is not clear for me. From where  you got $u^{40}$, $u^{80}$ is also not clear
Comment: @Levitan, $x^{120}=1$ because of Lagrange's theorem. Now write $3=120a+9b$ and conclude $x^3=1$. For the second part, $v=u^{120/3}$ has order $3$ and so does $v^2$.


How to disable access to a node

Question: What I want is whenever a registered user saves a page type node - that specific node should be made inaccessible to the user.
So if a registered user has save node/122, node/122 should be made inaccessible to the user.
How can I do it?
Comment: Are you looking to remove view or edit permissions (or both) after they have created t?
Comment: yes all permissions so that the page is taken offline to all but admin
Answer: Easy! When a new Page is created, just change its owner to a different user with appropriate role and permissions. In our case, let's say to admin.
First, install the Rules package, enable Rules and Rules Admin modules.
Navigate yourself to the Rules | Triggered rules | Add a new rule page:
Label: Detach page from creator
Event: After saving new content
Make sure the new rule is active. Save changes and on the next page Add a condition:
Select the condition to add: Content has type
Content types: Page
Save and Add an action:
Select an action to add: Load a user account
User id: 1
Save and again, Add an action:
Select an action to add: Set the content author
User, who is set as author: Loaded user
Done! This changes the node creator and the original author has control over it no more.
As you will see, this is just the quickest solution to your problem. Rules module enables you to go wild and achieve heaps of stuff that you would normally expect separate modules to be put together for. To get the idea, have a look at how I used Rules (in conjunction with Flag) to keep track of Recently viewed nodes in Drupal.
Note that the node creator always has view permission to the node, as long as they have access content, without which CMS wouldn't make much sense. Anyway, to keep track of the original creator, for display or so, you can use the CCK's User reference module.
Answer: For each content type that is associated with the Node module, the module defines the following permissions: create, edit any content, edit own content, delete any content, and delete own content. You can allow users with a role to create nodes of a specific content type, and not allow those users to edit those nodes; what the Node module doesn't allow is to forbid users with a role to view nodes basing of their content type.
If the question is how an administrator user can hide content from the ordinary users, then an administrator user can unpublish a node. This can be done in the node edit page, using the form fields in the "Publish options" field set; alternatively, it can be done from admin/content/node (admin/content in Drupal 7) selecting the nodes to unpublish and the "Unpublish" ("Unpublish the selected content" in Drupal 7) option in the "Update options" field set.
Comment: I mean as an user say user1 I can create node type Page and edit as well. But later admin may want to hide this page so as to make it inaccessible to the user who has created it( user1). For example when Admin has accepted the article submission so that the article is no longer available for the ordinary users.
Comment: I updated my answer.
Comment: Thanks but I was looking for hiding a page altogether from non-admin authors. Unpublishing does not hide them from their owner creators. In fact the article submitters will create articles only in unpublished states.
Comment: By default users cannot see unpublished nodes, if they don't have the permission to administer nodes; in that case, all they get when they try to view an unpublished node is an "access denied" page.

How to disable access to a node


Sum of integrals of gaussian function

Question: The background for this question is inferential statistics. I am trying to derive some characteristics about estimators in the context of design-based inference. Let us assume I have a population of $N$ elements. Each element is associated to a value $\beta_i$. I do not know the individual values of $\beta_i$ for each population element, but I know their mean (denoted as $\mu_\beta$) and variance (denoted as $\sigma_\beta^2$). To each population element, I apply the function:
$$\int_{2-\beta_i}^{\infty} \, e^{-t^2/2} \, dt. $$
Now, I want to sum the result of this function over each population element. I believe I can formally write this problem in the following format:
$$ \sum_{i=1}^{N} \int_{2-\beta_i}^{\infty} \,  e^{-t^2/2}  \, dt. $$
Do you think this can be simplified, expressed, or solved as a function of the only valid information I have, namely the mean and variance of $\beta_i$?
EDIT:   After the very good answers from Henry and Eduardo, there doesn't appear to be any further simplification possible. However, what would happen if I knew the distribution of values of βi, in addition to their mean and variance? Could this potentially lead to a multivariable calculus problem?
BTW I hope this edit in within the forum policy, I can create a new post if necessary....
Answer: I don't think you can simplify this expression further. You can rewrite the integral as: $$\int_{2- \beta_i}^\infty e^{-t^2/2} dt= \sqrt{\frac{\pi}{2}}\left(\text{erf}\left(\frac{\beta_i - 2}{\sqrt{2}}\right) + 1\right)$$
and then your sum becomes: $$\sqrt{\frac{\pi}{2}} \sum_{i = 1}^N \left(\text{erf}\left(\frac{\beta_i - 2}{\sqrt{2}}\right) + 1\right)=N\sqrt{\frac{\pi}{2}}+\sqrt{\frac{\pi}{2}}\sum_{i = 1}^N \text{erf}\left(\frac{\beta_i - 2}{\sqrt{2}}\right)$$
and I don't see any way of simplifying this.
Edit: As @Henry said in his comment, you can rewrite this in terms of the CDF of a standard normal, as: $$\Phi(x)=\frac{1}{2}\left(1+\text{erf}\left(\frac{x}{\sqrt 2}\right)\right)$$
thus: $$\text{erf}\left(\frac{x}{\sqrt 2}\right)=2\Phi(x)-1$$
So we can simplify the expression as: $$N\sqrt{\frac{\pi}{2}}+\sqrt{\frac{\pi}{2}}\sum_{i = 1}^N [2\Phi(\beta_i - 2)-1]=\sqrt{2\pi}\sum_{i=1}^N \Phi(\beta_i - 2)$$
Comment: Thank you @Henry. I didn't noticed that
Comment: thank you @Henry and Eduardo. Would the situation change if i know the distribution of values $\beta_i$?
Comment: I have no idea, I'm sorry but I'm not particularly good with probabilities. maybe @Henry can help.

Sum of integrals of gaussian function


First homology group of an abelian group

Question: Let $G$ be an abelian group and $R$ a commutative ring , with trivial G-action on $R$, I am trying to see that $H_1(G,R) \cong H_1(G)\otimes R \cong G\otimes R$, so by definition if we wake a projective resolution $F$ of $\mathbb{Z}$ over $\mathbb{Z}[G]$, we have that $H_1(G,R)=H_1(F\otimes_G R)$,  and now i have tried using something like the universal coefficient theorem but got nowhere. Thanks in advance.
Comment: Do you know that $H_1(G,\mathbf{Z})=G$ if $G$ is an abelian group?
Comment: Yes, i belive that $H_1(G,Z)$ is the abelinization for an arbitary group $G$ , im just a little confused on how to use the universal coefficient theorem because we have that tensor product over $G$.
Answer: The point of the Universal Coefficient Theorem for Group homology is that it is just the UCT for modules over $\mathbf{Z}$ adapted to the case of $\mathbf{Z}[G].$
To make this work, note that you can start with a projective $\mathbf{Z}[G]$ resolution of $\mathbf{Z}$. So you have
$$P_\bullet\to \mathbf{Z}$$ as $\mathbf{Z}[G]$ modules. Then you can tensor this with $-\otimes_{\mathbf{Z}[G]}R$ and note that you get a new complex $ P_\bullet\otimes_{\mathbf{Z}[G]}R$. The cohomology is defined as
$$H_{*}(G,R)=H_{*}(P_\bullet\otimes_{\mathbf{Z}[G]}R) $$
However note that in case $R$ is a trivial $G$-module, we have $$P_\bullet\otimes_{\mathbf{Z}[G]}R\cong (\mathbf{Z}\otimes_{\mathbf{Z}[G]} P_\bullet) \otimes_{\mathbf{Z}}R.$$
So you can apply the UCT for chain complexes of $\mathbf{Z}$ modules here which gives
$$H_{i}(G,R)=H_{i}(G,\mathbf{Z})\oplus \textrm{Tor}_1^{\mathbf{Z}}(H_{i-1}(G,\mathbf{Z}),R).$$
The general result now is that $H_1(G,R)=G/[G,G]\otimes R$ whenever $R$ is a trivial $G$ module, since the Tor term vanishes as $H_0(G,\mathbf{Z})=\mathbf{Z}$ is flat over itself.
The point is that the UCT for Group Homology only works in the case $R$ is a trivial $\mathbf{Z}[G]$ module, for then the coinvariant contribution of the $G$ action only comes from the projective complex.
Edit. Note that group homology is defined as the left derived functors  $L_i(\mathbf{Z}\otimes_{\mathbf{Z}[G]}(-))R.$ This is the same as taking the left derived functors $L_i((-)\otimes_{\mathbf{Z}[G]}R)\mathbf{Z}.$
Comment: Yes, these are the same thing. Your functor $(-)_G$ takes coinvariants. For a module with trivial $G$ action it does nothing. Now also $(-)_G\cong \mathbf{Z}\otimes_G(-)$  as functors, where tensoring over $G$ means tensoring over the ring $\mathbf{Z}[G].$
If $F_{\bullet}$ is the free $\mathbf{Z}[G]$ resolution of $R$ you need to compute $\textrm{Tor}_i^{\mathbf{Z}[G]}(\mathbf{Z},R)$. Equivalently, you can take a free $\mathbf{Z}[G]$ resolution of $\mathbf{Z}$ and tensor with $-\otimes_{\mathbf{Z}[G]}R$ since both give the same answer.
Comment: Now your final equality follows by noting that $\mathbf{Z}\otimes_{\mathbf{Z}[G]}(F_{\bullet}\otimes R)\cong (\mathbf{Z}\otimes_{\mathbf{Z}[G]}(F_{\bullet})\otimes_{\mathbf{Z}[G]} R\cong (F_{\bullet})_G\otimes_{\mathbf{Z}[G]}R\cong  (F_{\bullet})_G\otimes_{\mathbf{Z}} R, $ where the last isomorphism is true since both sides have trivial $G$-action.
Comment: no problem, hope it helped!
Comment: One thing ,i read the definition of Homology with coefficients in Brown's Book , where he defines $H_*(G,R) =H_*(F \otimes_G R)$, where $F \otimes_G R \cong (F \otimes R)_{G} \cong \mathbb{Z} \otimes_{\mathbb{Z} [G]} (F \otimes R) $, so im not sure that is the same thing you have there.
Comment: Oh yeah that works thanks alot !, sorry for the confusion i am little new to all of this.


Trouble aligning text with WYSIWYG

Question: I have added TinyMCE to work with one of my text formats, and I added the different alignment buttons. When I try to center some text it adds "text-align: center" to the p... but when I save it, it goes back to normal. I would like to fix that to be able to align text and images. I installed a module called WYSIWYG Filter and added "text-align" in Text properties... still doesn't work. I also added "p[style|text-align]" to the "HTML elements and attributes" section... still doesn't work.
Any ideas of what could I be missing?
...I'm using Drupal 7 BTW
Answer: If you're using the filtered HTML input format, that would be stripping it out.
If not, it sounds like your markup is weird. The way you describe it, what might work if it read
 (not that I recommend this) reads
. I think WYSWIG editors tend to prefer classes to putting styles right in the markup, so I'd do something like
 and add .centered-text{ text-align:center } to your stylesheet.
I would double-check your site with a DOM inspector to make sure your style on your
 isn't being overridden by a stylesheet. If nothing else works, you could use a different editor. jWYSIWYG, openWYSIWYG, Whizzywig, and nicEditor use align="wherever" instead of style="text-align:wherever" which might work (again, I don't recommend this, but it's a potential short-term solution. For reference, MarkItUp and WYMeditor don't offer alignment buttons, and CKEditor, FCKEditor, TinyMCE, and YUIeditor do it the "right" way, using style="")
Comment: thanks for your answer, but how do I change the default behavior of adding `style="text-align:center"` to adding `class="centered-text"`
Comment: added info about which wysiwyg editors have different default behavior, although none of the ones i've tried so far add a class.
Comment: Wait, are you using a separate TinyMCE module as well as the WYSIWYG module, or are you just using WYSIWYG with the TinyMCE library in sites/all/libraries/tinymce? My answer is based on using [WYSIWYG](http://drupal.org/project/wysiwyg) with the respective editor libraries installed in the libraries file. Try doing it that way and see if that works better, maybe?
Comment: OK, I eventually got it to work... it still does the "tinymce way" with styles instead of classes within the tags... I'm using the WYSIWYG Filter module to allow all the tags and attributes I need available... far from perfect, ugly as hell,.. but it works

Trouble aligning text with WYSIWYG


Como redimensionar imagens antes de realizar o upload?

Question: Estou precisando redimensionar as imagens ao realizar o upload junto ao db, no entanto apesar de encontrar soluções eu não estou conseguindo incorporar no código.
<code><?php
include "conexao.php";

$titulo = $_POST['titulo'];
$arquivo = $_FILES['arquivo']['name'];
$categoria = $_POST['categoria'];

// Pasta onde o arquivo vai ser salvo
$_UP['pasta'] = 'uploads/';
// Tamanho máximo do arquivo (em Bytes)
$_UP['tamanho'] = 1024 * 1024 * 2; // 2Mb
// Array com as extensões permitidas
$_UP['extensoes'] = array('jpg', 'png', 'gif');
// Renomeia o arquivo? (Se true, o arquivo será salvo como .jpg e um    nome único)
$_UP['renomeia'] = true;
// Array com os tipos de erros de upload do PHP
$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do    PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho    especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';
// Verifica se houve algum erro com o upload. Se sim, exibe a mensagem    do erro
if ($_FILES['arquivo']['error'] != 0) {
die("Não foi possível fazer o upload, erro:" . $_UP['erros']   [$_FILES['arquivo']['error']]);
exit; // Para a execução do script
}
// Caso script chegue a esse ponto, não houve erro com o upload e o  PHP    pode continuar
// Faz a verificação da extensão do arquivo
@$extensao = strtolower(end(explode('.', $_FILES['arquivo'] ['name'])));
if (array_search($extensao, $_UP['extensoes']) === false) {
echo "Por favor, envie arquivos com as seguintes extensões: jpg, png     ou gif";
exit;
}
// Faz a verificação do tamanho do arquivo
if ($_UP['tamanho'] < $_FILES['arquivo']['size']) {
echo "O arquivo enviado é muito grande, envie arquivos de até 2Mb.";
exit;
}
// O arquivo passou em todas as verificações, hora de tentar movê-lo    para a pasta
// Primeiro verifica se deve trocar o nome do arquivo
if ($_UP['renomeia'] == true) {
// Cria um nome baseado no UNIX TIMESTAMP atual e com extensão .jpg
$nome_final = md5(time()).'.jpg';
} else {
// Mantém o nome original do arquivo
$nome_final = $_FILES['arquivo']['name'];
}

// Depois verifica se é possível mover o arquivo para a pasta  escolhida
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] .     $nome_final)) {
    $sql = "INSERT INTO usuario(titulo, foto, categoria) VALUES   ('$titulo', '$nome_final', '$categoria')";
$query = $con->query($sql); /*= mysqli_query($sql, $cad_produto);*/

        if($query!=null){
            print "    <script>alert(\".\");window.location='../postar.php';</script>";
        }

 }

?>
</code>
Comment: qual erro você está tendo?
Comment: Neste código nenhum, o que desejo é adaptá-lo para poder redimensionar as imagens ao realizar o upload, no entanto não sei como fazer, eu encontrei esse tutorial mas ao tentar mesclar os dois o upload não é realizado. [https://www.linhadecomando.com/php/php-funcao-para-redimensionar-arquivos-de-foto]
Comment: Um começo: http://php.net/manual/pt_BR/function.imagecopyresized.php
Answer: Este código pode ajudar:
<code>    include("resize-class.php");

    // *** 1) Inicializar Imagem
    $resizeObj = new resize('sample.png');

    // *** 2) Redimensionar imagens (Opções: exato, retrato, paisagem, auto, crop)
    $resizeObj -> resizeImage(200, 200, 'crop');

    // *** 3) Salvar imagem
    $resizeObj -> saveImage('sample-resizeda.jpg', 1000);
</code>
resize-class.php
<code># ========================================================================#
   #  Requires : Requires PHP5, GD library.
   #  Usage Example:
   #                     include("resize_class.php");
   #                     $resizeObj = new resize('images/cars/large/input.jpg');
   #                     $resizeObj -> resizeImage(150, 100, 0);
   #                     $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
   # ========================================================================#

        class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;

            function __construct($fileName)
            {
                // *** Open up the file
                $this->image = $this->openImage($fileName);

                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }

            ## --------------------------------------------------------

            private function openImage($file)
            {
                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }
                return $img;
            }

            ## --------------------------------------------------------

            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];

                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);

                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }

            ## --------------------------------------------------------

            private function getDimensions($newWidth, $newHeight, $option)
            {

               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }

            private function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }

            private function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getOptimalCrop($newWidth, $newHeight)
            {

                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;

                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }

                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);

                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }

            ## --------------------------------------------------------

            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                   $extension = strtolower($extension);

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;

                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;

                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);

                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;

                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;

                    // ... etc

                    default:
                        // *** No extension - No save.
                        break;
                }

                imagedestroy($this->imageResized);
            }

            ## --------------------------------------------------------

        }
?>
</code>


Deleting intervals from $(0,1):$ what is the resulting set?

Question: Take the open interval $(0,1)$.

Split into thirds and consider only the open intervals at each end. We are left with:
$$\big(0,\tfrac13\big)\cup \big(\tfrac23,1\big)$$ For each of these:

Split into quarters and consider only the open intervals at each end. We are left with: $$\big(0,\tfrac{1}{12}\big)\cup \big(\tfrac{1}{4},\tfrac{1}{3}\big)\cup \big(\tfrac23,\tfrac34\big)\cup \big(\tfrac{11}{12},1\big)$$
For each of these:

Split into fifths $...$

$$\text{etc}.$$
Continuing this process indefinitely (a countably infinite amount of times), what are we left with?
Initially I would have said nothing, but having read and asked about similar Cantor set like things, I am not so sure...
Comment: @DanielFischer Read his question more carefully. It's not the Cantor set.
Comment: @coffeemath Right, didn't see it was not the (closed) middle thirds that were removed.
Comment: @DanielFischer  I don't think it can be described only using the ternary expansion, as at the second stage each remaining interval is quartered, at the third stage each remaining is cut in fifths, and so on.
Answer: You don't get nothing -- every infinite sequence of "left" and "right" that doesn't eventually end in all "left"s or all "right"s will map to a sequence of nested open intervals where both right and left endpoints move towards each other. They therefore have a point in common that never gets removed.
In fact, if you use closed intervals instead of open ones, you get something that is homeomorphic to the usual middle-thirds Cantor set, so with open intervals the result is homeomorphic to the middle-thirds Cantor set without its interval endpoints.
It can be viewed as a "thin" analogue of a fat Cantor set; how large a fraction of each interval you're removing at each step doesn't change the topology of the limit set (though it can change its measure, as the fat Cantor set shows).


Fast way to select small sample from huge table

Question: The table I have is huge about 100+ million entries, it is ordered by default by 'A'. There could be many items with the same column A, A increases from 0 to... A big number. I tried TABLESAMPLE but it does not quite select a good number from each A number, it skips some of them or maybe I am not using it well. So I would like to select the same amount of values from each A number. And I would like the total of selected rows to be a number, let's say 10 million or let's call it B.
Comment: Seems like you want a very specific set, not a sample. Does the set of values from each A number need to be different / random every time you run the query? Can you describe the index(es) on the table? An important distinction: a table isn't "ordered by default" - a table is an unordered set of rows. While there may be a clustered index that dictates allocation order, not all queries will return data in that order and it shouldn't be relied upon.
Comment: What database and version are you using?
Comment: How many rows are there per value of "A"?
Comment: by ordered i mean indexed by A
Comment: i dont know how many rows there are for each value of A
Answer: While it's not exactly clear to me what you need to achieve, when I have needed a large sample subset that is very well distributed between Parent and/or common Attribute values, I have done it like this:
SELECT  *
FROM    YourTable
WHERE   (YourID % 10) = 3

This also has the advantage that you can get another completely different sample just by changing the "3" to another digit.  Plus you can change the sub-sample size by adjusting the "10".
Answer: You can make use of NEWID():
SELECT TOP 100
  *
FROM
  YourTable
ORDER BY NEWID()

Answer: @RBarryYoung solution is right, generic and it works for any constant statistic distribution, like id sequences (or any auto-increment column). Sometimes, though, your distribution is not constant or you can run into performance issues (SQL Server has to scan all index entries to calculate the WHERE clause).
If any of those affects your problem, consider the built-in T-SQL operator TOP that may suit your needs:
SELECT TOP (30) PERCENT *
FROM YourTable;


Dar efeito na imagem e no hover voltar a deixar colorida

Question: Não sei se é possível.
Tentei com mix-blend-mode, filter, mas não dá certo.
Seria possível uma imagem começar com uma camada de cinza e em cima, uma camada verde.
Ao passar o mouse, a imagem volta a ficar colorida?
Comment: Poderia dar um exemplo da imagem original e da imagem com hover? Vai melhor descrever seu problema.
Answer: Uma sugestão seria desta forma: uma imagem com grayscale 100%, e sobre ela um pseudo ::after com fundo verde transparente. Ao passar o mouse, o pseudo some e a imagem volta ao grayscale 0% mostrando suas cores naturais:

#container{
   position: relative;
   width: 300px;
   height: 200px;
}

#container img{
   width: 100%;
   height: 100%;
   -webkit-filter: grayscale(100%);
   filter: grayscale(100%);
}

#container span::after{
   content: '';
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0;
   left: 0;
   background-color: rgba(0, 100, 0, .4);
}

#container span:hover img{
   -webkit-filter: grayscale(0%);
   filter: grayscale(0%);
}

#container span:hover::after{
   display: none;
}


Custom Views Filter - won't display as checkboxes

Question: Trying to do a custom filter so that the user can select multiple states to filter the data by.  This works (or will when I do some customizing to the query after) but it shows a select box.  Any ideas?  Tearing hair out :)
<?php
class custom_filters_handler_filter_state extends views_handler_filter_string{
  function value_form(&$form, &$form_state){
    $options = array(
     'DC' => 'DC',
     'MD' => 'MD',
     'VA' => 'VA',
    );
   $form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   );
return $form;
  }
}

Answer: I've the same issue, debugging the code I've seen that the exposed_translate() method changes any checkboxes form types to select if $form['#no_convert'] and #multiple are not set.
So you need to change it to:
$form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   '#no_convert' => TRUE,
);

Here is the code:
/**
   * Make some translations to a form item to make it more suitable to
   * exposing.
   */
  function exposed_translate(&$form, $type) {
    if (!isset($form['#type'])) {
      return;
    }

    if ($form['#type'] == 'radios') {
      $form['#type'] = 'select';
    }
    // Checkboxes don't work so well in exposed forms due to GET conversions.
    if ($form['#type'] == 'checkboxes') {
      if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
        $form['#type'] = 'select';
      }
      if (!empty($this->options['expose']['multiple'])) {
        $form['#multiple'] = TRUE;
      }
    }
    if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
      unset($form['#multiple']);
      $form['#size'] = NULL;
    }

    // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
    if ($form['#type'] == 'select') {
      $this->prepare_filter_select_options($form['#options']);
    }

    if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
      $any_label = variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('<Any>') : t('- Any -');
      $form['#options'] = array('All' => $any_label) + $form['#options'];
      $form['#default_value'] = 'All';
    }

    if (!empty($this->options['expose']['required'])) {
      $form['#required'] = TRUE;
    }
  }

Answer: In order to render select elements you should extend views_handler_filter_in_operator instead of views_handler_filter_string. I'm not aware of this, but it might be that views_handler_filter_string interferes with the value form in any way as to never allow multiple input or something like this.
Then, instead of defining the value_form on your own (which you can certainly do), you can also limit your impact and thus keep a certain configurability by overriding only the necessary class methods. In your case I would simple override views_handler_filter_in_operator::get_value_options like this:
function get_value_options() {
  if (isset($this->value_options)) {
    return;
  }
  $this->value_options = array(
    'DC' => 'DC',
    'MD' => 'MD',
    'VA' => 'VA',
  );
}

Comment: Thanks - I had tried this option earlier and gotten an error.  Hearing from you that this was the correct approach made me take a closer look at that error.  I'm trying to do this on a field in the Location module which is causing the problem.  But, I found another solution so thank you!
Comment: @Elizabeth For future reference, can you post your solution as an answer to this question if you find the time?


I want to create a newline containing incrementing numbers between each line of text

Question: I have lines of text as follows:
The cat and the mouse
Were in the house
They spotted some grouse

I want to put a new line between each line of text with an incrementing number after a ">" so that it looks like this
>1
The cat and the mouse
>2
Were in the house
>3
They spotted some grouse

I would like to do this in perl if possible s I can run it on a mac. Can anyone help?
Answer: Something like this should do it:
perl -pe 'print ">$.\n"' foo.txt

Answer: You can use perl from command line,
perl -pe 's|^|>$.$/|' file

$. is current line number, and $/ is input record separator (usually newline \n)
Comment: @user3632206 you can redirect output to file by adding `> file2` or do in place edit `perl -i -pe ..`
Comment: Awesome. How would I then save the result to a txt file rather than it printing out on the terminal?
Comment: Actually I was trying to upvote it as it did exactly what I wanted it to, but now Im locked out for a few hours
Comment: It told me my vote had been locked in and I couldnt change it unless I edited it. I could have sworn I upvoted the answer as it was really useful. Guess Ill try tomorrow


SQL SERVER perfomance?

Question: I Joined two tables , each one containing more than 5000 records . I used two methods to join . In the first query I used JOIN keyword and gave the condition in ON condition .
In the second query I just used a comma operator between the tables and gave the joining condition in WHERE clause .
Which one will be effective regarding time and cost ....?
When i look into the execution plan First query took 61 % cost for the TABLE SCAN and 38% for the HASH MATCH ( INNER JOIN )
The second query took 69 % cost for the TABLE SCAN and 31% for the HASH MATCH ( INNER JOIN ) .
Can you explain me this difference ?
Iam assuming that First one is effective , Because the table scan cost is less . Is it right...?
Comment: This question lacks meaning with indicating whether the fields in involved are indexed in either or both tables and the nature of the index
Comment: Your first query does a table scan - if possible you should set the foreign key on the table to a non-clustered index.  The query should then result in an index scan - significantly quicker.
Answer: TABLE SCAN's means it has to read through every single row in a table.  Normally with Execution plans you try to get rid of table scan by using indexes etc where possible.  Table scans are generally the main cause of slow running queries. (in my experience)
Percentage decrease is only an improvement if the overall time the SQL takes to run is reduces compared to what it was previously
For example if the first query with a slightly reduced TABLE SCAN took 20 seconds instead of 10, then it's not as effective.
Of course if your looking to optimise your query then there is a whole host of methods you can apply to try and improve it. (Index Tuning Wizard, Create Indexes (Clustered/Non Clustered), View Execution Plan - Identify potential bottlenecks etc…)
SQL Optimisation its an artform in itself
Answer: It sounds to me like the query plan was the same in both cases... since you had a table scan and a hash match both times...
Before you try and compare those percentages... let me illustrate the danger with this question:
which is bigger
61% of 465

or
69% of 234

??
You might see in this case that 69% of 234 would be by far "quicker" than 61% for 465.  Its all relative to the total cost of the query.
Be careful about just comparing percentages because you don't know what the actual value that corresponds to 100% in both cases is... e.g. the TOTAL execution cost might have been lower in the second case.
Answer: Define 'effective'. If speed is your goal, select 'show client statistics', run both queries at least a dozen times (in different query windows, of course), and evaluate the results.
Answer: the two techniques are logically equivalent
but can have vastly different performance hits depending on how the parser
plans the query.  You'll need to consider two key factors when deciding
between the techniques:

Which version produces a query plan that is better optimized.
Which is more maintainable should the code need to be retrofitted later
to incorporate more joined (INNER or OUTER) tables.

INNER JOIN vs WHERE clause

SQL SERVER perfomance?


Store authentication passwords on client securely?

Question: Let's say we have a client and a server. If the client wants to "connect" to the server, it needs to provide a password (in plaintext, transmitted over https). If the client were to remember the password, it open a whole lot of vulnerabilities. Are these avoidable?
Answer: I assume you mean if the server were to remember the password. The client remembering the password is a direct trade-off between convenience and security, not much to discuss there.
Run the password through a "hash". This is, essentially, a one-way process - you can get from the password to the hash, but not the hash to the password. On the server side, you only store the hash. When someone wants to authenticate, take their password, hash it, and compare it to your stored hash. You do not have to store the password in plaintext this way.
This is very basic password handling stuff. There are some subtlties to getting it right. There's some discussion about a c# implementation here: Hash and salt passwords in C#
If you do mean the client remembering the password, you still don't need to store the password itself. Authenticate with the server and have it return a token which expires after a certain time. This token is good as a credential for logging in while it's valid. Your client only needs to store the token.


Hypothesis testing for detecting a (damped) sinusoidal signal in noise

Question: I have a signal in white noise that has the following form:
\begin{equation}
r[t_i] = A e^{-t_i/\tau} \sin{(\omega t_i + \phi)} + n[t_i]
\end{equation}
I would like to test whether the signal (1st term) at a known frequency $\omega$ is present against the null-hypothesis of pure noise. I know for the noise term (Poissonian with $N>>1$) the standard deviation. $\phi$ and $\tau$ are unknown, however $\tau$ should be long compared to $t_\mathrm{max}$.
Is there a statistical test for this purpose? (If there are already implemented tests, Python is preferred but any language is fine)
I simulate a signal e.g. by
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)

# Signal parameters
f   = 0.25 # Known
tau = 50   # Unknown
phi = 0    # Unknown
A   = 0.07 # Unknown A<1

# Signal modeling
t = np.arange(25)
s = A*np.sin(2*np.pi*f*t+phi)*np.exp(-t/tau)

# Noise parameters:
N   = 20e3 # Mean number of counts (known)
c   = 0.3  # Contrast (known)

# Noise modeling
cts = N *(c-2-2*c*s)/(c-2)
r = np.random.poisson(cts)
plt.plot(r)
plt.title('signal with noise')
plt.show()

Comment: Can you post some of the data, or some reasonable simulation, so we can better understand what you're working with?
Comment: I edited the question. The simulated signal as fairly good SNR such that it is easier to understand what I am hunting for.
Comment: 1. Your terminology seems very strange to this statistician; in particular the use of the term "noise" for the model of $n$ seems odd there. It looks like it's not centered at 0, so it's more a *bias* on your damped sinusiodal "model", rather than mere *noise*. Note that the rest of the model (aside $n$) converges to 0, but your values are cycling around 20000. I sure wouldn't refer to that as just noise.       2. Maybe I misunderstood something but if $\tau$ is "long compared to $t_\max$", then wouldn't you only have a fraction of a cycle rather than many?
Answer: My intuition tells me:

build an optimal filter using e.g. a correlation with your expected signal r(t_i): see first example under https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.correlate.html
Run this filter over 1000 or more random noise signals, and observe the maxima of the correlation signals.
Then do it for your signal. If this maximum exceeds the 95% quantile of the observed maxima under the null hypothesis, then reject the null hypothesis with significance level 5%

For why this is sound see Rogers post which relates statistical signal processing and matched filters (optimal filters).
Answer: It may be possible to use Bayesian statistics here.
Let's set testing aside for a moment and instead focus on estimation.  If we can construct a model and assess the estimates of $A$, maybe we can say something substantive about the decay term.
A simple model in Stan would be
data {
    int n;
    array[n] int r;
    vector[n] t;
    real c;
    real N;
    real f;
}
parameters {
    real<lower=0> inv_tau;
    real<lower=-1, upper = 1> phi_scaled;
    real<lower=0, upper=1> A;
}
transformed parameters {
    vector[n] s = A .* sin(2 * pi() * f * t +  pi() * phi_scaled) .* exp(-t * inv_tau);
    vector[n] cts = N .*(c-2-2*c*s)./(c-2);
}
model{
    A ~ uniform(0, 1);
    phi_scaled ~ uniform(-1, 1);
    inv_tau ~ cauchy(0, 1);

    r ~ poisson(cts);
}
generated quantities {
   real estimated_tau = 1.0 / inv_tau;
   real estimated_phu = pi() * phi;

}

Here, I am modelling scaled_phi to be on the interval $[-1, 1]$ and simply multiplying it by $\pi$ in the signal part.  Additionally, I am modelling the inverse of $\tau$ rather than tau because I typically find that small parameters are often modelled more easily than large ones.
When I run the model, I get good diagnostics (note, you will need to install cmdstan and cmdstanpy if you want to replicate this).

import numpy as np
import cmdstanpy
import matplotlib.pyplot as plt
import arviz as az
def simulate_data():
    rng = np.random.RandomState(123)

    # Signal parameters
    f   = 0.25 # Known
    tau = 50   # Unknown
    phi = 0    # Unknown
    A   = 0.07 # Unknown A<1

    # Signal modeling
    t = np.arange(25)
    s = A*np.sin(2*np.pi*f*t+phi)*np.exp(-t/tau)

    # Noise parameters:
    N   = 20e3 # Mean number of counts (known)
    c   = 0.3  # Contrast (known)

    # Noise modeling
    cts = N *(c-2-2*c*s)/(c-2)
    r = rng.poisson(cts)

    return t, r, cts

def fit_model(*args, **kwargs):
    t, r, cts = simulate_data()

    model = cmdstanpy.CmdStanModel(stan_file="signal.stan")

    data = dict(t=t.tolist(), r=r.tolist(), n=r.size, f = 0.25, N = 20000, c = 0.3)

    fit = model.sample(data, **kwargs)

    return fit

fit = fit_model()

print(fit.diagnose())

Checking sampler transitions treedepth.
Treedepth satisfactory for all transitions.

Checking sampler transitions for divergences.
No divergent transitions found.

Checking E-BFMI - sampler transitions HMC potential energy.
E-BFMI satisfactory.

Effective sample size satisfactory.

Split R-hat values satisfactory all parameters.

Processing complete, no problems detected.

Now, we can look at some plots of the estimated parameters
var_names = ['A', 'estimated_tau', 'estimated_phi']

fig, ax = plt.subplots(dpi = 240, ncols=3, nrows=1, figsize = (15, 5))

for vn, a in zip(var_names, ax):
    x = fit.stan_variable(vn)
    a.hist(x, edgecolor='white')
    a.set_title(vn)

$A$ and $\phi$ are very well estimated.  Tau remains uncertain (95% credible interval: 21 - 389), perhaps that could be combatted with some better priors.
From these plots, we could conclude that $A>0$ and hence the first term is likely present.
Answer: In engineering context likelihood ratio test is a typical approach for signal detection. The Poissonian noise for $N\gg 1$ can be viewed as Gaussian, which allows to write the joint probability density for the observations at the selected time moments $t_1,..., t_K$. This probability could be compared to the probability that the observations are purely due to the noise. One the compares the ratio of the two probabilities to a specified threshold to decide whether the signal is present or not.
The detailed derivations can be likely found in older (pre-digital era) radio-engineering or physics textbooks. After a bit of googling I found these notes on Statistical signal processing, which seem to be pretty close to what the OP is asking.
Comment: +1 the notes talk about "matched filter" or in other words an optimal filter which is related to my post. Nice to see that there is sound background
Comment: PS: https://en.wikipedia.org/wiki/Matched_filter#Interpretation_as_a_least-squares_estimator also shows this connection (although less explicit than in the notes :) )
Comment: @Ggjj11 there is likely parallel terminology here, depending on whether one speaks in the context of *signal processing* or *random/stochastic processes* - even though one deals with the same problem (*signal detection*). I learned both in the context of detecting radio-waves (awhile ago, during my undergrad.)


Approach to handling the login attempts, php

Question: I want to handle the login attempts like this :
The ways I know to handle the attempt count is to use sessions, cookies or creating an attempt data in database;
As I know cookies are weak because they are being stored at the client side.
Sessions are safer to use rather than using cookies but from my research I get the result that even sessions that are created for handling login attempts can be controlled by hackers.
I decided to record the attempts to the database,

Keep records of the IP, attempt count, time.
After 3 unsuccessful attempts I am planning to display a CAPTCHA
After 2 unseccesful attempts with CAPTCHA I am planing to stop the user (which is trying from same IP) from trying login for 10 mins.

(The reason I am not using the CAPTCHA at the beginning, because it is annoying. Nobody wants to type an extra input)
So my first question is; is it a bad idea to keep tracking the attempts by recording data because of connecting the database and checking the count of the attempts on every reloading of the loginpage can be overload the website? (I am new to web programming so if my questions are silly, pardon me)
My second question;
Is this a good way to control user by IP or is there a better way to control this?
I am waiting to hear any suggestions from you.
Comment: An IP address doesn't usually correspond to one person. You might find an entire university behind a single public-facing IP address.
Comment: It is indeed a good way to attempt to secure yourself more, almost everyone big does something of that sort to control the number of attempts. Go ahead
Comment: Increasing a database counter of some kind on every page reload doesn't cause much load, even if you are running a frequently visited page this won't make your server slow. Using a combination of user-agent and IP would be a bit better if there are more than one user connected using the same IP (gateway).
Comment: But, keep in mind that people can spoof their ipaddress. Ofcourse it is better to have any kind of security than nothing at all.
Comment: @MikeSherrill'Catcall' I agree. It is also fairly trivial to claim to have a different IP address than I actually have.  For tracking legitimate user's login attempts this may be of some small use, but to enforce security it is futile.
Answer: For my sites I do the following

Limit based on IP, 5 failed attempts per IP in 1 hour, requires a captcha for 1 hour for that IP
Limit based on user, 5 failed attempts per user in 1 hour, requires a captcha for 1 hour for that user
Limit based on Overall failed logins, 100 overall failed in 1 hour, require a captcha for 1 hour for every log in attempt

so for example if 18.104.22.168 fails for a user called user all 3 counters are incremented (its implemented as a single row in the database, but the query shows all 3 values as 1). also Tweak the values depending on the size of the site.
Each time there is a captcha shown, if its required again after the 1 hour is increased by 30 minutes each time, But from the logs that has never happened yet.
Captchas like recaptcha get harder the more they are failed. So that takes care of brute forcing.
The connection to the database is a very slight over head and shouldnt even be considered when security is concerned.
I dont "reset" these counts on successful login either.
Comment: Yes, It stops people trying passwords like `password` or `123456` for every user too. IP's are fairly cheap to buy / use. Its very rare that this rule is triggered though. The first 2 are >95%  of the time the reason a captcha is showing
Comment: I think this is what I am looking for. Thank you. I am using recapthca, too. So if I misunderstand please correct me, for your third limit explanation; if there are 100 overal fails you require captcha for _every IP_ ?


A real vector space with an almost complex structure vs its complexification

Question: Suppose $(V, J)$ is a real vector space of dimension $2n$ equipped with an almost complex structure $J$ such that $J^2 = -Id$. $V$ can be realized as a complex vector space by setting $iv = J(v)$ for any $v \in V$. On the other hand one can consider the complexification of $V$, $V \otimes_{\mathbb R} \mathbb C$ and the complexification can be viewed as a complex vector space naturally. There are two almost complex structures on the complexification, one is the $\mathbb C-$linear extension of $J$ and the other is multiplication by $i$. What is the motivation behind considering the complexification in terms of doing complex geometry? Why can't we just consider the original tangent space?
I understand the complexification can be decomposed into eigenspaces of $J$, but what confuses me a bit is what is the benefit of doing so.
Comment: Thanks for the clarification, but I still do not see what is the point here. For the tangent space of a complex manifold, why do we need to consider its complexification?
Comment: The reason one may want to complexify the real tangent bundle of an almost complex manifold $(M,J)$ is that the eigenbundles $T^{1,0}M$ and $T^{0,1}M$ of $J$ contain useful information about $J$. For example integrability of the $J$ can be determined on these bundles or their dual. If your manifold is already complex then the complexified tangent space is isomorphic to the tangent space of the complexification of the underlying real analytic manifold. This also sees application every now and then.
Comment: Note that with $(V,J)$, $V$ refers to the entirety of the complexified space. On the other hand, with the complexification $V \otimes_R \Bbb C$, $V$ denotes the "real" subspace of the complexification. The point, perhaps, is that even in the first case where we are not given the "real" subspace, we can build it using the eigenspace structure of $J$.
Comment: Take this with a grain of salt because my primary experience with complexifications does not come from geometry. I would guess, however, that the point is that when one considers a complex manifold, there already exists a built-in definition of multiplication by $i$ whereas for $V \otimes_{\Bbb R} \Bbb C$, one constructs elements in order to make multiplication by $i$ make sense. In other words, the first approach is compatible with an existing complex-multiplication structure.
Comment: I don't see why you would need to consider complexifications if your manifold comes with a tangent space that already permits multiplication by complex numbers (i.e. is a complex vector space).
Answer: Say $V$ is a real vector space of dimension $2n$, and $J \colon V \to V$ is an operator squaring to $-1$. Then (as you know) the pair $(V, J)$ defines a complex vector space of dimension $n$, with $i \cdot v := Jv$ giving the action of $i$. This means that in any basis, the matrix of $J$ is an $n \times n$ diagonal matrix, with every diagonal entry equal to $i$. Stated in another way, $J$ now satisfies a linear polynomial $J - i = 0$, rather than a quadratic $J^2 + 1 = 0$.
On the other hand, the complexification $V_\mathbb{C} := V \otimes \mathbb{C}$ is also a complex vector space, this time of dimension $2n$, and the action of $i$ is given by $i \cdot (v \otimes z) = v \otimes iz$. The complexification $J_{\mathbb{C}} := J \otimes \operatorname{id}_\mathbb{C}$ is also an operator on this space, sending an element $v \otimes z$ to $Jv \otimes z$. $J_\mathbb{C}$ still satisfies the quadratic $J_\mathbb{C}^2 + 1 = 0$, and hence splits $V_\mathbb{C}$ into two subspaces: the $+i$ eigenspace and the $-i$ eigenspace of $J_\mathbb{C}$. We can see that
$$ J_\mathbb{C}(v \otimes 1 - Jv \otimes i) = Jv \otimes 1 + v \otimes i = i(v \otimes 1 - Jv \otimes i),$$
$$ J_\mathbb{C}(v \otimes 1 + Jv \otimes i) = Jv \otimes 1 - v \otimes i = -i(v \otimes 1 + Jv \otimes i),$$
and by further playing around with these eigenspaces you can see that they are each $n$-dimensional. Therefore the matrix of $J_\mathbb{C}$ in an appropriate basis here is diagonal, with $n$ entries equal to $i$, and $n$ entries equal to $-i$.
So in the case of the complex structure $(V, J)$, $J$ simply acts as the $n \times n$ multiplication-by-$i$ scalar operator, while in the complexification $V_\mathbb{C}$, the operator $J_{\mathbb{C}}$ is a particular $2n \times 2n$ diagonalisable operator with eigenvalues $\pm i$ (in particular, it is nothing like a complex structure, but still an operator of a special form).
As for why one wants to consider complex tangent bundles  by occasionally forgetting their complex structure and then remembering them again, I would draw an analogy with taking real and complex parts of a complex number (although this analogy is a bit dubious, as a "real structure" on a complex vector space is a different thing...), it allows one to work with all the usual tools one has for real vector spaces or manifolds, then try to use the complex structure to deduce things for the complex manifold.


$\lim\limits_{x \uparrow 1} \exp (-\sum\limits_{n=0}^{\infty}x^n)$

Question: I have to determine the following:
$\lim\limits_{x \uparrow 1} \exp (-\sum\limits_{n=0}^{\infty}x^n)$
My idea is the following:
$\lim\limits_{x \uparrow 1} \exp (-\sum\limits_{n=0}^{\infty}x^n) = \lim\limits_{x \uparrow 1} \exp (-\frac{1}{1-x^n})$=...
Comment: You should have $\frac{1}{1-x}$ instead of $\frac{1}{1-x^n}$.  Then, what is the conclusion of your idea?
Answer: By continuity of $\exp$ $$\lim_{x \uparrow 1} \exp \left(- \sum_{n=0}^\infty x^n \right)=\exp \left( \lim_{x \uparrow 1} - \sum_{n=0}^\infty x^n \right)=\exp \left( \lim_{x \uparrow 1} \frac{1}{x-1} \right)=\exp(-\infty)=0. $$


Proving $f\in H^\ast$

Question: Let $H$ be a Hilbert space and $\{f_n\}_{n=1}^\infty\in H^\ast$. Suppose $f_n$ weakly converges to a linear operator $f$ in $H.$ Then $f\in H^\ast$.
My idea: by Riesz representation theorem we can find $y\in H$ such that $f(x)=\langle x,y\rangle$ for all $x$. Then we now need to use the fact that $f_n$ weakly converges to $f$. Does $f_n$ weakly converges to $f$ means $\langle f_n,g\rangle\rightarrow\langle f, g\rangle$ for all $g\in H^\ast$? I thought $f_n$ weakly converges to $f$ if and only if $\lim_{n\rightarrow\infty}\|\varphi(f_n)-\varphi(f)\|=0$ for all $\varphi\in X^{\ast\ast}$. Or is it an equivalent definition?  Or should I use the fact that Hilbert space is reflexive?
Answer: This is an easy consequence of Uniform Boundedness Principle. For each $x$ the sequence $(f_n(x))$ is convergent, hence bounded. This implies that $\sup \{|f_n(x)|: n \geq 1, \|x\| \leq 1\}$ is finite by Uniform Boundedness Principle. Hence $\sup \{|f(x)|:  \|x\| \leq 1\}$ is finite so $f$ is a continuous linear functional.
Answer: It is a consequence of uniform boundedness principle:
If $\{A_\alpha\}$ is a collection of continous linear operators from a banach space $X$ to a normed vector space $Y$.(Here $X$ is $H$ and $Y$ is $\mathbb{C}$) If $$\sup_{\alpha}||A_{\alpha}(x)||_{Y}<\infty.$$ Then $\sup_{\alpha}||A_\alpha|| < \infty.$
So since for any $x\in H$, $f_n(x)$ tends to a limit $f(x),$ we have $\{f_n(x)\}$ is bounded for all $x$.So $\sup ||f_n|| < M$ for some $M>0$.
So for any $x\in H,$$$f(x)=\lim_{n\rightarrow \infty}f_n(x)\le \sup||f_n||||x||\le M||x||.$$
So $f$ is bounded too, and hence $f\in H^*$.
p.s for the proof of the uniform boundedness principle, click https://en.wikipedia.org/wiki/Uniform_boundedness_principle

Proving $f\in H^\ast$


eigenvalues of k-regular bipartite graph adjacency matrix.

Question: I need some help with this proof:
Let G be a k-regular graph. prove that:
a) If G is bipartite then -k is an eigenvalue of G's adjacency matrix.
b) If -k is an eigenvalue of G's adjacency matrix then G is bipartite.
Got stuck in figuring out what the general form of such an adjacency matrix.
Thanks!
Comment: Let $k=2$ or $k=3$ and play with some bipartite graphs, for example, $K_{3,3}$. What is its adjacency matrix? Is $3$ indeed an eigenvalue?
Comment: Its suppose to be minus k, so minus 3 or minus 2.
I just don't really know how to continue...
Comment: Given a graph, do you know how to find its adjacency matrix? If so, what is an adjacency matrix for a $K_{3,3}$?
Comment: This one is for K2,2 :
0 0 1 1
0 0 1 1
1 1 0 0
1 1 0 0
but I cant figure how to get from this to the proof because no one said its the complete bipartite graph, just k regular.
Answer: First we prove that if $G$ is regular then $k$ is an eigenvalue:
The easiest way to prove $k$ is an eigenvalue is to notice that $A-kI$ is not invertible because each row has sum $0$, but I provide another proof:
Recall that the sum of the $\lambda_i^j$ gives the number of closed walks of length $j$.
We can easily show the number of closed walks of even length $j$ is at least $k^{j-D}$ where $D$ is the diameter of the graph.
Notice that if the largest eigenvalue is less than $k$ we will have too few closed path of even length $j$ for large values of $j$.
An analogous proof can be used to prove no eigenvalue can be larger than $\Delta$ in any graph.

Now we assume $G$ is bipartite then  $-k$ is an eigenvalue.
One way is to assume it is not and notice that the sum of $\lambda_i^j$ will be positive for large odd $j$.
Another way is to look at the adjacency matrix, notice it is of form $\begin{pmatrix}
0A \\\
A^T0
\end{pmatrix}$
It is thus clear that if we write the characteristic polynomial and use the formula for the determinant as a sum of permutations, that each non-zero summand will need to have an even number of $x$ factors, so the characteristic polynomial can be expressed with the variable $x^2$, which means it can be factored in the way $(x^2-a_i)$, which tells us the spectrum is symmetric.

Now we must prove that if $-k$ is an eigenvalue the $G$ is bipartite.
Notice that this is not true in general, but it is if we ask for connectivity ( for a counterexample consider a graph with $K_4$ and $K_{3,3}$ as the only components)
Assume that it is not bipartite, we can prove that the number of closed walks of odd length $j+1$ is at least $d^{j-2D-l}$ where $l$ is the length of some odd cycle.
However for odd values the sum of $\lambda_i^j$ cancels out $k$ and $-k$, so we only have values of $\lambda_i$ with norm smaller than $k$. This means the sum is too small for large values of $j$.
For this part we need for $k$ to have multiplicity $1$, this can be verified by noticing $A^{2m+1}$ has only positive entries for large $m$, and using Perron-Frobenius on it.
Comment: But in the first direction it also suppose to be minus k and not k, is that a mistake?
Comment: Oh, I Made a mistake, I missread it, but it can be easily fixed.
Comment: Done !${}{}{}{}{}$
Comment: I didn't managed to understand your solution unfortunatley, can you please elaborate?
especially on this direction: if −k is an eigenvalue the G is bipartite.
Comment: What do you mean?
Comment: If you could please write a more elaborative proof, because I didn't understood how to prove this thm from the guidelines you left me. Thanks a lot!
Comment: No way I already wrote like $5$ paragraphs. When I had to learn it I was told it was a trivial application of the walk counting formula.
Comment: Proving (b) should be easier my way (see my answer).
Answer: For (a) you first prove that $k$ is an eigenvalue of $G$'s adjacency matrix $A$. This is simple and is already explained in Hidalgo's answer: $A-kI$ is not invertible.
Now I will show (a) in a different way from Hidalgo. This is taken from Bartlett's lecture notes: write
$$\mathbf A=\begin{bmatrix}\mathbf0&\mathbf B\\\mathbf B^T&\mathbf0\end{bmatrix}\qquad\mathbf v=\begin{bmatrix}\mathbf a\\\mathbf b\end{bmatrix}\qquad \mathbf{Av}=k\mathbf v$$
where $\mathbf B$ has dimensions $m×n$, $\mathbf a$ has length $m$ and $\mathbf b$ has length $n$. It is then easy to check that $(\mathbf a,-\mathbf b)^T$ is an eigenvector of $A$ associated to $-k$.
To prove (b) without counting walks, assuming $G$ is connected (otherwise, as Hidalgo's example shows, this is false in general) normalise the eigenvector $\mathbf v$ associated to $-k$ such that some component (say it lies at index $i$; these indices also label $G$'s vertices) is $1$ and all other components have absolute value at most $1$. Then, looking at the $i$th component of $\mathbf{Av}=-k\mathbf v$:
$$\sum_{j=1}^na_{ij}v_j=\sum_{j\text{ adjacent to }i}v_j=-kv_i$$
With the magnitude restrictions, $G$'s $k$-regularity and $v_i=1$, this means $v_j=-1$ for all neighbours $j$ of $i$. Negate $\mathbf v$ and repeat the argument for all the neighbours $j$; iterate until the whole graph is covered, by connectivity. This shows that all elements of $\mathbf v$ are $+1$ or $-1$ with signs differing if the corresponding vertices are adjacent in $G$.
Now assume $G$ is not bipartite, then it contains an odd cycle. However, the sign assignment above will run into a contradiction on this odd cycle. Hence $G$ is bipartite.

Combining the (b) argument with the proof in Bartlett's notes that $G$ having $\Delta(G)$ as an eigenvalue implies it is regular gives a proof that if a connected $G$ has $-\Delta(G)$ as an eigenvalue it is regular and bipartite.


Commerce multiple stores and multiple carts for B2B customers

Question: i have a problem with multiple stores.
i set up 2 stores of the same type. store B2B for B2B customers and store B2C for B2C.
all products are sold in store B2B and just a few also in store B2C.
when i add to cart products from B2B store, in cart page i have only one commerce_cart_form view.
when i add a product sold also in B2C store, i have 2 commerce_cart_form view.
the first one with products sold in B2B store and the second one with products sold in B2C store.
why are there 2 carts?
it seems that built multiple stores to manage B2B and B2C is not the right choice.
thanks
Answer: According to the Commerce 2 documentation, stores are optimized for two use cases:

We optimize for the two use cases:
One business that has one or more locations or 2. The marketplace
  model (where you have sellers)
One or more locations This is the most common eCommerce situation where we have a single person, company, or organization that is taking
  payments online.
Marketplace model The marketplace model is where you have many sellers who are taking payment for unique products.

Each store can have a different currency, payment method, order flow, and so on.  So, each store also has a separate, unique cart.
It seems there are two ways to do what you want.

Keep two different stores, one for B2B and one for B2C.  If the configuration is mostly the same, you will have to duplicate a lot of config between the two stores.  You will also need to keep the two stores separate so that B2B customers see the B2B store and B2C customers see the B2C store.
Just have one store.  Add a select field to the products for admin to indicate whether it is a B2B product, B2C product, or both.  Then, modify the views that show the products so that B2B customers see B2B products and B2C customers see B2C products.  This way, you don't have to duplicate the config for the payment flow and so on.
Comment: thanks. i choose the second option.

so multiple stores can have only unique products and not shared one. if i sell shared product i will have 2 or more cart in the cart page.

if it is true, why in the product edit form, store setting selection has multiple options?
Comment: @FabioRiva Multiple stores can share products.  But, if you buy products from different stores at the same time, you will have multiple shopping carts.  You need a cart for Store 1 and a cart for Store 2.  If you don't want the products to be mixed, you need to filter the products so that users only see products for the correct store.
Comment: Thank you Patrick. you don't think that is a strange behavior? when i buy products from different sellers in amazon i have one cart.
Answer: The 2 separate carts into 1 cart solution has not been developed.  Please refer to this discussion: How to checkout 2 carts at once like Etsy does on Commerce 2.x?


Rules with VBO in views

Question: I have a view (using the table display format) that is showing all the node of a content type (A), and that content type has a reference to nodes of another content type (B). I added a VBO field to that view.
How can I create a content type B node for each node of the selected node (content type A) by setting the values just one time in the content type B create form?
(I need to create B nodes with the same field values for each node of A.)
Answer: The best way to get started is to watch the video series Learn the Rules Framework.  It will demonstrate how to create the node and populate any data fields according to the content in your type A node.

Rules with VBO in views