Proof verification on the openness of the space of matrices of full rank

Question: Let be $m<n$ and $M_m(m\times n, \mathbb{R})$ be the set of the matrices $m \times n$ of full rank $m$.
I want to show that $M_m(m\times n,\mathbb{R})$ is an open subset of $M(m\times n,\mathbb{R})$
I reasoned as follows. Let $A$ be an element in $M_m(m\times n,\mathbb{R})$. Then $A$ has some $m\times m$ submatrix whose determinant is non zero. Let be $j_1,\dots,j_m$ the columns of one such submatrix of $A$, and let $\pi\colon M(m\times n,\mathbb{R})\to M(m,\mathbb{R})$  be the map who takes a matrix $B$ and associates the $m\times m$ submatrix obtained by taking the columns $j_1,\dots, j_m$. Then $\pi$ is smooth, and then continuous. I already know that $GL(m,\mathbb{R})$ is open in $M(m,\mathbb{R})$. So I conclude that $\pi^{-1}(GL(m,\mathbb{R}))$ is an open subset of $M(m\times n,\mathbb{R})$ contained in $M_m(m\times n,\mathbb{R})$ and containing $A$.
So $M_m(m\times n,\mathbb{R})$ is a neighbor of all its points, then it is open.

Is my proof correct?
Answer: Obviously you are right.
I give here something different. I show $S:=$ set of all matrices of rank strictly less than $m$ , is a closed subset of $M(m\times n, \mathbb{R})$ . So let $\{A_p\}_{p\in \Bbb N}$ be a sequence in $S$ converging to some $A\in M(m\times n, \mathbb{R})$. If possible let $A\in M_m(m\times n, \mathbb{R})$. Then we have a matrix $B\in M_m(n\times m, \mathbb{R})$ such that $AB=I_m$. Now $\{A_pB\}_{p\in \Bbb N}$ converges to $AB$. But notice that $det(A_pB)=0$ for each $p$ , since $rank(A_pB)≤rank(A_p)<m$ , also $rank(AB)=rank(I_m)=1$.
Now $det$ is a continuous function i.e. $0=det(A_pB)\rightarrow det(AB)=1$ as $p\rightarrow \infty$, contradiction. Therefore $S$ is closed in  $M(m\times n, \mathbb{R})$ i.e. $ M_m(m\times n, \mathbb{R})$ is open in $ M(m\times n, \mathbb{R})$.
Existence of $B\in M_m(n\times m, \mathbb{R})$ for $A\in  M_m(m\times n, \mathbb{R})$ with $AB=I_m$ can be given as : $ dim(column\ space(A))=dim(row\ space (A))=m$ , so that j-th column $e_j$ of $I_m$ can be written as $Ab_j=e_j$ where $b_j$ is column matrix, for each $j=1,....,m$. Therefore define $B=[b_1,....,b_m]$.
Comment: Thank-you. It's very beautiful. Let me only check a few things:

1) $\{A_pB \}_{p\in\mathbb{N}}$ converges to $AB$ by the continuity of the row-column product, right?

2) I have that the columns $A_1,\dots,A_n$ of $A$ are $n$ elements of $\mathbb{R}^m$ and they contain a basis of $\mathbb{R}^m$ since they contain $m$ linear indipendent vectors. Now $e_j$ is an element of $\mathbb{R}^m$, so I can write $e_j=b_j^1 A_1+\dots+ b_j^nA_n$. Now the product $Ab_j$ with $b_j=$ the column $(b_j^1,\dots, b_j^n)$ is exactly the linear combination which gives $e_j$, right?
Comment: You are actually right.


How to set focus on a particular row in a datagrid/gridview?

Question: I have a datagrid/gridview. I'm populating the grid with 10 rows initially. On a button click every time,I'm keeping on adding 10 rows to the datagrid/gridview. Now I want to set the focus to the last row every time the grid is populated. I can get the index of that row,but I can't set focus to that particular row.
Do anyone of you have any idea how to do it in C#?
Answer: Try this
dataGridView1.ClearSelection();
int nRowIndex = dataGridView1.Rows.Count - 1;

dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.Rows[nRowIndex].Cells[0].Selected = true;

Comment: Thanks.I tried your code but it's giving error as "GridviewRow doesn't contain a definition for 'Selected' and no extension method 'Selected' accepting a first argument of type System.Web.UI.WebControls.GridViewRow could be found".Am I missing any directive or assembly reference?
Comment: Friend,I'm setting the focus in that button's click event.And I can't find any property for gridview as 'Row' and'.Selected'.Please tell me how can I get them..
Answer: For WinForms DataGridView:
myDataGridView.CurrentCell = myDataGridView.Rows[theRowIndex].Cells[0];

For WebForms GridView, use the SelectedIndex property
myGridView.SelectedIndex = theRowIndex;

Comment: @Sukanya There is for [DataGridView](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcell.aspx). Are you working with the WebForm GridView? If yes, please mark this in your question.
Comment: Friend,I'm using .net 4.0.I'm creating web form.I'm getting only 2 asp grid and they are DataGrid and Gridview.For both these grids,I'm not getting .CurrentCell property.Is anything wrong from my side?And second point is I've been able to set the point to a particular rowindex using 'SelectedIndex' but my problem is I've not been able to focus to that particular row..
Answer: Try this...
DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow;

rowToSelect.Selected = true;

rowToSelect.Cells[0].Selected = true;

this.dgvJobList.CurrentCell = rowToSelect.Cells[0];

this.dgvJobList.BeginEdit(true);

Answer: Try this, it's work for me
   public static void ItemSetFocus(DataGrid Dg, int SelIndex)
    {
        if (Dg.Items.Count >= 1 && SelIndex < Dg.Items.Count)
        {
           Dg.ScrollIntoView(Dg.Items.GetItemAt(SelIndex));
           Dg.SelectionMode = DataGridSelectionMode.Single;
           Dg.SelectionUnit = DataGridSelectionUnit.FullRow;
           Dg.SelectedIndex = SelIndex;
           DataGridRow row = (DataGridRow)Dg.ItemContainerGenerator.ContainerFromIndex(SelIndex);
                row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

Answer: This post has been a god send.  I am using VB in Visual Studio 2017 and just needed to go to the bottom of a DATAGRID to allow user to input data.  By studying these answers I came up with this solution and thought others might find it useful.
Private Sub AddBUTTON_Click(sender As Object, e As RoutedEventArgs) Handles
AddBUTTON.Click
        ' Go to bottom to allow user to add item in last row
        DataGrid.Focus()
        DataGrid.UnselectAll()
        DataGrid.SelectedIndex = 0
        DataGrid.ScrollIntoView(DataGrid.SelectedItem)
        Dim endofitems As Integer = DataGrid.Items.Count
        DataGrid.ScrollIntoView(DataGrid.Items.GetItemAt(endofitems - 1))
    End Sub

Answer: In my case, I had a button which add new row to datagridView1 and activate newly added row's second cell C# Windows Form Application.
int rowIndex = datagridView1.Rows.Count - 1;
datagridView1.CurrentCell = datagridView1.Rows[rowIndex].Cells[1];
datagridView1.BeginEdit(false);

Answer: Try this, I'm works well with below script snippet in Extjs 4.2.0.
//currentIndex is the index of grid row
var rowElement = this.getView().getRecord(currentIndex);
this.getView().focusRow(rowElement);


Trying to round to nearest $5, $10, $50, and $100 when computing the next minimum bid in an auction

Question: I'm working on a big program that utilizes a bunch of smaller methods to create a functioning auction system. I'm having trouble with this particular method where I have to raise the minimum bid for an item given the current or "now highest bid"
The instructions are as follows:
If a bid is accepted, then you need to raise the minBid on that item by 5% above the current bid,rounded up to the nearest $5 below $100.00,
rounded up to the nearest $10 between $100.01 and
$1000.00, rounded up to the nearest $50.00 between
$1000.01 and $10000.00, and rounded up to
the nearest $100 above $10000.00
My main issue is figuring out exactly I can round up by just 5 or just 10, depending on the amount of the bid. Here's my code so far, any help would be greatly appreciated :)
public class computeMinNextBid
{
    public static double computeMinNextBid(double currentBid)
    {
        double minNextBid = (currentBid * 0.05) + currentBid;
        if(minNextBid <= 100.00)
        {
            minNextBid = Math.round(minNextBid);
        }

        else if(minNextBid >= 100.01 && minNextBid <= 1000.00)
        {
            minNextBid = Math.round(minNextBid);
        }

        else if(minNext Bid >=1000.01 && <= 10000.00)
        {
            minNextBid = Math.round(minNextBid);
        }

        else(minNextBid >= 10000.01)
        {
            minNextBid = Math.round(minNextBid);
        }
        return minNextBid;
    }

    public static void main(String [] args)
    {
        double currentBid = Double.parseDouble(args[0]);
        double minNextBid = computeMinNextBid(currentBid);
        System.out.println("The next minimum bid is: " + minNextBid);
    }
}

Comment: I think you can find the answer here: http://stackoverflow.com/questions/584948/rounding-to-nearest-100?rq=1
Comment: You probably want to use mod
Answer: The general expression for rounding to N (using integer arithmetic) is:
x = (x + N/2)/N * N;

This rounds to the nearest multiple of N. For example, for x = 45 an N = 100, this yields 0 (i.e., it rounds 45 down to 0). For x = 55, this yields 100 (i.e., it rounds 55 up to 100).
To round down (also known as truncation), remove the "+ N/2" part:
x = x/N * N;

To round up to the nearest N, use:
x = (x + N-1)/N * N;

For example, for x = 35 and N = 100, this yields 100 (i.e., it rounds any x between 0 and 99 up to 100).


Up to date ClamAV on Debian Wheezy (ClamAV installation is OUTDATED log message)

Question: I've installed ClamAV on Debian Wheezy from the offical repositories, using apt. System is up to date and I don't get any updates via apt-get upgrade, but still I get this message in the logs:
Your ClamAV installation is OUTDATED!

My version is:
$ clamscan -V
ClamAV 0.98.1/19186/Sun Jul 13 00:34:56 2014

On the official page:

Latest ClamAV® stable release is: 0.98.4

Looks like the official stable repos for Wheezy are not up to date. The only information I've found is official info about Debian Volatile project, which is now closed since Squeeze.
Are there any alternative repositories?
How can I keep ClamAV always up to date and be sure the system is stable?
Edit:
My /etc/apt/sources.list:
deb http://ftp.ru.debian.org/debian/ wheezy main non-free contrib
deb http://security.debian.org/ wheezy/updates main contrib non-free
deb http://ftp.ru.debian.org/debian/ wheezy-updates main contrib non-free

$ dpkg -l 'clamav*'

||/ Name                                     Version                   Architecture              Description
+++-========================================-=========================-=========================-======================================================================================
ii  clamav                                   0.98.4+dfsg-0+deb7u2      amd64                     anti-virus utility for Unix - command-line interface
ii  clamav-base                              0.98.4+dfsg-0+deb7u2      all                       anti-virus utility for Unix - base package
ii  clamav-daemon                            0.98.4+dfsg-0+deb7u2      amd64                     anti-virus utility for Unix - scanner daemon
un  clamav-data                              <none>                                              (no description available)
ii  clamav-docs                              0.98.4+dfsg-0+deb7u2      all                       anti-virus utility for Unix - documentation
ii  clamav-freshclam                         0.98.4+dfsg-0+deb7u2      amd64                     anti-virus utility for Unix - virus database update utility

Answer: I had the same problem. I down some digging read The Perfect Server - Debian Wheezy (Apache2, BIND, Dovecot, ISPConfig 3) - Page 3 This sorted my "Your ClamAV installation is OUTDATED!"
First make sure that your /etc/apt/sources.list contains the wheezy-updates repository (this makes sure you always get the newest updates for the ClamAV virus scanner - this project publishes releases very often, and sometimes old versions stop working), and that the contrib and non-free repositories are enabled (some packages such as libapache2-mod-fastcgi are not in the main repository).
Add these lines to your /etc/apt/sources.list
# wheezy-updates, previously known as 'volatile'
deb http://ftp.de.debian.org/debian/ wheezy-updates main contrib non-free
deb-src http://ftp.de.debian.org/debian/ wheezy-updates main contrib non-free

Then run command apt-get update then apt-get dist-upgrade worked for me.
Answer: Make sure the basic wheezy repository is enabled in /etc/apt/sources.list.
It's a bit odd; newest clamav on Wheezy is not on wheezy-updates repository, but wheezy repository instead:
wheezy-update: 0.98.1+dfsg-1+deb7u4
wheezy       : 0.98.4+dfsg-0+deb7u2

If you haven't enabled any apt pinning (need not worry about it if you don't know those settings, otherwise the pinning must be undone), apt-get upgrade or apt-get dist-upgrade should be fetching newest version after apt-get update.
Comment: Added the list of packages.
Comment: @Sfisioza You already have newest package. `clamscan` reporting different version highly suggests another custom installed ClamAV. Can you try running this command: `type clamscan` and check where this `clamscan` comes from?
Comment: `clamscan is /usr/bin/clamscan`. The updates came with the latest wheezy upgrades, do I don't get the warnings for now.
Comment: Then you can try `clamscan -V` now.
Comment: Yes, currently is up to date.
Comment: Looks like it's enabled. I've updated the question with the sources.
Comment: @sfisioza, maybe you want to post output of `dpkg -l 'clamav*'` on your post? There's some slight possibility that old deb package version might contain epoch number, which blocks installation of any newer version.


Can we regard a A-module $M$ as a $A/radA$-module?

Question: Let $A$ be a finite dimensional algebra over a field, and $M$ be a finitely generated module of $A$. Can we regard $M$ as a $A/radA$ module with module structure inherited from $M$ as a $A$ module?
For example, we define $(a+radA)m=am$ , where "am" is aleady defined as "am" in A-module $M$.
My teacher's answer to this question is NO, but I think this satisfies the definition of module.
Comment: ony if $(rad A) M = 0$
Comment: if the module is simple then you can do what you said as @Exodd pointed out
Comment: The problem is that your product is not well defined in general: you need that if $a+rad(A)=a'+rad(A)$, then $am=a'm$ for any $m\in M$. This is equivalent to ask that $rad(A)M=0$.
Comment: There is of course another possibility, which is when $A\to A/\mathrm{rad}A$ splits. Then there is an embedding $A/\mathrm{rad}A\to A$ and we can use restrictions of scalars. For example, every module over the path algebra of a quiver is a tuple of vector spaces supported at the vertices, together with linear maps between them. Forgetting the linear maps gives a module for a product of fields, which is a subalgebra isomorphic to the quotient $kQ/\mathrm{rad}kQ$.
Answer: Recall that the annihilator of $M$ is the ideal $$\operatorname{Ann}(M)=\{a\in A\mid aM=0\}.$$
You can always consider $M$ as an $A/\operatorname{Ann}(M)$-module, and more generally an $A/I$-module as long as $I\subseteq \operatorname{Ann}(M)$. Your construction is well-defined as long as $\operatorname{Rad}(A)\subseteq \operatorname{Ann}(M)$, i.e. $\operatorname{Rad}(A)M=0.$
Answer: Your teacher is right.
How would you define $(a+\operatorname{rad}A)m$? If you define it as $am$, you need that, when $a+\operatorname{rad}A=b+\operatorname{rad}A$, then also
$$
am=bm
$$
which is precisely the needed condition, namely

for every $r\in\operatorname{rad}A$ and every $m\in M$, $rm=0$

For instance, consider the localization $\mathbb{Z}_{(p)}$ of $\mathbb{Z}$ at the prime ideal $(p)$, where $p$ is any prime. Then
$$
\operatorname{rad}\mathbb{Z}_{(p)}=p\mathbb{Z}_{(p)}
$$
and
$$
\mathbb{Z}_{(p)}/\operatorname{rad}\mathbb{Z}_{(p)}\cong \mathbb{Z}/p\mathbb{Z}
$$
But, clearly, $\mathbb{Z}_{(p)}$ itself cannot be considered as a module over the quotient ring modulo the radical.
You can easily find examples for algebras over fields, using a similar idea, namely, local rings.


Repeating the tonic when the scale is ascending and then descending

Question: When I started to learn piano about 2 years ago, I practiced scales with my piano teacher. For practicing C Major, she recommended repeating the tonic:
C D E F G A B C C B A G F E D C
When I switched to another teacher, he said I should not repeat the tonic and practice the scale like this:
C D E F G A B C B A G F E D C
Both of them were certain that their way was the right way to do it.
How would you advise a beginner (or even an expert) to practice a scale?
Comment: I've never heard of repeating the tonic, only holding out to double the duration of the other notes, but I suppose in some ways, it makes sense. As that middle tonic functions both as the end to one octave and the beginning of another, some people may want to emphasize that. For me, the two-octave scale is an entity in itself, not two disjunct parts crammed together.
Comment: Repeating the tonic is all I've ever known. I think the two systems are equally prevalent; which one to use is pretty unimportant.
Answer: There is no "right" way, though I've never heard of it being repeated myself, or seen it that way in scale books.  Most music I've seen involving scales doesn't do that sort of repetition either.
In the end it's about what trains your fingers better.  If you have difficulty with the repetition, it may be useful to practise it with the repetition.  Likewise, if you have trouble keeping the transtition from ascending to descending smooth (or vice-versa) then practising the other way might help.
If you need a concrete suggestion: Do it without the repeated note.
Answer: I agree that there is no "right" way. Those two ways test different things:
When you don't repeat the C, it is testing your ability to move up and down smoothly.
When you do repeat the C, it is testing your ability to hit the same note in succession. It is rhythmically harder to play and less intuitive (for me at least). So perhaps this might pull you out of your comfort zone if you find the former version easier.
There are many other variations of playing a scale which would improve different aspects of your playing. In the end it's all about what you want to get better at.
Comment: Expanding on the third paragraph… you might try hitting different notes twice each time you play the scale. It'll certainly test your knowledge and ability in fingering, as it takes your muscles slightly out of their ingrained patterns.


Compactness and Limit points

Question: If $A$ is compact how can it be shown that any sequence $\{x_n\}$ in $A$ has a limit point in $A$?
I know this is proven in a lot of textbooks but I'm finding this hard to conceptualise.
Comment: By limit point do you mean a point $x$ such that every neighborhood contains infinitely many $x_i$ (not necessarily distinct), or do mean a point $x$ such that each neighborhood $U$ intersects the sequence in a point different from $x?$
Answer: I assume that $\{x_n\}_{n \in \mathbb{N}}$ is infinite, otherwise the statement is false (if you mean accumulation point); suppose that such a set hasn't got an accumulation point, then it's an infinite discrete  closed subset of a compact space, which is impossible. In fact  having no accumulation points implies that your subset is closed in $A$ and so it's compact; for each point there 's an open set which contains only a point of your subset (no limit points) and so that open cover has no finite subcover.
(I still have the doubt that you mean cluster point)
Comment: Sequentially closed is not the same as closed.
Comment: Sorry, I made the same confusion myself...
Comment: Yes I believe it should be cluster point, though the notes I am following have it written as above.
Comment: I meant no accumulation points, since the OP somehow confused those two terms
Comment: I think in the space $(\mathbb R_{\ge0},\tau)$, where the topology is generated by all intervals $[0,x),\ x\ge0$, the set $\mathbb N$ is an infinite sequence without a cluster point, but it is not closed as there are adherence points outside of $\mathbb N$. So in a non-$T_1$ space a sequence without an accumulation point isn't automatically closed.
Comment: Correct me if I'm wrong, but is OP asking that every compact space is sequentially compact? If so, that is false. See: http://math.stackexchange.com/questions/44907/whats-going-on-with-compact-implies-sequentially-compact
Comment: @StefanH: I repeat myself: I meant accumulation point, not cluster point for the sequence.
Comment: I thought accumulation point is the same as cluster point. That's what Wikipedia says http://en.wikipedia.org/wiki/Accumulation_point. Then what do mean by accumulation point? A limit point?
Comment: A cluster point for a sequence is a point (not necessarily in the image of that sequence) such that chosen one of its neighborood you get infinitely many naturals $n$ for which $x_n$ is in that neighborood. An accumulation point is a point such that each of its  neighborhood intersects the set minus that point.
Comment: Isn't that called a *limit point*? See the same wikipedia-page.
Comment: It's a bit ambiguous in my opinion: a cluster point doesn't need to be an acc point (think of a constant sequence)
Comment: No, a cluster point and an accumulation point are equal by definition, except you define an accumulation point to have infinitely many points in each of its neighborhoods, but then it is called a $\omega$-accumulation point.
Comment: Tell me where I make that infinite request
Comment: Please, use "@Stefan" in your comment, else I don't get notified about your comment. I translated word for word from German, that's why I missed a word, I meant "... except **if** you define ...". Never mind, I now notice your comment from earlier where you wrote how you define it. But I think the notion *limit point* is more common for what you refer to as *accumulation point*. Also the OP wanted to know if it has a cluster point, not a limit point. What you proved is that the sequence has a limit point, which is a cluster point only if the space is $T_1$.
Comment: Does the reverse hold? If every sequence in a space X has at least one cluster point, is the space X necessarily compact?
Comment: By the way, there's a flaw in your proof. It should be 'for each point there's an open set which contains only finite points of your subset (no limit points)'.

Compactness and Limit points


Show progress on html file input?

Question: I want to show a progress bar or spinner when I choose a file for upload, I'm not talking about server upload success, I already got that covered, I want to show a spinner when image is loading right after I click the "Choose file" button from the input file, is that possible?
I'm using Vue.

<input :id="field.id" type="file">

Comment: https://bootstrap-vue.js.org/docs/components/progress/
Comment: https://github.com/hilongjw/vue-progressbar
Comment: https://vuejsexamples.com/tag/progress/
Answer: Check out the input and change events on file inputs - after the value of the file input changes, it should fire those events - try both, see which one suits your needs.
Show the 'loading' indicator when the event first fires, hide the indicator on server upload success!

Show progress on html file input?


describe the surfaces r=constant theta=constant and a =constant in the cylindrical coordinate system

Question: A question arises in my Multivariable calculus book that appears as follows:
Describe the surfaces
$r=$constant,
$\theta$ = constant,
$z$ = constant
in the cylindrical coordinate system.
I am unsure they mean to consider each one separately or together. If r is constant we have a circle, and if z is constant we have a flat 2-dimensional plane translated z units, not sure about theta. Any thoughts or answers appreciated.
There is a similar question concerning spherical co-ordinates:
if
$\rho$ is constant
$\theta$ is constant
$\phi$ is constant
Comment: @Dr.MV can you say why? I remember reading this somewhere.
Answer: From the text it seems that they wish you to describe the 3 surfaces, each having one variable as a constant.
Regarding your question, you are close but not quite correct.
If $\rho=constant$ then you get a cylinder. You don't get a circle since your circle can be in different heights according to the $z$ axis.
if $\theta=constant$ then you get half a plane excluding the z axis.
if $z=constant$ then you get a plane parallel to $(x,y,0)$.
Elaboration on $\theta$:

keep in mind that there is no top, no bottom and it goes on forever since:
$\matrix{{z\in(-\infty,\infty)}\\{\rho\in(0,\infty)}&{}&}$
Spherical Coordinates:
now, I'm going to answer in $(\rho,\theta,\phi)$ meaning $\phi$ is the opening from the $z$ axis and $\theta$ is in plane $xy$.
if $\rho=constant$ then you get a sphere.
if $\theta=constant$ you will once again get a plane, the same as last time. Imagine that you have a constant angle at which you can look up and down since $\phi\in(-\frac{\pi}{2},\frac{\pi}{2})$ and there is no limit to your range since $\rho>0$.
if $\phi=constant$ you get a circle that's increasing in it's radius as you climb up the z axis. Try to imagine it, you have an increasing radius and a circle in every radius. You get a cone.
Elaboration on $\phi$:
Comment: When I studied it, in cylindrical coordinates we used $\rho$ instead of $r$ so sorry for the confusion.
Comment: Can you elaborate on $\theta$. Also I edited the question to add the next part since I am so utterly confused. Also I think you mean if $r$ is constant.


Why $T(n) = 2T(n/2) + \log n$ is in $ O(n)$?

Question: My professor said that  $T(n) = 2T(n/2) + \log n$ is in $O(n)$
I checked with Master Theorem and I did not really understood why.
By Case1 (which would give us exactly $O(n)$) we have
$a = 2, b = 2, f(n) = \log n$
$\log n = O(n^{\log n - c})$ for c > 0
well, if c must be > 0, then $n^0$ gives us $1$, which is constant time and $\log n$ is not in $O(1)$
Thus, I am confused how using Master Theorem we are getting $O(n)$ running time
Answer: Case 1 says
If $f(n) = O\left( n^{c} \right)$ where $c < \log_b a$
then:
$T(n) = \Theta\left( n^{\log_b a} \right)$.
Here $\log_b a = 1$. So we can use $c=0.99$.
Since your $f(n)$ is $\lg n$, and $\lg n = O(n^{0.99})$, the conditions are satisfied.


DHCP server on bridged connection

Question: I want to put DHCP server on Ubuntu server to listen on 10.0.0.1 (internal network).
I also need to configure OpenVPN server on Ubuntu server (DHCP is going to lease addresses to OpenVPN clients), therefore I need to bridge one hardware interface (eth1) and one virtual interface (TAP from OpenVPN) in bridge mode (br0).
Where should I put DHCP to listen (on br0 or on eth1) ?
Should I put a gateway in the following configuration or not (if the DHCP listens on that interface) ?
I have the following configuration (/etc/network/interfaces):
<code># This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth2
iface eth2 inet dhcp

# Other interfaces - not used
#auto eth0

# Internal interface - is now in bridge
#auto eth1 iface eth1 inet static
#     address 10.0.0.1
#     netmask 255.255.0.0

# Bridge
auto br0
iface br0 inet static
#ip, netmask, gateway
address 10.0.0.1
netmask 255.255.0.0
#gateway 10.0.0.1
#network interfaces on which to enable the bridge
bridge_ports eth1
#optional configuration if the machine is VM
#bridge_fd 9
#bridge_hello 2
#bridge_maxage 12
#bridge_stp off
</code>
Answer: DHCP needs to listen on the bridge interface.
Comment: Do I need to setup an gateway on that interface br0 ?
Comment: If you want to communicate outside the 10.0.0.0/16 network, yes. The bridge interface needs to be configured with the same parameters as a "normal" interface.

DHCP server on bridged connection


tcl spawn sftp not working

Question: I am trying to run a very simple tcl script
package require Expect
spawn sftp user@host

the error I get is

The system cannot find the file specified.
      while executing
  "spawn sftp user@host"

The only reason I see it's that sftp path should be specified somehow. I call this from a batch script and I've also tried changing the directory to sftp location before calling the script but the error is still the same.
Answer: By far the most likely cause of the issue here is that the sftp program is not in a directory that is on your PATH. The concept is almost the same across platforms, but with some minor niggles.
Working with the Unix PATH
Check to see if sftp is available in a PATH-known directory by typing:
which sftp

At your shell prompt. It should respond with the location of the sftp program, but if it isn't found then you get no response at all. If it isn't found, you'll need to find it yourself and add its location (strictly, the directory that contains the program) to the PATH. Find the program with something like:
locate sftp

Or (very slow!):
find / -name sftp -print

To append a directory to the PATH, do this in your shell:
PATH=$PATH:/the/dir/to/append

You can add a directory within the Expect script too (as long as it is before the spawn, of course!):
append env(PATH) : /the/dir/to/append

Working with the Windows PATH
On Windows, use Windows Search (Windows+F IIRC) and look for a file called sftp.exe (there's also a command line search tool, but I forget how to use it).
With the Windows PATH, a little more care is required:
append env(PATH) ";" {C:\the\dir\to\append}

# Or this...
append env(PATH) ";" [file nativename C:/the/dir/to/append]

Which is to say, the Windows PATH uses a different separator character (because : is used for separating drive names from directory parts) and the native name of the directory must be used, rather than the somewhat-more-convenient forward-slash variation (the backslashes interact with Tcl's syntax, hence the {braces}). Forward-slashes can be used provided you use file nativename to convert before appending, as in my second version.
Some Tcl Techniques that can Help
You can use the Tcl command auto_execok to find out whether a program is on your PATH or not. For example:
puts [auto_execok sftp]

However, for some commands (notably start on Windows) you get a more complex response; the command really exists as part of the code that supports interactive Tcl usage, describing how to run some external program which can sometimes be a lot more complex than it appears to be at first glance. Still, it approximates to a cross-platform version of which as listed in the beginning of this answer...
Tcl 8.6 provides $tcl_platform(pathSeparator) variable as a way to get the PATH element separator character (a : or ;, depending on platform). Probably doesn't help you though, as 8.6 hasn't yet been distributed as widely as previous versions.
Comment: I'm launching the tcl that tries to establish the sftp connection from a Windows batch command not from a linux script.
Comment: @user Ah! An important detail! The problem is still the PATH but the way you set it up and find programs is a bit different.

tcl spawn sftp not working


Effect of missing data and outliers on least square estimation

Question: Why is it that "missing data" and "outliers" can affect the performance of least square estimation?
Comment: Context, details, or a real or hypothetical example would help focus this discussion greatly.
Comment: @user3125. Pls be more specific. Also why did you tag it regression? One of the regression methods is related to least sqaure, but not necessarily the same.
Answer: I'm not sure about the "missing data", but I can give an answer on "outliers"
This is basically due to the "unbounded" influence that a single observation can have in least squares (or at least in conventional least squares).  A very, very simple example of least squares should show this.  Suppose you only estimate an intercept $\mu$ using data $Y_i \ (i=1,\dots,n)$.  The least square equation is
$$\sum_{i=1}^{n} (Y_i-\mu)^2$$
Which is minimised by choosing $\hat{\mu}=n^{-1}\sum_{i=1}^{n} Y_i=\overline{Y}$.  Now suppose I add one extra observation to the sample, equal to $X$, how will the estimate change?  The new best estimate using $n+1$ observations is just
$$\hat{\mu}_{+1}=\frac{X+\sum_{i=1}^{n} Y_i}{n+1}$$
Rearranging terms gives
$$\hat{\mu}_{+1}=\hat{\mu}+\frac{1}{n+1}(X-\hat{\mu})$$
Now for a given sample $\hat{\mu}$ and $n$ are fixed.  So I can essentially "choose" $X$ to get any new average that I want!
Using the same argument, you can show that deleting the $j$th observation has a similar effect:
$$\hat{\mu}_{-j}=\hat{\mu}+\frac{-1}{n-1}(Y_{j}-\hat{\mu})$$
And similarly (a bit tediously), you can show that removing $M$ observations gives:
$$\hat{\mu}_{-M}=\hat{\mu}+\frac{-M}{n-M}(\overline{Y}_{M}-\hat{\mu})$$
Where $\overline{Y}_{M}$ is the average of the observations that you removed.
The same kind of thing happens in general least squares, the estimate "chases" the outliers.  If you are worried about this, then "least absolute deviations" may be a better way to go (but this can be less efficient if you don't have any outliers).
Influence functions are a good way to study this stuff (outliers and robustness).  For example, you can get an approximate change in the variance $s^2=n^{-1}\sum_{i=1}^{n}(Y_i-\overline{Y})^2$ as:
$$s^2_{-j} = s^2 +\frac{-1}{n-1}((Y_j-\overline{Y})^2-s^2) + O(n^{-2})$$
Answer: If you're using R, try the following example.
<code>library(tcltk)
demo(tkcanvas)
</code>
Move the dots around to create all of the outliers you want.  The regression will keep up with you.
Answer: An graphical example on outliers that requires no software and can be read in 2 minutes is Wikipedia on Anscombe's quartet


Postulate or Theorem: The areas of similar plane figures are proportional their linear dimensions squared?

Question: In Penrose's The Road to Reality, after introducing the barest basics of classical Euclidean geometry, Penrose goes on to prove the Pythagorean theorem.  As part of his first proof he promulgates:

Now, it is a general property of similar plane figures that their areas are in
  proportion to the squares of their corresponding linear dimensions.

My paraphrase of Penrose's restatement of Euclid's postulates is:
1) Connecting any two points, there is a unique line segment.
2) Every line segment lies on a (continuous) line (of infinite extent).
3) Associated with every point-radius pair, is a circle.
4) All right angles are congruent.
5) If the sum of consecutive interior angles is less than $\pi$, the two lines will intersect somewhere on that side of the transversal.
Nothing in those speaks directly about area.
In his Advanced Calculus of Several Variables, Edwards develops the general definition of area, beginning with the definition of the area of an interval in $\mathbb{R}^{2}$, as the product of the lengths of the component intervals, each in $\mathbb{R}^{1}$.  That is, $\Delta{x}\times{\Delta{y}}$, where $\Delta{x},\Delta{y}\in\mathbb{R}^{1}$.
Edwards then expands that definition using limits of partitions.  In short, Edwards doesn't treat the general definition of area as a trivial extension of the fundamental definition of the area of a rectangle.  In the case of Edwards, there is no direct appeal to physical measurement.  His definitions are strictly founded on abstract real numbers.
Is Penrose obligated to provide an argument similar to that of Edwards, in order to sustain his above quoted assertion?
Penrose's (proposed) proof is delightfully simple, if we accept his proposition.

One of the simplest ways to see that the Pythagorean assertion is indeed
  true in Euclidean geometry is to consider the confguration consisting of
  the given right-angled triangle subdivided into two smaller triangles by
  dropping a perpendicular from the right angle to the hypotenuse [figure reproduced below]. There are now three triangles depicted: the original one and the two into which it has now been subdivided. Clearly the area of the original triangle is the sum of the areas of the two smaller ones.
Now, it is a simple matter to see that these three triangles are all similar
  to one another. This means that they are all the same shape (though of
  different sizes), i.e. obtained from one another by a uniform expansion or
  contraction, together with a rigid motion. This follows because each of the
  three triangles possesses exactly the same angles, in some order. Each of
  the two smaller triangles has an angle in common with the largest one and
  one of the angles of each triangle is a right angle. The third angle must also
  agree because the sum of the angles in any triangle is always the same.
  Now, it is a general property of similar plane fgures that their areas are in
  proportion to the squares of their corresponding linear dimensions. For
  each triangle, we can take this linear dimension to be its longest side, i.e. its
  hypotenuse. We note that the hypotenuse of each of the smaller triangles is the same as one of the (non-hypotenuse) sides of the original triangle.  Thus, it follows at once (from the fact that the area of the original triangle
  is the sum of the areas of the other two) that the square on the hypotenuse
  on the original triangle is indeed the sum of the squares on the other two
  sides: the Pythagorean theorem!

Of course, Penrose may sidestep my challenge by noting that a right triangle is half of a rectangle.
NB: I am sending a message to Dr. Penrose informing him that I have quoted from his book.  If he objects, which I seriously doubt, I will remove the extended quote.
Comment: Already "the area of the original triangle is the sum of the areas of the two smaller ones" may require some justification before one can prepend it with "Clearly"
Comment: I think that depends on whether we consider geometry to be a science of visual spacial reasoning, or as a purely numerical discipline.
Answer: The definition of area in geometry can be done in several ways. See for instance Hilbert's "The foundations of geometry", Chapter IV. That areas of similar figures are in duplicate ratio than their sides is obvious, as the result holds for triangles and any polygon can be decomposed into triangles. Areas of non-polygonal figures can be defined by the method of exhaustion. See for instance Euclid's proof for the circle.
Notice that Penrose's proof of Pythagoras' theorem is not new: it also appears in Euclid's Elements, Prop. 31 in Book VI.
Comment: So, it appears that you agree with me that Penrose "hand-waved" the proof.  Given his acumen, I have to suspect his purpose was to induce the reader to seek a more complete understanding.
Answer: A far better postulate for area is that the area of a rectangle is proportional to its length, its breadth being held constant. From this postulate, it is easy to prove that the ratio of the areas of rectangle A and rectangle B are equal to the ratio of the product of the length and width of A, and the length and width of B.


Root of an equation given by an infinite series

Question: Consider the equation $$e^{-x} = x-1 $$.
We know that there is only one real root, $r$. How can it be shown that $$r= 1 + \sum_{n=1}^{\infty}\frac{(-n)^{n-1}e^{-n}}{n!}$$
Answer: We begin with the equation
$$e^{-x}=x-1 \tag 1$$
Now let $y=x-1$.  Then, we can write $(1)$ as
$$ye^y=e^{-1} \tag 2$$
Therefore, solution to $(2)$ in terms of Lambert W Function is given by
$$y=W\left(\frac1e\right) \tag 3$$
whereupon solving for $x$ reveals
$$x=1+W\left(\frac1e\right)$$
Using the Taylor Series for the Lambert W yields
$$\bbox[5px,border:2px solid #C0A000]{x=1+\sum_{n=1}^\infty \frac{(-n)^{n-1}e^{-n}}{n!}}$$
where the series can be found using Lagrange's Inversion Theorem.


Find limes of multivariable function

Question: How to prove that lim (x,y)->(0,0) (((x-y)^2)/(x^2y^2)),   this limes  doesn't exist. By introduction of polar coordinates I got that it is equal to 0, but using wolphram alpha I got it doens't exist. Any help would be great.
--------edit----------
so by polar coordinates I got x=r cos a; y = r sin a;
so lim becomes lim (r)->(0) (((r^2 cos^2a -2 r^2 cos a sin a + r^2 sin a)) /(r^4 cos^2 a sin^2 a))
lim (r)->(0) ((-2 cos a sin a )/(r^2 cos^2 a sin^2 a)) ... = ... inf
Comment: The limit does not exist; share your work for how you got a limit of 0, and we'd be able to help you find your mistake.
Comment: @ndhanson3 I made the edit
Answer: If you do it in polar coordinates, then, since $x=r\cos\theta$ and $y=r\sin\theta$, you have$$f(x,y)=f(r\cos\theta,r\sin\theta)=\frac{\bigl(\csc(\theta)-\sec(\theta)\bigr)^2}{r^2}.$$And you can deduce from this that, indeed, the limit at $(0,0)$ does not exist, since $\theta\mapsto\bigl(\csc(\theta)-\sec(\theta)\bigr)^2$ is unbounded. In fact, for each $r>0$ and for each $k>0$, there is some $\theta\in\Bbb R$ such that $\bigl(\csc(\theta)-\sec(\theta)\bigr)^2>kr^2$, and therefore, for such a $\theta$, $f(r\cos\theta,r\sin\theta)>k$.
So, in this case WolphramAlpha is right. It happens.
Answer: I'm introducing $$f(x,y) = \frac{(x-y)^2}{x^2y^2}$$ for your function. Remember that the limit of $f(x,y)$ as $(x,y)\to (0,0)$ exists only if for each sequence $(x_n,y_n)\to (0,0)$ the limit of $f(x_n,y_n)$ exists.
Now consider the sequence $x_n = 1/n$ and $y_n=-1/n$. Then $$f(x_n, y_n) = \frac{(\frac{2}{n})^2}{\frac{1}{n^4}} = 4n^2.$$
Since $x_n\to 0$ and $y_n \to 0$ but the limit as $n\to \infty$ of $f(x_n,y_n)$ does not exist, the limit as $(x,y)\to (0,0)$ of $f(x,y)$ can not exist as well.

Find limes of multivariable function


Show that the Wronskian of $x^{(1)},x^{(2)},x^{(3)}$ is identically zero or else never vanishes.

Question: My task is to prove that:
If $x^{(1)},x^{(2)},x^{(3)}$ are solutions of  $X'=A(t)X$ on some interval $I$, show that the Wronskian of $x^{(1)},x^{(2)},x^{(3)}$  is identically zero or else never vanishes.
After a long calculation I computed that the Wronskian is:
$e^{\int {(a_{11}+a_{22}+a_{33})dt}}$. Where $a_{11},a_{22},a_{33}$ are entries from the matrix $A$. My question is:
How from $e^{\int {(a_{11}+a_{22}+a_{33})dt}}$ the conclusion of my task follows?
I don't get it, any help is highly appreciated.
Answer: You have forgotten a mulitplicative term, that is, the term $\det\left(x^{\left(1\right)}\left(t_{0}\right),x^{\left(2\right)}\left(t_{0}\right),x^{\left(3\right)}\left(t_{0}\right)\right) $ where $t_{0}$ is the initial time given in your initial conditions. I let you check your calculus, and find your answer thanks to this last term.
Comment: Thanks @Nicolas but I dont get it, kindly enlighten me.
Comment: I got it now @Nicolas but how can that $t_0$ will help on showing what I want to show?
Comment: @JrAntalan the Wronskian is defined as the determinant of the solutions of the differential equation, which is also the determinant of the resolvant applied to the initial conditions...
If you do not see how to do, I can write a full answer.
Comment: Ok if you are fine with this term. Now the determinant of a family of vectors is non-zero if and only if these vectors are linearly independant...
Comment: Thanks again @Nicolas but how can i use it to show what i need to show?
Comment: Well, as you have observed, the exponential term never vanishs. Let us focus on the determinant term : if the initial conditions are linearly independant (as vectors in the vector space of the solutions of your linear differential equation), then for every time $t$, the Wronskian will not be zero. Instead, if the initial conditions are linearly dependant, then your Wronskian will be zero for all time $t$. The interesting thing here is that you can check the independance of your solutions by only checking the independance of the initial values.
Comment: Got it now, thanks @Nicolas


How to retrieve attachment url with Rails Active Storage with S3

Question: rails version 5.2

I have a scenario where I need to access the public URL of Rails Active Storage with Amazon S3 storage to make a zip file with Sidekiq background job.
I am having difficulty getting the actual file URL. I have tried rails_blob_url but it gives me following
http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBZUk9IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9598613be650942d1ee4382a44dad679a80d2d3b/sample.pdf

How do I access the real file URL through Sidekiq?
storage.yml
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

development:
  service: S3
  access_key_id: 'xxxxx'
  secret_access_key: 'xxxxx'
  region: 'xxxxx'
  bucket: 'xxxxx'

development.rb
  config.active_storage.service = :development

I can access fine these on web interface but not within Sidekiq
Comment: sorry why amazon ? I don't have a configuration called :amazon?
Comment: `config.active_storage.service = :amazon`
Comment: http://edgeguides.rubyonrails.org/active_storage_overview.html#what-is-active-storage-questionmark
Answer: Use ActiveStorage::Blob#service_url. For example, assuming a Post model with a single attached header_image:
@post.header_image.service_url

Update: Rails 6.1
Since Rails 6.1 ActiveStorage::Blob#service_url is deprecated in favor of ActiveStorage::Blob#url.
So, now
@post.header_image.url

is the way to go.
Sources:

Link to the corresponding PR.
Link to source.
Comment: thanks for that answer. I'm used to using paperclip, so i'm trying to get down Active Storage. implemented an S3 solution w/ Active Storage and it works great. however, this solution is saying it's a temporary URL? do you know how to get the permanent URL of the image? is that possible with Active Storage? paperclip only returned the default permanent URL so i was expecting something similar with Active Storage
Comment: This doesn't seem to create public URLs? I get `Request specific response headers cannot be used for anonymous GET requests.` from Amazon
Comment: @JamesN
https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files
Rails provides a rails blob url to redirect to the actual service
Comment: @HappyCry I have the same problem, but I can't find any docs about this. the only lead I have is https://kevinjalbert.com/rails-activestorage-configuration-for-minio/
Comment: Hey all, I had the same needs/issues as this comment chain and ended up here, so I added my final solution below for posterity https://stackoverflow.com/a/55172966/484689
Comment: This works! Hallelujah. My object has multiple attachments and this worked for me: @listing.images.first.service_url. I only need the first image, but could easily create a loop to get all pics if needed.
Comment: As explained in the docs (https://api.rubyonrails.org/classes/ActiveStorage/Blob.html#method-i-service_url) this will return only a temporarily accessible URL.
Comment: As such, you can use it if the URL is only required for a short time. However, if e.g. those URLs will be cached somewhere else and reused later, they will not work anymore. In that case, rails_blob_url is more convenient, since the URL will be a permalink
Comment: Late here but I strongly recommend denormalizing the `service_url` on a column of the object this image is for. You don't want accidental n+1 problem when you load a multitude of posts, for example.
Comment: FYI url method should be used to generate short-lived private URLs which then shouldn't be visible to users directly as documentation suggest here -> https://api.rubyonrails.org/v6.1.0/classes/ActiveStorage/Blob.html#method-i-url However, it does not specify how to get long-lived url which will redirect user to the signed url. It can be done like this -> Rails.application.routes.url_helpers.url_for(blob)
Comment: Thanks. It helped me to read an ActiveStorage S3 image with Rmagick
Answer: If you need all your files public then you must make public your uploads:
In file config/storage.yml
amazon:
  service: S3
  access_key_id: zzz
  secret_access_key: zzz
  region: zzz
  bucket: zzz
  upload:
    acl: "public-read"

In the code
attachment = ActiveStorage::Attachment.find(90)
attachment.blob.service_url # returns large URI
attachment.blob.service_url.sub(/\?.*/, '') # remove query params

It will return something like:
"https://foo.s3.amazonaws.com/bar/buz/2yoQMbt4NvY3gXb5x1YcHpRa"
It is public readable because of the config above.
Comment: I can't believe how badly documented is Rails in general
Comment: Where in the world is this documented?
Comment: https://github.com/rails/rails/blob/f33d52c95217212cbacc8d5e44b5a8e3cdc6f5b3/activestorage/lib/active_storage/service/s3_service.rb#L21
Answer: My use case was to upload images to S3 which would have public access for ALL images in the bucket so a job could pick them up later, regardless of request origin or URL expiry. This is how I did it. (Rails 5.2.2)
First, the default for new S3 bucked is to keep everything private, so to defeat that there are 2 steps.

Add a wildcard bucket policy. In AWS S3 >> your bucket >> Permissions >> Bucket Policy

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your-bucket-name/*"
        }
    ]
}

In your bucket >> Permissions >> Public Access Settings, be sure Block public and cross-account access if bucket has public policies is set to false

Now you can access anything in your S3 bucket with just the blob.key in the url. No more need for tokens with expiry.
Second, to generate that URL you can either use the solution by @Christian_Butzke: @post.header_image.service.send(:object_for, @post.header_image.key).public_url
However, know that object_for is a private method on service, and if called with public_send would give you an error. So, another alternative is to use the service_url per @George_Claghorn and just remove any params with a url&.split("?")&.first. As noted, this may fail in localhost with a host missing error.
Here is my solution or an uploadable "logo" stored on S3 and made public by default:
#/models/company.rb
has_one_attached :logo
def public_logo_url
    if self.logo&.attachment
        if Rails.env.development?
            self.logo_url = Rails.application.routes.url_helpers.rails_blob_url(self.logo, only_path: true)
        else
            self.logo_url = self.logo&.service_url&.split("?")&.first
        end
    end
    #set a default lazily
    self.logo_url ||= ActionController::Base.helpers.asset_path("default_company_icon.png")
end

Enjoy ^_^
Answer: I had a few problems getting this working. Thought I'd document them for posterity.

In rails 6.0 use @post.header_image.service_url
In rails >= 6.1 use @post.header_image.url as @GeorgeClaghorn recommends.

I got this error:
error: uninitialized constant Analyzable

It's a weird bug in rails 6.0, which is fixed by placing this in config/application.rb
config.autoloader = :classic

I then see this error:
URI::InvalidURIError (bad URI(is not URI?): nil) Active Storage service_url

Fix it by simply adding this to your application_controller.rb
include ActiveStorage::SetCurrent

Now something like @post.image.blob.service_url will work as you expect =)
Answer: Using the service_url method combined with striping the params to get a public URL was good idea, thanks @genkilabs and @Aivils_Štoss!
There is however a potential scaling issue involved if you are using this method on large number of files, eg. if you are showing a list of records that have files attached. For each call to service_url you will in your logs see something like:
DEBUG -- : [8df9220c-e8c9-45b7-a1ee-b746e623ca1b]   S3 Storage (1.4ms) Generated URL for file at key: ...

You can't eager load these calls either, so you can potentially have a large number of calls to S3 Storage to generate those URLs for each record you are showing.
I worked around it by creating a Presenter like this:
class FilePresenter < SimpleDelegator
  def initialize(obj)
    super
  end

  def public_url
    return dev_url if Rails.env.development? || Rails.env.test? || assest_host.nil?

    "#{assest_host}/#{key}"
  end

  private

  def dev_url
    Rails.application.routes.url_helpers.rails_blob_url(self, only_path: true)
  end

  def assest_host
    @assest_host ||= ENV['ASSET_HOST']
  end
end

Then I set an ENV variable ASSET_HOST with this:
https://<your_app_bucket>.s3.<your_region>.amazonaws.com

Then when I display the image or just the file link, I do this:
<%= link_to(image_tag(company.display_logo),
    FilePresenter.new(company.logo).public_url, target: "_blank", rel:"noopener") %>

<a href=<%= FilePresenter.new(my_record.file).public_url %>
   target="_blank" rel="noopener"><%= my_record.file.filename %>

Note, you still need to use display_logo for images so that it will access the variant if you are using them.
Also, this is all based on setting my AWS bucket public as per @genkilabs step #2 above, and adding the upload: acl: "public-read" setting to my 'config/storage.yml' as per @Aivils_Štoss!'s suggestion.
If anyone sees any issues or pitfalls with this approach, please let me know! This seemed to work great for me in allowing me to display a public URL but not needing to hit the S3 Storage for each record to generate that URL.
Answer: Also see public access in rails active storage. This was introduced in Rails 6.1.
Specify public: true in your app's config/storage.yml. Public services will always return a permanent URL.
Answer: Just write this if You are using minio or aws S3 to get attachment url on server.
@post.header_image&.service_url&.split("?")&.first

Answer: A bit late, but you can get the public URL also like this (assuming a Post model with a single attached header_image as in the example above):
@post.header_image.service.send(:object_for, @post.header_image.key).public_url

Update 2020-04-06

You need to make sure, that the document is saved with public ACLs (e.g. setting the default to public)
rails_blob_url is also usable. Requests will be served by rails, however, those requests will be probably quite slow, since a private URL needs to be generated on each request.
(FYI: outside the controller you can generate that URL also like this: Rails.application.routes.url_helpers.rails_blob_url(@post, only_path: true))
Comment: Hi @Christian, just tried it now, but does not seem to work(the code returns a shorter URL though): "This XML file does not appear to have any style information associated with it. The document tree is shown below." Do I have to set some configurations for the URL to work.
Comment: It's bad practice to use 'send' - the private method is a private method for a reason - so that the implementation can change "under the hood" and if the implementation changes your code won't break. This suggestion could well break when you upgrade to a new version of Rails or ActiveStorage.
Comment: @RicardoGreen This error means probably that you did not grant public access rights to the document and AWS is sending an XML containing an error message back. This will fail with the error above because XML was not expected as a response
Comment: @oskarpearson Thank you very much for your commend. Indeed, "send" is a dirty way to call private methods, which can change at any time, and should be avoided whenever possible. However, ActiveSupport did not support providing public URLs, which was required in my case, in order to share the URLs with third parties. Thus, they needed to be valid for a long time and not just a few minutes, like the URLs provided by "service_url"
Comment: commend -> comment


Does maximum likelihood minimize a kind of generalized "0-1 loss"?

Question: A very good point was raised here about how the optimal betting strategy under 0-1 loss was to bet on the mode, while under MSE loss the optimal strategy was to bet on the mean.
Maximum likelihood is, in many cases, equivalent to a posterior mode. Does the "all-or-nothing loss function" analogy extend to more general cases? Is MLE sub-optimal, in a decision-theoretic sense, for statistical inference, as compared to something like least squares?
Answer: I am not sure what you mean by "does 0-1 loss function analogy extend to more general cases?"
As you noted, depending on your loss function, you can find a different point estimate that maximizes your posterior.  For e.g., if you care about least-squares error, you would pick the posterior distribution's mean.  For absolute value loss, you pick the median.  Here is a doc that outlines proofs for all these http://www.cogsci.ucsd.edu/~ajyu/Teaching/Tutorials/bayes_dt.pdf.
However, note that the full information for decision making is contained in the distribution in the spirit of true Bayesian thinking.


Handling custom parsing and importing with Feeds

Question: I've been wading through the Feeds module and documentation, and for whatever reason have been unable to figure the best way to do this, so I'm hoping someone will be able to point me in the right direction.
I need to get video node information from one D6 site to another.  I've set up a feed via Views on the source site, and I want to use Feeds to ingest the info into the target site. There are two custom things I need to do, and I can't figure the best way to do them.

There are two taxonomy vocabularies on the source site that I need to get to specific vocabularies on the target site. One is a tags vocabulary, and one is titled Channel (same on both sites). I've added the tid for the target Channel term to the feed as <channel-map> and I need to import that value into the assigned Channel term on the target node. The problem is that the core Taxonomy module dumps all taxonomy terms, regardless of vocabulary, into the source feed as <category>; the only way to differentiate between vocabs when importing the feed item is to look at the domain attribute, which is the URL for that term. There is a Tags target in the standard feed importer, but I need to filter out the Channel terms, as well as the terms for other vocabs that only exist on the source site.
The target site has a custom video formatter that plays the embedded video from the source site when you enter the source site URL into the Video field on the target node in the format http://mysourcesite.com/node/$nid. I've added the source nid to the feed as <source-nid>, so I just need to take that value and construct the URL the source site URL is already stored in a variable on the target site as part of the custom formatter settings), and then insert it into the Video field on the new target node.

So what I'm trying to figure out is the best way to handle these instances when importing the feed.  It looks like one option is to write a custom parser and/or importer plugin.  However, I don't need to rewrite the whole parsing and importing processes; I just need to handle the two cases above. There are already targets defined for the two fields I need to import into, so would it just be a matter of using the feeds_node_processor_targets_alter() hook and override the existing node processor? Or would I need to write my own custom plugins?
Thanks.
EDIT: I tried creating my own callback as a wrapper for content_taxonomy_feeds_set_target() using hook_feeds_node_processor_targets_alter(), but by that point in the process, all that is provided is the term name with no additional information to indicate the source vocabulary.
Answer: I finally got everything to work with some code voodoo and changing parsers. One thing that I didn't add to the original question above as an edit was the fact that using the common syndication parser, my custom items that I added to the source feed were never available. I then switched to using the SimplePie parser, and was able to extend that functionality to do what I need.
According to the Feeds module documentation for developers and this blog post, you can do some custom parsing by overriding the parseExtensions() method of FeedsSimplePieParser class. First, you have to declare the class with hook_feeds_plugins():
/**
 * Implementation of hook_feeds_plugins().
 */
function mymodule_feeds_plugins() {
  $info = array();

  $info['MyModuleFeedsParser'] = array(
    'name' => 'Custom Parser',
    'description' => 'Custom parser for my video import.',
    'handler' => array(
      'parent' => 'FeedsSimplePieParser',
      'class' => 'MyModuleFeedsParser',
      'file' => 'MyModuleFeedsParser.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/plugins/feeds/',
    ),
  );
  return $info;
}

You also want to implement hook_enable to clear caches.
/**
 * Implementation of hook_enable.
 */
function mymodule_enable() {
  //clear the cache to display in Feeds as available plugin.
  cache_clear_all('plugins:feeds:plugins', 'cache');
}

Next you create the class.
/**
 * Custom Feeds parser class used to parse custom info from source site video feed.
 */

class MyModuleFeedsParser extends FeedsSimplePieParser {
  /**
   * Add the extra mapping sources provided by this parser.
   */
  public function getMappingSources() {
    return parent::getMappingSources() + array(
      'source-nid' => array(
        'name' => t('Video NID - SimplePie'),
        'description' => t('.'),
      ),
      'channel-map' => array(
        'name' => t('Channel Map - SimplePie'),
        'description' => t('Target Channel tid - SimplePie.'),
      ),
    );
  }

  /**
   * Parse the extra mapping sources provided by this parser.
   */
  protected function parseExtensions(&$item, $simplepie_item) {
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'source-nid')) {
      $item['source-nid'] = $value[0]['data'];
    }
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel-map')) {
      $item['channel-map'] = $value[0]['data'];
    }
    // Filter out non-Tags terms.
    $categories = $simplepie_item->get_categories();
    // Cycle through the categories and delete any items
    // in feed item that aren't tags. The array id values
    // are synchronized between $categories and $item['tags'].
    foreach($categories as $id => $category) {
      if (!strstr($category->scheme, '/tag/')) {
        unset($item['tags'][$id]);
      }
    }
  }
}

This code does a few things:

getMappingSources() creates a couple sources that are available for mapping. You set these in your importer settings for your processor.
Gets the source-nid value from the feed source and add it to the item.
Gets the channel-map value from the feed source and add it to the item.
Filters out the non-tags terms from the categories (aka taxonomy terms). The scheme value is the URL to the taxonomy term (e.g. mysite.com/tag/tag-term), so I use that to identify non-tag terms and unset them.

Finally, I have to create the values for the video field and the Channel vocabulary. This is done with some custom callbacks defined in hook_feeds_node_processor_targets_alter().
/**
 * Implements hook_feeds_node_processor_targets_alter().
 */
function mymodule_feeds_node_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['field_source_url'] = array(
    'name' => 'Source Video URL',
    'description' => 'The URL of the source video',
    'callback' => 'mymodule_feeds_set_source_url',
  );

  $targets['channel'] = array(
    'name' => 'Target Channel',
    'description' => 'The target video channel',
    'callback' => 'mymodule_feeds_set_channel_target',
  );
}

And the callbacks themselves:
/**
 * Custom callback to set the video source URL in field_video.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_source_url(&$node, $target, $value) {
  $source_url = variable_get('emvideo_source_domain', '') . '/node/' . $value;
  $node->field_video[0]['embed'] = $source_url;
}

/**
 * Custom callback to set the target vocabulary term.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_channel_target(&$node, $target, $value) {
  $term = taxonomy_get_term($value);
  $node->taxonomy[(int)$value] = $term;
}

You then define these as targets in your Processor mapping (to coincide with the Source values above), and you're good to go.


How to assign echo to a variable in Bash?

Question: I have simple command:
echo "foo=bar" | cut -d "=" -f1

to cut some string from some string.
How can I assign this result to some variable?
Nothing works:
(echo "foo=bar" | cut -d "=" -f1)
$test=`(echo "foo=bar" | cut -d "=" -f1)`
$test=`$(echo "foo=bar" | cut -d "=" -f1)`
$test="$(echo "foo=bar" | cut -d "=" -f1)"

Output:
foo
script.sh: 14: =foo: not found
script.sh: 1: foo: not found
script.sh: 15: =: not found
script.sh: 16: =foo: not found

Comment: Why down vote? What is wrong with my question? Downvote without any comment? :-/ what should I improve?
Comment: If you're actually trying to get the part of a variable before an "`=`", you don't need to use `echo` or `cut`, just built-in variable substitution: `var="foo=bar"; test="${var%%=*}"`. See [the bash manual on parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html), and look for the section on `${parameter%%word}`.
Comment: @vimov32802 : A downvote usuall means that you didn't have put enough of your own effort in it. From your question, it looks to me that you did not search on the Net for the problem - as you can see,this topic has been discussed already many times on [so], and even more often on other websites - but just tried out a few commands, without really knowing what you are doing.
Answer: You can use $() (command substitution):
test=$(echo "foo=bar" | cut -d "=" -f1)
echo "$test"
foo


What's involved getting domain name pointed at my dedicated server (Win2008)?

Question: I am paying for a dedicated server (2.66GHz Duo, 2GB RAM) from GoDaddy.com; it is running Windows Server 2008 Standard Edition, and I have a static IP address.
The server is being used to host a web application. I have a domain name that I need to point at it, what do I need to do?
I thought I would need to add the DNS server role to this machine, but don't really know. I know the purpose of DNS and the basics, but I am definitely a novice at networking issues, I spend more of my time developing web applications than dealing with issues like these.
If you can point me in the right direction, that's all I really need. Do I really need to setup the server as a DNS server as well or is there something else I need to do? Will running DNS on this box adversely affect the web app?
Thanks!
Answer: I would recommend setting an account up at EveryDNS. It will be much easier, and much more secure, than running your own - especially if this is a 'one off' domain you need to set up.
Also, GoDaddy gives you the choice to use their own DNS servers for hosting DNS. I don't use them (nor trust them) but that would be an option too, if it is registered via GoDaddy.
Comment: Okay, I thought it was a bit much to be dealing with it myself - thanks for the link to EveryDNS - that should be perfect, the web app I am hosting is going to have a very short lifespan, it is for an niche-industry conference that lasts 4 days, and will be used for a month or so afterwards, but that's it. Thanks!
Answer: You do not need to (and IMHO should not) set up your server as a DNS server. If you're hosting a web site or sites, email, ftp, etc. you simply need to create the appropriate DNS resource records in your DNS zone using the tools available via your registrar (or the entity that hosts your DNS records, I'm assuming it's also GoDaddy). Log in to your account, find the DNS management tool and create whatever records you need.
For instance, create an A record for your server (server.yourdomain.com) that points to your static ip address, then create CNAME records for each "service" and point them at the A record. For instance, create a CNAME record named www that points to the A record (server.yourdomain.com). If you host multiple unique web sites on the same static ip address, add CNAME records for those and then set up host headers on your web sites.
Comment: Thank you also for the information - I figured I shouldn't be running my own DNS server, seemed a bit risky to me. I really do appreciate your response!
Comment: More than happy to help.


Cluster analysis- Caring only about the number of clusters in the data not what they are?

Question: I know some analysis exists for calculating k for kmeans or kmediods but they dont seem to be rigrous enough if i only care so much about k not what are in the clusters. Is there a rigorous process/algorithm to estimate number of clusters in my data ?
Comment: Check this intruduction, too https://stats.stackexchange.com/a/358937/3277.
Answer: Yes, and it's a very well-developed field. The approach for estimating the optimal number of clusters in a data set is called "cluster validity."
See:
N. Speer, C. Spieth, and A. Zell.
Biological cluster validity indices based on the gene ontology.
Lecture Notes in Computer Science, 3646:429--439, 2005.
D. Davies and D. Bouldin.
A cluster separation measure.
IEEE Trans. on Pattern Analysis and Machine Intelligence, 1(2):224--227, 1979.
J. Dunn.
Well separated clusters and optimal fuzzy partitions.
J. Cybernetics, 4:95--104, 1974.
P. Rousseuw.
Silhouettes: A graphical aid to the interpretation and validation of
  cluster analysis.
Computational and Applied Mathematics, 20:53--65, 1987.
M. Gonzalez~Toledo.
A comparison in cluster validation techniques.
Master's thesis, University of Puerto Rico - Mayaguez Campus, 2005.
N. Bolshakova and F. Azuaje.
Cluster validation techniques for genome expression data.
Signal Process., 83(4):825--833, 2003.
Comment: Thank you so much. This will help me get started.


Different attribute selection widget in a view

Question: I have a product display that lists multiple products with various pack sizes.
I added a taxonomy field to a Product for the attribute
e.g.
T shirt 1 pack
T shirt 3 pack
I have set the product display to list the pack sizes as a radio list for selection. Easy enough, in Configure Taxonomy Field I just set the "Enable this field to function as an attribute field on Add to Cart forms." and set the attribute selection widget to Radio buttons.
I would also like to show all the product displays in a view, also easy however, I would like the add to cart form in the view to display the pack sizes as a Select list.
T Shirt > dropdown 1 & 3 pack
Trousers > dropdown 1 & 3 pack
Any suggestions how I can achieve this?
Answer: Since the field definition isn't context sensitive (i.e. it can't have one value on a standalone page and another on a View for that setting), you're going to have to do this yourself via a form alter. Just be mindful that the options array for radio buttons / select lists are treated differently with respect to sanitization when formatted for display.


Does bootstrapping help with power concerns?

Question: I am running a logistic regression, similar to the following:
<code>Pr(Y = 1) = B0 + B1*X1 + B2*X2 + B3*X3 + e
</code>
X1 is an indicator variable. I find B1 is statistically insignificant. A colleague is worried that B1 may be insignificant because I have too few observations where X1 = 1 (about 0.50% of my sample of 10,000 observations). His suggestion is to randomly draw control observations to match the number of treatment observations and rerun the regression.
Alternatively, could I address this concern by simply bootstrapping my standard errors in my original regression and sample? Is bootstrapping a valid way to address power concerns?
Comment: The formula you posted in the code block isn't a logistic regression, it's a linear regression.  Is this really what you used?
Comment: @jbowman I'm using logistic. That is just the convention of how it is written in my profession.
Answer:
His suggestion is to randomly draw control observations to match the
  number of treatment observations and rerun the regression.

This is not bootstrap, but oversampling. With bootstrap, you would be sampling from your data randomly with replacement, $n$ cases out of sample of size $n$. So, with bootstrap, you would end up with same sample size and approximately similar distribution to your initial data, so bootstrap would not cure anything about insufficient sample size.
When confronted with unbalanced data (see also other questions tagged as unbalanced-classes), oversampling (randomly sampling more observations from the minority class and appending them to the dataset) is one of the possible approaches. People use it, but the fundamental problem is that by oversampling the minority class you don't really get more data, since you are just looking at the same data multiple times. This means that you could easily overfit to the available data. So even if you could use it to virtually adjust the sample size, this does not solve your problem.
Comment: One way to see it is that oversampling the minority class creates dependent observations, which invalidates p-values.
Answer: So just from what you have told me, a quick back of the envelope calculation shows your minimum detectable effect of 0.79.  According to Cohen's 1988 paper, that is fairly large.  If you think the effect of the covariate (on the log odds scale) is quite small, you may not have enough power to detect it.
My suggestion is not to bootstrap your regression.  Instead, hypothesize the size of the effect and do some simulations to see if your sample size and prevalence of exposure lead to acceptable power.
Also, what are the confidence intervals like?  Are the really narrow or really wide?


Deregister all styles and scripts from a certain Wordpress plugin

Question: i want to wp_deregister all styles and scripts from a certain plugin.
For example
$plugin = getAllStyles('PLUGIN-NAME');
foreach ($plugin as $value) {
    wp_deregister_style($value);
}

$plugin = getAllScripts('PLUGIN-NAME');
foreach ($plugin as $value) {
    wp_deregister_script($value);
}

Is this possible?
Answer: Yes it's possible with MU-PLUGINs, that looks into request url and selectively disable plugins. That is possible because MU plugins are loaded before regular plugins.
1) Create new Mu-plugin in /wp-content/mu-plugins/Removeplugin.php
2) Add this Code
/*
    Plugin Name: plugins remover
    Plugin URI:
    Description:  Removes  plugin
    Author: Author name
    Version: 1.0
    Author URI:
*/

3) Now add action hook option_active_plugins
add_filter( 'option_active_plugins', 'disable_plugin_callback_fun' );
function disable_plugin_callback_fun($plugins){
     $key = array_search( 'plugin_directory_name/plugin_filename.php' , $plugins );
     if ( false !== $key ) unset( $plugins[$key] );
}

Example if you remove the contact form 7 plugin css and js
add_filter( 'option_active_plugins', 'disable_plugin_callback_fun' );
    function disable_plugin_callback_fun($plugins){
        $key = array_search(  'contact-form-7/wp-contact-form-7.php', $plugins );
    if ( false !== $key ) { unset( $plugins[$key] );}

}

NOTE: This action hook disable the plugin for site,So  i suggest  to Load  plugin from selected page like bellow code Check the current page.
$current_page = add_query_arg( array() );
add_filter( 'option_active_plugins', 'disable_plugin_callback_fun' );
        function disable_plugin_callback_fun($plugins){
         $current_page = add_query_arg( array() );
         if($current_page!='contact'){//contact us page url where to load plugin only
         $key = array_search(  'contact-form-7/wp-contact-form-7.php', $plugins );
        if ( false !== $key ) { unset( $plugins[$key] );}
        }
    }

For more information check this https://wordpress.stackexchange.com/questions/114345/load-plugin-selectively-for-pages-or-posts-etc

EDIT

If you need remove  only all style and script from plugin. need to find all css and jquery and put it one by one in bellow function.
No other way to remove all the style and script from plugin
NOTE : It's only work when plugin used to add style or js useing wp_enqueue_style() and wp_enqueue_script( ) other wise this code is not working
add_action('wp_print_scripts', 'disable_pluginsjs_selectively', 100 );
function disable_pluginsjs_selectively( ) {
   wp_deregister_script( Name of the enqueued jQuery);
   wp_dequeue_style('Name of the enqueued stylesheet');
}

Comment: But code will disable the plugin completely (on special pages). I only want to remove all styles and scripts from the plugin, not the plugin himself.


trying to do a query session for Parse

Question: using the gem parse-ruby-client and im trying to do a query session, here is my code.
im just curious on how to implement most of the https://parse.com/docs/rest/guide. Also i dont know if i created a session to begin with? i think the gem does it automatically? not too sure
class LoginController < ApplicationController
  def index

  end
  def log_in
    user = Parse::User.authenticate(params[:user][:username], params[:user][:password])
        @username = params[:user][:username]
        rescue Parse::ParseProtocolError
            redirect_to :controller => "login"
end
    def logout
                Parse.client.post("https://api.parse.com/1/logout", {})
                rescue Parse::ParseProtocolError
                redirect_to :controller => "login"
            end
    def query_session
                Parse.client.post("https://api.parse.com/1/users/", {})
    end
end

here is log_in.html.erb

You are logged in as:  <%= @username %>

<%= link_to "logout", :controller => "login", :action => 'logout' %>

<%= link_to "test", :controller => "login", :action => 'query_session' %>

routes.rb
Rails.application.routes.draw do
  root 'login#index'

  get 'login/log_in' => 'login#log_in'
  post 'login/log_in' => 'login#log_in'

  get 'login/logout'

  get 'login/query_session' => 'login#query_session'
end

this is my parse.rb
require 'parse-ruby-client'

Parselogin::Application.configure do
config.parse = Parse.init :application_id => 'APIKEY',
                         :api_key        => 'APIKEY'
                       end

i get back this error when i click on 'test' button from the log_in.html.erb
201: missing user password

Answer: You are missing the initialization of the Parse.client. This is an example from the gem's official documentation.
require 'parse-ruby-client'

client = Parse.create :application_id => '<your_app_id>',
                      :api_key        => '<your_api_key>',
                      :quiet          => true | false

To use the client later on, do the actions like this.
client.post("https://api.parse.com/1/logout", {}), where client is the variable from 1st snippet.
In order to respond to the second part of your question, please consider the gem's documentation.
Comment: In that case, you are misusing it. Use the variable to which you assign the result of Parse.create to later communicate with the parse API.
Comment: also i dont know if you noticed but this is what im using: https://github.com/adelevie/parse-ruby-client/tree/v0.3.0#configuration

trying to do a query session for Parse


How to solve $\int_0^\pi{\frac{\cos{nx}}{5 + 4\cos{x}}}dx$?

Question: How can I solve the following integral?
$$\int_0^\pi{\frac{\cos{nx}}{5 + 4\cos{x}}}dx, n \in \mathbb{N}$$
Comment: Use the formula $$\cos{nx}=2\cos{x}\cos{(n-1)x}-\cos{(n-2)x}$$.

By singing $I_n=\int_0^\pi{\frac{\cos{nx}}{5 + 4\cos{x}}}dx$ try to find recursive formula for $I_n$.
Answer: Here is a solution without residue calculus:
Via partial fractions and geometric series one arrives at
$$\eqalign{{1\over 5+4\cos x}&={1\over(2+e^{ix})(2+e^{-ix})}=\ldots\cr &={1\over 3}-{1\over3}{e^{ix}/2\over 1+e^{ix}/2}-{1\over3}{e^{-ix}/2\over 1+e^{-ix}/2}\cr &= {1\over3}+{1\over3}\sum_{k=1}^\infty(-1)^k{e^{ikx}\over 2^k} +{1\over3}\sum_{k=1}^\infty(-1)^k{e^{-ikx}\over 2^k}\cr &={1\over3}+{2\over3}\sum_{k=1}^\infty(-1)^k{\cos(k x)\over 2^k}\ .\cr}$$
Therefore
$$\int_0^\pi{\cos(n x)\over 5+4\cos x}\ dx={2(-1)^k\over3\cdot 2^n}{1\over2}\int_{-\pi}^\pi \cos^2(nx) dx={(-1)^n\over 3\cdot 2^n}\pi\qquad(n\geq0)\ .$$
Comment: A nice answer using the orthogonality of $\{\cos(nx)\}$
Comment: @juantheron: It's the orthogonality relations: $\int_{-\pi}^\pi \cos(mx)\cos(nx)\>dx=0$ when $m\ne n$.
Comment: your answer is very useful but i couldnot get how can one reduce it in partial fraction form.Can you please throw some insight on it.
Comment: @navinstudent: Write $e^{ix}=z$, $e^{-ix}=1/z$, and go through the motions.
Comment: @Christian Blaster would you like to explain how you get $\cos^2(nx),$ in last line and how all other terms are vanished.Thanks
Answer: To elaborate on Pantelis Damianou's answer
$$
\newcommand{\cis}{\operatorname{cis}}
\begin{align}
\int_0^\pi\frac{\cos(nx)}{5+4\cos(x)}\mathrm{d}x
&=\frac12\int_{-\pi}^\pi\frac{\cos(nx)}{5+4\cos(x)}\mathrm{d}x\\
&=\frac12\int_{-\pi}^\pi\frac{\cis(nx)}{5+2(\cis(x)+\cis(-x))}\mathrm{d}x\\
&=\frac12\int_{-\pi}^\pi\frac{\cis(x)\cis(nx)}{2\cis^2(x)+5\cis(x)+2}\mathrm{d}x\\
&=\frac{1}{2i}\int_{-\pi}^\pi\frac{\cis(nx)}{2\cis^2(x)+5\cis(x)+2}\mathrm{d}\cis(x)\\
&=\frac{1}{2i}\oint\frac{z^n}{2z^2+5z+2}\mathrm{d}z
\end{align}
$$
where the integral is counterclockwise around the unit circle and $\cis(x)=e^{ix}$.
Factor $2z^2+5z+2$ and use partial fractions. However, I only get a singularity at $z=-\frac12$ (and one at $z=-2$, but that is outside the unit circle, so of no consequence).
Now that a complete solution has been posted, I will finish this using residues:
$$
\begin{align}
\frac{1}{2i}\oint\frac{z^n}{2z^2+5z+2}\mathrm{d}z
&=\frac{1}{6i}\oint\left(\frac{2}{2z+1}-\frac{1}{z+2}\right)\,z^n\,\mathrm{d}z\\
&=\frac{1}{6i}\oint\frac{z^n}{z+1/2}\mathrm{d}z\\
&=\frac{\pi}{3}\left(-\frac12\right)^n
\end{align}
$$
Comment: @xcn: since $5+4\cos(x)$ is even, adding $i\sin(nx)$ to the numerator adds $0$ to the whole integral. That is, $$ \frac12\int_{-\pi}^\pi\frac{\cos(nx)}{5+4\cos(x)}\mathrm{d}x=\frac12\int_{-\pi}^\pi\frac{\cos(nx)+i\sin(nx)}{5+4\cos(x)}\mathrm{d}x $$
Comment: Didn't you forget to write $\cos(nx)$ in the same way as in the denominator? Then you get singularity at 0.
Answer: Of course it can be solved easily with complex residues. Since $\cos x$  is even you replace it with 1/2 the integral from $0$ to $ 2 \pi$. Then you make the substitution $z=e^{i\theta}$. You end-up with an integral over the unit circle.  You end-up with a function which has singularities only at $0$ and $-\frac{1}{2}$. Then find the residues.
Comment: Could you please elaborate a little on this solution?
Answer: $2 I(n+1) + 5I(n) + 2I(n-1) = 0$
d'ou $I(n) = (-1/2)^n . I(0) = (-1/2)^n . \pi/3$
fjaclot
Comment: J'adore cette solution!
Answer: Evaluating some $n$ ($n=5$), points at something like $\displaystyle \frac{(-1)^n \pi}{6\cdot 2^{n-1}}$...(tbc)
Comment: Good guess! :-)


How can we autocreate an organic group during registration

Question: How can I do this using the rules module?:
User registers (as profile type a) -> create organic group using field value from registration and make the user the manager/admin of the group
I have also the modules Profile 2 and Profile2 Registration Path.
Answer: Creating a group is really just creating a node.
Create a rule that reacts on "After saving a new user account".
Add Action: Create a new entity.
Set content type to: Group.
You can set the title of the node (the name of the group) to the new user's name or any value you want using available tokens.
Set the author of the node to the new user (it's usually called "account" in rules) and the new user will be the owner/manager of the group.


Compute the flow $\Phi_t$ of $\mathbb{X}(x,y)=(y,x)$

Question: Let $\mathbb{X}$ be the vector field on $\mathbb{R}^2$ given by  $$ \mathbb{X}(x,y) = (y,x). $$ Compute the flow $\Phi_t$ of
$\mathbb{X}$
I was reading through an answer on math.stackexchange entitled "Finding the flow of a pushforward of vector field" and the first part of his problem was this question.
The solution he gave was $\Phi_t(x,y)=(\frac{x+y}{2}e^t+\frac{y-x}{2}e^{-t},\frac{x+y}{2}e^t +\frac{x-y}{2}e^{-t})$
My understanding is that to calculate the flow, you consider: $\Phi_t(x,y)=(\dot{x},\dot{y})=(y,x)$ and try to solve.
Why cant the flow be $\Phi(x,y)=((y-x)e^{-t},(x-y)e^{-t})$?
It is probably a problem with definitions, but any help would be greatly appreciated.
Answer: No, it is not a problem with definition.
Hint. The flow of the linear vector field $Az$ is given by its matrix exponent $e^{tA}z$. In your case
$$
A=\begin{bmatrix}
0&1\\
1&0
\end{bmatrix}
$$
and $z=(x,y)^\top$. Hence you need to calculate
$$
e^{tA}
$$
and see the result.
Addition.
There are different methods to calculate $e^{tA}$, but here I can use simply the defintion
$$
e^{tA}=I+tA+\frac{t^2}{2!}A^2+\ldots
$$
Simply by noting that $A^2=I$ I find
$$
e^{tA}=\begin{bmatrix}
1+\frac{t^2}{2!}+\frac{t^4}{4!}+\ldots& t+\frac{t^3}{3!}+\ldots\\
t+\frac{t^3}{3!}+\ldots&1+\frac{t^2}{2!}+\frac{t^4}{4!}+\ldots
\end{bmatrix}=\begin{bmatrix}
\cosh t&\sinh t\\
\sinh t&\cosh t
\end{bmatrix},
$$
where, as usual,
$$
\cosh t=\frac{e^t+e^{-t}}{2},\quad \sinh t=\frac{e^t-e^{-t}}{2}.
$$
Now you can see you flow by multiplying $e^{tA}$ by the vector of initial conditions.
Comment: @Dansmith I am not sure that I can give you an ultimate reference. The flows of linear constant coefficients vector fields are linear transformation groups defined simply by $e^{tA}$. There is not much to learn here. Try Arnold's ODE, if you can get through his deceivably easy-to-understand writings, you will learn the general theory of flows, transformation groups, and vector fieleds.
Comment: Did you hear about the matrix exponent?
Comment: See the addition. If you cannot get through it, you should start with the book I advised you.
Comment: yes I remember reading that, thanks for the help, will give it another go
Comment: Another hint to see where you are a little confused: not every solution to the system of ODE will give you the flow. Only those, where you can simply replace two arbitrary constants with two initial conditions.
Comment: thanks, can you reference a good source on linear vector fields that would explain all of this, cant seem to find any.
Comment: I have run into a wall and cannot get close to the solution, using $z(t)=e^{At}z_0$, I get $z(t)=e^t(y_0,x_0)^\top$, what is the best way to proceed? Dont see how I can reach the solution.
Comment: Yes I understand how that works, is the solution given in my question what I am trying to derive, I can't even get close
Comment: Just figured it out as you posted solution, thank you so much for all your help
Answer: Another way to see this result without needing to use the exponential map is the following:
For $Y = x\frac{\partial}{\partial y} + y\frac{\partial}{ \partial x}$ we obtain the differential equations $x'(t) = y$ and $y'(t) = x$. We note that differentiating either of the equations gives us that $y''(t)=y(t)$ and similarly for $x(t)$. We know that the general solution to each of these equations is $y(t)= d_1e^t +d_2e^{-t}$ and $x(t) = c_1e^t +c_2e^{-t}$. Now our global flow must satisfy $x(0)=y$ and $y(0)=x$, and thus we impose the conditions that $c_1 +c_2 =y$ and $d_1+d_2 =x$. Now given that $x'(t) = y(t)$ we have the following relationship between coefficients: $c_1=d_1$ and $c_2 =-d_2$. Plugging these in to the system of equations above and solving for $c_1$ and $c_2$ we obtain that $c_1 = \frac{x+y}{2}$, and $c_2 = \frac{y-x}{2}$. Thus our flow becomes $\theta_t(x, y) = (\frac{x+y}{2}e^t + \frac{y-x}{2}e^{-t}, \frac{x+y}{2}e^t-\frac{y-x}{2}e^{-t})$.


How to calculate expected value and standard deviation if I have 100 values divided into 15 groups (normal distribution)?

Question: These are the values:
18.2    17.6
------------------------------------------------------------------------------------------------------------
18.9    18.6
------------------------------------------------------------------------------------------------------------
20  19.7    19.8    19.6
------------------------------------------------------------------------------------------------------------
21.4    20.6    21
------------------------------------------------------------------------------------------------------------
21.9    22.1    22.2    22.2    21.6
------------------------------------------------------------------------------------------------------------
23.1    22.6    23.2    23  22.9    23.2    23.2    23  22.5    22.5
------------------------------------------------------------------------------------------------------------
23.8    24.1    23.8    23.6    24.3    23.7    24  24.2    24.4    23.8    23.5
------------------------------------------------------------------------------------------------------------
24.7    24.9    25  25.4    25.1    25.3    25.3    25.2    25.2    24.7    24.6    24.5    24.5
------------------------------------------------------------------------------------------------------------
25.6    26  25.6    25.6    25.6    25.7    25.6    26.3    26.3    26.2    26  25.9    26.2    26
------------------------------------------------------------------------------------------------------------
27  27.2    27  27.2    26.7    27  26.6    27.3    26.8    26.6    26.9    27  26.5
------------------------------------------------------------------------------------------------------------
28.2    27.7    28.1    27.9    27.6    27.7    28.1    28.2    27.5
------------------------------------------------------------------------------------------------------------
28.6    29.1    28.7    29.1
------------------------------------------------------------------------------------------------------------
30.3    29.6    29.7    29.5
------------------------------------------------------------------------------------------------------------
30.9    31  31  30.5
------------------------------------------------------------------------------------------------------------
32.3    31.6
------------------------------------------------------------------------------------------------------------

These are the groups:
 - 17.5 -   18.5
 - 18.5 -   19.5
 - 19.5 -   20.5
 - 20.5 -   21.5
 - 21.5 -   22.5
 - 22.5 -   23.5
 - 23.5 -   24.5
 - 24.5 -   25.5
 - 25.5 -   26.5
 - 26.5 -   27.5
 - 27.5 -   28.5
 - 28.5 -   29.5
 - 29.5 -   30.5
 - 30.5 -   31.5
 - 31.5 -   32.5

I'm supposed to calculate the standard deviation and the expected value ...
How is it different comparing to having only 15 values and not divided them into groups?
If I only have 15 values, I know how to calculate the stand.deviation and the exp.value.
I use the formulas that are well-known:
Exp.value: ............(1/n)*Sum(xi)..................where xi = all the 15 values

Stand.deviation: ...(1/(n-1))*Sum( xi - u)^2...where xi = all the 15 values and u =  exp.value

Comment: is this homework? What is the rationale behind the grouping? What is the application / context?
Comment: (1) Note that the "Stand.deviation" formula actually is for an *estimator* of a *variance* and that both formulas incorrectly refer to 15 values, whereas 100 values are in this dataset.  (The use of "exp.value" in place of "mean" suggests these data should be treated as a *population,* whence the `n-1` probably should be replaced by `n`.) (2) You ask about the difference between treating these data as 100 values and 15 values.  Why don't you just compute the formulas you think should apply and compare what you get?
Comment: My guess is that they are referring to grouped means and grouped standard deviations. A question like that came up once recently either here or on the mathematics site. The grouped mean is obtained by taking a weighted average of the midpoint of the bin where the weight is the number of cases falling in the bin. The same goes for the variance except the square differences are taken by square the difference of the midpoint of the bin with the weighted mean obtained previously as the grouped mean.  I don't see where the normal distribution assumption comes into play.
Comment: If you have the actual values, why not ignore the categories and just calculate the mean and standard deviation?  Using categories makes the calculation less precise.  Or is this a homework exercise to help you understand that?
Comment: @whuber my source was math.stackexchange.com/questions/148629/calculating-expected-value-standard-deviation-when-i-have-frequencies-and-intervals-in-percentage or math.stackexchange.com/questions/148629 for short
Comment: I have no idea what do they mean by that... Presumably, the exp.value is gonna be calculated the same as in the case of 15 values. However, the stand.deviation should probably be calculated for each group separately and then getting the stand.deviation by using those stand.deviation of each group. [The resuls are:  exp.value: 25.37 and stand.deviation: 3.103]
Comment: You're probably thinking of http://stats.stackexchange.com/questions/18797/, @Michael.  A related question is http://stats.stackexchange.com/questions/10433/.
Comment: @whuber Those are both appropriate references but not the question I saw.  I will look for my reference.
Comment: @JoelW That seems like the right thing to do but the question was phrased in a way to make me think he was looking for something else based on the reference he was reading.  He could do it either way with his data but your suggestion would gie a mor accurate answer.
Comment: I think I finally understood the difference the grouping makes. The expected value is not calculated as an arithmetic mean of the values but I have to find the midpoint of each group and then the weighted average of all the midpoints will give me the expected value. However, the calculation of the stand.deviation is no different...
Answer: The statement is confusing, but I guess:
Given the 100 sample values, you know the common way (not unique) to estimate the mean and standard deviation:
$$ \bar{x}= \frac{1}{100} \sum_{i=1}^{100} x_i=25.175
, \hspace{2cm} \hat{\sigma} = \sqrt{\frac{1}{99} \sum_{i=1}^{100} (x_i - \bar{x})^2 } = 3.47529
$$
But suppose, instead, that you have grouped your data (for example, to compute an histogram) assuming intervals centered at representative points $(18,19,20 \cdots 31, 32)$
That means that, for example, the data point $x_i=29.6 $ will be counted as belonging to the interval $(28.5,29.5)$ (representative value=29), and that's the only information you retain.
Then, the "new" (approximate) mean and variance will be computed only counting how many values fall in each group, which is equivalent to compute the above but assuming that each value is replaced by the representative value (the center of each interval).
$$ \bar{x}= \frac{1}{100} \sum_{i=1}^{100} y_i= \frac{1}{100} \sum_{g=1}^{15} n_g \, y_g
= 25.37
$$
$$ \hat{\sigma} = \sqrt{\frac{1}{99} \sum_{g=1}^{15} n_g (y_g - \bar{x})^2 } = 3.1031
$$
Here, $n_g$ is the number of values that fall in each interval, and $y_g$ is the central point of that interval.
Of course, this is less precise, because you are loosing information - it would hardly make sense to compute this instead of the former, but I guess this is an exercise to understand the difference.


How to allow routing to get url localhost:4200/overview? Partid=number

Question: problem
How to change routing to get this URL localhost:4200/overview? Partid=number ?
number here any dynamic number as 5 etc .
I need when write on URL of my angular app
localhost:4200/overview? Partid=number ?
then it will go to overview component and it will change in URL as
localhost:4200/overview? Partid=number ?
so How to change routing to get this is URL specified
app-routing.module.ts

import { QualificationsComponent } from './Pages/qualifications/qualifications.component';
import { FamilyComponent } from './Pages/family/family.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OverviewComponent } from './Pages/overview/overview.component';
import { ManufacturingComponent } from './Pages/manufacturing/manufacturing.component';
import { PackageComponent } from './Pages/package/package.component';
import { ParametricComponent } from './Pages/parametric/parametric.component';

const routes: Routes = [
  { path: '', component: OverviewComponent },
  { path: 'overview', component: OverviewComponent },
  { path: 'family', component: FamilyComponent },
  {path:'manufacturing',component:ManufacturingComponent},
  {path:'package',component:PackageComponent},
  {path:'parametric',component:ParametricComponent},
  {path:'qualifications',component:QualificationsComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

overview component

import { CompanyService } from './../../service/company.service';
import { Component, OnInit } from '@angular/core';
import { PartDetailsService } from 'src/app/service/part-details.service';

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.css']
})
export class OverviewComponent implements OnInit {

  public companyProfile;
  constructor(public partDetailsService: PartDetailsService
    ,         public companyService: CompanyService) {

   }

  ngOnInit() {
     //How to catch or rcognize Partid=10 here on component overview
  }

Answer: In app-routing.module.ts
{ path: 'overview/:Partid', component: OverviewComponent },

In Component.ts
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
////
constructor(public partDetailsService: PartDetailsService
    ,         public companyService: CompanyService, public route: ActivatedRoute)
////
this.route.params.subscribe((params: ParamMap) => {
                const Partid = Convert.StringToInt(params['Partid']);
});

Comment: thank you for reply convert not defined give me compile error me cannot find name convert
Comment: You can try 'parseInt(params['Partid'])' instead of Convert.StringToInt(params['Partid'])