FindIndex extension in LINQ

Question: I am trying to find the indexes as follows.
But the following LINQ says there is no extension of FindIndex.
foreach (var distinctClassId in distinctClassIds)
{
    var indexes = classComponents.Where(x=> x.ClassId.Equals(distinctClassId)).
                  FindIndex(x => x.Id == Constants.Classes.ClassID.ToString() ||
                   x.Id == Constants.Courses.CoursesID.ToString());
}

Comment: `classComponents.Where(x=> x.ClassId.Equals(distinctClassId))` returns an `IEnumerable`  where as the FindIndex() method is applicable on List.  Change following to `var indexes = classComponents.Where(x=> x.ClassId.Equals(distinctClassId)).ToList().
                  FindIndex(x => x.Id == Constants.Classes.ClassID.ToString() ||
                   x.Id == Constants.Courses.CoursesID.ToString());`
Comment: https://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
Comment: What exactly should `FindIndex` do? You know that there is a `Where` overload that gives you the index of the current item as parameter to the predicate? And a `Select` overload as well?
Comment: To avoid confusion: you named the variable `indexes`, do you expect `FindIndex` to return _multiple_ indices? `FindIndex` only returns the index of the first item that matches the predicate...
Comment: @RenéVogt Yes, it could be more than one.
Comment: ok, edited my answer accordingly
Answer: FindIndex() is an instance method of List<T>. But Where() returns an IEnumerable<T> (or maybe an IQueryable<T> depending on what classComponents is in your code).
So you need to convert that Where result to list before you can call FindIndex():
foreach (var distinctClassId in distinctClassIds)
{
    var indexes = classComponents.Where(x=> x.ClassId.Equals(distinctClassId)).ToList(). // here -> ToList()
                  FindIndex(x => x.Id == Constants.Classes.ClassID.ToString() ||
                   x.Id == Constants.Courses.CoursesID.ToString());
}

But FindIndex() only gives you the index of the first matching item. Your variable is called indexes, so you might want to find the indices of multiple matching items. This can be done by using the linq overloads that give you the index, too:
foreach (var distinctClassId in distinctClassIds)
{
    var filtered = classComponents.Where(x=> x.ClassId.Equals(distinctClassId)).ToList();

    var indexes = filtered.Select((item, index) => new {item, index})
                          .Where(x => x.item.Id == Constants.Classes.ClassID.ToString() ||
                   x.item.Id == Constants.Courses.CoursesID.ToString())
                          .Select(x => x.index);
}

This creates objects of anonymous type containing the item and its index, then checking which items match and finally returning their indices.
Note: if you actually wanted the indices in the source list (classComponents), you should combine the Where statements like that:
foreach (var distinctClassId in distinctClassIds)
{
    var indexes = classComponents.Select((item, index) => new {item, index})
                    .Where(x => x.item.ClassId.Equals(distinctClassId) &&
                                (x.item.Id == Constants.Classes.ClassID.ToString() ||
                                 x.item.Id == Constants.Courses.CoursesID.ToString()))
                    .Select(x => x.index);
}

FindIndex extension in LINQ


How do I mimic Windows Explorer multi-select/drag-n-drop behavior in a DataGridView?

Question: I'm trying to mimic the way Windows Explorer handles multiple selection.  In a default DataGridView, you can select multiple items using Ctrl-click.  But if you release the Ctrl key and then try and drag/drop the selected items, it clears the selected items and only selects the "hit" row.  I found the following solution somewhere online.
protected override OnMouseDown(MouseEventArgs e)
{
  int hitRowIndex = HitTest(e.X, e.Y).RowIndex;
  if(!SelectedRows.Contains(Rows[hitRowIndex]))
  {
    base.OnMouseDown();
  }
}

However, this causes other side effects.  With the CTRL key pressed and mousing down on a selected item, the item remains selected.  This makes sense because the mousedown event is bypassed if the row clicked on is selected.  From looking at the behavior of Windows Explorer, it looks like the deselection of an item with the CTRL key held is not handled until the MouseUp event.  Has anyone tried to do this?
Answer: I have created a custom component to fix this, and some other annoying issues I had with multi selection in datagridview. This is the code, hope it helps anyone:
public partial class CustomDataGridView : DataGridView
{
    public CustomDataGridView()
    {
        InitializeComponent();
    }
    public CustomDataGridView(IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    private bool _delayedMouseDown = false;
    private Rectangle _dragBoxFromMouseDown = Rectangle.Empty;

    private Func<object> _getDragData = null;
    public void EnableDragDrop(Func<object> getDragData)
    {
        _getDragData = getDragData;
    }

    protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
    {
        base.OnCellMouseDown(e);

        if (e.RowIndex >= 0 && e.Button == MouseButtons.Right)
        {
            var currentRow = this.CurrentRow.Index;
            var selectedRows = this.SelectedRows.OfType<DataGridViewRow>().ToList();
            var clickedRowSelected = this.Rows[e.RowIndex].Selected;

            this.CurrentCell = this.Rows[e.RowIndex].Cells[e.ColumnIndex];

            // Select previously selected rows, if control is down or the clicked row was already selected
            if ((Control.ModifierKeys & Keys.Control) != 0 || clickedRowSelected)
                selectedRows.ForEach(row => row.Selected = true);

            // Select a range of new rows, if shift key is down
            if ((Control.ModifierKeys & Keys.Shift) != 0)
                for (int i = currentRow; i != e.RowIndex; i += Math.Sign(e.RowIndex - currentRow))
                    this.Rows[i].Selected = true;
        }
    }
    protected override void OnMouseDown(MouseEventArgs e)
    {
        var rowIndex = base.HitTest(e.X, e.Y).RowIndex;
        _delayedMouseDown = (rowIndex >= 0 &&
            (SelectedRows.Contains(Rows[rowIndex]) || (ModifierKeys & Keys.Control) > 0));

        if (!_delayedMouseDown)
        {
            base.OnMouseDown(e);

            if (rowIndex >= 0)
            {
                // Remember the point where the mouse down occurred.
                // The DragSize indicates the size that the mouse can move
                // before a drag event should be started.
                Size dragSize = SystemInformation.DragSize;

                // Create a rectangle using the DragSize, with the mouse position being
                // at the center of the rectangle.
                _dragBoxFromMouseDown = new Rectangle(
                    new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
            else
                // Reset the rectangle if the mouse is not over an item in the datagridview.
                _dragBoxFromMouseDown = Rectangle.Empty;
        }
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
        // Perform the delayed mouse down before the mouse up
        if (_delayedMouseDown)
        {
            _delayedMouseDown = false;
            base.OnMouseDown(e);
        }

        base.OnMouseUp(e);
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        // If the mouse moves outside the rectangle, start the drag.
        if (_getDragData != null && (e.Button & MouseButtons.Left) > 0 &&
            _dragBoxFromMouseDown != Rectangle.Empty && !_dragBoxFromMouseDown.Contains(e.X, e.Y))
        {
            if (_delayedMouseDown)
            {
                _delayedMouseDown = false;
                if ((ModifierKeys & Keys.Control) > 0)
                    base.OnMouseDown(e);
            }

            // Proceed with the drag and drop, passing in the drag data
            var dragData = _getDragData();
            if (dragData != null)
                this.DoDragDrop(dragData, DragDropEffects.Move);
        }
    }
}

Answer: May be this help you:
    protected override void OnMouseDown(MouseEventArgs e)
    {
        int hitRowIndex = HitTest(e.X, e.Y).RowIndex;
        if ((!SelectedRows.Contains(Rows[hitRowIndex])) || ((ModifierKeys & Keys.Control) != Keys.None))
        {
            base.OnMouseDown(e);
        }
    }


Algorithms that approximate the volume of concave/convex hull formed by some n-dimensional data points

Question: Suppose now I have 1000 d-dimensional data points. Is there a convenient algorithm that can approximate the volume of the concave/convex hull formed by these points?
Thanks in advance!
Comment: Hmm, depends on what you mean by convinient. For large d, unless there is some other structure you can take advantage of I would probably just use a Monte Carlo simulation. https://en.wikipedia.org/wiki/Monte_Carlo_method
Answer: According to Wikipedia, given a membership oracle, we can compute an $\epsilon$ approximation of the volume of the convex hull in polynomial time in $n$ (=1000), $d$ and $\frac{1}{\epsilon}$.
Combining with this answer, it seems that membership can also be tested fairly quickly.
However, if this is convenient enough for you, I don't know.


Visitors from strange IP addresses

Question: Almost every day I have new users on my website that come from strange IP addresses:
184.108.40.206
220.127.116.11
188.8.131.52
etc.

Maxmind says these IP addresses belong to Poland, Cloudflare. But CloudFlare is a company that offers reverse proxy services. How is it possible that people come from these IP addresses?
At the same time RIPE reports that these IP addresses are not even European IP addresses.
These are not spiders, bots but real people. They create profiles, upload photos etc
So, does anyone know something about these IP addresses?
Comment: You have a publicly accessible website. I'm not sure what you expected, but I would have expected to see connections from any ip address... anywhere in the world.
Comment: Why do you think these connections are "strange"?
Comment: As long as the visitor is not from 126.96.36.199 ... you probably [don't need to worry](http://www.ipvoid.com/scan/188.8.131.52/)
Comment: Geolocation services are not perfect.
Comment: RIPE is right, MaxMind is wrong.
Answer: Every server on the internet is constantly bombarded with requests from all kind of spiders and bots and as long as your system is secure and updated, there is usually no need to worry about it.
Comment: Maybe spammers ... Anyway, it you can't filter them and maybe block them with stuff like Captchas, you have to live with it. There is no need to "know anything about these IP addresses".
Comment: These are not spiders, bots but real people. They create profiles, upload photos etc.
Answer: Just ask CloudFlare via www.cloudflare.com
They will know the answer.
And check THIS out:
126.96.36.199 spam attacks log

Date/ time (GMT)    Email   Sender Nickname Anti-spam app
Dec 15, 2015 08:45:18   firstname.lastname@example.com   herpes simplex cure v2.33 WordPress
Dec 05, 2015 23:36:17   email@example.com  marisakh60  v5.33 WordPress
Dec 05, 2015 15:35:37   firstname.lastname@example.com rapidpharma.mediahostforph.com  v2.33 WordPress
Dec 01, 2015 09:35:50   email@example.com    www.rapidpharma.biz v2.33 WordPress
Nov 29, 2015 12:54:24   firstname.lastname@example.com   bcbgmaxazria fringe dress red   v2.33 WordPress
Nov 29, 2015 12:27:13   firstname.lastname@example.com    belstaff vancouver 2015 v2.33 WordPress
Nov 29, 2015 12:49:12   email@example.com jaeger lecoultre reverso batman v2.33 WordPress

Those seem to be simply a spambots.

Visitors from strange IP addresses


New uploads not refreshing to Advanced API call (Vimeo Plus Account)

Question: How long should I expect to wait until a video I uploaded to an album shows up through my API call?
It has been 3 hours since the "processing" on Vimeo was completed, and it's still not showing up. It only shows up on the Vimeo website directly.
I am on a Vimeo Plus account.
Answer: If you are making an authenticated API request to see your own list of videos, and you were the user who uploaded the video, you should see the video as soon as you have completed the upload.
Basically if you can see it on site, you should see it in the API.
Comment: Thanks. I wasn't using OAuth to make my call. I added the authentication to my request and now I see my uploads immediately.


Probability of $A+C>B+D$ for $A\sim U(x,1)$, $B\sim U(y,1)$, and $C,D\sim U(0,1)$

Question: Let $A$ be uniformly distributed on $[x,1]$ and $B$ be uniformly distributed on $[y,1]$, where $0\leq x,y\leq 1$.
If $C$ and $D$ are uniformly distributed on $[0,1]$, what is the probability that $A+C > B+D$?
I know that both $A+C$ and $B+D$ will be between $x$ and $2$ and $y$ and $2$, respectively, but definitely not uniformly. I'd imagine it's some type of normalized distribution but I haven't been able to find anything on how to do something like this. I know what the distribution of adding two numbers from the same uniform distribution is, but this is different.
Comment: Welcome to math.SE! [Here](https://math.meta.stackexchange.com/questions/5020)'s a tutorial and reference for typesetting math on this site.
Comment: You're essentially asking what is the probability that A+C+ -B +-D >0,  I suppose you can work out the convolution of these by hand relatively easily, and you'd end up with a cubic pdf
Answer: I will setup the integral you need to compute this probability and then provide a Mathematica script for evaluating it.

We have $A\sim\mathcal U(x,1)$ and $B\sim\mathcal U(y,1)$ with $0\leq x,y\leq 1$ as well as $C,D\sim\mathcal U(0,1)$.  Assuming all random variables are mutually independent we define $U=A+C$ and $V=B+D$.  The goal is then to find
$$
P=\mathsf P(U>V).
$$
We first find the density of $U$.  By the convolution of probability densities
$$
\begin{aligned}
f_U(u)
&=\int_{-\infty}^\infty f_A(t)f_C(u-t)\,\mathrm dt\\
&=\int_{-\infty}^\infty \frac{1}{1-x} \mathbf 1_{t\in(x,1)}\mathbf 1_{u-t\in(0,1)}\,\mathrm dt\\
&=\frac{1}{1-x}\int_{-\infty}^\infty \mathbf 1_{t\in(x,1)}\mathbf 1_{t\in(u-1,u)}\,\mathrm dt\\
&=\frac{1}{1-x}\int_{-\infty}^\infty \mathbf 1_{t\in(x,1)\cap t\in(u-1,u)}\,\mathrm dt\\
&=\frac{1}{1-x}\int_{\max(x,u-1)}^{\min(1,u)}\mathrm dt.
\end{aligned}
$$
Thus,
$$
f_U(u)=\frac{1}{1-x}(\min(1,u)-\max(x,u-1)),\quad u\in(x,2)
$$
and
$$
f_V(v)=\frac{1}{1-y}(\min(1,v)-\max(y,v-1)),\quad v\in(y,2).
$$
To find $P$ we need to integrate $f_{U,V}(u,v)=f_U(u)f_V(v)$ over the region $u>v$ that also coincides with the support of $(U,V)$.  The region is complicated because it is described differently depending on if $x\geq y$ or $x<y$. Combining each case we can write the probability $P$ as
$$
P=\int_{\max(x,y)}^2\int_y^u f_U(u)f_V(v)\,\mathrm dv\mathrm du.
$$
For the special case $x=y$ we can show $P=1/2$ by symmetry.
Finally, here is a Mathematica script to evaluate $P$ for specific choices of $x$ and $y$:
<code>x = 0.4;
y = 0.3;
fU[u_] := 1/(1 - x) (Min[1, u] - Max[x, u - 1]);
fV[v_] := 1/(1 - y) (Min[1, v] - Max[y, v - 1]);
Integrate[fU[u, x] fV[v, y], {u, Max[x, y], 2}, {v, y, u}]
</code>
Comment: @user17670386 You're right.  It's fixed now.
Comment: is case 1 not the same as 1 - case 3 and swap x and y?
Comment: also case 2 is just 0.5 for any x and y pair


position item in a center

Question: I have a very simple question, yet I cannot figure out how to solve it.
I have a slider, where in the middle I want to display some text like below:

The problem is, that I cannot force it to align middle vertically with the image. Here is my CSS:
.caption {
    position: absolute;
    height: auto;
    text-align: center;
    zoom: 1;
    color: white;
    display:table;
    left:20%;
    width: 60%;
    margin-top: auto;
    margin-bottom: auto;
    padding: 10px 0;
    background:rgba(138, 138, 138, 0.55);
}

What am I doing wrong?
Comment: vertically at which position you want?
Comment: I would like to see the box with the text in the middle of picture
Answer: As you have already use position tag which is perfectly fine just use top property and transform property like this
.caption {
    position: absolute;
    height: auto;
    text-align: center;
    zoom: 1;
    color: white;
    display:table;
    left:20%;
    top:50%;
    transform:translate(0,-50%);
    width: 60%;
    margin-top: auto;
    margin-bottom: auto;
    padding: 10px 0;
    background:rgba(138, 138, 138, 0.55);
}

With both properties div will be vertically center no matter whatever is the height

example : https://jsfiddle.net/y2z94ez3/

position item in a center


Website farm apache best practices

Question: I've set up an app which builds new websites.  I am creating virtual host files automatically when a user signs up.
Is there a "right" way to enable the virtual host and reload apache from the web app or should I delegate that task to a cron job with root privileges?  I added www-data to the sudoers folder but I still have a permission denied in my error log.
Ubuntu 11.10 running Apache/Mod_PHP
Answer: Seems like dynamic vhosts are very useful in your situation.
You don't need to reload apache in case with vhosts at all.
Comment: You're right, this seems like the best path = )

Website farm apache best practices


cck fieldgroup tabs appear but all fields in one tab

Question: I am using cck fieldgroup tabs to group various fieldsets under different tabs and I want them to appear in tabs to anonymous user.
Somehow the tabs are not working. The tabs are all there sitting above but all the fields within each fieldset are all shown on the same page and the tab links work as if they are internal links for the same page. You click on any link and you are moved down to the fields in that fieldset on the same page.
I looked into the generated page in firebug and it came out that the classes responsible for generation and grouping of tabs are all wrong in the div and ul tags. when I changed them to the correct ones using firebug , they all looked fine in browser.
Now I dont know how are these classes put into div tags in the backend so that i can rectify it. Can someone help please.?
Comment: anyone please????
Answer: Check the permissions to ensure the fields are available to the anonymous users.
Comment: I dont think its a permissions issue because it should at least be visible in tabs to admin, but thats not the case. Isn't it?


Formatar uma string para formato de telefone

Question: Tenho a seguinte string "49988070405" e quero formata-la para "(49) 98807-0405".
Tentei o código:
Convert.ToUInt64("49988070405").ToString(@"\(00\)\ 00000\-0000");

Mas sem sucesso.
Answer: Você pode fazer da seguinte forma:
long.Parse("49988070405").ToString(@"(00) 00000-0000"); // (49) 98807-0405

Outro exemplo, utilizando extensões:
using System;

public static class Program
{
    public static void Main()
    {
        var phoneString = "49988070405";

        Console.WriteLine(phoneString.FormatPhoneNumber()); // (49) 98807-0405

        var phone = 49988070405;

        Console.WriteLine(phone.FormatPhoneNumber()); // (49) 98807-0405
    }

    public static string FormatPhoneNumber(this long number) {
        return number.ToString(@"(00) 00000-0000");
    }

    public static string FormatPhoneNumber(this string number) {
        return long.Parse(number).FormatPhoneNumber();
    }
}

Veja os exemplos funcionando no .NET Fiddle.
Comment: A primeira forma foi suficiente, mas é estranho não haver uma forma mais direta para fazer isso. Primeiro tive que converter a _string_ para _long_, depois para _string_ novamente para poder formatar.
Comment: @MatheusSaraiva Porque esse é o correto, o que você quer converter é um **número**, e o C# é uma linguagem fortemente tipada, logo não faz sentido nenhum usar uma string para armazena um número. Tem algum motivo para que o número realmente precise ser uma _string_? Pois o correto seria você já tê-lo como _long_.
Answer: Pode fazer o seguinte, segue um exemplo:
String.Format("{0:(###) ###-####}", 8005551212);

Que tem como resultado:
(800) 555-1212

Comment: Mas eu quero o resultado (49) 98807-0405, já tentei esse exemplo ai, não funcionou.
Answer: Você pode usar o seguinte:
string phone = "49988070405"
string formatted = string.Format("{0:(##) #####-####}", phone);

Answer: As respostas não aceitas não funcionam e a aceita tem um erro conceitual convertendo um dado descritivo para número para fazer a formatação, o que é, inclusive, ineficiente.
Você acha que o fato de funcionar sempre fazendo isto não impede o uso? Ok, espero que respeite os conceitos corretos em outras ocasiões que podem não funcionar mais. E espero que ficar ligando e desligando a acurácia conceitual não traga problemas (minha experiência mostra o contrário).
De qualquer forma não tem por que fazer uma conversão só porque parece ser mais simples fazer o código, a formatação deveria ser feita com a forma mais simples ainda, só que não é pronta. Inclusive porque o método Format() é bem ineficiente.
Também fiz funcionar com números que não são celular. Não me preocupei com números fora do padrão no Brasil porque acho que não existem mais (existia há algum tempo), e não me preocupei com números internacionais. Considerei que é garantido que o número vem sempre correto, caso isto não ocorra tem que verificar e impedir.
Eu não fiz tão simples porque preferi dar o máximo de eficiência usando ReadOnlySpan para não alocar no heap.
Usei ranges que é um conceito que muitos programadores C# ainda não conhecem, apesar de já ser quase antigo.
using static System.Console;
using System;

WriteLine(FormataTelefone("49988070405"));
WriteLine(FormataTelefone("4988070405"));

static string FormataTelefone(string number) {
    if (number.Length != 10 && number.Length != 11) throw new ArgumentException($"Tamanho da string deve ser 10 ou 11", nameof(number));
    ReadOnlySpan<char> span = stackalloc char[number.Length];
    span = number.AsSpan();
    var offset = 11 - number.Length;
    return $"({span[0..2]}) {span[2..(7 - offset)]}-{span[(7 - offset)..]}";
}

Veja funcionando no .NET Fiddle. Também coloquei no GitHub para referência futura.


Are all transcendental numbers a zero of a power series?

Question: So I came across the concept of extending the notion of irrationality to higher degree polynomials. The base case of this is standard irrationality. That is, a number is irrational if it cannot be expressed as the ratio of two integers. This is equivalent to it not being able to be expressed as a root to a linear equation with integer coefficients:
$$r=\frac{p}{q}\rightarrow qr-p=0$$
where $p,q\in\mathbb{Z}$.
$\sqrt 2$ is an example of a number that cannot satisfy the above. Thus it is irrational. However , we can extend this condition to quadraic polynomials:
$$ax^2+bx+c=0$$
$\sqrt 2$ does satsify the above given $a=1$, $b=0$ and $c=-2$. Thus in this scheme $\sqrt 2$ would be a $1$st degree irrational.
(I think degree of irrationality is already a term in math. Is it equivalent to what I am talking about? If it's not we can use something like "level $1$ irrational".)
And in general an $n$th degree irrational number is a real number that can be expressed as a zero of an $n$-degree polynomial and not an $n+1$ degree polynomial. (This is so every number has a unique degree of irrationality.)
This brings us to transcendental numbers, which are not the solution to any finite degree polynomial with integer coefficients. This is their definition. This leads me to my question:
Is a transcendental number a real number whose degree of irrationality is infinite (or maybe countably infinite if that distinction is relevant or even valid)? So any transcendental (and any real as a result) is the root of a power series with integer coefficients (centered at 0)?
Or is a transcendental number a number that simply isn't the solution to any finite degree polynomial? This would seem to be a weaker statement then the one above.
Comment: (You probably want only power series centered at 0 with integer coefficients.)
Comment: You're right, changed it.
Comment: In your quadratic, with c=-4, the roots are 2 and -2.  If you want √2 for a root, change it to c=2.
Comment: Whoops, you're right, changed it. Although I think you mean $c=-2$.
Comment: Every real number is the sum of a power series. Decimal notation expresses any number $x$ as $\Sigma_{n=\ceiling(\log_{10}x)}^\infty d_n$, where $d_n$ are the digits of $x$.
Answer: What you call the "degree of irrationality" of a number is the degree of its minimal polynomial over $\mathbb Q$, sometimes called the degree of the number over $\mathbb Q$. This concept is defined and explored in field theory.
Every real number is the root of a power series with integer coefficients.
Comment: Only the real numbers in $(-1,1)$.  Transcendental numbers outside of this range cannot be roots of power series because their powers get larger and larger, so the addends in any power series of it cannot converge to 0 and thus the sum does not converge.
Comment: @alphacapture I think this problem goes away if you allow rational coefficients, which is probably the more interesting question here.
Comment: @PaŭloEbermann I suppose whether that counts as a series depends on whether the OP wants to allow series centered around other points.

OzanerHansha You can't expand it because you would need an infinite sum to find each of the coefficients, and the infinite sum in question does not necessarily converge.
Comment: @alphacapture can't you get a series centered around a different number $c$ (i.e. $\sum_{n=1}^\infty k_n(x-c)^n$? Or does this not count as "integer coefficients" anymore?
Comment: So are all transcendental numbers the root of a power series with integer coefficients but not necessarily centered at zero? But can't this be remedied by expanding the binomial? Unless this becomes a problem in an infinite series...


Fourier transform in S′

Question: In class we have next definition for Fourier transform in $\mathcal{S}'$: $$\langle \hat{f}, \varphi \rangle = \langle f, \hat{\varphi} \rangle = \frac{1}{\sqrt{2\pi}}\int\limits_{\mathbb{R}}f(y)\int\limits_{\mathbb{R}}\varphi(x)e^{ixy}dx dy$$
I tried to solve through the definition: $$\frac{1}{\sqrt{2\pi}}\int\limits_{\mathbb{R}_{-}}\cos(y)\int\limits_{\mathbb{R}}\varphi(x)e^{ixy}dxdy + \frac{1}{\sqrt{2\pi}}\int\limits_{\mathbb{R}_{+}}y^2\int\limits_{\mathbb{R}}\varphi(x)e^{ixy}dxdy.$$ But I didn't succeed. I also tried to solve using limits in second integral (and then using Fubini's theorem) or convolution, but failed again.
Can you please suggest ideas for a solution?
Comment: The question appears to have been edited into such a state that it is no longer clear what is being asked. Please clarify the body of the question and consider a more descriptive title.
Comment: I don't know this very well but shouldn't you just calculate the ordinary Fourier transform of $f$?
Comment: $f(x)$ is not a "generalized" function. It's just a function.
Comment: @FShrike I think you are right if f is an absolutely integrable function
Comment: @jjagmath we obtain a generalized function $F$ from $f$ by a formula $F(\varphi) = \int\limits_{\mathbb{R}}f(x)\varphi(x)dx$
Comment: Then why the title says "generalized function $f =$ ..."?
Comment: @jjagmath Sorry, fixed it.
Comment: The formula is often difficult to use directly. Instead some laws and special transforms are derived using it, and these are then used.
Comment: Is $f$ the function that is $\cos(y)$ for $y<0$ and $y^2$ for $y>0$?
Answer: Let $f$ be the function defined as
$$f(x)=\begin{cases}\cos(x)&, x<0\\\\x^2&,x>0
\end{cases}$$
Then, for $\phi\in \mathbb{S}$, we have
$$\begin{align}
\langle \mathscr{F}\{f\},\phi\rangle&=\langle f,\mathscr{F}\{\phi\}\rangle\\\\
&=\int_{-\infty}^0 \cos(x)\int_{-\infty}^\infty \phi(k)e^{ikx}\,dk\,dx+\int_0^{\infty} x^2\int_{-\infty}^\infty \phi(k)e^{ikx}\,dk\,dx \\\\
&=-\lim_{L\to\infty}\int_0^L \cos(x)\int_{-\infty}^\infty \phi(k)e^{-ikx}\,dk\,dx\\\\
&+\lim_{M\to \infty}\int_0^M x^2\int_{-\infty}^\infty \phi(k)e^{ikx}\,dk\,dx\\\\
&=-\lim_{L\to\infty}\int_0^L \cos(x)\int_{-\infty}^\infty \phi(k)e^{-ikx}\,dk\,dx\tag{1a}\\\\
&-\lim_{M\to \infty}\int_0^M \int_{-\infty}^\infty \phi''(k)e^{ikx}\,dk\,dx\tag{1b}
\end{align}$$
where we used the fact that $x^2e^{ikx}=-\frac{d^2e^{ikx}}{dk^2}$ and then integrated twice by parts to arive at $(1b)$.  Next, we will apply the Fubini-Tonelli Theorem.

Inasmuch as $\phi\in \mathbb{S}$, the Fubini-Tonelli theorem guarantees that we can interchange the order of integration in $(1a)$ and $(1b)$.  Proceeding we find that
$$\begin{align}
\int_0^L \cos(x)\int_{-\infty}^\infty \phi(k)e^{-ikx}\,dk\,dx&=\frac i2\int_{-\infty}^\infty \phi(k) \left(\frac{e^{-i(k+1)L}-1}{k+1}+\frac{e^{-i(k-1)L}-1}{k-1}\right)\,dk\\\\
&=\frac12 \int_{-\infty}^\infty \phi(k) \left(\frac{\sin((k+1)L)}{k+1}+\frac{\sin((k-1)L)}{k+1}\right)\,dk\tag{2a}\\\\
&+\frac i2 \int_{-\infty}^\infty \phi(k)\left(\frac{\cos((k+1)L)-1}{k+1}+\frac{\cos((k-1)L)-1}{k-1}\right)\,dk \tag{2b}
\end{align}$$
and
$$\begin{align}
\int_0^M \int_{-\infty}^\infty \phi''(k)e^{ikx}\,dk\,dx&= \int_{-\infty}^\infty \phi''(k)\frac{e^{ikM}-1}{ik}\,dk\\\\
&=\int_{-\infty}^\infty \phi''(k)\frac{\sin(kM)}{k}\,dk\tag{3a}\\\\
&-i\int_{-\infty}^\infty \phi''(k)\frac{\cos(kM)-1}{k}\,dk\tag{3b}
\end{align}$$

Using the result in THIS ANSWER or THIS ONE, we let $L\to \infty$ in $(2a)$ and $M\to\infty$ in $(3a)$ to reveal
$$\lim_{L\to\infty}\frac12 \int_{-\infty}^\infty \phi(k) \left(\frac{\sin((k+1)L)}{k+1}+\frac{\sin((k-1)L)}{k+1}\right)\,dk=\frac\pi2 \left(\phi(-1)+\phi(1)\right)$$
and
$$\lim_{M\to\infty}\int_{-\infty}^\infty \phi''(k)\frac{\sin(kM)}{k}\,dk=\pi\phi''(0)$$
$$$$

Finally, to evaluate the remaining limits we use the following analysis. Note that
$$\begin{align}
\lim_{M\to\infty}\int_{-\infty}^\infty \phi(k)\frac{\cos(kM)-1}{k}\,dk&=\lim_{M\to\infty}\text{PV}\int_{-\infty}^\infty \phi(k)\frac{\cos(kM)}{k}\,dk\\\\
&-\text{PV}\int_{-\infty}^\infty \frac{\phi(k)}{k}\,dk\\\\
&=\lim_{M\to\infty}\text{PV}\int_{|k|<1} \phi(k)\frac{\cos(kM)}{k}\,dk\\\\
&+\lim_{M\to\infty}\text{PV}\int_{|k|>1} \phi(k)\frac{\cos(kM)}{k}\,dk\\\\
&-\text{PV}\int_{-\infty}^\infty \frac{\phi(k)}{k}\,dk\\\\
&=\underbrace{\lim_{M\to\infty}\int_{|k|<1} (\phi(k)-\phi(0))\frac{\cos(kM)}{k}\,dk}_{=0\,\,\text{using the Riemann-Lebesgue Lemma}}\\\\
&+\phi(0)\lim_{M\to\infty}\underbrace{\text{PV}\int_{|k|<1} \frac{\cos(kM)}{k}\,dk}_{=0\,\,\text{since the integrand is odd}}\\\\
&+\underbrace{\lim_{M\to\infty}\text{PV}\int_{|k|>1} \phi(k)\frac{\cos(kM)}{k}\,dk}_{=0\,\,\text{using the Riemann-Lebesgue Lemma}}\\\\
&-\text{PV}\int_{-\infty}^\infty \frac{\phi(k)}{k}\,dk\\\\
&=-\text{PV}\int_{-\infty}^\infty \frac{\phi(k)}{k}\,dk
\end{align}$$

Putting it all together, we find that in distribution
$$\mathscr{F}\{f\}=i\text{PV}\left(\frac{2k}{k^2-1}\right)+\frac{\pi}2 \left(\delta(k+1)+\delta(k-1)\right)-\pi \delta''(k)- i \left(\frac2{k^3}\right)_D$$
where $\left(\frac{2}{k^3}\right)_D$ is the distributional derivative of $\text{PV}\left(\frac1k\right)$

Fourier transform in S′


Difference between the effect and the contribution of a regressor

Question: I have a very basic question about the difference between effect of a regressor and its contribution. Consider the following simple case. In economics, Gross Domestic product is defined as the sum of consumption, investment, government expenditure and net exports. Consider that we have the following time series of observations: $C_{t},I_{t},G_{t},X_{t}-M_{t}$
Now, $Y_{t}$
 is defined as:$$Y_{t}=C_{t}+I_{t}+G_{t}+X_{t}-M_{t}$$
If we were to run a regression of $Y_{t}$
 on the RHS regressors, we would get an $R^{2}$
 of 1 and \beta
  of 1 as well. This is because this model is deterministic. My question is, although the effect of these regressors is all the same, how can we judge the contribution of each of these to the regressand? Is partial $R^{2}$
 a good way to do this? Also, the contribution will be different for each observation. Would the partial $R^{2}$
 be a measure of average contribution?
Answer: I think I figured the answer out. Ultimately, I am trying to compare the partial $R^{2}$
  to the coefficient. They are in some ways related. Consider we have a model:$$y=x\beta+\epsilon$$
 where $x$
  is a single variable. Now, we know that:$$\beta=\frac{cov(x,y)}{var(x)}$$
Moreover, we know that $$R^{2}=\rho^{2}$$
  Also,$$\rho_{xy}=\frac{cov(x,y)}{\sigma_{x}\sigma_{y}}$$
This implies that $$\rho_{xy}=\beta\frac{\sigma_{x}}{\sigma_{y}}$$
 which implies that:$$R^{2}=\beta^{2}\frac{var(x)}{var(y)}$$
 This is the difference between "importance" and "significance." We can have a completely/highly significant regressor, but if its variation is not "large" compared to the "regressand", it is not important. We do however, identify the partial effect of x
  consistely, given appropriate exogeneity assumptions. This is why we make a distinction between things that are economically significant and things that are statistically significant.


Azure Virtual Machine Firewall

Question: I have multiple virtual networks, a VPN VN with site-to-site VPN, an AADDS VN, a production website cluster of virtual machines on a VN and a test website cluster of virtual machines on a VN. I also have a series of app services.
I have been advised to add a virtual machine firewall and it's got me a little stumped.
I have a public IP on the web server on each cluster, and the VPN.
The virtual machine based firewall (WatchGuard FireBox) only allows a single NIC on the untrusted side.
I could use an application gateway to route traffic to each website (production, test and app services) from a single IP, and a jumpbox to RDP to each VM (6 in total across test/prod), this would allow me to use ports of this single NIC to route traffic to its destination. This isn't ideal.
How can I intercept all external traffic using the firewall and still access multiple IPs using azure? Is a jumpbox and application gateway the only way?
Little confused to be honest. All input appreciated.
Comment: when you say firewall, do you mean an actual Firewall like Azure Firewall or Watchguard, or a Web Application Firewall (WAF) such as App Gateway, you mention both. What are you actually trying to protect?
Comment: I mean a VM installed with watchguard firebox cloud. Then i would use the public IP of that as the entry point (with NAT rules) to forward it to an application gateway (so i can route the traffic based on host headers) or to a jumpbox for RDP access
Answer: I'm not overly familiar with Watchguard, however assuming it only supports a single NIC as you say then first you need capabilities to route traffic to your web applications based on the path or url. If the FW doesn't support this then yes you would need something after the Firewall to handle that routing. Application Gateway is one way to do this with Azure and is probably the simplest approach. You could also look at any other reverse proxy like Nginx etc.
As far as being able to RDP to your VM's, I would look to avoid exposing this to the internet and FW at all. I would recommend looking at using Azure Bastion, which effectively provides a jump box as a service, you can then use this to access all your VM's.
Comment: I was actually intending to add JIT rules to this box.

Azure Virtual Machine Firewall


How can I run multiple expressions inside of a list comprehension python?

Question: I was trying to write a complex list comprehension but I am not sure how I am supposed to do it.
I have the following for loop which I am trying to turn into a list comprehension
number = 10
deci_list = []

for i in sorted(list(range(9)), reverse=True):
    if 2**i <= number:
        deci_list.append(1)
        number -= 2**i
    else:
        deci_list.append(0)

I was struggling to turn this into a list comprehension and this is what I have so far:
thing = sorted(list(range(9)), reverse=True)
new_thing = ['1' if 2**i <= number number -= 2**i else '0' for i in thing]

however, I do not know how to add the line number -= 2**i because it gives me an error every time I try to add it
    new_thing = ['1' if 2**i <= number number -= 2**i else '0' for i in t
hing]
                 ^^^^^^^^^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression

Comment: it is actually cleaner in a for loop.
Comment: also,  did you mean `number -= 2**i` (in the `if` statement) ??
Comment: Possible but not recommended method: `['1' if 2 ** i <= number and ((number := number - 2 ** i) or True) else '0' for i in reversed(range(9))]`
Answer: You're getting a syntax error due to the assignment, =, operator. It isn't supposed to be used in a list comprehension. Here's one way to work around the situation. Note that sorted(list(range(9)), reverse=True) could be replaced with range(8, -1, -1).
number = 10

def operator(index):
    global number

    if 2 ** index <= number:
        number -= 2 ** index
        return 1
    else:
        return 0

print([operator(index) for index in range(8, -1, -1)]) # Or: list(map(operator, range(8, -1, -1)))

Edit: As suggested by @ShadowRanger in the comment section, it is generally not a good idea to play with global variables in a function as it couples the two [essentially requiring you to reset the global variable or do something similar when you want to reuse the function]. You could wrap the two in a class to make it reusable.
However, I would recommend list comprehensions only at places where they do not compromise on readability. What you have in the original snippet is completely alright.
Comment: Even cleaner than `range(8, -1, -1)` to my mind is just the reversing slice, `range(9)[::-1]`; `range` supports that and produces a `range` equivalent to `range(8, -1, -1)`, just easier to read. `reversed(range(9))` also works, but who needs to type all those characters? :-) That said, writing a function that relies on a global like this is... suboptimal. It's basically a non-function; you can't use it without resetting the global variable. Typically you'd write a simple class in such a case, so the state was per-instance (and the same code could be used reentrantly, threaded, etc.).
Comment: I understand that this is suboptimal. Thanks for pointing out how a class would help! The overall intention was to recommend avoiding a list comprehension as no matter what you do, you're only going to write more code that required for the problem. I'll update my answer to cover the intention.


ngFor not working and no error in console

Question: user.service.ts
@Injectable()
 export class UserService  {constructor(private http: Http) {
  }

  getUsers(): Observable<User[]> {
    console.log("in users http Get request");
    return this.http.get("/assets/users.json")
   .map((res: Response) => res.json());

user.ts
import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { UserService } from './user.service';
import { Observable } from 'rxjs/Rx';

@Component ({
    selector: 'users',
    providers: [UserService],
       template :`

 Unable to load data

      ID
      Name

      {{user.id}}
      {{users.name}}

`
   })

export class User{   //created user class with properties
    UserService: Observable<User[]>;
    user: string;
    constructor(public service1:UserService) {

   }
  ngOnInit() {
      console.log("in ngoninnit");
      this.UserService = this.service1.getUsers();
    }
}

users.json
 [
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "email@example.com",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "email@example.com",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }

  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "email": "firstname.lastname@example.com",
    "address": {
      "street": "Douglas Extension",
      "suite": "Suite 847",
      "city": "McKenziehaven",
      "zipcode": "59590-4157",
      "geo": {
        "lat": "-68.6102",
        "lng": "-47.0653"
      }

  }
]

I am getting below result:
Unable to load data
ID  Name

Not getting the users data.
Comment: Your `ngFor` is trying to loop through a collection called `users`, but I can't see that you've created a variable called `this.users` anywhere in your .ts file
Comment: Side note: shouldn't this be singular (user instead of userS): {{users.name}}
Comment: this are really basic errors, you should take the tour of heroes to gain a better understanding of some basic concepts https://angular.io/tutorial
Answer: Beside the typos, you are not calling subscribe anywhere:
export class User{   //created user class with properties
    UserService: Observable<User[]>;

  ngOnInit() {
      this.UserService = this.service1.getUsers();
    }
}

Since you're saving the observable, you must use async to trigger getting the data:
<tr *ngFor="let user of users | async"


Simplenews does not apply templates and does not resend

Question: I have a strange issue. Simplenews sends ok html formatted emails but it does not read the extra info I write in template. It actually doesn read them at all.
The second issue it doesn't resend no matter how much I try.
Comment: Which templates are you using? Where are they stored?
Comment: Templates are provided by the simplenews modules and they need to be copied in your theme folder.
Answer: About You Second Issue - Here is a "dirty" solution.

Go to phpMyAdmin and find simplenews_newsletters table
Edit that table and change s_status on the newsletter you want from 2 to 0.

s_status - 2 Newsletter has been sent
s_status - 0 Newsletter has not been sent
s_status - 1 Sending Newsletter
Comment: Well I need the clean bushido way to do it :). Is this a simplenews bug?
Comment: Well I don't know if this is a bug.
That's what I'm doing to send one newsletter few times.
Because I want to test it on several email clients.
(send test newsletter options it's not enought)
It's not very convinient way but at leaset I am sure my Newsletter is OK before sending thousands emails.
Answer: Attention for the mailing items that may be present in the table "simplenews_mail_spool". In this table the remaining recipients are present for the mailing in status "pending".  they will be send out the next time the cron-job starts.


JavaFX 8: shifting table cells when using borders for table row

Question: I'd like to mark a number of rows in my TreeTableView with red borders but I've run into the problem of table cells shifting away from their respective columns.
Visually it looks like this:
https://i.stack.imgur.com/GBiWz.png
style.css:
.style {
    -fx-border-style: solid line-join round ;
    -fx-border-color: ...;
}

For every column in the tree it seems to shift a little further from the right by what appears to be the width of the border (1px default). Not a problem with only 2 columns but the final application is supposed to hold a dozen of them.
I can set the insets of the border to be on the outside of the cells and that fixes the shifting but then you can't see the side borders anymore which also looks odd.
I'm guessing setting styles for a row is just convenience for having the engine set it for every cell.
Is there a way to stop the TreeTableCells from shifting? Maybe setting individual styles for the cells rather than styling the whole row?
Answer: Assuming .style is applied to TreeTableRows:
.style {
    -fx-background-color: red, -fx-background ;
    -fx-background-insets: 0, 1 ;
}

I usually find I have to dig into the source for the default stylesheet to figure these out. You may want to mess with the insets and implement some kind of logic to prevent the double border on adjacent rows with the style class applied.
Here's an SSCCE:
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class StyledTreeTableView extends Application {

    private static final int MAX_VALUE = 1000 ;

    @Override
    public void start(Stage primaryStage) {
        TreeTableView<Item> treeTable = new TreeTableView<>();
        treeTable.setRoot(createTreeItem(1));

        treeTable.setRowFactory(ttv -> new TreeTableRow<Item>() {
            @Override
            public void updateItem(Item item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                    getStyleClass().remove("highlight");
                } else {
                    setText(item.toString());
                    if (item.getValue() % 10 == 3 || item.getValue() % 10 == 4) {
                        if (! getStyleClass().contains("highlight")) {
                            getStyleClass().add("highlight");
                        }
                    } else {
                        getStyleClass().remove("highlight");
                    }
                }
            }
        });

        TreeTableColumn<Item, String> nameCol = new TreeTableColumn<>("Item");
        nameCol.setCellValueFactory(cellData -> cellData.getValue().getValue().nameProperty());
        treeTable.getColumns().add(nameCol);

        for (int colIndex = 1 ; colIndex < 10 ; colIndex++) {
            TreeTableColumn<Item, Number> valueCol = new TreeTableColumn<>("Value * "+colIndex);
            final int multiplier = colIndex ;
            valueCol.setCellValueFactory(cellData -> cellData.getValue().getValue().valueProperty().multiply(multiplier));
            treeTable.getColumns().add(valueCol);
        }

        BorderPane root = new BorderPane(treeTable);
        Scene scene = new Scene(root, 600, 600);
        scene.getStylesheets().add("styled-tree-table.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private TreeItem<Item> createTreeItem(int value) {
        Item item = new Item("Item "+ value, value);
        TreeItem<Item> treeItem = new TreeItem<>(item);
        if (value < MAX_VALUE) {
            for (int i = 0 ; i < 10; i++) {
                treeItem.getChildren().add(createTreeItem(value * 10 + i));
            }
        }
        return treeItem ;
    }

    public static class Item {
        private final StringProperty name = new SimpleStringProperty();
        private final IntegerProperty value = new SimpleIntegerProperty();

        public Item(String name, int value) {
            setName(name);
            setValue(value);
        }

        public final StringProperty nameProperty() {
            return this.name;
        }

        public final java.lang.String getName() {
            return this.nameProperty().get();
        }

        public final void setName(final java.lang.String name) {
            this.nameProperty().set(name);
        }

        public final IntegerProperty valueProperty() {
            return this.value;
        }

        public final int getValue() {
            return this.valueProperty().get();
        }

        public final void setValue(final int value) {
            this.valueProperty().set(value);
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}

with the stylesheet:
.highlight {
    -fx-background-color: red, -fx-background ;
    -fx-background-insets: 0, 1 ;
}

Comment: Ah, `TreeTableView`, not `TableView`. Updated accordingly and added example.
Comment: That is pretty much what I was looking for, the double borders aren't much of an issue really. If I understand the CSS right, then this sets the background of the row to be red then overlays it with the default? Anyhow, thanks for the tip, complete with code!


Numpy Matrix into an image

Question: I have a 2d array with int value that I want to convert into an image.
The 2d array is generated randomly between 1-3, with consideration for what the neighboring int it in the array, I want to convert 1,2,3 to R,G,B in an image to better see what the outcome of the generator is.
What is the best way to do this?
Answer: I would use the matplotlib library. Just use plt.imshow or plt.pcolormesh (the second one is technically better for discrete values). The default colormap is pretty close to RGB in this case, but you could use another colormap if you wanted to. For example:
import numpy as np
import matplotlib.pyplot as plt

# Creating random 1-3 data in a 2D array
data = np.random.randint(1,4,[100,150])

plt.pcolormesh(a)

I'm using IPython and %matplotlib inline, you might need to call plt.show() to get it to draw if you are not using IPython.

Numpy Matrix into an image


Finding the rank of sub-matrix

Question: A Boolean matrix $M$, of rank $r$, is of the form
$$\begin{bmatrix}
A & B \\
C & D \\
\end{bmatrix}$$
where the sub-matrix $A$ is a all zero matrix or all one matrix (i.e. $A$ is monochromatic). So $\text{rank}(A)$ is at most $1$.
Then a typical upper bound on $\text{rank}(B) + \text{rank}(C)$ is $2r$.
Can we have anything better than that? Can we say $\text{rank}(B) + \text{rank}(C) \le r+1$ ? How?
Answer: First, argue that the matrix $M'=\pmatrix{0 & B \\ C & D}$ has rank at least $\text{rank}(B)+\text{rank}(C)$: Let $U$ be the space spanned by the columns of $\pmatrix{0 \\ C}$. Then $\text{dim}(U)=\text{rank}(C)$. Next, choose a set of columns of $B$ forming a basis for the span of the columns of $B$, and let $V$ be the space spanned by the corresponding columns of $\pmatrix{B \\ D}$. Then $\text{dim}(V)=\text{rank}(B)$, and $U\cap V=0$. Therefore $\text{dim}(U+V)=\text{rank}(B)+\text{rank}(C)$, and since $\text{rank}(M')\geq \text{dim}(U+V)$, it follows that $\text{rank}(M')\geq\text{rank}(B)+\text{rank}(C)$.
Now, $M$ differs from $M'$ by a matrix of rank at most 1, and the result follows.
Comment: Hi Brent thanks for your answer. Can you please elaborate on why dim(V)=rank(B)? I understand that set of basis for the span of columns of B counts as rank of B. But what if rank of D is more than rank of B? then should not dim(V) be equal to rank(D)? Or may be I am missing something trivial here.
Comment: Let's say there are $b$ basis vectors for the span of the columns of B. Then these $b$ vectors remain linearly independent when we extend them with additional components coming from the corresponding columns in $D$, and there still remain just $b$ of them; therefore they span a space of dimension $b$. The way I have defined $V$, $\text{dim}(V)$ will always be $b$, regardless of what the rank of $D$ is.

Finding the rank of sub-matrix


Apache mod_proxy - Pass through from localhost to another domain?

Question: I'm not at all experienced when using proxies but hopefully this is possible.
I have apache running on my development machine which hosts a website (www.testdomain.com). I need to look at www.testdomain.com from my phone. I don't want to root my phone so all I can do is enter the IP address of my machine (10.8.0.1). The site hosted at www.testdomain.com won't work correctly as the default site in apache.
I need some way of passing through a request to 10.8.0.1 to www.testdomain.com without my phone having to look up the DNS record for www.testdomanin.com
Is this possible using mod_proxy? Is there something else that will do the job?
Answer: First of all, I don't really understand why can't you point your cellphone browser to www.testdomain.com.
Anyway, you could use a proxy, but I think a better approach would be to use a ServerAlias directive in your www.testdomain.com vhost:
<VirtualHost *:80>
    ServerName www.testdomain.com
    ServerAlias 10.8.0.1
    (...)

If you still want to use a proxy, you could setup a different vhost for 10.8.0.1:
<VirtualHost *:80>
    ServerName 10.8.0.1
    ErrorLog ...
    TransferLog ...
    LogLevel warn

    # ReverseProxy
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass        / http://www.testdomain.com/
    ProxyPassReverse / http://www.testdomain.com/
    (...)

ref: http://httpd.apache.org/docs/current/vhosts/name-based.html
Comment: putting testdomain.com in my mobile will do a domain lookup for it, which will take me to the live server and not my dev machine. The website I'm working on is built in a stupid way that will only work correctly with a known domain name.


If $f(0)=0$ and $0\le f'(x)\le2f(x)$ for all $x\in(0,1)$, prove that $f\equiv0$.

Question: Let $f: [0,1]\to \Bbb R$ be a continuous function such that $f(0)=0$ and it's differentiable on $(0,1)$. In addition, we know that $0\le f'(x)\le2f(x)$. Prove that $f=0$.
I know that if the function $f$ is continuous on $[a,b]$, differentiable on $(a,b)$ and $f'(x) = 0$ on $(a,b)$, then $f$ must be a constant function on $[a,b]$.
But I do not quite know how to use the inequality.
Comment: If $f$ is constant and $f(0)=0$ then $f\equiv 0$
Comment: Just like that. But when proving that the function is constant I only use the mean value theorem. When should I use the inequality  $0\le f'(x) \le 2f(x)$?
Comment: You don't need the MVT or anything.
Comment: My guess is there is a typo/read again carefully. As stated, it's obvious by first comment.
Answer: Since $f(0)=0$ and $f'(x)\ge 0$ on $(0,1)$, $f(x)\ge 0$ on $[0,1]$. Let $g(x)=f(x)e^{-2x}$ on $[0,1]$. Then $g$ is continuous on $[0,1]$ and differentiable on  $(0,1)$. On the one hand, $g(x)\ge 0$ on $[0,1]$. On the other hand, since $g(0)=0$ and $g'(x)=e^{-2x}(f'(x)-2f(x))\le 0$ on $(0,1)$, $g(x)\le 0$ on $[0,1]$. The conclusion follows.
Answer: It is true even if you ignore the assumption of being constant (which surely must be a typo.)
Note that since $f'(x) \geq 0$, $f$ is non-decreasing. Hence $f(x) \geq 0$ for $x \in [a,b]$. Also, since $f$ is differentiable, it is continuous.
Let $0 \leq a < b \leq 1$, then $f(b)-f(a) \leq \sup_{\xi \in (a,b)} f'(\xi) (b-a) \leq 2 f(b)(b-a)$. Now suppose $f(a) = 0$ and $b-a < \frac{1}{2}$. Then the inequality gives $f(b) \leq 2 f(b) (b-a)$, or $0 \leq f(b)(2(b-a)-1)$. Hence $f(b) = 0$.
Take $a=0,b<\frac{1}{2}$. Then the above shows that $f(b) = 0$ for $b \in (0,\frac{1}{2})$, and continuity shows $f(\frac{1}{2}) = 0$. Now apply the same argument with $a=\frac{1}{2}, b<1$, to get $f(1) = 0$, from which the desired conclusion follows.
Comment: I wish I had known you were writing this - I was about 30 seconds from posting an almost identical proof when yours appeared ;-).
Comment: I think @richard's proof is the nicest.
Comment: @copper.hat: I think your argument looks more natural compared with mine. +1.
Comment: @Anna: No. The first inequality is just the mean value theorem. It is true here as long as $a<b$. The second comes from the fact that $f'(\xi) \leq 2 f(\xi)$, so $\sup_{\xi \in (a,b)} f'(\xi) \leq \sup_{\xi \in (a,b)} 2 f(\xi) = 2 f(b)$.
Comment: Yes, I noticed that just after posting the comment, that's why I deteted it :) Thanks.


Evaluate a triple integral with spherical coordinates

Question: $$\iiint_{Q}z\ dV$$ Where $Q$ is the common region of the spheres $x^{2}+y^{2}+z^{2}\leq 1$ and $x^{2}+y^{2}+(z-1)^{2}\leq 1$
I have tried nothing.
Comment: Welcome to math SE. What have you tried?
Comment: Switch to cylindrical coordinates $(r,\theta,z)$.  $\theta$ integrates out trivially, so you need to get limits for $(r,z)$ integral.
Comment: I have already calculated it with cylindrical coordinates. I know that it's easier, but I need to do it with the spherical coordinates too. I don't know which are the limits for those coordinates.
Answer: Switching to polar coordinates $I=\int_Vzrdrd\theta dz$. Limits $0\le \theta\le 2\pi$.  For $(r,z)$  The area of interest is the overlap of two unit circles in the $(r,z)$ plane centered at $(0,0)$ and $(0,1)$  The circles intersect at $z=\frac{1}{2}$.  Using the symmetry around the $z$ axis the net result is:
$I=4\pi(\int_0^\frac{1}{2}z\int _0^\sqrt{1-(1-z)^2}rdrdz+\int_\frac{1}{2}^1z\int _0^\sqrt{1-z^2}rdrdz)=2\pi(\int_0^\frac{1}{2}z(1-(1-z)^2)dz+\int_\frac{1}{2}^1z(1-z^2)dz)$
Comment: Well, with cylindrical coordinates I get the same answer, but I tried with the spherical coordinates and I couldn't solve the integral. I have trouble with the limits for $\Phi$.
Comment: When I tried, I got $0\leq\theta\leq 2\pi$ and $2\cos\Phi\leq\rho\leq 1$.
Answer: The triple integral in spherical coordinates consists of two integrals, whose limits are determined by the intersection of the two circles $x^{2}+y^{2}+z^{2}=1$ and $x^{2}+y^{2}+(z-1)^{2}=1$. They intersect at $z=\frac12$, or $\theta = \frac\pi3$. So, the $\theta$-limits in the spherical coordinates are $(0,\frac\pi3)$ and $(\frac\pi3,\frac\pi2)$
Thus, the volume integral is,
$$2\pi\int_0^{\frac\pi3}\int_0^1 (r\cos\theta)\>r^2\sin\theta\>dr d\theta
+2\pi\int_{\frac\pi3}^{\frac\pi2}\int_0^{2\cos\theta} (r\cos\theta)\>r^2\sin\theta\>dr d\theta
=\frac{3\pi}{16}+\frac{\pi}{48}=\frac{5\pi}{24}$$
Answer: We have to use spherical coordinates $(x=r\sin\theta\cos\varphi, \quad y=r\sin\theta\sin\varphi, z=r\cos\theta)$, so we will have $$x^2+y^2+z^2 \le 1 \Leftrightarrow r^2 \le 1 \Leftrightarrow r \le 1$$ and $$x^2+y^2+(z-1)^2 \le 1 \Leftrightarrow x^2+y^2+z^2 \le 2z \Leftrightarrow r^2 \le 2r\cos\theta \Leftrightarrow r \le 2\cos\theta.$$
Next, since both spheres have their centers on $z$-axis, one center is $P_1=(0,0,0)$ and another one is $P_2=(0,0,1)$ we know that it will hold: $$0 \le \varphi\le 2\pi,$$ and since both spheres have radius $1$ it is not hard to see that it will hold: $$0 \le \theta \le \frac{\pi}{2}.$$
Finally, your integral will be equal to $$\int_{0}^{2\pi}d\varphi \int_{0}^{\frac{\pi}{2}}\sin\theta \cos\theta d\theta \int_{2\cos\theta}^{1}r^3 dr=2\pi\int_{0}^{\frac{\pi}{2}}\sin\theta \cos\theta(\frac{1}{4} - 4\cos^4\theta)d\theta =...= \frac{-13\pi}{12}.$$
Comment: With $\phi$ I got the same limits, but with $r$, I got $2\cos\theta\leq r\leq 1$.
Comment: Will edit soon my answer...
Comment: And with cylindrical coordinates, the integral is equal to $\frac{5\pi}{24}$


Induction question

Question: I have this homework question in Proofs by Mathematical Induction and I don't have a clue how to resolve it, is there anyone that can help me?
When you roll a die you have $6$ possible outcomes $1,2,\ldots,6$. When you roll two dice you have $11$ possible outcomes $2,3,\ldots,12$  and when you roll three dice the possible outcome is 16. Use basic and inductive steps to show when $n\ge 1$ dice are rolled then the possible outcome is $5n+1$.
Answer: Hint: The induction hypothesis is

When you roll $n$ dice, you can get any outcome from $n$ to $6n$.

Hint: There are $6n - n + 1 $ integers between $n$ and $6n$ inclusive.
Comment: An induction hypothesis would never start with "Show that".
Comment: @MichaelHardy Point taken.

Induction question


Convergence of the Power Method

Question: Given a vector $x^{(0)}$ with $\left\|x^{(0)}\right\|_{2}=1$, I wish to show that the power method :
$$
x^{(k)}=\frac{A x^{(k-1)}}{\left\|A x^{(k-1)}\right\|_{2}}, \quad \mu^{(k)}=\left(x^{(k)}\right)^{T} A x^{(k)}
$$
generates the pair $\left(x^{(k)}, \mu^{(k)}\right)$ such that $\displaystyle x^{(k)}=\frac{A^{k} x^{(0)}}{\left\|A^{k} x^{(0)}\right\|_{2}}$ for any matrix $A$.
My attempt by induction:
Base Case: For $k=1, \displaystyle x^{(1)}=\frac{A x^{(0)}}{\left\|A x^{(0)}\right\|_{2}}$ by definition.
For the inductive step, it seems trivial but I can't seem to figure it out, any help is much appreciated!
Answer: [Note] : The inductive step is indeed trivial, now assume that $\displaystyle x^{(k)}=\frac{A^{k} x^{(0)}}{\left\|A^{k} x^{(0)}\right\|_{2}}$ all you have to do is work things out simply by substituting $x^{(k)}$ in $x^{(k+1)}$ due to its recursive nature as you can see :
$$
x^{(k+1)}=\frac{A x^{(k)}}{\left\|A x^{(k)}\right\|_{2}}=\frac{\displaystyle\frac{A^{k+1} x^{(0)}}{\left\|A^{k} x^{(0)}\right\|_{2}}}{\displaystyle\frac{\left\|A^{k+1} x^{(0)}\right\|_{2}}{\left\|A^{k} x^{(0)}\right\|_{2}}}=\frac{A^{k+1} x^{(0)}}{\left\|A^{k+1} x^{(0)}\right\|_{2}}
$$
Since $\displaystyle A x^{(k)}=A \frac{A^{k} x^{(0)}}{\left\|A^{k} x^{(0)}\right\|_{2}}=\frac{A^{k+1} x^{(0)}}{\left\|A^{k} x^{(0)}\right\|_{2}}$ and $\displaystyle\left\|A x^{(k)}\right\|_{2}=\frac{\left\|A^{k+1} x^{(0)}\right\|_{2}}{\left\|A^{k} x^{(0)}\right\|_{2}} .$

Convergence of the Power Method


mysql_num_row com inner join

Question: Tenho 2 tabelas:

Leads
Lojas

O relacionamento é o seguinte:
1 loja -> N leads

Preciso listar o número de leads cadastrados para cada loja e depois ordenar por ordem decrescente para saber qual loja possui mais leads
O inner join que estou usando duplica as lojas quando executa a query. HELP
Answer: seria algo mais ou menos assim?

SELECT COUNT(le.id) AS total_leads FROM leads AS le
INNER JOIN lojas AS lo ON le.id_loja = lo.id
GROUP BY lo.id
ORDER BY lo.id DESC

Comment: Cara, perfeito!!!!! Me retornou certinho!Só que não apareceu o NOME_LOJA no resultado final. Como adiciono isso?
Comment: tenta colocar algo como: SELECT COUNT(le.id) AS total_leads, nome_loja.... Vê se funciona.
Comment: Aliás, no caso, você quer o nome da loja e o total de lojas? Me explica direito essa parte.
Answer: Eu faria assim:
SELECT nome_loja, uf, (SELECT COUNT(*) FROM leads
                               WHERE loja_selecionada = nome_loja) AS 'total'
FROM lojas ORDER BY total DESC

Também da certo. =)
Veja funcionando
Comment: ANIMAL! Parabéns, era exatamente isso! Obrigado!
Comment: só fiz uma mudança do order by para o total e show!! tks brow
Comment: @LéoKovaski... XD ... Tranquilo!

mysql_num_row com inner join


Cannot find implementation for sun.nio.ch.FileChannelImpl.read

Question: I am using sun.nio.ch.FileChannelImpl.read to read a file in linux environment in my java project, I am getting a permission denied on one of my environments, the file has read/write/execute permissions for everyone, but in my environment we have strict policy to allow some commands so I need to find out what commands is this method using to enable this command on my machine.
To find the command I followed up the code until i hit some native methods inside
sun.nio.ch.FileDispatcherImpl

the method is
 static native int read0(FileDescriptor fd, long address, int len)
     throws IOException;

I followed up and found the implementation which is obviously written with C, you can find it in this link
The native implementation is
JNIEXPORT jint JNICALL
Java_sun_nio_ch_FileDispatcherImpl_read0(JNIEnv *env, jclass clazz,
                             jobject fdo, jlong address, jint len)
{
    jint fd = fdval(env, fdo);
    void *buf = (void *)jlong_to_ptr(address);

    return convertReturnVal(env, read(fd, buf, len), JNI_TRUE);
}

Now I need to open read function to figure out what it exactly does, but I am unable to find the implementation or even the header file where this function is declared, following the header files included
#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
#include "jlong.h"
#include "sun_nio_ch_FileDispatcherImpl.h"
#include "java_lang_Long.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <unistd.h>
#if defined(__linux__)
#include <linux/fs.h>
#include <sys/ioctl.h>
#endif
#include "nio.h"
#include "nio_util.h"

any help is appreciated.
Answer: read() is a POSIX standard function to read from an open file descriptor.  It is usually provided by your systems libc.so if dynamically linked, or libc.a if statically linked.
One implementation can be found here:  https://www.gnu.org/software/libc/


PHP - Como fazer com que o left join com mais de um registro nas demais tabelas não retorne valores repetidos nas colunas?

Question: Estou precisando realizar um query SQL no PHP, onde preciso criar uma tabela a partir de outras 9 tabelas, juntando todas as colunas com um LEFT JOIN, e com o campo 'Cliente' como chave entre as tabelas. Porém, em cada tabela há mais de um registro da mesma chave, ou seja, mais de uma linha com o mesmo número de 'Cliente', e com isso a consulta está me retornando valores repetidos, mudando apenas os valores das colunas que são de dados diferentes.
Eu gostaria que esses valores repetidos das colunas, apenas aparecesse um só vez, e nos demais, me retornasse com NULL. Vou colocar logo abaixo uma imagem mostrando como está sendo me retornado os valores.
Alguém faz ideia de como resolver isso?
Agradeço imensamente desde já!
Segue o código da query:
    SELECT *
      FROM completo_sem_saldo
 LEFT JOIN posicao_contabil ON (completo_sem_saldo.Cliente = posicao_contabil.Cliente)
 LEFT JOIN saldo_analitico ON (completo_sem_saldo.Cliente = saldo_analitico.Cliente)
 LEFT JOIN titulos_em_ser ON (completo_sem_saldo.Cliente = titulos_em_ser.Cliente

COMO ESTA RETORNANDO:

COMO QUERO QUE RETORNE:

CÓDIGO COMPLETO DA TABELA:
$query1 = mysqli_query($con, "SELECT * FROM completo_sem_saldo as a LEFT JOIN posicao_contabil as b ON (a.Cliente = b.Cliente_Posicao) LEFT JOIN saldo_analitico as c ON (a.Cliente = c.Cliente_Saldo_Analitico) LEFT JOIN titulos_em_ser as d ON (a.Cliente = d.Cliente_Titulos_Em_Ser) ) as e");

$num = mysqli_num_rows($query1);
$resul1 = mysqli_fetch_assoc($query1);
$arquivo = 'exemplo.xls';
$tabela = '
';
$tabela .= '
';
$tabela .= 'Formulario
';
$tabela .= '
';
$tabela .='
';
$tabela .='Nome	';
$tabela .='Sld_dev_ctbl	';
$tabela .= 'Saldo	';
$tabela .='Vlr_atual	';
$tabela .='
';

while($resul1 = mysqli_fetch_assoc($query1)) {

$nome = $resul1['Nome'];
$sld_dev_ctbl = $resul1['Sld_dev_ctbl'];
$saldo = $resul1['Saldo'];
$vlr_atual = $resul1['Vlr_atual'];

$tabela .= '
';
$tabela .= ''.$nome.'	';
$tabela .= ''.$sld_dev_ctbl.'	';
$tabela .= ''.$saldo.'	';
$tabela .= ''.$vlr_atual.'	';
$tabela .= '
';
}
$tabela .= '
';

Comment: Ja testou um GROUP BY ?
Comment: Posta uma imagem do que você quer que retorne e o que está retornando. Não consegui entender o quer exatamente. :(  Se for para anular as repetições você tem que ver o que está igual, humanamente. Seria somente adicionar isto: `GROUP BY Nome`
Comment: Atualizei com o código na descrição.
Comment: Na verdade já, mas nem funfou. O que realmente preciso é que a join me retorne apenas os valores encontrados nas tabelas, e não repita os demais valores anteriores. :/
Comment: as colunas `Sld_dev_ctbl` e `Saldo` têm sempre o mesmo valor? Aparecendo a soma do `Vlr_atual` para determinado cliente resolve?
Comment: Na verdade apenas a coluna 'Saldo' sempre irá ter o mesmo valor para um cliente. As colunas 'Sld_dev_ctbl' e 'Vlr_atual' sempre irão ter valores diferentes, quando aparecem mais de um vez pra um cliente.
Comment: Por que vc não faz esse tratamento na aplicação ao invés de tratar por sql? Eu desconheço outra maneira a não ser aplicar `pivot`... Em linhas curtas, acho que seu select está certo.. você tem que tratar na aplicação o que você quer.
Comment: Acabei de colocar outra imagem mostrando como realmente quero que fique o resultado da query. Pode perceber que os valores repetidos na primeira imagem, não se repetem na segunda, só aparecem uma única vez.
Comment: tu tentou usar "select distinct ..."?
Comment: Na verdade, o DISTINCT faz com que retorne os valores que são duplicados, e não é bem isso que preciso. Preciso que ele pegue os valores duplicados, exclua (NULL), e só deixe apenas o primeiro registro.
Comment: É isso que você quer? http://stackoverflow.com/questions/14286417/mysql-join-return-null-for-duplicate-results-in-left-table
Answer: Isso não é um problema de SQL, no momento em que você faz um join você está gerando um "Produto Cartesiano".
O que posso te sugerir é durante o processamento dos dados, exibir apenas as informações que você não quer que repita na primeira ocasião do ID do cliente.
Não sei como está o seu código, mas vai um exemplo genérico:
<?php
$rows = array();

$row['cliente_id'] = 1;
$row['nome'] = 'fulano';
$row['saldo'] = 10;
$row['valor'] = 1;
$rows[] = $row;

$row['cliente_id'] = 1;
$row['nome'] = 'fulano';
$row['saldo'] = 10;
$row['valor'] = 2;
$rows[] = $row;

$row['cliente_id'] = 1;
$row['nome'] = 'fulano';
$row['saldo'] = 10;
$row['valor'] = 3;
$rows[] = $row;

$row['cliente_id'] = 2;
$row['nome'] = 'fulano';
$row['saldo'] = 10;
$row['valor'] = 1;
$rows[] = $row;

$row['cliente_id'] = 2;
$row['nome'] = 'fulano';
$row['saldo'] = 10;
$row['valor'] = 2;
$rows[] = $row;

echo "
";
echo "
";
echo "ID	";
echo "Nome	";
echo "Saldo	";
echo "Valor	";
echo "
";

$last_id = null;
foreach($rows as $row){
    echo "
";
    echo $last_id != $row['cliente_id'] ? "$row[cliente_id]	" : "	";
    echo "$row[nome]	";
    echo $last_id != $row['cliente_id'] ? "$row[saldo]	" : "	";
    echo "$row[valor]	";
    echo "
";
    $last_id = $row['cliente_id'];
}
echo "
";

Se tu postar o teu código, como está montando a tabela podemos ajudar no caso real.
Comment: Acabei de atualizar na descrição o código completo. Se poder me ajudar brother, ficarei imensamente grato. Dá uma olhadinha no código.
Answer: Você pode usar o comande DISTINCT após o operador SELECT e chamar o campo que você não quer que se repita, geralmente você faz isso no ID, assim ele não vai combinar todas entradas do plano cartesiano.
Exemplo em W3Schools (Inglês)
Exemplo em MySQL Tutorial (Inglẽs)


Dreamhost - mirror site while in development

Question: new to dreamhost here and have followed the wiki on this but still need some additional help if possible. I want to be able to preview a site while I work on it, before I point the live domain to my dreamhost server. I've added the domain via the Control Panel, and all my files sit in the directory, /home/user/mysite.com - which is correct I think. When trying to follow the wiki with regards the mirroring details, I find that the only option I have is as follows, where I can't change any of these details:
Create the mirror at: mysite.com
Mirror this site: existingsite.com
The existingsite.com is just a live site sitting on the same server space. Is there something I'm missing here? Probably a newb mistake no doubt :)
Answer: Mirroring is for you to point a domain to an existing site. Hence this means you can mirror on 1 site. ie. both existingsite.com and mirrorsite.com points to the same server space.
If you want to create a development site, you probably are talking about 2 installations.
In this case, a quick and dirty trick I use is to create a development subdomain, dev.existingsite.com and fully host it. You normally get a /home/user/dev.existingsite.com folder with this. When your site is fully ready, you can edit your fully hosted existingsite.com and point the web directory to dev.existingsite.com. A better way is to SSH in and move the files.
There's an option copy files over in the settings page. Anyway dreamhost live help is pretty good. This is definitely something they will answer.
Comment: Hi, thanks for the reply. Is it not possible to view the development site via a server name or IP, without having to copy the files. On previous servers, I've been able to do things like go to http://serverIP/~domain-account-name to preview the site. Unfortunately I don't have the live chat option in my control panel
Comment: You can, if you own a domain, you can create as many subdomains as you want. If you don't even have a domain, I suggest you just spend that $9.95 to get one for testing. So much easier to work with and you can then play with the DNS settings etc.
Comment: Sorry actually you can. Just spoof your own `hostname` file to add `someuniquedomain.com` and set it to point to dreamhost IP. You must add `someuniquedomain.com` as a fully hosted domain. That way, you can minimize migration pains if you set your development site to have the exact same URL as your live one.
Comment: Thanks again :) I think I might have cracked it, pretty closely following your suggestion: I created a subdomain, newsite.existingsite.com - then I set the Web Directory for this subdomain to be the directory of the new domain, i.e /home/user/newsite.com. It's not working yet, hopefully changes taking effect. Does this sound like it should work?
Comment: Yep - that worked like a charm! So, this allows me to use a subdomain for testing without having to copy the files anywhere else for going live once the domain is pointed to my server.


An inequality regarding mean and standard deviation : $\frac{1}{n}\#x_i \in (\bar{x}-ks,\bar{x}+ks) \geq 1-\frac{1}{k^2}$

Question:
Let $x_1,\cdots,x_n \in \mathbb{R}$. Define
  $$\bar{x}=\frac{1}{n}\sum_{i=1}^n x_i, \quad s=\sqrt{\frac{1}{n-1}\sum_{i=1}^n (x_i-\bar{x})^2}$$
  To show that the proportion of $x_i$'s in the interval $(\bar{x}-ks,\bar{x}+ks)$ exceeds $1-\frac{1}{k^2}$.

In other words, we have to show that
$$\frac{1}{n}\#\{x_i : \frac{x_i-\bar{x}}{s} \in (-k,k)\} \geq 1-\frac{1}{k^2}$$
Any help would be much appreciated. Thank you.
Answer: Let $y_i = \frac{x_i - \bar{x}}{s}$, the problem becomes

Given $y_1, \ldots, y_n \in \mathbb{R}$ such that $\sum_{i=1}^n y_i = 0$ and $\sum_{i=1}^n y_i^2 = n -1$. How to show
  $$\# \{ y_i : |y_i| < k \} > n\left(1-\frac{1}{k^2}\right)
$$

Notice
$$n > n-1 = \sum_{i=1}^n y_i^2 \ge \sum_{i=1,|y_i|\ge k}^n y_i^2
\ge k^2 \sum_{i=1,|y_i|\ge k}^n 1
= k^2 \# \{ y_i : |y_i| \ge k \}$$
This leads to
$$\#\{ y_i : |y_i| \ge k \} < \frac{n}{k^2}
\quad\implies\quad \# \{ y_i : | y_i | < k \} >  n - \frac{n}{k^2} = n\left(1- \frac{1}{k^2}\right)$$


Future tasks in Java 1.6

Question: In Java 1.7 we can have future task where the rest of the processes of obj will continue in new threads without waiting for the results of another.
private static ExecutorService executorService
  = Executors.newFixedThreadPool(1);

public void update(MyObject obj) {
    executorService.execute(new FutureTask<>(new MyFutureTask(obj)));
}

Is there any way to do something similar to this in java 1.6?
Comment: So you have a single threaded pool. Calling it FIFO_TYPE is a bit confusing. IMHO.
Comment: Why are you passing FIFO_TYPE as the number of threads in the pool?
Comment: actually int FIFO_TYPE = 1
Comment: Please don't ask questions that you can answer yourself in 30 seconds by READING THE JAVADOCS ...
Comment: Java 6 does not have the diamond operator, so delete it from the `new FutureTask` part.
Answer: FutureTask<V> introduced in java 1.5, you can use it in java 1.6 without any doubt :) .
Check the documentation
Comment: @SubhrajyotiMajumder your answer really helped me and java 1.6 has Future Task in similar way.http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html

Future tasks in Java 1.6


RANDOM #s. Type two statements using nextInt() to print two random integers between 0 and 9. End with a newline. Ex: 5 7

Question: Hey all I'm having trouble figuring this out. Just learning java for the first time. Any help would be awesome thanks!
Type two statements using nextInt() to print two random integers between 0 and 9. End with a newline. Ex:  5 7
import java.util.Scanner;

import java.util.Random;

public class DiceRoll {
public static void main (String [] args) {

Random randGen = new Random();

int seedVal = 0;

randGen.setSeed(seedVal);

  `enter code here`/* Your solution goes here  */

return;
   }
}

Comment: See [here](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range)
Answer: Try this:
int  a = randGen.nextInt(10);
int  b = randGen.nextInt(10);
System.out.println(a);
System.out.println(b);

Answer: I noticed the problem requested you only write two lines.  I believe this would get you the exact same results as requested by the problem.
    System.out.println(randGen.nextInt(10));
    System.out.println(randGen.nextInt(10));


Transfer amount from a user account to another user account

Question: I have a database that contains users data like useraccountid, userid, balance,   totalwithdrawal,  creationdate. I have finished with the structure and the code but keep giving me no response and the fund on the sender account doesn't change.
below is the HTML form that handles the transaction

 Wallet To Wallet

        <form class="form-horizontal" action="" role="form" novalidate>

                    <input type="text" name="userid" class="form-control" id="fname" placeholder="Agent Account ID">

                    <input type='number' name='balance' class="form-control" id="sname" placeholder="Amount">

                    Transfer

        </form>

below is the php code that handle the transaction
class TransactionDemo {

    const DB_HOST = 'localhost';
    const DB_NAME = 'trans';
    const DB_USER = 'root';
    const DB_PASSWORD = '';

    public function transfer($from, $to, $amount) {

        try {
            $this->pdo->beginTransaction();

            // get available amount of the transferer account
            $sql = 'SELECT balance FROM useraccount WHERE userid=:from';
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute(array(":from" => $from));
            $availableAmount = (int) $stmt->fetchColumn();
            $stmt->closeCursor();

            if ($availableAmount < $amount) {
                echo 'No money in your account';
                return false;
            }
            // deduct from the transferred account
            $sql_update_from = 'UPDATE useraccount
                SET balance = balance - :balance
                WHERE userid = :from';
            $stmt = $this->pdo->prepare($sql_update_from);
            $stmt->execute(array(":from" => $from, ":balance" => $amount));
            $stmt->closeCursor();

            // add to the receiving account
            $sql_update_to = 'UPDATE useraccount
                                SET balance = balance + :balance
                                WHERE userid = :to';
            $stmt = $this->pdo->prepare($sql_update_to);
            $stmt->execute(array(":to" => $to, ":balance" => $balance));

            // commit the transaction
            $this->pdo->commit();

            echo 'The amount has been transferred successfully';

            return true;
        } catch (PDOException $e) {
            $this->pdo->rollBack();
            die($e->getMessage());
        }
    }

    /**
     * Open the database connection
     */
    public function __construct() {
        // open database connection
        $conStr = sprintf("mysql:host=%s;dbname=%s", self::DB_HOST, self::DB_NAME);
        try {
            $this->pdo = new PDO($conStr, self::DB_USER, self::DB_PASSWORD);
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }

    /**
     * close the database connection
     */
    public function __destruct() {
        // close the database connection
        $this->pdo = null;
    }

}

?>

now I created a transaction.php and like it on the form action="" but I am not getting any error and the fund does not move.
what am I doing wrong?
Comment: What is `$stmt->closeCursor()`?
Comment: .. besides that first query could be more like `UPDATE useraccount
                SET balance = balance - :balance
                WHERE userid = :from' AND balance >= :balance`    then that `SELECT` can also be skipped..
Comment: @RaymondNijland i was able to remove the SELECT still the issue, the page will reload but nothing happen
Comment: i never said it would fix it consider [this](https://www.db-fiddle.com/f/6DTSHVrxFGR6sikJF7Np5L/7) to possibly handle it complety in a transaction.. Toy around a bit with the balances for `userid = 1`  And research the manual how or why it works..
Comment: @RaymondNijland i was able to insert the code but giving me an error....... Parse error: syntax error, unexpected '@' in C:\xampp\htdocs\project\dashboard\ajax\makeTransaction.php on line 5..  where am i suppose to insert the code.  the code structure seems incorrect
Comment: @RaymondNijland you can update it on the link u pasted earlier https://www.db-fiddle.com/f/6DTSHVrxFGR6sikJF7Np5L/2
Comment: Not sure you never let read me the code or which error you got after trying mine example suggestion for that matter the problem could be anything..  But most likely mine [example](https://www.db-fiddle.com/f/6DTSHVrxFGR6sikJF7Np5L/7) is more suitable to be handled with a MySQL [stored procedure](https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html) instead..
Comment: @RaymondNijland thetable u create has on id=1 and 2............... and the code will be between the two id. but in a situation whereby you are dealing with many users with different id and they are to send fund to each other.
Comment: yes i have that example like that with a reason, handling it as one transaction between two users... if you need to deal more transactions from one user to multiple users use a loop per money transaction.. trust me on this that this is the most easy and most save approach to implement in this case..
Comment: @RaymondNijland can u update the link with that so has to see how u structure it........... this is an opportunity for me to learn. Please
Comment: @RaymondNijland check my new answer below and also the new issue am facing
Answer: you added wallet-to-wallet.php in this href.

                Transfer

Remove this or move the code from transaction.php and paste in  wallet-to-wallet.php  page.
Comment: check my new answer and the new found problem
Comment: i need more answer
Answer:  * PHP MySQL Transaction Demo
 */
class TransactionDemo {

    const DB_HOST = 'localhost';
    const DB_NAME = 'transferfund';
    const DB_USER = 'root';
    const DB_PASSWORD = '';

    /**
     * Open the database connection
     */
    public function __construct() {
        // open database connection
        $conStr = sprintf("mysql:host=%s;dbname=%s", self::DB_HOST, self::DB_NAME);
        try {
            $this->pdo = new PDO($conStr, self::DB_USER, self::DB_PASSWORD);
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }

    /**
     * PDO instance
     * @var PDO
     */
    private $pdo = null;

    /**
     * Transfer money between two accounts
     * @param int $from
     * @param int $to
     * @param float $amount
     * @return true on success or false on failure.
     */
    public function transfer($from, $to, $balance) {

        try {
            $this->pdo->beginTransaction();

            // get available amount of the transferer account
            $sql = 'SELECT balance FROM useraccount WHERE userid=:from';
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute(array(":from" => $from));
            $availableAmount = (int) $stmt->fetchColumn();
            $stmt->closeCursor();

            if ($availableAmount < $balance) {
                echo 'Insufficient amount to transfer';
                return false;
            }
            // deduct from the transferred account
            $sql_update_from = 'UPDATE useraccount
                SET balance = balance - :balance
                WHERE userid = :from';
            $stmt = $this->pdo->prepare($sql_update_from);
            $stmt->execute(array(":from" => $from, ":balance" => $balance));
            $stmt->closeCursor();

            // add to the receiving account
            $sql_update_to = 'UPDATE useraccount
                                SET balance = balance + :balance
                                WHERE userid = :to';
            $stmt = $this->pdo->prepare($sql_update_to);
            $stmt->execute(array(":to" => $to, ":balance" => $balance));

            // commit the transaction

                if ($this->pdo->commit()) {

                    header("Location: ../wallet2wallet_success.php");

                }else{

                    header("Location: ../wallet2wallet_error.php");

                }
            return true;
        } catch (PDOException $e) {
            $this->pdo->rollBack();
            die($e->getMessage());
        }
    }

    /**
     * close the database connection
     */
    public function __destruct() {
        // close the database connection
        $this->pdo = null;
    }

}

 // test the transfer method
$obj = new TransactionDemo();

// transfer from account 1 to 2
$from = isset($_POST["from"]);
$to = isset($_POST["to"]);
$balance = isset($_POST["balance"]);

$obj->transfer ($_POST["from"], $_POST["to"], $_POST["balance"]);

i was able to solve the problem with this codes above,Thanks for your contribution

 Wallet To Wallet

<form class="form-horizontal" action="ajax/makeTransaction.php" role="form" method = "POST">

<select id="inputState" type="number"  class="form-control" name="from" class="form-control">
<option selected><?php echo $_SESSION['user_id']; ?></option>
</select>

<input type="number"  class="form-control" name="to" placeholder="Receiver Agent Account ID" value="">

<input type='number'  class="form-control" name="balance" placeholder="Amount" value="">

<button type="submit" name="transfer" class="outline-btn info">Transfer</button>

</form>

Comment: This isn't a complete solution so why did you add it to the answers area?
Comment: @FunkFortyNiner   its complete but i have a new problem in it
Comment: That should have been a new question. Instead, you added to it, that isn't how things are done on Stack.


Can I search Taxonomy terms within display suite

Question: I don't think so, but I'm throwing it out just in case I am incorrect
Answer: What do you mean by search?
You can apply ds layouts to taxonomies
Comment: I think he meant that my answer was not really an answer and more like a critique or request clarification, so i should have commented your question instead of answer it.
Comment: Search, you can use Display suite as a search mechanism for a site.  But I don't see that you can configure the search on tax terms the way you do on a content type.  Is there an add on aor am I missing a configuration
Comment: I don't understand this feedback. It's my question. I'm answering his comment


Dificuldade ao baixar e instalar Bibliotecas de Python

Question: Eu pesquisei bastante, mas não encontrei um jeito de baixar e instalar bibliotecas para python no computador. Não estou com um erro ao baixar, ou erro ao instalar. Somente não sei como fazer isso. Precisa de ajuda nisto.
Comment: Quando diz "bibliotecas de Python" você se refere às bibliotecas padrões do Python ? Se é isso, elas já vem na instalação do Python dentro da pasta `Python/Python/Lib`.
Comment: @JeanExtreme002 Desculpa. Não estou falando dessas. Mas mesmo que eu tivesse falando dessas bibliotecas, não existe essa pasta /Lib, nos arquivos do Python
Comment: Consegui resolver o problema. Descobri como instalar. Muito obrigado!
Answer: caso queira instalar qualquer outra biblioteca, eu aconselho usar o PIP
sudo apt-get install python3-pip (para instalar caso seja sistema linux)
pip install 'pacote'
Ex.: pip install tensorflow


Is (1,1,1,...) a part of hilbert space

Question: In linear algebra and its application professor Gilbert Strang writes:
"A much better idea is to keep the familiar definition of length, using a sum of squares, and to include only those vectors that have a finite length:
Length squared = $||v||^2 = v_1^2 +v_2^2 + v_3^2 + ...$
The infinite series must converge to a finite sum. this leaves (1, 1/2, 1/3,...) but not (1,1,1,...). The vectors with finite length can be added $(\|v + w\| \le \|v\| + \|w\|)$ and multiplied by scalars, so they form a vector space. It is the celebrated  hilbert  space."
this leaves (1, 1/2, 1/3,...) but not (1,1,1,...)? does this make sense. to me partial sums of this (1,1,1,...) do not converge
Comment: By "this leaves" the author means "this includes."  Can also think of it as in "this leaves (1, 1/2, 1/3, ...) as an element of the space but (1,1,1,...) is not an element of the space."
Comment: But we're not looking at the partial sums. We're looking at partial sums of the _square_ of the terms in the sequence. And $1+\frac14+\frac19+\cdots$ converges just fine.
Comment: It does say $\|v\|^2 = v_1^2 +v_2^2 + v_3^2 + \cdots$ right up there in your question. You even typed it in _yourself_ a little over an hour ago (with a minor correction just now). Those are the squares of the terms of the sequence that are added together, yes.
Comment: I've just noticed that Gilbert is a letter off of Hilbert.
Comment: It's a language thing. You start with the space of all sequences, and then _remove_ those that have infinite length. You're _left with_ elements like $(1, 1/2,1/3, \ldots)$. In other words, the process of removing the infinite elements _leaves_ $(1, 1/2,1/3, \ldots)$ behind, or it _leaves_ $(1, 1/2,1/3, \ldots)$ alone, or it _leaves_ $(1, 1/2,1/3, \ldots)$ be, or whatever else you want to use to complete that phrase.
Comment: @tilper : the partial sums of (1,1/2,1/3,...) diverge away to infinity as well.
Comment: @Arthur : the partial sums of (1,1/2,1/3,...) diverge away to infinity as well
Comment: @arthur: what about "The infinite series must converge to a finite sum". maybe i can answer myself? he is defining sum to be the sum of squares? confirm
Comment: @arthur: that was a typo which i corrected in the question. it is ||v||^2 = ....
Comment: That typo doesn't matter. It's the right-hand side that is important, and the terms there all have little $^2$'s on them. That means that you square each element before you add them together.
Comment: @Arthur: yes got it
Comment: What Arthur said.
Answer: What you've described is an example of a Hilbert space. Our vectors need not be lists of coordinates, and our measurement of length doesn't need to be the usual sum of squares (that is, we can define different inner products). However: you can indeed say that $(1,1,\dots)$ fails to be an element of the Hilbert space that you've described.

Is (1,1,1,...) a part of hilbert space


How can I redirect the user to my view?

Question: I made a view ("exampleview") that needs an argument: myarg. I can load my page at "exampleview/myarg" and at "exampleview".
When I call drupal_goto(exampleview/myarg), the destination is only "exampleview".
I get the same result with $arr = array('exampleview','myarg');.
Can anybody help me?
Comment: Are you not just missing the '' around the path? `drupal_goto('exampleview/myarg');`
Comment: no, not so simple
Comment: try use this `url()` function. If it is creating right output then `drupal_goto()` should work.
Comment: I just tested drupal_goto('view/path/argument') with D7 views 3, which display with "subfolder" arguments and it worked fine, another issue perhaps?
Answer: This is from drupal_goto

Usually the redirected URL is constructed from this function's input parameters. However you may override that behavior by setting a destination in either the $_REQUEST-array (i.e. by using the query string of an URI) This is used to direct the user back to the proper page after completing a form. For example, after editing a post on the 'admin/content'-page or after having logged on using the 'user login'-block in a sidebar. The function drupal_get_destination() can be used to help set the destination URL.

It seems like your destination parameter is set so you have to clear destination parameter or use header function

How can I redirect the user to my view?


Converter string em array junto com delimitador

Question: Estou a separar uma string em array caso haja uma certa preposição nela ('com', 'para', 'por'), porém quero o retorno dessa string contendo também o delimitador, ou seja, a preposição.
Utilizando o preg_split e explode, eu tenho o mesmo resultado e não satisfatório:
$string = 'Programação com Stackoverflow';

$resultado = explode('com', $string);
$resultado2 = preg_split('/com|para|by|por/', $string);

Array
(
    [0] => Programação
    [1] =>  Stackoverflow
)

O resultado esperado para o que procuro:
Array
(
    [0] => Programação
    [1] => com
    [2] =>  Stackoverflow
)

Comment: Você quer que, quando contenha `com`, "exploda" a string? Não terias que verificar primeiro a palavra `com|para|by|por` com `preg_match`?
Comment: Sim, @WallaceMaxters. E preciso da preposição junto do resultado.
Answer: Não seria algo assim?
$regex = 'Filme com pipoca';

if (preg_match('/com|by|para|por/u', $string)) {
    $array = preg_split('/\s+/u', $string, -1, PREG_SPLIT_NO_EMPTY);
}

Resultado:

['Filme', 'com', 'Pipoca']

Utilizamos uma expressão para verificar se  existe algum dos valores na string e, em seguida, quando esse valor é achado, a string é divida pelos espaços, a fim de separar as palavras em um array.
Creio que é uma boa ideia utilizar o PREG_SPLIT_NO_EMPTY, para não retornar nenhum valor vazio.
Comment: Exatamente, @Wallace. Eu receberei uma string e a separarei em 3 partes, consegui da seguinte maneira: preg_split('/(com|para|by|por)/', $string, false, PREG_SPLIT_DELIM_CAPTURE );
Comment: Porém, caso tenha algo mais na palavra, ele também retorna como uma chave no array. Ex: 'Stackoverflow por Wallace Maxter' ele retorna:  `['Stackoverflow', 'por', 'Wallace', 'Maxter']` quando deveria ser apenas: `'[Stackoverflow', 'por', 'Wallace Maxter']`
Comment: Entendi. Você quer que `por` entre no processamento de divisão da expressão regular e, ao mesmo tempo, quer que ele "continue" no `array`.
Comment: Legal. Agora entendi pra que serve o tal do `Delim Capture`
Comment: Vou adicionar na resposta :)
Comment: Não adicionou, @Wallace.
Answer: preg_split('/(com|para|by|por)/', $string, false, PREG_SPLIT_DELIM_CAPTURE );


How to change the default permission name?

Question: I want to change the default permission name created by django after migrating django model.
The docs says Providing default_permissions = [] in the class Meta works but

It must be specified on the model before the model is created by
  migrate in order to prevent any omitted permissions from being
  created.

But is it possible to change the permission Name (codename also if possible) after the model migration also ?
 class ContactPage(models.Model):
        full_name = models.CharField(max_length=255)
        email = models.EmailField()
        msg = models.TextField()
        sent_on = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.full_name

        class Meta:
            default_permissions = [] # works in the first migrate
            permissions = [
                ('can_view_contacts', 'Can View Contacts'),
                ('can_delete_contacts', 'Can Delete Contacts'),
            ]

Comment: Any news yet? looking for an answer to the same question...
Answer: I did it by creating an empty migration file and doing the job manually in that.


Allow LAN to access External Internet, Iptables

Question: I have an internal network behind my router on eth0, and I have my router connected to the internet thorugh wlan0. I can't access the internet from inside the lan, how can I fix this?
wlan0: 192.168.1.108
eth0:  10.1.1.0/24

Comment: You're not providing the operating system, and the only clue we have to go on is that it's some flavor of *nix based on the interface names.
Comment: This is supposed to be a professional IT environment (being on-topic here)...?
Answer: You need to set up NAT in order for your box to act as a router. Once this is done, set the default gateway on your LAN systems to  the internal IP of the box.
Instructions here:
http://www.revsys.com/writings/quicktips/nat.html
echo 1 > /proc/sys/net/ipv4/ip_forward

# /sbin/iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
# /sbin/iptables -A FORWARD -i wlan0 -o eth0 -m state
   --state RELATED,ESTABLISHED -j ACCEPT
# /sbin/iptables -A FORWARD -i eth0 -o wlan0 -j ACCEPT


Advanced CSS/JS Aggregation Module Breaks My Site Layout

Question: When I enable my module Advanced CSS/JS Aggregation it breaks my site layout.  Is there something I need to do before or after when enabling this module.
To fix the site layout I need to disable the Advanced CSS/JS Aggregation module and it works again.
Comment: Check your status page and log messages. Probably a permissions issue.
Answer: I faced the same issue, here is some steps to check:

check if your css loaded and optimised in your page source code some files like <code>/sites/default/files/css/css_QnKw33sohmgUyVqs9lGXvHTJTZsphXTkXdkVVmt25ts.css</code> if it's no check if there is any errors in your console, if this is the case Check your status page and log messages, and permissions
If it's yes all files well loaded this is was my case i had some css errors that's why even my css files loaded not taking any effect:
So i had to check / validate all my css files and correct any errors.
I used this https://codebeautify.org/cssvalidate.
there is a lot other websites to validate your css.
I hope this help you !


Find $\int x^2 d(x^2)$

Question: Here is my problem:
$$I = \int x^2 d(x^2)$$
I used a $u = x^2$ substitution
$$\frac{d(x^2)}{du} = 1$$
$$d(x^2) = du$$
Putting that into I,
$$I = \int u du$$
$$I = \frac{u^2}{2}$$
$$I = \frac{x^4}{2} + C$$
However I think my working out might be incorrect, intuitively I was expecting I to have an x to the power of 3.
Thanks for the help!
Comment: What you have done is correct if you add a constant of integration.
Comment: The classic forgot the plus C mistake, thanks for your help
Comment: How do we know $d(x^2) = 2x dx$ ?
Comment: @DanielGilbert The derivative of $f(x)=x^2$ with respect to $x$ is $2x$, so the differential of $x^2$ at $x$, i.e. $df(x)$ equals $f'(x)\,dx = 2x\,dx$. You can take it as a definition of differential. You can generalise to integrals of $x^n\,d(x^n)$: the differential of $x^n$ is $nx^{n-1}\,dx$, then integrating you have $\int nx^{2n-1}\,dx = (1/2)x^{2n}+\text{const}$.
Comment: @DanielGilbert $\mbox{d} g(x) = g'(x)\,\mbox{d}x$; now take $g(x)=x^2$.
Answer: What you did was correct. To see this, we can calculate $I$ more explicitly using $d(x^2)=2x\,dx$, then $$I=\int x^2 d(x^2)=\int 2x^3 dx=\frac{x^4}{2}+C$$

Find $\int x^2 d(x^2)$