For each pair of points in an open connected set, is there a connected open precompact subset that contains both points?

Question: Let $U$ be an open connected subset of $\mathbb{R}^n$, and let $x,y \in U$. Does there exist a connected open and precompact subset $V$ of $U$ such that $x,y \in V$?
My thoughts so far: If $U$ is path connected then there exists a path $\phi:[0,1] \to \mathbb{R}^n$ from $x$ to $y$. Then we could take $V$ to be a "tube" around $\phi([0,1])$ that is sufficiently "narrow" that it's contained in $U$. The problem, as I have just discovered, is that $U$ being connected does not that $U$ is path-connected, so this idea doesn't work...Without asumming path-connectedness I'm pretty stumped. Any suggestions would be appreciated.
Answer: Take a path $p:[0, 1]\to U$ such that $p(0) = x$ and $p(1) = y$. This is possible since open connected subset of $\mathbb{R}^n$ is path-connected. To see this, for example, $\mathbb{R}^n$ is locally path-connected, hence $U$ has open path-connected components (a space is locally path-connected iff every open subset has open path-components), this of course means it has to be path-connected itself.
Note that $r = d(\text{im}(p), U^c) > 0$ (without loss of generality assume $U^c$ is non-empty) since $\text{im}(p)$ is compact.
Let $V = B(\text{im}(p), r/2) = \{x\in\mathbb{R}^n : d(\text{im}(p), x) < r/2\}$. Then $V\subseteq U$ is open, connected and precompact, with $\overline{V}\subseteq U$.
Comment: @Leonidas Its a union of sets $\text{img}(p)\cup B(x, r/2)$ for $x\in\text{img}(p)$ which are connected, and have non-empty intersection (since it contains $\text{im}(p)$). Union of connected sets with non-empty intersection is connected
Comment: @Thanks a lot for your answer! I did not know that open connected subsets of $\mathbb{R}^n$ are path connected, so that's good to know. One question: What's the easiest way of seeing that your choice of $V$ is connected?


MongoDB change streams

Question: I've started dealing with MongoDB change streams and have set up some streams to watch for changes on around 30 databases. I need to watch only two collections and I was wondering if I can write some pipe or filter to watch collections with the name or part of the name provided.
For example I get the collection name from the namespaceDocument of ChangeStreamDocument, and I wanna watch collections that are equal to "players" for example, on all of the databases.I'm watching the whole server for changes, but now i get notification for every collection that is changed and I don't want that, only specific collections.
<code> final ChangeStreamPublisher<Document> publisher = client.watch(Arrays.asList(
            Aggregates.match(
                    Filters.in("operationType", Arrays.asList("insert", "update", "delete"))
            ))).fullDocument(FullDocument.UPDATE_LOOKUP);
</code>
I was thinking if I could put some filter there to make the stream watch only collections with corresponding names.
Documentatin: https://docs.mongodb.com/manual/changeStreams/
Answer: According to the Documentation, you can set watch on a deployment, database or collection. So, perhaps you can set watch on collections named 'players'. The other alternative would be to set additional filters in Aggregates.Match. Each changestream event returns a namespace object called 'ns', which has the database and collection name participating in the change.

MongoDB change streams


Exposed filter for file field

Question: I have a content type with several file fields. I have a view listing nodes of that content type. Now I want to add an exposed filters for each file field to let users filter only those nodes which have a file attached to corresponding field (or not have, whatever they choose).
So, I see choice options like this:

Any
Has file attached
No file attached

Is there a module for this? Or my only way is to write a custom Views filter?
Answer: Answering to myself :]
Add a new filter for, say, field_file:fid, make it exposed and choose Is not empty operator.
It will not work :D It is a known Views issue. Luckily, comment #70 in that issue has a patch to fix this operator behavior, apply it and enjoy :)
Comment: Patch works, but you get a strict warning.  :-P  Better than nothing.
Answer: I was able to work around it using Grouped filters.
I added Content File:fid filter and exposed it.
Then I selected Grouped filters option (instead of the Single filter).
In the table that appears where you can set your options, the first one is Any (default), in the second one I added
Label YES
Operator Is greater than
Value 0

and I removed the third table row as I didn't need it.
This filter works! It shows the filter with 2 options: Any and YES. Any is default and shows all results. If I select YES it only shows results that have a file attached :)
I also added Content: file among Fields so it's easy to test the filter.
Answer: My approach for this was based on experimentation on previous answer by prkos
My case included a image field with images uploaded to my site.
So the file-path output for the field was - http://example.com/sites/default/files/001.png
In the views exposed filter, I have used File: Path (grouped) after adding relationship for file.
Now for the grouped options
- Any -
Yes | Operator: Length is greater than | Value: 0
No  | Operator: is empty (Null)        | Value: NULL

This works for me. This gives me a filter for whether an image field is empty or not.

Exposed filter for file field


Show the motion of a particle occurs along a quadric surface

Question: Given the formula $g(t)=(t \sin \theta,t\cos \theta, \sqrt{3}t),$ $0\leq t\leq4\pi$, how can I show this motion to be along a quadric surface?
Comment: The reason I didn't understand this was because my prof never covered this, some more digging gave me that $g(t)$ translated to $x^2+y^2-\frac{z^2}{3}=0$ which is an elliptic cone. For anyone asking the same question.
Answer: Your particle is travelling on an "elliptic cone". To see this, note that for any point (note that we lose $t$ dependence in our computation)
$$
(x,y,z)=(t\sin \theta,t\cos \theta,\sqrt{3}t)
$$
defined by your parametric curve, you have
$$
3x^2+3y^2-z^2=0\implies z^2=3(x^2+y^2)
$$
Comment: @HorribleATMath no problem!


Multiplying column values in datagridview

Question: I am currently making a payroll system and I am trying to make calculations between columns. I am trying to multiply a constant value to the values in a column named PayRate
I currently have two forms. the first form is where I tick off all necessary deductions and earnings. when this is accomplished, a button will be clicked and a second form containing the datagridview with the employee details and pay rate will be shown.
here is my code:
    Private Sub btnPayroll_Click(sender As Object, e As EventArgs) Handles btnPayroll.Click
    myConnection.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;   Data Source = C:\Users\MatMat\Documents\PBIPayrollMgmt1.accdb;"
    myConnection.Open()

    datagridshow()

    Me.Hide()
    viewPayroll.Show()

    If CheckBox1.Checked Then
        Try
            Dim icell As Double
            Dim totalpay As Double

            icell = viewPayroll.DataGridView1.CurrentRow.Cells(5).Value

            totalpay = icell * 11.0

            viewPayroll.DataGridView1.CurrentRow.Cells(5).Value = totalpay

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End If

End Sub

what it does what i need to but it only multiplies the value in the first row. How do I apply it to all rows? Is there such a thing as "CurrentColumn"?
Picture below for reference:
2nd Form
Comment: You need to learn about loops, which are one the most fundamental building blocks in any programming language.
Answer:
but it only multiplies the value in the first row

Naturally. You are doing the calculations to only the CurrentRow:
Instead, you need to loop through all the rows in the DatagridView and apply the calculations, like so:
For Each rowX As DataGridViewRow In dgv.Rows
    rowX.Cells(5).Value = rowX.Cells(5).Value * 11.0m;
Next

Also, you gonna need to place your loop in a more appropriate handler, such as DataGridView.DataBindingComplete event.
Comment: @BozhidarStoyneff Ran my mouth before my mind. Sorry. I already figured it out. For others who need help, "dgv.Rows" wherein dgv is the namin of your datagridview and rowX.Cells[5] returns an error. it should be rowX.Cells(5). Thanks so much Bozhidar! God Speed!
Comment: That is C# code. Question was in VB with no C# tag.
Comment: Thanks for the idea sir! Although this seems to be in C#, the idea of the loop is actually a stepping stone already. I will study this then. Thank you so much!
Comment: How do I change the "currentRow" selection for each loop iteration? i mean a formula perhaps? I tried using for but it doesn't move to the next row. Only the first row is being multiplied.
Comment: @jmcilhinney: Opps. That's my bad. I've changed it to VB.NET already. Thanks for the hint.
Comment: @matmatpancakes: You change the selection by setting the `DataGridViewRow.Selected` property. But you don't need to in that particular case. Just apply the calculation to a cell's value within the `rowX` and that's it.
Comment: @BozhidarStoyneff i am sorry i didn't quite understand the code. Specifically "dgv.Rows" and "rowX" This is the first time i have seen these syntaxes.


determine constant for biweight (bisquare) function

Question: In robust statistics a  biweight (bisquare) function is defined as follows
$$\rho \left( x \right) = \gamma\left( {1 - {{\left( {1 - {{\left( {\frac{x}{c}} \right)}^2}} \right)}^3}} \right){{\bf{1}}_{\left| x \right| \le c}} + \gamma{{\bf{1}}_{\left| x \right| > c}}$$
For an n-dimensional random variable the constant $\gamma$ can be determined using the consistency equation and c is given by the quantile of ${\chi}^2_{1-\alpha,n}$ $$ E\left[ {\rho \left( \|X \|_2\right)} \right] = n$$
If $X$ is standard n-dimensional multivariate random variable then we need to solve the following to get the value of $\gamma$
$$\int ... \int_{\textbf{R}^n}
      {\rho \left( {\sqrt {{z^ \top }z} } \right)} {\frac{1}{{{{\left( {2\pi } \right)}^{n/2}}}}\exp \left\{ { - \frac{1}{2}{z^ \top }z} \right\}}\,dz_n\,dz_{n-1}\,...dz_1 = n$$
This integral can be solved numerically for low dimensions or by simulation by simulating variables from a standard multivariate normal distribution, calculating the average loss using the bisquare function and setting up an optimization problem to minimize the absolute difference between the average loss and dimension n.
However, I am also interested in evaluating the integral analytically or atleast make the integral more tractable to solve. The idea I have is that, the sum of squares of normal random variables has a chi-square distribution. Hence a transformation such as, $k = {z^ \top }z$, where k is chi-square random variable can collapse the integral to a univariate integral. Can someone point an example on how to convert a multidimensional integral to univariate integral or point out what the integrator and limits of the new integrator in the transformed space should be.
Comment: https://books.google.com/books?id=ce5yKCu8HRoC&pg=PA19&lpg=PA19&dq=%22biweight+objective+function%22&source=bl&ots=-YQXnjLbwr&sig=r8zPCldUSBRlb32NB6Lt-0b0rFU&hl=en&sa=X&ved=0CCoQ6AEwA2oVChMIwp6X7K6pxwIVwyqICh35KQHi#v=onepage&q=%22biweight%20objective%20function%22&f=false. The real issue is solving the integral and getting a transformation.
Comment: The use of spherical coordinates will immediately reduce this to a problem involving the second, fourth, and sixth moments of a $\chi^2$ distribution. Equivalently, it can be expressed in terms of the first three moments of a Gamma distribution.
Comment: Don't you want both powers in the formula to be $2$, rather than one of them $3$? Where does this "consistency equation" come from? Given that $|\rho|\lt 1$ and the multivariate normal is supported everywhere, necessarily $E[\rho(\cdot)] \lt 1$, so this consistency equation cannot be solved for $n\ge 1$. Something must be missing... .
Comment: If you search for bisquare objective function you should see the functional form I suggested. For the other comment, I edited my question, so now it should appeal to you.
Answer: I will essentially summarize what is said in [1,p185-186]. Your notation is in many places different from the usual one, so I took the liberty of rewriting some of the introductory concepts so that we're on the same tune.
Denote $w(d(\pmb x))=\rho^\prime(d(\pmb x))$, the weight function corresponding to the (multivariate version of the) bi-square loss function:
$$\rho^\prime(d(\pmb x))=1_{|d(\pmb x)|\leq c}\left(d(\pmb x)\left(1-\left(\frac{d(\pmb x)}{c}\right)^2\right)^2\right)$$
and $d(\pmb x)=(\pmb x-\hat{\pmb u}_{\infty})^\top\hat{\pmb\varSigma}_{\infty}^{-1}(\pmb x-\hat{\pmb u}_{\infty})$.
Then we want the final estimates to be consistent in the sense that:
$$(0)\quad E\left(w(d(\pmb x))(\pmb x-\hat{\pmb u}_{\infty})(\pmb x-\hat{\pmb u}_{\infty})^\top\right)=\hat{\pmb\varSigma}_{\infty}$$
where $\pmb\mu$ is the parameter, $\hat{\pmb\mu}$ is the estimate of $\pmb\mu$ and $\hat{\pmb\mu}_{\infty}$ the asymptotic value of said estimate (and likewise for $\hat{\pmb\varSigma}_{\infty}$).
The multivariate S estimator is affine equivariant, so we can set w.l.o.g. set $\hat{\pmb\varSigma}_{\infty}=\pmb I_n$ (the rank $n$ identity matrix) and $\hat{\pmb u}_{\infty}=\pmb 0_n$ (the $n$ dimensional origin). So $d(\pmb x)$ becomes $||\pmb x||^2/c$ and $(0)$ simplifies to:
$$(1)\quad E\left(w\left(\frac{||\pmb x||^2}{c}\right)||\pmb x||^2\right)=nc.$$
Since as you pointed out, when $\pmb x$ is $n$-variate standard normal $||\pmb x||^2$ has a $\chi^2_n$ distribution, we obtain a consistent estimate of $\pmb\varSigma$ in the normal case by replacing $\hat{\pmb\varSigma}_n$ by  $\hat{\pmb\varSigma}_n/c$ with $c$ defined as the solution of:
$$(2)\quad\int_0^{\infty}w\left(\frac{z}{c}\right)\frac{z}{c}g(z)dz=n$$
where $g$ is the density of the $\chi_n^2$ distribution. I guess you could use a root finding algorithm and numerical integration to solve $(2)$ for $c$, depending on the application it could be fairly quick nowadays.

Edit:
whuber's comment is spot on in that the problem above can be simplified considerably using the first 6 moments of the $\chi^2_n$ distribution (see [2]). It can also be done using the first 3 moments of a gamma distribution, but it turns out this second solution is more expensive computationally (see [2] for the source of this claim). The details are well explained in [2], but for completeness, I will put the main result. The constant $c$ in $(2)$ must satisfy [2,equation 32]:
$$(3)\quad\frac{1}{2}=\frac{3n}{c^2}\left(\Psi_{n+2}^c-(n+2)\frac{\Psi_{n+4}^c}{c^2}+(n+2)(n+4)\frac{\Psi_{n+6}^c}{3c^4}+\frac{c^2}{3}\frac{1-\Psi_{n}^c}{n}\right)$$
where $\Psi_n^c=\text{Pr}(\chi^2_n<c^2)$ and the $\frac{1}{2}$ on the lhs of $(3)$ is actually the breakdown point you want your estimate to be consist at (i.e. a number in $(0,0.5]$).
So compared to $(2)$, $(3)$ bypasses the need for numerical integration so that it can be solved using a root finding algorithm only, which is of course much faster.

[1] Robust Statistics: Theory and Methods (2006). Maronna, R. A., Martin, D. R. and V. J. Yohai.
[2] On consistency factors and efficiency of robust S-estimators (2014). M. Riani , A. Cerioli and  F. Torti.


Logging sshfs reads + writes - Possible?

Question: We use sshfs in quite a few situations.
We were wondering if there was a way to log the read / writes made to the sshfs mounts we have so we could optimize things on our local side (eg: tweaking cache, locally caching objects, etc).
Any ideas?
Comment: I'm not sure if there are sshfs logging functions.. but you could probably get a good amount of change info running something like AIDE or tripwire.
Answer: sshfs is a client application, it uses sftp on the server side. Have a look at the manual pages of sftp-server(8) and sshd_config(5).
In /etc/ssh/sshd_config, you should put something like (not sure if quotes are needed, try it yourself):
Subsystem sftp "/usr/lib/ssh/sftp-server -l INFO"

This will log details using the AUTH facility (/var/log/auth.log on Debian with rsyslogd). To separate SFTP logs from regular authentication messages, you can specify a different facility or redirect the logs. For rsyslogd, you can create /etc/rsyslog.d/sftp.conf containing:
:programname,isequal,"sftp-server" /var/log/sftp.log

Note that if your sftp user is chrooted, you need to create a /dev/log socket such that sftp can send messages to the syslog daemon. For rsyslogd, this can be done by creating the dev directory and adding the following line to sftp.conf:
$AddUnixListenSocket /home/user/dev/log


Standard error for slope/intercept estimate in linear regression

Question: Given a linear model $\mathbf{y} = \beta \mathbf{X} + \epsilon$, it is well known that the estimate for $\beta$ that gives the minimum residual sum of squares (RSS) is given by $\hat{\beta} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}$.
Of course, since $\hat{\beta}$ is just an estimate, then we want to know how far it deviates from the true values $\beta$.
In the derivation I am reading (How are the standard errors of coefficients calculated in a regression?), the variance of the estimate is given by:
$$ V(\hat{\beta}) = V((\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{Y})= (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\sigma^2 \mathbf{I}\mathbf{X}(\mathbf{X}^T\mathbf{X})^{-1} = \sigma^2 (\mathbf{X}^T\mathbf{X})^{-1}$$
Please help me understand what happened in this derivation.
(Or you can present a simpler derivation)
Thanks
Comment: Ben Lambert has a good video about the derivation of $V(\hat \beta)$ in matrix form for OLS [here](https://www.youtube.com/watch?v=11J0M7WBMy8). Hope this helps.
Answer: $\hat{\beta} = (X^TX)^{-1}X^TY$ where only $Y$ is random. This means that the variance of the estimator is completely induced by the distribution of $Y$.
It can easily be shown that if $X$ is some fixed matrix or vector and $Y$ is random then $Var(XY) = XVar(Y)X^T$ (assuming that $X$ and $Y$ are compatible). Thus if we let $Z = (X^TX)^{-1}X^T$ (which is fixed) then we have that $\hat{\beta} = ZY$. We haven't changed anything but this will make the steps a little clearer.
$Var(\hat{\beta}) = ZVar(Y)Z^T$ by the identity mentioned above. Now we just need $Var(Y)$ and the rest is just plugging things in and cancelling. By assumption $Y = X\beta + \varepsilon$ where $\varepsilon \sim N(0, \sigma^2 I)$ so $Var(Y) = \sigma^2I$ (again, because $X$ is fixed).
This means that $Var(\hat{\beta}) = ZVar(Y)Z^T = Z \sigma^2I Z^t = \sigma^2 ZZ^T$. Now we can replace $Z$ with what it really is to get $Var(\hat{\beta}) = $
$$\sigma^2 (X^TX)^{-1}X^T ((X^TX)^{-1}X^T)^T = \sigma^2 (X^TX)^{-1}X^TX(X^TX)^{-1} = \sigma^2 (X^TX)^{-1}.$$
This uses the fact that $(X^TX)^{-1}$ is symmetric and $(AB)^T = B^TA^T$.
Comment: In $Y=X\beta + \epsilon$, why is $Var(X\beta) = 0$?
Comment: Because $X$ and $\beta$ are constants/parameters and the variance of a non-random quantity is 0. $X$ is assumed to be fixed and $\beta$ is a parameter. The whole point is to estimate this parameter. It's just like estimating the mean of a normal sample.
Comment: You're very welcome.


Checkout and Transaction API Permissions error

Question: I am currently trying to create a transaction or checkout from Postman, I set the Header with a full access token but the API always response:
<code>{
    "errors": [
    {
            "category": "AUTHENTICATION_ERROR",
            "code": "FORBIDDEN",
            "detail": "You have insufficient permissions to perform that action."
        }
    ]
}
</code>
Attach the OAuth screen.Permissions image
and the postman request.  https://www.getpostman.com/collections/4fe6fec54384fc10d152
Answer: Unfortunately, this is due to you not being in one of the countries currently available to Square's APIs: https://docs.connect.squareup.com/articles/faq-international-availability?q=country. You will not be able to make payments using the API when outside of the countries listed above.
Furthermore, you should never share your personal access token with anyone (which you show in your screenshot). Please change this immediately, by navigating to your Square dashboard and clicking "Replace" on your "Credentials" tab.


Is it possible to keep an iOS app running for ever listening to location update and enabling Maps Car Routing?

Question: How does app like Google Maps keep running in the background, the app is not killed but it runs forever.. how does that work?
Answer: 1.You can go to .plist  and add one item as "Application does not run in background",then set this to "NO"
2.Add one item as "Required background modes" ,set it with you use type
it is my method,i hope that can help you :)


Unable to render table on GitHub Readme

Question: <code>| Reference        | Contract          |
| ------------- |:-------------:| -----:|
| EIP-20 Token      | 0x4c7507262dA41A5A96ae3F836D602d74Eb10A6d0 |
| Uniswap V2     | 0x35775d560e7e0370259c69475c44dbe5cf183afa     |
| Uniswap V3 |  0xa00822c70f9ba29d74d92207c798c0d9cad3735e   |
</code>
This is my code for Readme table. It is working on VSC with a Markdown Preview and here on Stack Overflow:

Reference
Contract

EIP-20 Token
0x4c7507262dA41A5A96ae3F836D602d74Eb10A6d0

Uniswap V2
0x35775d560e7e0370259c69475c44dbe5cf183afa

Uniswap V3
0xa00822c70f9ba29d74d92207c798c0d9cad3735e

but not working well on GitHub.
Comment: How many columns does it have? One possible problem would be more obvious if you aligned them.
Answer: As I suspect @jonrsharpe alludes, you have a syntactical error. Your delimiter row (second line) specifies three columns. However, your header row (line 1) and data rows (lines 3 and 4) have just two columns. See GitHub Flavored Markdown, Tables.
Remove the extraneous third column from your header specification (line 2) like this:
<code>| Reference        | Contract          |
| ------------- |:-------------:|
| EIP-20 Token      | 0x4c7507262dA41A5A96ae3F836D602d74Eb10A6d0 |
| Uniswap V2     | 0x35775d560e7e0370259c69475c44dbe5cf183afa     |
| Uniswap V3 |  0xa00822c70f9ba29d74d92207c798c0d9cad3735e   |
</code>

Unable to render table on GitHub Readme


How to add div's inside a div dynamically until the width and height of parent div is full/completed

Question: Background: I am making a web-page where User will enter the tile Width & Height and Floor Width & Height.
The Floor Width & Height is used to calculate the area of Floor.
The Tile input is in INCHES & the Floor Input is in FEET.
Technical Info: I have set 1 foot equals to 60 pixels & 1 inch equals to 5 pixels for calculations.
Where Am I Now ?
Right now I am stuck in drawing all the tiles (child div's) in the area (parent div). For now I am using simple for loop for making the tiles (div's).
For Now Output is Something Like this...

What I Want ? Well I am trying to make a functionality that when user clicks the Calculate Button, he/she see's the design of the floor. I will be coloring & adding patterns later on.
The output should be like this (Beg me your pardon, if the borders are not align, this was made with Windows Paint) :

Code:

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) {
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());

                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));

                for (let r = 0; r<10  ; r++) {
                    // const element = array[r];
                    $("#area").append("

");

                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 1px solid; /* use instead of border */
        }

Tile Width (inches):
<input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">

Tile Height (inches):
<input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">

Area Width (foot):
<input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">

Area Height (foot):
<input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>

External Link of Fiddle: https://jsfiddle.net/22gLkguL/
I Have tried, to archive all of this but failed..!
Would someone please help me OR guide me in right path...?
Comment: you mean to see all `div`  vertical in the end of `erea`(foot)???
Comment: @לבנימלכה I added more details, for how the output should be..!
Comment: so, u want the inner divs to fill the box and not go out of box?
Comment: Yes @GautamNaik , This is exactly what I want !
Comment: Have u thought of using canvas?
Comment: No @GautamNaik , actually I didn't know how to use canvas ! I new to all this stuff !
Comment: @Zakawat maybe you can do it by create table... If you think so tell me I will help you
Comment: okay @לבנימלכה let's give it a shot with table !
I was working with div's because I thought it is better approach..!
Actually I don't know about this fonrtend stuff, I am Backend guy !
Answer: Use display: flex and flex-wrap: wrap
#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

and calculate the numbers of the divs that each side (width or height) can be filled the most.

$(document).ready(function() {
  $("#btnCalculate").click(function(e) {
    e.preventDefault();

    $("#area").empty();

    const foot = 60,
      inch = 5;

    let tileW = parseFloat($("#tileWidth").val());
    let tileH = parseFloat($("#tileHeight").val());

    let areaW = parseFloat($("#areaWidth").val());
    let areaH = parseFloat($("#areaHeight").val());

    var areaHeight = (foot * areaH)
    var areaWidth = (foot * areaW)
    var divHeight = (inch * tileH)
    var divWidth = (inch * tileW)

    $("#area").css("height", areaHeight);
    $("#area").css("width", areaWidth);

    var nums = Math.floor(areaWidth/divWidth) * Math.floor(areaHeight/divHeight)

    for (let r = 0; r < nums; r++) {
      var $div = $('
', {
        id: 'tile_' + r,
        class: 'border_color',
        height: divHeight,
        width: divWidth,
      })
      $("#area").append($div);

    }
  });
});
#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.border_color {
  outline: 1px solid;
}

Tile Width (inches):
<input type="numbers" id="tileWidth" placeholder="Tile Width" value="6">

Tile Height (inches):
<input type="numbers" id="tileHeight" placeholder="Tile Height" value="4">

Area Width (foot):
<input type="numbers" id="areaWidth" placeholder="Area Width" value="11.5">

Area Height (foot):
<input type="numbers" id="areaHeight" placeholder="Area Height" value="6.5">
<button id="btnCalculate">Calculate</button>

Answer: use display: flex; flex-wrap: wrap for area element.
and calculate the number of Tiles as ---

(areaWidthInPixels/tileWidthinPixels) *
  (areaHeightInPixels/tileHeightinPixels)

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) {
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());

                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));

                let noOfTiles = Math.floor( ((foot * areaW)/(inch * tileW)) )* Math.floor( ((foot * areaH)/(inch * tileH)) );

                alert("noOf TIles :: " + noOfTiles);

                for (let r = 1; r <= noOfTiles  ; r++) {
                    // const element = array[r];
                    var bgColor = r % 2 == 0 ? "red" : "green";
                    $("#area").append("

");

                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
            display: flex;
            flex-wrap: wrap;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 0px solid; /* use instead of border */
        }

Tile Width (inches):
<input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">

Tile Height (inches):
<input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">

Area Width (foot):
<input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">

Area Height (foot):
<input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>

Comment: jsfiddle is added !


Rate of convergence of gradient descent inference in likelihood maximization

Question: I am reading this classic paper on convergence properties of EM for Gaussian Mixture Models. In section 5, the authors compare EM with a gradient based inference approach.
The gradient approach requires step-size $\eta$ for parameter update at each iteration $k$ i.e. updation of paramters from $\Theta^k$ to $\Theta^{k+1}$.
The authors claim that for local convergence, one can use Taylor series expansion of the likelihood around the true parameter $\Theta^*$ and claim that the following condition needs to hold true:
$$\left\|\Theta^{(k+1)}-\Theta^{*}\right\| \leq\left\|I+\eta H\left(\Theta^{*}\right)\right\|\left\|\Theta^{(k)}-\Theta^{*}\right\|$$
Here $H$ is the Hessian of the likelihood. I am trying to derive this condition.
Here is my attempt:
Let $L$ be the likelihood. Expanding $L$ around the true parameter $\Theta^*$ gives
$$L(\Theta^k) \approx L(\Theta^*) + \nabla L(\Theta^* - \Theta^k) + 0.5(\Theta^* - \Theta^k)^{T}H(\Theta^* - \Theta^k) $$
Similarly, I expand $L$ for $\Theta^{k+1}$.
$$L(\Theta^{k+1}) \approx L(\Theta^*) + \nabla L(\Theta^* - \Theta^{k+1}) + 0.5(\Theta^* - \Theta^{k+1})^{T}H(\Theta^* - \Theta^{k+1}) $$
Also, at $\Theta^*$, the gradient $\nabla L = 0$. Subtracting the above two equations, using the condition to ensure montonocity of $L$ at each iteration, I have
$$ (\Theta^* - \Theta^k)^{T}H(\Theta^* - \Theta^k) - (\Theta^* - \Theta^{k+1})^{T}H(\Theta^* - \Theta^{k+1}) < 0 $$
I am unable to simplify further. Is this the right approach?
Thank you in advance!
Answer: That expression does not guarantee convergence, in fact it is just application of Cauchy-Schwartz inequality. Let's see.
First, we use a second order approximation of our cost function $L:\mathbb{R}^n\rightarrow \mathbb{R}$(negative log-likelihood in your case) around the optimum $\Theta^{*}$, taking into account that $\frac{\partial L(\Theta)}{\partial\Theta}\Big|_{\Theta^*}=\vec{0}$:
$$
L(\Theta^*+\Delta \Theta) \approx L(\Theta^*) + \frac{1}{2} \Delta \Theta^T \frac{\partial^2 L(\Theta)}{\partial^2\Theta}\Big|_{\Theta^*}\Delta \Theta
$$
Now, we compute an approximation of the gradient around the optimum:
$$
\frac{\partial L(\Theta)}{\partial \Delta \Theta} \approx \frac{\partial^2 L(\Theta)}{\partial^2\Theta}\Big|_{\Theta^*}(\Theta-\Theta^*) = H(\Theta-\Theta^*)
$$
Which is used in the gradient descent method as follows:
$$
\Theta^{k+1} = \Theta^k - \eta \frac{\partial L(\Theta)}{\partial \Theta} \approx \Theta^k - \eta H(\Theta-\Theta^*)
$$
Which leads to:
$$
\Theta^{k+1} - \Theta^* \approx (I - \eta H)(\Theta-\Theta^*)
$$
Now, taking norms and applying Cauchy–Schwarz inequality:
$$
\Vert\Theta^{k+1} - \Theta^*\Vert \approx \Vert(I - \eta H)(\Theta-\Theta^*)\Vert \leq \Vert I - \eta H \Vert \Vert \Theta-\Theta^* \Vert \leq \lambda_M \Vert \Theta-\Theta^* \Vert
$$
Where $\lambda_M$ is the greatest eigenvalue of $I - \eta H$. This expression is true independently of convergence. To guarantee convergence, this condition is necessary:
$$
\Vert\Theta^{k+1} - \Theta^*\Vert \leq \Vert\Theta^{k} - \Theta^*\Vert
$$
Putting together both inequalities, it arise that convergence condition is:
$$\Vert I - \eta H \Vert <\lambda_M <1$$
Comment: Thanks for the detailed answer! If I understand correctly, the key idea in this approach is to approximate the gradient around the optimum using the Hessian and study the appropriate step size, convergence rate, etc. I have never come across this approach. Is this a widely used approach? Can you please point me towards some references ?


Why is $S = \{(x,y) \in \mathbb{R}^2 \mid \text{$x$, $y$ even integers}\}$ not a subspace of $\mathbb{R}^2$?

Question: Let $S = \{(x,y) \in \mathbb{R}^2 \mid \text{$x$, $y$ even integers}\} \subset \mathbb{R}^2$.
Why is this not a subspace of $\mathbb{R}^2$? $0$ seems to be in it ($2(0) = 0$), $x+y$ seems to be in it, and $kx$ where $k$ is an integer seems to be in it as well.
Thanks!
Comment: **When** $k$ **is an integer**; but what about the non-integer scalars?
Comment: But if you consider $\mathbb{R}^2$ has a $\mathbb{Z}$-module, however.
Comment: You need $k(x,y)\in S$ for all $(x,y)\in S$ and for all $k\in\mathbb R$.  The statement you give---that this holds when $k$ is an integer, is not enough.
Comment: @user110076 : for any vector space there is an associated _field_.  Most often people use the real numbers, sometimes people use the complex numbers, $\mathbb{F}_2$, or other fields.  If your field is $\mathbb{R}$, then $S$ must be closed under scalar multiplication, which it isn't (multiply $(1,0)$ by $1/2$).
Answer: Subspaces have to be closed under more general linear combinations than just $x + y$. That is, you have to have
$$
c_1 x + c_2 y \in S
$$
whenever $x,y \in S$ for any $c_1,c_2 \in \mathbb R$ (since the original vector space is a real-vector space, the scalars for linear combinations are, in general, real numbers)
Answer: It is not a subspace of $\mathbb{ R}^2$ because $kx$ has to be in it for every real $k$, not just integer $k$.
Answer: But $k$ must live in a field, and $\mathbb{Z}$ isn't.
Comment: In fact, $k$ has to be in the reals.


!heap -s not showing growing heaps in windbg

Question: I have written an application that is leaking memory - I've done the following in the past

find the heap that's leaking with
!heap -s
inspect the heap with
!heap -stat -h
see the callstack for the allocation with
!heap -p -a

to get the callstacks I add +ust to gflags
while I've done this in the past with great success, !heap -s isnt showing any growth today? I have no idea whats wrong?
it's like my allocations are in a heap hidden from !heap -s?
ideas?  I'm compiling (both x86 and x64) using Visual Studio 2010 pro.  Using windbg to debug
Comment: FWIW: I modified my program to leak a ton of memory - taskmgr shows the memory usage going WAY up but !heap -s does not
Comment: this is on a 64 bit machine, with 64 bit leaking app, windbg, and gflags
Answer: the punchline - when allocations are <1MB (default) they go to HeapAlloc(),  when they're bigger than 1MB they go to VirtualAlloc instead
VirtualAlloc doesnt appear with !heap -s
Comment: how are you allocating? Your own custom allocator?


Convergence of $\lim_{n\to\infty}(a_n)^n$

Question: What can we say about $\displaystyle\lim_{n\to\infty}(a_n)^n$ given a real sequence $(a_n)$? In particular what happens when $(a_n)$ is convergent? Is it possible for the described limit to converge if $(a_n)$ is not convergent?
Answer: $(1,1,1,\ldots)$ converges and $(1^1,1^2,1^3,\ldots)$ converges.
$(2,2,2,\dots)$ converges and $(2^1,2^2,2^3,\dots)$ diverges.
$(\frac12,\frac13,\frac12,\frac13,\ldots)$ diverges and $((\frac12)^1,(\frac13)^2,(\frac12)^3,(\frac13)^4,\ldots)$ converges.
$(2,3,2,3,\ldots)$ diverges and $(2^1,3^2,2^3,3^4,\ldots)$ diverges.
Answer: We does not say about of (convergence of) $(a_n)$. For example, $\lim_{n\to\infty} n^{1/n} =1$. But $\lim_{n\to\infty} (n^{1/n})^n$ does not converge. But $\lim_{n\to\infty} 1 =1$ and $\lim_{n\to\infty} 1^n=1$.
Answer: Neither convergence implies (or is implied by) the other.
Consider $a_n=2$ for all $n$. This converges, but the sequence of $a_n^n$ does not.
On the other hand, consider $a_n=\frac12\cdot(-1)^n$. This fails to converge, but $a_n^n$ converges.
Answer: If a sequence $\{a_n\}_{n\ge1},\{b_n\}_{n\ge1}$ converges then $\{a_nb_n\}_{n\ge1}$  also converges, so for $k\in N$ $\{(a_n)^k\}_{n\ge1}$ also converges if $\{a_n\}_{n\ge1}$ converge but we cant say anything abt the convergence of $\{(a_n)^n\}_{n\ge1}$
That is if the power is also variable(depending on n) then we cant say anything abt. the convergence of the new series.


Como agrupar notificações

Question: Quero fazer um sistema de notificações que se agrupam quando são o mesmo tipo, como as do Facebook. Por enquanto tenho a tabela com as seguintes colunas:
user_id (pessoa que recebe a notificação),
icon (Geralmente a foto de perfil de outro usuário),
description (a descrição do que se refere a notificação),
registry (data de registro),
seen (um booleano que verifica se a pessoa já visualizou)
Como eu crio as notificações? Bom, isso acontece na hora que a ação é executada. Por exemplo, eu clico no botão de seguir Fulano, dentro da função eu registro a notificação, assim:
user_id: Id do usuário que eu segui,
icon: Minha foto de perfil,
description: Insanity começou a seguir você!,
registry: CURRENT_TIME(),
seen: 0
Tenho dois problemas principais:

Se eu ficar clicando no botão de seguir várias vezes, vai enviar várias notificações.
O problema do agrupamento: Se mais de uma pessoa seguir, vamos supor que 1000 pessoas façam isso, vai aparecer 1000 notificações. Como agrupar igual o Facebook, exemplo: "Geraldo, Thiago e mais 998 pessoas começaram a seguir você!".
Comment: acho que a logica do face book é caso tenha mais de x notificações ele ao invés de exibir todas ele vai exibir a ultima e quantas outras notificações tem do mesmo tipo
Comment: isso é meio complexo. Mas vc vai precisar mudar a estrutura do db: criar uma tabela com os tipos de atividade e então relacioná-las com a sua tabela atual (ao invés do campo description). Isso vai ajudar o servidor a comparar os registros: é muito mais rápido verificar dois ints que duas strings. (veja sobre normalização do banco)
Answer: Utilize a cláusula GROUP BY, que é utilizada para agrupar (ou agregar) as linhas da tabela segundo um critério escolhido pelo utilizador, podendo depois ser aplicada uma função de grupo a cada um dos grupos. Usando GROUP BY não é possível selecionar linhas individuais.
O exemplo abaixo determina o salário médio de cada função (JOB):
SELECT job, AVG(sal)
FROM emp
GROUP BY job;

JOB       AVG(SAL)
--------- ----------
CLERK     1037,5
SALESMAN  1400
PRESIDENT 5000
MANAGER   2758,3
ANALYST   3000

5 rows selected

Como agrupar notificações


Number of ways to interleave two ordered sequences.

Question: Suppose we have two finite, ordered sequences $x = (x_1,\dots,x_m)$ and $y = (y_1,\dots,y_n)$. How many ways can we create a new sequence of length $m+n$ from $x$ and $y$ so that the order of elements is preserved?
How many ways can we do this using $k$ ordered sequences instead of two?
Comment: http://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter3.pdf
Comment: you may need some tutorial about combinatorics
Answer: This is the same as taking $m + n$ places, and deciding which $m$ of them get the $x_i$, i.e., $\binom{m + n}{m}$.
For $k$ ordered sequences, the basic idea is the same; you'll get an $k$-nomial coefficient.
Answer: Suppose that you have $k$ ordered lists of elements--where the $j$th list has $n_j$ elements for $1\le j\le k$--and that you wish to interleave them, as described.
Now, all told, there will be $n_1+n_2+\cdots+n_k$ places that we must fill. So, first, we assign the elements of the first list to their places, and since we want to preserve order, then choosing the places will also determine which elements of the first list go to which places. There are $\binom{n_1+n_2+\cdots+n_k}{n_1}$ ways to do this.
Next, we choose which $n_2$ of the remaining places will have members of the second list. There are $\binom{n_2+\cdots+n_k}{n_2}$ ways to do this. We continue in this fashion, until finally we have only the members of the $k$th list to place. There are $\binom{n_k}{n_k}$ ways to do this.
All told, then, there are $$\prod_{i=1}^k\binom{\sum_{j=i}^kn_j}{n_i}$$ ways to interleave the lists in the desired fashion. Still, this expression is a bit ugly. Fortunately, we can make it simpler, by noting that for nonnegative integers $n,r$ with $r\le n$ we have $$\binom{n}{r}=\frac{n!}{r!(n-r)!}.$$ Hence, we're looking at the product $$\frac{(n_1+n_2+n_3+\cdots+n_k)!}{n_1!(n_2+n_3+\cdots+n_k)!}\cdot\frac{(n_2+n_3+\cdots n_k)!}{n_2!(n_3+\cdots n_k)!}\cdots\frac{(n_{k-1}+n_k)!}{n_{k-1}!n_k!}\cdot\frac{n_k!}{n_k!0!}.$$ Since $0!=1,$ then a chain of cancellations show us that this is simply $$\frac{(n_1+n_2+\cdots+n_k)!}{n_1!n_2!\cdots n_k!}=\binom{n_1+n_2+\cdots+n_k}{n_1,n_2,\dots,n_k}.$$


Pfsense over Ubuntu 12.04

Question: Is it required to install virtual box in order to install pfsense?
I mean I would like to directy install pfsense over ubuntu 12.04 operating system without needing any virtualbox like software?
Does pfsense have capability of running over real operating system directly?
Thanks in advance
Comment: Which rule I have violated that makes you down voting?
Comment: The underlying assumptions of your question seem to be grossly inaccurate. This is likely leading people to downvote your question due to not meeting the `professional capacity` requirement.
Answer: Um... no.
The pfSense homepage begins by saying:

pfSense is a free, open source customized distribution of FreeBSD tailored for use as a firewall and router.

It's not really designed or intended for you to install the pieces separately and "roll your own" as it were.
(And, saying FreeBSD isn't a real operating system is not only inaccurate, but insulting.)

Pfsense over Ubuntu 12.04


Como realizar concatenação SQL

Question: Preciso concatenar ano e mês. Como eu poderia fazer isso?
    select cast(year(orderdate) as int) + ' ' + cast(month(OrderDate)as int) as Year_Month
    From sales.SalesOrderHeader

Comment: Alguma das respostas solucionou teu problema?
Answer: Usa a função CONCAT.
SELECT CONCAT(YEAR(OrderDate), '-', MONTH(OrderDate)) AS Year_Month
FROM sales.SalesOrderHeader

Nesse caso, o segundo parâmetro do concat é o separador ('-') que você define o que vai ser.
Answer: Pode usar o CONCAT do sql
https://docs.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql
select Concat(cast(year(orderdate) as int),  '_'  ,cast(month(OrderDate)as int)) as Year_Month From sales.SalesOrderHeader

Comment: Não é necessário fazer um `Cast` em `Ano` e `Mês`, pois os valores que são passados como argumentos dentro da função `Concat` são diretamente convertidos para `texto`
Answer: Deram a opção do CONCAT, mas ele foi implatado no SQL SERVER 2012, é bem provável que esteja utilizando o 2008 e seja incompatível.
Para fazer a concatenação, é necessário que seja uma string. Da forma como está fazendo ocorrerá erro, então concatene da seguinte maneira utilizando YEAR() e MONTH com CAST():
SELECT CAST(YEAR(orderdate) AS NVARCHAR(4)) + ' ' + CAST(MONTH(orderdate) AS NVARCHAR(2)) AS year_month

Ou utilizando DATEPART:
SELECT CAST(DATEPART(yyyy, orderdate) AS NVARCHAR(4)) + ' ' + CAST(DATEPART(mm, orderdate) AS NVARCHAR(2)) AS year_month

Answer: CONCAT (Transact-SQL)

Retorna uma string que é o resultado de concatenar dois ou mais
valores de seqüência de caracteres. Está disponivel a parti do SQL- Server 2012.

Query:
select CONCAT('O ano em que estamos é ', YEAR(GETDATE()),' e o mês é ',
MONTH(GETDATE())) as Data

Nota: Todos os argumentos são implicitamente convertidos em tipos de string e, em seguida, concatenados. Então não é necessário usar o T-SQL CAST conforme perguntando.
SQLFiddle
Answer: Joana, no código sql que você postou fique atenta para os meses cujo valor numérico é menor do que 10. Por exemplo, 12/11/2008 ficará como "2008 11" mas 12/1/2008 ficará como "2008 1", quando me parece que o esperado é "2008 01".
Uma forma simples e rápida de obter o que desejada é utilizar a função CONVERT(), convertendo de date para string. Algo assim:
-- código #1
SELECT convert (char(7), orderdate, 23) as Year_Month
  from sales.SalesOrderHeader;

Se não desejar o hífen entre ano e mês, eis uma variação:
-- código #2
SELECT replace (convert (char(7), orderdate, 23), '-', ' ') as Year_Month
  from sales.SalesOrderHeader;

Observe que com essa solução não é necessário o uso de operador ou função de concatenação e nem de se preocupar com meses cujo valor seja menor do que 10. Mas se estiver interessada em realizar concatenação, sugiro a leitura do artigo Concatenação de cadeias de caracteres.
Answer: Joana, fiz isso e deu certo. Talvez também funcione pra você:
select
    concat(cast(year(orderdate) as varchar),'-', cast(MONTH(OrderDate) as varchar)) as Year_Month
From sales.SalesOrderHeader

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Como realizar concatenação SQL


the jquery method works fine but when made as a function not working

Question: my Jquery code works fine if i dont keep the code inside function and call it but as a function not working

Answer: because this inside the function does not refer to the clicked radio element, since you are writing it as a separate function pass the clicked element as a parameter
$(document).ready(function(){
    $("input:radio").change(function(){
        checkResult(this);
    });
});
function checkResult(el) {
    var $this = $(el).parent("div.QA");
    $this.slideUp();
}

Answer: Pass the function name - checkResult as callback, so that this will refer to the changed element.
$(document).ready(function(){
    $("input:radio").change(checkResult);
});
function checkResult()
{
    $this=$(this).parent("div.QA");
    $this.slideUp();
}


Exponential distribution $P(Z \geq 5)$

Question: Exponential distribution
Let $Z ∼ Exponential(4)$. Compute each of the following
(a) $P(Z \geq 5)$
$$P(Z \geq 5) = \int_{5}^{\infty} 4e^{-4x}dx$$
Let $u = -4x$, then $du = -4dx \leftrightarrow -\frac{1}{4}du = dx$
$$-\int_{-\infty}^{-20} e^{u} du =  -e^{u}|_{-\infty}^{-20} = -(e^{-20} - \lim_{u\to-\infty}e^{A}) = -e^{-20} + 0 = -e^{-20}$$
Answer is $e^{-20}$. Where did I go wrong or is the solution wrong?
Answer: First of all, the solution is obviously wrong. You've got a negative probability.
The problem is in the $$-\int\limits_{-\infty}^{-20}$$ step.
Your original range was from $5$ till $\infty$. You substituted a new variable, $u = -4x$, hence its range is from $-20$ to $-\infty$, i.e.
$$P(Z \geq 5) = \int\limits_5^{\infty}4e^{-4x}\mathrm{d}x = -\int\limits_{-20}^{-\infty}e^u\mathrm{d}u = \int\limits_{-\infty}^{-20}e^u\mathrm{d}u = e^{-20}$$
Answer: $P(Z \ge 5)=1-P(Z \lt 5)$
$=1-(1-e^{-20})=e^{-20}$
Answer: Just this:
$$\int_5^\infty 4 e^{-4x}\mathsf d x= \lim_{x\to\infty}(-e^{-4x})-(-e^{-4\cdot 5})$$
When you apply the substitution
$$\begin{split}\int_{-20}^{-\infty} 4e^{u}\dfrac{\mathsf d u}{-4} &= -\int_{-20}^{-\infty}e^u\mathsf d u \\ &=\int_{-\infty}^{-20}e^u\mathsf d u \\ &=e^{-20}-\lim_{u\to-\infty}e^u\end{split}$$
Answer: It should be pointed out that the notation $$Z \sim \operatorname{Exponential}(4)$$ is imprecise, because it does not tell us whether the $4$ is a rate parameter (as you have implied in your computation), or a scale parameter.  That is to say, does the above mean $$\operatorname{E}[Z] = 1/4, \quad f_Z(z) = 4e^{-4z}, \quad z \ge 0,$$ or does it mean $$\operatorname{E}[Z] = 4, \quad f_Z(z) = e^{-z/4}/4, \quad z \ge 0?$$  The probability $\Pr[Z \ge 5]$ will be quite different depending on the parametrization.
For the sake of completeness, we should observe that $$\Pr[Z \ge z] = S_Z(z) = 1 - F_Z(z) = 1 - (1 - e^{-\lambda z}) = e^{-\lambda z},$$ if parametrized by rate, and $$\Pr[Z \ge z] = e^{-z/\theta}$$ if parametrized by scale.
This ambiguity also carries over into other members of the exponential family; e.g., the gamma distribution.  Both parametrizations are used in the literature and there is no universally accepted preference of rate versus scale.

Exponential distribution $P(Z \geq 5)$


Finding circumcentre

Question: Tangents are draw from $P(2,3)$ to $x^2+y^2=4$ meeting at $Q,R$ on circle. Parallelogram $PQSR$ is completed. Find the circumcentre of triangle $QSR$.

My attempt: Clearly, the parallelogram is a rhombus. $S$ will be mirror image of $P$ in chord of contact. But, I want to know a good way of finding the circumcentre other than it lies on $PS$ and dropping perpendiculars and other boring stuff. Maybe a nice geometrical solution? Or combining it with coordinate?
Comment: Can you draw the picture? Maybe I can help you but not now, it's already midnight here.
Comment: Here too... Will make using paint.
Comment: @Tunk-Fey Done
Comment: You do not want the usual intersection of the perpendicular bisectors?
Comment: @Sawarnik Clearly RP is 3 units and we can find the angle by writing joint pair of equation of tangents.
Comment: @N.Owad I want an efficient and fast way.
Comment: @Awesome Done! See my answer below.
Answer: Here's an overview ...
Note that the circumcenter (call it $C$) of $\triangle PQR$ is easy to find: It's the intersection of $\overline{PS}$ (a line through the origin) and the (horizontal) perpendicular bisector of (vertical) segment $\overline{PQ}$ with known endpoints. Now, the circumcenter you want (call it $D$) is clearly the reflection of $C$ in $\overline{QR}$; this implies that $\overline{CQ} \cong \overline{DQ}$. Thus, the circle with center $Q$ through $C$ meets $\overline{PS}$ at $D$.

Details ...
$$\overline{PS}:\;\; y = \frac{3}{2}x,\qquad\text{perp bis of } \overline{PQ}:\;\; y = \frac{3}{2}\qquad \implies \qquad C = \left( 1, \frac{3}{2} \right)$$
Then, writing $D = \left(d, \frac{3}{2}d\right)$, we have
$$\begin{align}
|\overline{DQ}|^2 = |\overline{CQ}|^2 \quad &\implies \quad\left(d-2\right)^2 + \left(\frac{3}{2}d - 0\right)^2 = \left( 1 - 2 \right)^2 + \left( \frac{3}{2} - 0 \right)^2 \\[6pt]
&\implies 13 d^2 - 16 d + 3 = 0 \\[6pt]
&\implies d = \frac{3}{13} \qquad (\text{or } d = 1, \text{ but that gives } C ) \\[6pt]
&\implies D = \left(\frac{3}{13}, \frac{9}{26}\right) \qquad \square
\end{align}$$
Comment: All hail symmetry...
Comment: ¡H$\large{⊍}$ZZ$\large{⩀}$H!
Answer:
 This is meant to be a useful drawing for the problem, not an answer. You should be able to take it off the screen to use for a proof.
Answer: The equation of the circle with center $(0, 0)$ and radius $r$ is
$$x^2 + y^2 = r^2.$$
The equation of tangent to this circle at the point $(x_p, y_p)$ on the circle is
$$x_px + y_py = r^2,$$
then the equation of tangent at the point $(2,3)$ is
$$2x + 3y = 4\quad\Rightarrow\quad y=\frac{4-2x}3.$$
Now, we determine the points of tangency (coordinates of $R$ and $Q$).
$$
\begin{align}
x^2+y^2&=4\\
x^2+\left(\frac{4-2x}3\right)^2&=4\\
x_1=2\quad&;\quad x_2=-\frac{10}{13}\\
&\text{and}\\
y_2=0\quad&;\quad y_2=\frac{24}{13}.\\
\end{align}
$$
We obtain $Q(2,0)$ and $R\left(-\dfrac{10}{13},\dfrac{24}{13}\right).$ Since $PQRS$ is a parallelogram, then $PQ\parallel RS$ and $PR\parallel QS$. It's easy to notice that $PQ$ is perpendicular with $x$-axis, therefore $RS$ is also perpendicular with $x$-axis and line $RS: x=-\dfrac{10}{13}$.
Line $PQ:\ x=2$
Line $PR:$
$$
\begin{align}
\frac{y-y_P}{y_R-y_P}&=\frac{x-x_P}{x_R-x_P}\\
\frac{y-3}{\frac{24}{13}-3}&=\frac{x-2}{-\frac{10}{13}-2}\\
y&=\frac{5}{12}x+\frac{13}{6}
\end{align}
$$
Line $RQ:y=-\dfrac{2}{3}x+\dfrac{4}{3}$
Since $PR\parallel QS$, then gradient line $PR$ is equal to gradient line $QS$, $m=\dfrac{5}{12}$. Therefore, line $QS:$
$$
\begin{align}
y-y_Q&=m(x-x_Q)\\
y-0&=\dfrac{5}{12}(x-2)\\
y&=\dfrac{5}{12}x-\dfrac{5}{6}\\
\end{align}
$$
The coordinate of $S$ is the intersection point line $RS$ and $QS$. Hence $x_S=-\dfrac{10}{13}$ and
$$
y_S=\dfrac{5}{12}x_S-\dfrac{5}{6}=-\dfrac{15}{13}.
$$
Now, we determine line that is perpendicular to line $RQ$ and passes through point $S$, let's call this line as $SS'$. The gradient of $SS'$ is $-\dfrac1{m_{RQ}}=\dfrac32$, then the equation is
$$
\begin{align}
y-y_S&=m(x-x_S)\\
y+\dfrac{15}{13}&=\dfrac32\left(x+\dfrac{10}{13}\right)\\
y&=\frac32 x.
\end{align}
$$
The midle point of line $RS$ is
$$
y_M=\frac12(y_R+y_S)=\frac12\left(\dfrac{24}{13}-\dfrac{15}{13}\right)=\frac9{26}.
$$
It is clearly that the circumcentre $\Delta QSR$ on the intersection point of line $SS'$ and line $QM$. I think you can handle it the rest.
P.S. : Unfortunately, I cannot find the fastest way than this.
Comment: Why will circumcentre lie on intersection of $SS'$ and $y=0$?
Comment: Also the answer is wrong. Circumcentre is no equidistant from all 3 points.
Comment: @Awesome Circumcentre is a point on the intersection point of the lines that is perpendicular with lines $QS,SR$, and $QR$. The line that is perpendicular with $QR$ is $SS'$ and the line that is perpendicular with $RS$ is $x$-axis.
Comment: The perpendicular bisectors
Comment: I think you found orthocentre
Comment: Anyways I wanted a better way... I have said in my question that I know this method.
Comment: @Awesome Sorry, I can fix it if you want but it looks like you're not satisfy with my answer. So?
Comment: This was in my MCQ test. This cannot take longer than 5 minutes. There are 60 questions in 180 minutes.
Comment: I have been trying geometry with futile attempts. Maybe it's vectors?
Comment: @Awesome I'm sorry, I can't provide you other method right now.
Comment: I think there is no alternate way.
Comment: @Awesome Perhaps any, but I don't know yet.
Comment: But we can find centroid, you have orthocentre and use the fact that they lie on euler line and are in ratio 1:2.
Comment: I don't like not knowing :(
Comment: @Awesome I found it using geometry approach. Try to draw the $\Delta QRS$ and use also formula of distance 2 points, you can obtain it by yourrself.

Finding circumcentre


Differences between ActionExecutingContext and HttpActionContext

Question: When I add a filter attribute to an api controller it doesn't work because of using ActionExecutingContext. When I find the solution which is I have to use HttpActionContext it works fine. So what is the major differences between them ?
Answer: I can see that in one of my earlier MVC solutions, my custom filter used ActionExecutingContext. In that solution, the packages.config says:
package id="Microsoft.AspNet.Mvc" version="4.0.20710.0"

In a newer MVC solution, when I create a similar custom attribute / filter, the override for OnActionExecuting wants me to now pass in a HttpActionContext.. and that NuGet is:
package id="Microsoft.AspNet.Mvc" version="5.2.3"

I'm still researching what the difference is, too. But, I can definitely see they changed this up between versions of AspNet.Mvc


Moonlight Sonata 3rd Movement tied notes

Question: I'm currently playing the 3rd Movement of Moonlight Sonata and noticed myself always hitting the last note in Measure 22 (f##) even though it is a tied note.
I never thought about not playing it, because every performer I have seen/heard playing this piece always played this note as well. Thus my ears were used to hear it and so I automatically played it without thinking.
Now the question is, how am I supposed to know when to play the tie, and when to actually play the note, even though the notation tells me not to do it.
There is actually an indication in Measure 23 which tells me to use the thumb to play the g#, therefore one could conclude, that the note has to be played even though it is tied. Any ideas on this? Or am I missing something here?

 It's the slow melody passage at 0:27
Comment: As it stands, I find this a confusing question. Bar 22 or 23?  23, the last G# is not tied to anything.
Comment: What do you mean with serious problem? As I stated, it came to my mind when thinking about the score. I knew that I was probably playing it right I just didn't know the explanation for it. That's why I asked. And I'm glad that Richard read the question, understood it, and then answered it without blaming me for asking. And just to let you know, yes I am clearly not a beginner, I play since more than 16 years now but that does not mean I'm perfectly good at reading sheet music. It's actually the opposite because I never had a teacher who taught me reading it. But hey that's another story.
Comment: It's both bars. Same pattern at the end. Richard got it right.
Comment: This question seems to be very constructed in my eyes. You play the 3rd movement of the Moonlight Sonata, you know the ties and slurs and what is a double sharp ...I hardly can believe that this is a serious problem recognizing the difference between a tie and a slur, as  in the previous bars  you have encountered many ties and slurs, even in bar 22. And the following motif is totally clear. If you ask this question representative for a beginner  ... I think this was not the best example.
Comment: Sorry, I didn't mean to blame you. *There is actually an indication in Measure 23 which tells me to use the thumb to play the g#, therefore one could conclude, that the note has to be played even though it is tied*. This exactly shows us that the g# isn't tied. You played it correctly.
Comment: You're welcome! I recommend to watch some youtube videos about *phrasing*.
Answer: It seems that you may be conflating phrasing slurs with ties.
Ties and slurs are notated similarly, but the context determines what is intended. Ties in this style will only ever connect two of the exact same notes, and there will not be any intervening pitches; instead, the tie's purpose is to lengthen the duration of a pitch you are currently playing. This happens in the first half of m. 22; on beat 2, the F-doublesharp is tied into beat 3!
A phrasing slur, however, will often connect multiple different pitches, including perhaps multiple instances of a single pitch. That is what is happening at the end of m. 22. During beats 3 and 4, those two F-doublesharps are not tied together, but are rather part of a larger phrasing slur. As such, you will articulate both of those F-doublesharps.
And the same applies to the G♯s at the end of m. 23 and the A♯s at the end of m. 24.
In the instance that you would want to hold the F-doublesharp for the duration of this slur, you would need to use separate voices, like so:

(This looks a little ugly, but mainly that's because it's a manufactured example. Beethoven would have written this differently had he wanted the F-doublesharp held.)
Comment: So the thing is that there is an intervening note between  the F-Doublesharps that's why it's a slur and not a tie. I got that. But out of curiosity, how would the notation be for the other case? Holding the F-DoubleSharp until the end?
Comment: @brimosimo In that case you would use separate voices, with the voices clarified by different stem direction. See my edit.
Comment: This looks kind of ugly indeed however now I know the difference. Thank You very much for the clear explanation!
Answer:
I never thought about not playing it, because every performer I have seen/heared playing this piece always played this note as well.

As you say in your comment to Tim both figures are identical: and also in the next bar 24 we have the same motif.

It's both bars. Same pattern at the end.
Now the question is, how am I supposed to know when to play the tie, and when to actually play the note, even though the notation tells me not to do it.

The notation doesn't tell you not to play the last notes. There are no ties in the second motif.
As you can see in the previous motif  (2 tied notes F##) the ties are always between two consecutive notes and not from the beginning to the end of a phrase or a motif. The latter bows are slurs to mark the phrasing: This means play the notes under one bow, with no stop, in one breath, but at the end of the slur there is a breathing. The last note under the slur is played softly and shortened. Look at the performer: the pianist lifts the hands at the end of the slur.
Comment: that's actually the way I play it. Now that I know why, it makes perfect sense. But it wasn't as clear to me before asking (obviously otherwise I wouldn't have gone through the trouble of posting a question here in the first place) but thank you for elaborating on it more.
Comment: I understand. Excuse me for being so skeptically ;) . (It is here also allowed to ask questions where you know the answer - representative for others)


cytoscape.js - why do I not see a sample graph in my Chrome browser?

Question: I'm new to frontend development and cytoscape.js and I wanted to create a simple example to get a feeling for how to use the cytoscape.js library. I want to create a simple graph example and used the tutorial at http://blog.js.cytoscape.org/2016/05/24/getting-started/ .
Could someone tell me why I do not see a graph yet in my Chrome browser? I created an area for the graph and a graph instance. Below is the code that is not working. Thank you much for any help.
<!doctype html>

    <title>Tutorial 1: Getting Started</title>

Answer: The following line:

should be changed to:

Comment:


Download filtered tableOutput in Shiny

Question: I have the following data:
> data
        products         id
1             P1     280386
2             P1     285184
3             P2     293154
4             P1     294245

I have built a simple shiny code. I first filter the table and then I want to download the filtered table. I write the following
library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)

data <- read.csv("Desktop/data.csv")
products <- unique(data$products)

ui <- fluidPage(
  fluidRow(
    column(4,
           selectInput("product", "Product", products,
                       multiple = TRUE),
           downloadButton("download", "Download")),
    column(8,
           tableOutput("errorTable")
    )
  )
)

server <- function(input, output, session) {

  output$errorTable <- renderTable({
    subset(data, products == input$product)
  }
  )

  output$download <- downloadHandler(
    filename = function() {
      paste("data-",Sys.Date(), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(data, file)
    }
  )

}

shinyApp(ui, server)

However, this code only downloads the full table, not the filtered one. I have searched some question but none explained this case specifically. thanks in advance
Comment: your example is not reproducible.
Comment: @J.Doe. I added a sample data frame
Answer: Try this
library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)

data <- read.csv("Desktop/data.csv")
products <- unique(data$products)

ui <- fluidPage(
  fluidRow(
    column(4,
           selectInput("product", "Product", products,
                       multiple = TRUE),
           downloadButton("download", "Download")),
    column(8,
           tableOutput("errorTable")
    )
  )
)

server <- function(input, output, session) {

  #you need to create a reactive object with a NULL starting value
  listofitems <- reactiveValues(data = NULL )

  #observe the changes in input$product and update the reactive object
  observeEvent( input$product, {
    print("Hello: observeEvent for input$product is triggered")
    #debug using browser()
    listofitems$data <-  subset(data, products == input$product)

    showNotification("Products updated",
                     type =  "message",
                     duration = 4,
                     closeButton = TRUE)
  }, ignoreInit = T,ignoreNULL = TRUE)

    output$errorTable <- renderTable({
      listofitems$data
    }
    )

  output$download <- downloadHandler(
    filename = function() {
      paste("data-",Sys.Date(), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(listofitems$data, file)
    }
  )

}

shinyApp(ui, server)

Download filtered tableOutput in Shiny


How to create a "random-pareto" in NetLogo?

Question: Since I am not well-versed in mathematics, I am struggling with the implementation of a random number generator in NetLogo which follows roughly a pareto distribution. This is the follow-up question of this one here, where I would like to substitue the random-float with something like "random-pareto" in order to have events taking place in the model following a pareto distribution (thinking of simulated earthquakes and their degree of destructiveness).
The code in question is:
  ask hits [
     let %draw (random-float 100)
     let %strength 0  ;; no damage
     if (%draw < 50) [set %strength (%strength + 1)]  ;;1 for little damage
     if (%draw < 10) [set %strength (%strength + 1)]  ;;2 for middle damage
     if (%draw < 5) [set %strength (%strength + 1)]  ;;3 for strong damage
     if (%draw < 1) [set %strength (%strength + 1)]  ;;4 for complete destruction

     ifelse pcolor = red [die]
     [ ask n-of %strength patches [ set pcolor red ]]
   ]

I got inspired by this question here to do the same in R and the Netlogo Dictionary here about the fact that random-exponential can be written as (- mean) * ln random-float 1.0.
Can somebody help?
Answer: What you need is the equation to convert from a uniform distribution (random-float) to the distribution you want. This might be a better question for the stackexchange stats. However, according to Wikipedia, the formula is:
$$
T = \frac{m}{U^\frac{1}{\alpha}}
$$
where $U$ is the uniform input, $T$ is the Pareto distributed random number, $m$ (minimum) and $\alpha$ are parameters of the distribution. If this is correct, you could code in NetLogo as
to-report random-pareto [alpha mm]
  report mm / ( random-float 1 ^ (1 / alpha) )
end

Say you wanted a random Pareto from the distribution with minimum of 1 and alpha of 3, you could then get one with the code random-pareto 3 1
Comment: looks like there's no maths markdown on stackexchange!
Comment: Thank you very much, JenB. Now I understand better how to "transliterate" a formula into NetLogo.
Comment: is there a way to have a max value for this formula, like `random` netlogo command has?
Comment: If you want to have a truncated distribution, use a while loop and keep generating a random value until it falls within the limits you want. If this is not enough explanation, please ask a separate question (which is what you really should do anyway).


Cartesian Product of Two Complete Metric Spaces is Complete

Question: This is a problem I'm stuck on that our professor gave us for additional practice (not homework, but its recommended that we understand how to prove it).
We know X and Y are complete metric spaces, and we need to show that $X \times Y$ is complete. I'm really lost on the proof technique. We were given an outline as follows, but I could only fully figure out (1). Part 3 is what we've been really stuck on though.  I was wondering whether someone could give an proof for say a more specific space where $X = \mathbb{R}, Y = \mathbb{R}$, so I could understand the principle.
Outlined:
1) Show that $d_{X \times Y} ( (a_1,b_1) , (a_2,b_2)) = \max \{ d_X (a_1,a_2) , d_Y (b_1, b_2)\}$ is a metric.
2) Prove that this gives the product topology on $X \times Y$.
3) Prove that  if  $a_n, b_n$ are Cauchy sequences, where $a_n \in X$ and $b_n \in Y$, then $(a_n,b_n )$ is Cauchy.
Comment: 1) is a little strange. You can show that $d_{X\times Y}$ is a metric. That it is the product metric, is not a theorem, but a definition. Moreover it is not the only reasonable definition. Note, e.g., that for $X=Y=\mathbb{R}$,$d_{X\times Y}$ is not the "natural" Euclidean distance.
Comment: Thanks a lot for all the clarifications. They are really helping me get a better picture of this sort of problem, in particular the sort that involves Cartesian products of two spaces.
Comment: 3) is also strange to me, I feel that the reverse: $(a_n,b_n)$ is Cauchy then $a_n, b_n$ are Cauchy is what we need
Answer: As for (2), it suffices to prove that the balls produced by the distance $d_{X\times Y}$ are a basis for the product topology.
So let's write down what it is a ball for the distance $d_{X\times Y}$ with center $(a,b)$ and radius $\varepsilon > 0$:
$$
B_{X\times Y}((a,b); \varepsilon) = \left\{ (x,y) \in X\times Y \ \vert \ d_{X\times Y} ((a,b), (x,y))= \max  \left\{ d_X(a,x) , d_Y (b,y) \right\}   < \varepsilon \right\} \ .
$$
But
$$
\max  \left\{ d_X(a,x) , d_Y (b,y) \right\}   < \varepsilon \quad \Longleftrightarrow \quad d_X(a,x) <\varepsilon \ \text{and} \ d_Y(b,y) < \varepsilon \ .
$$
Hence we see that
$$
B_{X\times Y }((a,b); \varepsilon)\  = \ B_X (a;\varepsilon ) \times B_Y (b; \varepsilon ) \ .
$$
That is: a ball for the distance $d_{X \times Y}$ is the same as a product of balls for the distances $d_X$ and $d_Y$. Which means that balls for the distance $d_{X\times Y}$ form a basis for the product topology.
Answer: For 3) if you are given an $\epsilon$, you can find $N$ such that $|a_n-a_m|<\epsilon \text{ if } n,m>N$ and similarly for $M$ and the $b$ series.  Doesn't $\max{(N,M)}$ give a limit that $|(a_n,b_n)-(a_m,b_m)|<\epsilon$?
Comment: @TaylorRendon:  Yes, we never used that the spaces are complete.  If they are not complete, the sequence may not have a limit, but the sequence is still Cauchy.
Comment: Is $3)$ true for Cauchy sequences in general (I.e., for any pair of metric spaces)?
Answer: If ${a_n}$, ${b_n}$ are Cauchy, then for some N, $d_X(a_n,a_m) < \epsilon$, $d_Y(b_n,b_m) < \epsilon$ when $n,m \geq N$. Because of this, $d_{X \times Y} ((a_n,b_n),(a_m,b_m)) < \epsilon$ for $n,m \geq N$.
Answer: Actually if we want to prove that a product space is complete then we have to take a Cauchy sequence from the product space and then show that it converges to a point in it.
Observe that for all $a_1, a_2 \in X$ and $b_1, b_2 \in Y,$$d_X (a_1,a_2) \leq \max \{ d_X (a_1,a_2) , d_Y (b_1, b_2)\}\tag1$   $d_Y (b_1,b_2) \leq \max \{ d_X (a_1,a_2) , d_Y (b_1, b_2)\} \tag2$.
Suppose we have a Cauchy sequence $((a_n, b_n))$ in $X \times Y $. Then given $\epsilon > 0$ there exist $N$ such that for all $n,m \geq N$ we have $\max \{ d_X (a_n,a_m) , d_Y (b_n, b_m)\} < \epsilon$
Due to $(1)$ and $(2)$ we have $d_X (a_n,a_m) < \epsilon$ and $d_Y (b_n,b_m) < \epsilon$ for all $n,m \geq N$ implying that $(a_n)$ and $(b_n)$ are Cauchy in $X$ and $Y$ respectively. Since $X$ and $Y$ are both complete $(a_n)$ converges to some $a \in X$ and $(b_n)$ converges to some $b \in Y$ and thus $(a,b) \in X \times Y.$
Now it is a matter of showing that $((a_n, b_n))$ converges to $(a,b)$ in $X \times Y$ which is easy to do since  $\lim_{n \to \infty }d_{X \times Y} ( (a_n,b_n) , (a,b)) = \lim_{n \to \infty } \max \{ d_X (a_n,a) , d_Y (b_n, b)\} = 0.$


Crontab doesn't start, no errors

Question: I have the below crontab configuration ;
45 9 * * * sh /home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log

And my script is as below ;
#!/bin/bash
### Backup Folder dir ###
BAK="/var/www/backup/mysql/"
GZIP="$(which gzip)"
### FTP SERVER Login Stuff###
FTPU="someuser1"
FTPP="somepass1"
FTPS="someftpsite1"
FTPUU="someuser2"
FTPPP="somepass2"
FTPSS="someftpsite2"
NOW=$(date +"%d-%m-%Y")

[ ! -d $BAK ] && mkdir -p $BAK || /bin/rm -f $BAK/*

mysqldump -u root -h localhost --all-databases | gzip -9 > /var/www/backup/renko_backup_$NOW.sql.gz

lftp -u $FTPU,$FTPP -e "mput /var/www/backup/renko_backup_$NOW.sql.gz; quit" $FTPS >  /home/renko/mysql_back_log.log
lftp -u $FTPUU,$FTPPP -e "cd some_dir;mput /var/www/backup/renko_backup_$NOW.sql.gz; quit" $FTPSS >  /home/renko/mysql_back_log.log
mutt -s "database backup" firstname.lastname@example.com  -a /var/www/backup/renko_backup_$NOW.sql.gz >  /home/renko/mysql_back_log.log
mutt -s "Sunucu yedekleme" firstname.lastname@example.com -a /var/www/backup/renko_backup_$NOW.sql.gz >  /home/renko/mysql_back_log.log

If I use the mysql.backup.sh command as below;
sudo sh /home/renko/mysql.backup.sh

the script works perfectly...
However for some reason crontab doesn't make this script work.
I can't find the log for crontab errors.
Oh and before you ask I added the job in crontab via ;
sudo crontab -e

and restarted cron service via;
sudo service cron restart

I can't seem to find the problem.
I am using Ubuntu Server with kernel 2.6.38-8.
Any advice and pointing to any source would be welcomed.
Comment: how about 45 9 * * * /bin/sh /home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log  ?
Comment: you can try this
* */1 * * * sh /home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log 2>&1

check the log after 2 hours to whether it runs (assume your backup need 2 hrs)
Comment: @Tommy I'm sorry to say both did not work :(
Answer: A couple of things to check. You don't need the sh as commands in a crontab are passed to a shell anyway. Your particular problem can probably be fixed using the -c flag e.g.
45 9 * * * sh -c "/home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log"

This tells sh to read the commands from the command string rather than stdin.
Normally you would use
45 9 * * * /home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log

Update 1:
I think part of your problem is that you are redirecting the output of the script in your crontab and you are then redirecting the output of various commands to the same file. Remove the output redirection to the log file from within the script.
Update 2:
From the comments.
Check that your user has permissions to write to the directory containing the log file. Also check that your user has at least x permission on the directories in the path to your log file.
Comment: I tried what you have told me however it did not work. I have tried both versions :( and no cigar.
Comment: are you sure you reset the server clock to 9:45 ?
Comment: no what i did is that i changed the cron clock to 10:45 which was a few moments ago. Its now "Tue Oct 18 10:48:39 EEST 2011
" according to the "date" command. Just for extra information : I have set the cron job to "45 10 * * * /home/renko/mysql.backup.sh > /home/renko/mysql_back_log.log"
Comment: Put some echo commands in it to debug it.
Comment: All of your redirections are `>` they should be `>>`.
Comment: @Iain even "mysqldump -u root -h localhost --all-databases | gzip -9 > /var/www/backup/renko_backup_$NOW.sql.gz" ???
Comment: Perhaps not that one.
Comment: Sorry still does not work... :(
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1605/discussion-between-johnroach-and-iain)
Answer: While we're checking stuff, could we go lowest-common-denominator?  Put in crontab
* * * * *  /bin/touch /tmp/nose

If you could first do a /bin/touch /tmp/nose ; ls -al /tmp/nose ; rm /tmp/nose so we can verify /tmp exists and is world-writeable (you'd be surprised), then we can at least say whether cron is the issue, or something peculiar to your script.
Edit: OK, that's progress.  Now, can we address the timing of your script?  Could you add
45 9 * * *  /bin/touch /tmp/toes

to your crontab?  That way, we can confirm that cron thought that things that should go off at that time, like your script, really were supposed to go off.
Comment: yeah it is world readable... So I am expecting my nose to be touched every 1 minute... And the result is : YAY! I can touch my nose... It seems the problem is in my script?? Could you please proof read my script if it won't be much of a bother? Because I can't find what's wrong with it... After all it does work when I call it as "sudo sh /home/renko/mysql.backup.sh"
Comment: See edit above.
Comment: Thank you for your answer. I just found the problem. It was permission problem. @Iain has helped me solve it. Thank you again.

Crontab doesn't start, no errors


Algebraic 1-cocycles and Galois gerbs

Question: We have the following set up: $K/F$ is Galois, $D$ is an algebraic group of mult. type and $E$ is an extension of groups:
$$1\to D(K)\to E\to Gal(K/F)\to 1$$
Now take a linear algebraic group G over F. An algebraic 1-cocycle is a map $w \mapsto x_w$ from $E$ to $G(K)$ s.t.  $x_{w_1 w_2}= x_{w_1} w_1(x_{w_2})$, where $E$ acts on $G(K)$ via $E\to Gal(K/F)$.
Furthermore we have a Galois action on morphisms $v:D(K)\to G(K)$ via $\sigma(v)(d)=\sigma(v(\sigma^{-1}(d))$ (cf here section 2.2/2.3 for more details).
In the above paper it is claimed then that for $w\in E$ which maps to $\sigma$
$$x_w\cdot\sigma(v)\cdot (x_w)^{-1}=v$$
as a cosequence of the cocycle condition. Here $v$ is the restriction of the cocycle to $D$ (i.e. $v(d)=x_d$).
But my calculation only gives me:
$$(x_w\cdot\sigma(v)\cdot (x_w)^{-1})(d)=x_w\cdot\sigma(x_{\sigma^{-1}(d)})\cdot (x_w)^{-1}=x_{w\sigma^{-1}(d)}\cdot \sigma( x_{w^{-1}}) =x_{w\sigma^{-1}(d)w^{-1}}$$
and I am not able to conclude the desired result.
Answer: It seems to me that Kottwitz's review of the notion of Galois gerb used by Langlands and Rapoport was not meant to be competely self-contained, and that it was meant only to highlight differences of a technical nature. In particular---even though he does not review this point---for any Galois gerb $E$, the induced conjugation action of $G(K/F)$ on $D(K)$ is required to coincide with the standard Galois action. In other words, given an element $w$ in $E$ that maps to $\sigma$ in $G(K/F)$, we require that$$wdw^{-1} = \sigma(d)$$for all $d$ in $D(K)$. Here the left-hand side is conjugation in the group $E$, while the right-hand side is the standard Galois action of $\sigma$ on $D(K)$. The requirement that this equality hold is part of the definition of Galois gerb.
For this reason the subscript$$w\sigma^{-1}(d)w^{-1}$$occurring at the far right end of your calculation simplifies to $d$.
Comment: Yes, I already assumed these two actions to coincide, but I was not sure if this was just per definition.

Algebraic 1-cocycles and Galois gerbs


Find the latest string based on time and display those

Question: I have a text file as shown below:
testdatabase-21-07-15-12-00
testdatabase-21-07-15-18-00
testdatabase-21-07-15-23-00
testdatabase-22-07-15-12-00
testdatabase-22-07-15-18-00
testdatabase-22-07-15-23-00
and many more like this (dynamically generated)

I am comparing (21/22-07-15) with another text file and if a match is found, I need to see which is the latest one. Like, if match is found for date 21-07-15, I need to retrieve the latest (which is 23) from the many of 21. Same as the case for 22,.... if match is found.
What I have done so far is:
$temp = Get-Content "C:\RDS\temp.txt"
foreach($te in $temp)
{
 $t = $te -split '-'
 $da = $t[1]
 $mo = $t[2]
 $yea = $t[3]
 if("$da-$mo-$yea" -match $temp1)
 {
  # need to write the concept here
 }else
 {
  #nothing
 }
 }

How can I get this done.? Any help would be really appreciated.
Answer: I think you need new approach. If parse your file to hashtable then you will be able to receive last date+time by date.
# I use string variable for debugging
$temp = "testdatabase-21-07-15-12-00
testdatabase-21-07-15-18-00
testdatabase-21-07-15-19-00
testdatabase-21-07-15-20-00
testdatabase-21-07-15-21-00
testdatabase-21-07-15-23-00
testdatabase-22-07-15-12-00
testdatabase-22-07-15-13-00
testdatabase-22-07-15-14-00
testdatabase-22-07-15-15-00
testdatabase-22-07-15-18-00
testdatabase-22-07-15-23-00" -split "`r`n"

# parse $temp to hashtable by date
$hash = @{}
foreach ($te in $temp) {
    if ($te -match "testdatabase-(\d\d-\d\d-\d\d)") {
        [Array]$hash[$Matches[1]] += $te
    }
}

Now $hash look like:
Name       Value
----       -----
21-07-15   testdatabase-21-07-15-12-00
           testdatabase-21-07-15-18-00
           testdatabase-21-07-15-19-00
           testdatabase-21-07-15-20-00
           testdatabase-21-07-15-21-00
           testdatabase-21-07-15-23-00

22-07-15   testdatabase-22-07-15-12-00
           testdatabase-22-07-15-13-00
           testdatabase-22-07-15-14-00
           testdatabase-22-07-15-15-00
           testdatabase-22-07-15-18-00
           testdatabase-22-07-15-23-00

After these manipulations you can access to array by key like <day>-<month>-<year> and get latest element from it:
$temp1 = "21-07-15"

if ($hash.ContainsKey($temp1)) {
    $array = $hash[$temp1]
    # last element in array
    $last = $array[$array.Length - 1]

    Write-Host $last -ForegroundColor Blue
}

Output:
testdatabase-21-07-15-23-00

Comment: But I wont know what all dates are there in that dynamic file. If that is the case how can I say $temp1 = " somevalue " exactly...
Answer: I used a custom object to organize the list with 3 properties: filename, full date, date only. The date values are cast and stored as actual [datetime] vars. With that true time, you can use native powershell grouping and sorting functions to get the most recent file for each day.
I'm located in the US, where my OS defaults to mm/dd/yy. If your region has different defaults, you may need to adjust the right side of the var assignment for $dateFull and $dateOnly.
$crossref = @()
gc dates.txt | foreach {
    ($name, $day, $month, $year, $hour, $minute) = $_.split("-")
    $dateFull = [datetime]"$month/$day/$year $hour`:$minute"
    $dateOnly = [datetime]"$month/$day/$year"
    $crossref += New-Object PSCustomObject -Property @{"fileName" = $_; "dateFull" = $dateFull; "dateOnly" = $dateOnly;}
}
# raw unsorted data from our new object
$crossref | ft -a

# most recent file for each day
$crossref | group-object dateOnly | foreach {$_.Group | Sort-Object dateFull | Select-Object -Last 1} | fl

PS C:\temp> .\fault.ps1
dateFull           dateOnly          fileName
--------           --------          --------
7/21/2015 23:00:00 7/21/2015 0:00:00 testdatabase-21-07-15-23-00
7/22/2015 23:00:00 7/22/2015 0:00:00 testdatabase-22-07-15-23-00
7/21/2015 12:00:00 7/21/2015 0:00:00 testdatabase-21-07-15-12-00
7/21/2015 18:00:00 7/21/2015 0:00:00 testdatabase-21-07-15-18-00
7/22/2015 12:00:00 7/22/2015 0:00:00 testdatabase-22-07-15-12-00
7/22/2015 18:00:00 7/22/2015 0:00:00 testdatabase-22-07-15-18-00

dateFull : 7/21/2015 23:00:00
dateOnly : 7/21/2015 0:00:00
fileName : testdatabase-21-07-15-23-00

dateFull : 7/22/2015 23:00:00
dateOnly : 7/22/2015 0:00:00
fileName : testdatabase-22-07-15-23-00


Convergence of subsequence of partial sums implies full convergence?

Question: Define $S_n = \sum_{j=1}^n a_j$ a sum of real numers.
Suppose there is a subsequence such that $S_{n_j} \to S$ for some $S$, i.e., the infinite sum converges along this subsequence. Does this imply that $S_n$ converges too?
It seems like it should, since it's simply an index which is increasing but there may be a counterexample I can't think of..
Comment: If all the terms $a_j$ are positive, then it is true.  Since $S_n$ is then an increases sequence which converges if and only if it is bounded, if and only if a subsequence is bounded (since it's increasing).
Answer: No, if e.g. $a_j = (-1)^j$ then $S_{2k} = 0$ for all $k$ but the series itself does not converge.
Comment: If it is Cauchy I think it does.
Comment: @Johan   The sequence $S_n$ is not cauchy.  It's $-1$ for odd indexes, and $0$ for even indexes.  Cauchy sequence must have elements that get close to each other.
Comment: @maddib I know it was just a remark to the case when it holds.
Comment: @Johan  Understood.
Comment: @Johan do you mean when $a_n$ are cauchy?  Because even that doesn't work (if you are only asking about arbitrary subsequencs), you can just take $a_j$ to be $n^2$ copies of $1/n^2$ and then $n^2$ copies of $-1/n^2$, etc...  [edit: Actually, now I think about it, I think you meant when $S_n$ are cauchy and you have a convergent subsequence, which is true]
Comment: Isn't it true if you have $a_j \rightarrow 0$ and $S_{2n}$ converges (ie, only consider subsequences that have a bounded distance from one index to the next)
Comment: Yes, it's true if $a_j\to0$ and $S_{2n}$ converges.


Survival analysis cox model and accelerated failure time (AFT) variable selection

Question: I'm reading a paper about survival analysis. After doing the univariate analysis, the paper only put covariates which have significant results in the univariate analysis into the multivairate regression.
My questions are:

Is it the right way to include only significant covariates in the multivariate regression?

2.If not, for survival analysis, what are the best variable selection methods for cox model and aft models? And is there any recommended packages in R?
Answer: The method you are describing is known as bivariate screening. It is a very common method, but not a good one. For details, see Frank Harrell's book Regression Modelling Strategies but, briefly, all the output will be off: Standard errors will be too low, p values too low, parameter estimates biased away from 1.00, etc.  Worst of all, using an automatic method prevents the analyst from thinking.
The best method is to use substantive knowledge. If you must use an automated method, LASSO is more reasonable than bivariate screening (or forwards or backwards or stepwise).


How to deploy Azure Webjob from Azure DevOps to wwwroot\App_Data\jobs\triggered\MyWebJob?

Question: I have a release pipeline for a web app. Now I want to release also webjobs from the same solution. But if I publish a webjob after I have published a web app, it will publish it to wwwroot and overwrites my web app. How should I configure release pipeline to deploy webjob to wwwroot\App_Data\jobs\triggered\MyWebJob, not to wwwroot?
Somewhere was an answer to build and publish whole solution and webjobs will be also deployed successfully. But I am not able to build and publish the whole solution. I have to pick just some of the projects (csproj).
Comment: Does these help?
https://stackoverflow.com/questions/50045752/how-do-you-deploy-an-azure-webjob-and-app-to-the-same-app-service-via-vsts/50046561#50046561

https://stackoverflow.com/questions/45688605/deploy-azure-webjob-using-vsts/46661421#46661421
Comment: Are your web app and web job project on the same repository/solution? If yes right click on the web app project, add webjob, from existing project, select your webjob project. Visual studio is going to package the webjob with the web app automatically during the package app step. No need to have a separate step for the webjob
Comment: @baywet How that should be done? Those are in the same solution. But is there a way to add project to other project? In my case webjob.csproj to webapp.csproj. I tried following but didn't work: right click on webapp.csproj -> add existing item (there isn't any "add existing project", because this is a project not solution) -> webjob.csproj. But output doesn't include "webjob.exe".
Comment: @PanuOksala I have tried those but seems that they aren't same as my problem. But probably I'll find some hints from there also.
Comment: Just to make sure, you are using visual studio 2017 and you have the azure components selected?
Answer: If I'm understanding you correctly, you have a web project along with two web jobs that you want to deploy to Azure App services using Azure Dev Ops. If that's the case, I would suggest deploying your web jobs to separate app services. If your app service is under a standard or premium plan, you can leverage deployment slots. The Visual Studio Build task will zip up your projects for Web Deploy so on the release side of the pipeline you'll simply select the project zip file from the artifact for the Azure App Service Deploy.
Hope this helps.


PHP Variables and its checking for null with some discipline

Question: i want some hints for php
Here is my variables like this
$error;
$a=$_POST["sdf"];
$b=$_POST["dsf"];
$c=$_POST["ssdfsdfdf"];
$d=$_POST["ssdfsddf"];
$e=$_POST["sdfsdfdf"];
$f=$_POST["sfsdfsdf"];
$g=$_POST["sdsdff"];
$g=$_POST["sdsdfsdff"];

I want to check whether those variables are empty or not and dispaly message like this
if(empty($a)){
$error.="Hey you missed the $a "; // $a value
}

now i have to repeat all those codes ...
Imagine i have more than 40 variables can i get some hints to short that code
i tried switch statement but it's not working ..i want to display all error message of anyone variable is missing...
Regards
Answer: $required = ["sdf", "dsf", "ssdfsdfdf"]; //etc. etc.
$arr = [];
//Loop through and santize input.
foreach($_POST as $key => $value)
{
    //sanitize input here

    //store in array
    $arr[$key] = $value;
}

//check empty
foreach($arr as $key => $value)
{
    if(in_array($key, $required)
    {
       if(empty($value))
       {
           throw new Exception("One of the required attributes is empty");
       }
    }
}

Comment: why do you store `$_POST` array into another array ?
Comment: Great idea thanks for giving a best solution and thanks to ling.s as well
Comment: @krishna Not necessary, you can directly process $_POST array
Comment: @ling.s that what i am asking.for what reason he chose it where there is more simpler option available
Comment: @leemo can you say how to diplay message like this $a is missing or $b is misssing like that ?
Comment: @user3689984 instead of `throw new Exception` just add `print($key . " is missing")`. Regarding storing the `$_POST` array in a new array, its force of habit and as ling.s suggested, it is not strictly necessary I just dont like directly working with superglobals, storing in a new array keeps me certain that I have properly sani
tized the input
Answer: Don't assign to a variable. You can process the POST array directly
foreach($_POST as $value) {
if(is_array($value)) {
    foreach($value as $val) {
       if(empty($val)){
          $error.="Hey you missed the $val "; // $a value
       }
    }
} else {
     if(empty($value)){
          $error.="Hey you missed the $value "; // $a value
     }
}
}

Comment: @user3689984, see leemo's answer
Answer: If you want to check all POST variables in the page try using foreach like this
foreach($_POST as $key=>$values)
{
if($values == "")
echo "Hey you missed out ".$key;
}

Note: Use sensible naming in key(POST variables) so that it helps in displaying message


Editors choose layout

Question: I want to give editors the ability to take advantage of a grid system we have on our site.  I can easily jump into a node and add this to the Body

one column

content on the left

content on the right

one column

...

Editors aren't savvy enough with HTML and CSS to do this themselves, and that's fine, that's what wysiwyg editors are for, and why we use Drupal in the first place (mainly).
But, this is a system of layout that can be applied consistently on any node. I'd think it would be easy enough to allow editors to take advantage of it. I'd love to let them create as many rows with as many columns as they want on any node without having to code it up themselves.
I know I can create template files that will apply structured HTML to all nodes of a given type, or one node, or some subset of nodes.  However, I don't want to make that choice for editors.  And besides, you can't split up the body content of a node into rows and columns like that from a tpl.php file.
I've looked into Panels too, but from what I can tell that's just a GUI means of creating tpl.php files.  Same problem.
This is very similar to the unanswered question Select Panel Node Layout on Node edit form.  I'm using 7.
Answer: You're asking a chicken and egg problem. Nodes just hold data and no information about the theme (usually). You're describing mixing the two in the Body field of a node, in essence hard-coding the look (layout) of your "node" in the database.
Drupal in many respects fights this as the page content is 1 item and drupal7 cares nothing about whats around it. In D8 their is a UX initiative to make a nicer page layout creation system.
In D7 you may be interested in context_layouts found in Context. See this youtube video on its usage.
I've done something similar (but not Grid aware) using Spaces, spaces_node and Dashboard (spaces dashboard) in Drupal6 per node (I also used node_block heavily). Every node/page could have their own unique layout using Spaces and its submodule of Dashboard; you can set any content to any block/region of the page as needed using a drag-and-drop overlay. Actually, the site I'm mentioning is UCSB SageCenter. Unless your logged in and editing a Space/Dashboard you dont really see anything in the source. I added a node field to pre-assign a known space for node pages on node creation. This site was hard.
Here's a video demo on spaces_node -- its not supported anymore really.
Comment: I like the Context solution, and I find it similar to Panels.  It's great if you just want to take single chunks of content and place them in the same place on every template that governs that content, but that's not really flexible enough for me, I think.
Answer: My advice would be to use Field Collection.

Add a "collection field" and set it as "multiple values". Each value will be a row.
In that collection field, set one text field and one option field (like select list : text)
For that option field, the options will be the regions where the text will be displayed.
Create a Panel for the node, and in each region, place a view that displays the text, filtered by the option field that goes with that region.

EDIT: I just saw that you also wanted "as many columns as they want"... Then you'll have to play with your option field and set it to a numeric value, that you'll use in css or something like that. It will be quite more complicated, but feasible !
Comment: I really like this solution.  What's great is it gives me the flexibility to let editors create as many or as few chunks of structured content.  The content could be a simple text area, or it might be a text area followed by a select list followed by a link.  And I can create a tpl.php to govern the styling of that repeating region (and the rest of the page).  If I want to, I can get really creative and add optional text areas to be displayed above and below the region.  In general I think this option gives me the most flexibility with the least amount of custom tpls and custom content types.
Answer: I'd possibly use something like Context Entity Field in conjunction with Delta and Omega (which it looks like you're using).  You could create a couple of delta templates for a user to choose from, and then put a Context entity field onto your nodes.
Then you set up a couple of Contexts to react based on the value of the Context entity field.
For example:
Contributor one adds some content, and wants to use a delta template you've called "Awesome 6 column layout".  They set the value of their Context entity field to "Awesome 6 column layout".  When they view their content, Context changes the delta template being used!
Comment: Thank you for the suggestion, fwiw I'm actually using a custom child of http://drupal.org/project/ninesixty.
Answer: I think you should give Panels another shot. If you use the Clean Markup module, you can change the markup and classes of Panel panes and regions. allowing you to put grid classes on them.
If you also use Panelizer, you can change the  Panels layout and markup on a per node basis.
Comment: By the way, I _really_ recommend against putting layout markup inside content. It makes responsive design harder to implement and it will give you major headaches when you need to migrate the content later.

Editors choose layout