C++ code example: What makes this loop so many times?

Question: I found a code example here: N-QUEEN Backtracking problem solved
It shows this code:
#include <iostream>
using namespace std;

/** this is the size of chess board */
#define N 8

/** Given a completed board, this prints it to the stdout */
void print_solution(int state[N][N])
{
    int i,j;
    for (i = 0; i < N; ++i)
    {
        for (j = 0; j < N; ++j)
            cout << state[i][j] << " ";
        cout << endl;
    }
    cout << endl;
}

/** return true if placing a queen on [row][col] is acceptable
else return false */
bool accept(int state[N][N], int row, int col)
{
    int i,j;

    /* check the column */
    for (i = 0; i < N; ++i)
    {
        if (state[row][i])
            return false;
    }

    /* check the row */
    for (i = 0; i < N; ++i)
    {
        if (state[i][col])
            return false;
    }

    /* check the upper left diagnol */
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
    {
        if (state[i][j])
            return false;
    }

    /* check the lower left diagnol */
    for (i = row, j = col; i < N && j >= 0; ++i, --j)
    {
        if (state[i][j])
            return false;
    }

    /* check the upper right diagnol */
    for (i = row, j = col; i >= 0 && j < N; i--, ++j)
    {
        if (state[i][j])
            return false;
    }

    /* check the lower right diagnol */
    for (i = row, j = col; i < N && j < N; ++i, ++j)
    {
        if (state[i][j])
            return false;
    }

    /* return true if all tests passed */
    return true;
}

void solve_state(int state[N][N], int row)
{

    int i;

    /* if all queens have been placed at non conflicting positions */
    if (row == N)
    {

        print_solution(state);
        return;
    }

    /* Place queens on all positions in a given row and
    check if the state is acceptable
    Continue the process till all possibilities found */
    for(i=0; i<N; ++i){

        if(accept(state, row, i)){
            state[row][i] = 1;
            solve_state(state, row+1);
        }
        state[row][i] = 0;
    }
}

int main()
{
    /* initialise the board */
    int state[N][N] = {0};

    solve_state (state, 0);

    return 0;
}

I fail rather hard with logic and I have even more trouble trying to learn recursion and such. What really ticks me off is that I just cannot comprehend why this code loops through all the 92 solutions of the 8 queens in chess problem. At first I thought it only found one solution but I was surprised once I tested the code and it ran all the possible solutions.
I must be missing something very basic here because I've even attempted to make it "stop" after just one solution but I just fail.
So I suppose what I am asking here is that in order to understand this, given this code, if I just wanted it to loop through once, and find the first solution, what would need to be changed? What kind of sorcery makes this thing loop all these times?!
Comment: There are so very many programs out there that will auto-indent c++ code for you.
Comment: You really shouldn't be that lazy: if you format the code as expected you might get more 'readers' and a good answer.
Answer: /* Place queens on all positions in a given row and
check if the state is acceptable
Continue the process till all possibilities found */
for(i=0; i<N; ++i){

    if(accept(state, row, i)){
        state[row][i] = 1;
        solve_state(state, row+1);
    }
    state[row][i] = 0;
}

This loop does exactly what you described. You are looping on the eight column of a row, thus giving the eight possibilities. If you want to stop on the first acceptable state, you have to update the inner condition and remove the recursive call. Instead you can call your print_solution function to print the result.
This gives you something like:
for(i=0; i<N; ++i){

    if(accept(state, row, i)){
        state[row][i] = 1;
        print_solution(state);
        return; // this prevents printing the solution multiple times
                // in case the queen may be placed on other colum on the same row
    }
    state[row][i] = 0;
}

Side note: for me this code is a C code (variables declared at the beginning of the functions, plain old C arrays, use of int where a bool would do the job), and the only C++ part is the use of std::cout and std::endl in the print_solution function, which can easily be replaced by a good-old printf.
Comment: Your code doesn't even begin to work.  You have removed the recursion.  It just prints the first partial solution (one queen in position 1 in row 1) and exits.
Comment: " I just wanted it to loop through once, and find the first solution, what would need to be changed?" -> my code stops after the first solution, no ?
Comment: No. To generate a solution requires recursive descent into solve_state N times.  `accept(state, row, i)` just checks whether a queen can be placed into row `row` in position `i`.  So your function returns after putting a Queen in the first position in the first row.
Comment: You know that you can place a lot of additional recursion if you want ?
Answer: The first step to understanding a recursive method is to verbalize what the method does, like this:
/** solve_state(state, n) finds all possible solutions given a state where
 * the first n rows already have legally placed queens
 */

Then examine the body of the method and verbalize it:
/**
 * if n == N we're done, there is a queen in every row.  print the solution.
 * otherwise for every legal spot in the current row,
 * put a queen there, and then solve the remaining rows.
 */

One very easy way to have the program exit after printing one solution is to throw an exception after printing the solution.
Or, perhaps more elegantly, you could modify solve_state to return 1 when it finds a solution, and stop the recursion that way:
int solve_state(int state[N][N], int row)
{
    int i;

    /* if all queens have been placed at non conflicting positions */
    if (row == N)
    {
        print_solution(state);
        return 1; // done!
    }

    /* Place queens on all positions in a given row and
       check if the state is acceptable
       Continue the process till all possibilities found */
    for(i=0; i<N; ++i){
        if(accept(state, row, i)){
            state[row][i] = 1;
            if (solve_state(state, row+1)) return 1;
        }
        state[row][i] = 0;
    }

    return 0; // not yet
}

Answer: Maybe my code will help you, I'm not the best English speaker...
//coded by SwinGYOu

#include<iostream>
#pragma warning(disable:4996)
using namespace std;

/* this is the size of chess board */
const int boardSize=8;

/* Given a completed board, this prints it to the console */
void print_solution(int board[boardSize][boardSize], int i=0, int j=0){
    if(i==boardSize){ cout<<endl; return; }
    if(j==boardSize){ cout<<endl; print_solution(board, ++i, 0); return; }
    cout<<"[";
    if((i+j)%2)
        putwchar(board[i][j] ? '\u2655' : ' ');
    else
        putwchar(board[i][j] ? '\u265B' : ' ');
    cout<<"]";
    print_solution(board, i, ++j);
}
/* Check up, up left and up right to veritify that there are no other Queens, return true if right */
bool accept(int board[boardSize][boardSize], int row, int col, int rowD=0, int colD=0){
    if(!(rowD||colD)){
        return
            accept(board, row, col, -1, 0)&&
            accept(board, row, col, -1, -1)&&
            accept(board, row, col, -1, 1);
    }
    if(!(row>=0&&col>=0&&row<boardSize&&col<boardSize)){
        return true;
    }
    if(board[row][col]==1) return false;
    return accept(board, row+rowD, col+colD, rowD, colD);
}
/* check and return sultions for every sultion that possible*/
void solve_board(int board[boardSize][boardSize], int row=0, int col=0){
    //if the row befor was the last row of the table, its meants that is a sultion, print it.
    if(row==boardSize){
        print_solution(board);
        return;
    }
    //if col is out of the board, dont run check on it, its not a vaild path.
    if(col==boardSize) return;
    //run for this, if true, go to next row until end of row's or until a not vaild row is given than carry on with checking the next col.
    if(accept(board, row, col)){
        board[row][col]=1;
        solve_board(board, row+1);
    }
    board[row][col]=0;
    //carry on to next spot on the col in the given row.
    solve_board(board, row, col+1);
}

int main(){
    /* Make board */
    int board[boardSize][boardSize]={0};

    solve_board(board);

    return 0;
}


launch button every 2 hours without click

Question: I need to launch the web page every 2 hours without click the button and every time the old page web should be closed to open the new one.
this the html page:

@using (Html.BeginForm("Import", "Monitoring", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.Raw(ViewBag.Error)

    <input type="submit" value="Launch" />
}

this is my Import method:
string path4 = "D:/Project/TProdPlan.xlsx";

Excel.Application application4 = new Excel.Application();
Excel.Workbook workbook4 = application4.Workbooks.Open(path4);
Excel.Worksheet worksheet4 = workbook4.ActiveSheet;
Excel.Range range4 = worksheet4.UsedRange;
List<TProdPlan> ListTProdPlan = new List<TProdPlan>();
for (int row = 2; row <= range4.Rows.Count; row++)
{
     TProdPlan S = new TProdPlan();
     S.Num= (((Excel.Range)range4.Cells[row, 1]).Text);
     S.stat = (((Excel.Range)range4.Cells[row, 2]).Text);
     ListTProdPlan.Add(S);
 }

ViewBag.ListTProdPlans = ListTProdPlan;

//close excelsheet after reading data
workbook4.Close(0);
application4.Quit();

return View("Monitoring");
}

this is the "Monitoring View"

Total Seasame Tickets Status (From 16/04 To 22/04)

            Number
            Status
            Color Code

                @foreach (var Ts in ViewBag.ListTsesames)
                {

                        @Ts.Number
                        @Ts.Status
                       @if (@Ts.Status == "Resolved")
                       {

                       }
                       else if (@Ts.Status == "Opened")
                       {

                       }
                       else if (@Ts.Status == "Assigned")
                       {

                       }
                       else if (@Ts.Status == "PendingCustomer")
                       {

                       }
                       else if (@Ts.Status == "Closed Complete")
                       {

                       }

                }

Total is : 115

Answer: You can submit using javascript/jquery, but if you only want to redirect a user from one page to another just use
window.location = "http://www.yoururl.com";

javascript/jquery allows you to use timers and in the fire event of the timer you can just add the redirection code I mentioned.
 setInterval(yourfunction, 1000*60*60*2);

Comment: Post your code that you tried and we will have a look at it
Comment: i need to refresh the web page every 1 hour, i extract the data from the excel sheet and i display it in "Monitoring" view.
Comment: i used this code before `HttpContext.Response.Headers.Add("refresh", "120; url=" + Url.Action("Import"));` but the web page can't be refreshed
Comment: you are trying to redirect the user from server side... this will be difficult because the user will have to request something to get to the server... rather do it on client side code(with javascript) like the code snipet examples that i provided


How to change format of DateTime reading into chart.js chart?

Question: Currently the DateTime is being read into chart.js from a SQL database using this line of code:
var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Select(x => x.DateTime).ToList());

The format of the DateTime is shown like this:
2019-05-14T15:30:02.703

I would like for the T to be removed as well as the milliseconds from this as it's making the graph look messy.
I currently have the data also reading into a table and it appears like this:
12/04/2019 23:01:01

This is how I would like it to appear in the charts as well.
Comment: Remove it on the client side, where you are reading/deserializing json data
Comment: Just look intothis https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
Comment: https://www.chartjs.org/docs/latest/axes/cartesian/time.html
Comment: `DateTime` has no format at all. It's a binary value, just like byte or int. Formats apply *only* when it's converted to a string, or parsed from a string. The defacto standard for date *strings* in JSON is ISO 8601, ie `2019-05-14T15:30:02.703` which Javascript has no trouble using and parsing into its own `Date`.
Comment: If you want to change how a *chart* works, you'll have to modify the *chart's* settings. What does your Javascript code look like? Have you set a format string for the X labels?
Comment: [This possibly duplicate](https://stackoverflow.com/questions/20371867/chart-js-formatting-y-axis) question shows how to format axis labels using your own function
Answer: Welcome.
Try formatting it like this to get your output as you require:
DateTime.Now.ToString("dd/MM/yy HH:mm:ss")

Did you try searching this in the stack overflow or google before putting the question up here? In the future, try searching out as this is a duplication of couple of questions like these: C# DateTime to "YYYYMMDDHHMMSS" format
You should be able to make your own answers from them. Have a nice day.
Comment: @BFieldy DateTime has no format, it's a binary value. JSON has a defacto standard date format, ISO8601. You'll get into trouble only if you try to use your own non-standard format
Comment: Thanks, I was converting to datetime and it was causing the formatting issue.


Why am i getting this exception error ? ArrayOutOfBounds?

Question: I'm trying to check if the integers in an array are increasing. But I'm getting ArrayOutOfBounds exception, and I do not understand why. I'm new to programming.
for (int i =0; i > newArray.length ; i++){
    if (newArray[i] > newArray[i+1]){
        System.out.println("Not increasing");
    }
}

Thank you for your help.
Comment: The loop condition should be `i < newArray.length`, but actually the loop should not even be executing for a non zero sized array.
Comment: the stop condition shd be i < newArray.length. Additionally, newArray[i+1] is accessed, so in fact it shd be i < newArray.length-1.
Comment: @TimBiegeleisen yeah thanks i copied the wrong code from my IDE .
Answer: Let's say your array length is 8 so the positions are from 0 to 7
In the last run of the for loop i=7 and i+1 =8
You don't have newArray[i+1]
You should put the first if inside a new if
if(i<(newArray.length - 1)){
if (newArray[i] > newArray[i+1]){
System.out.println("Not increasing");
}
}

Answer: the ArrayOutOfBounds exception happens when you are trying to access a non-existent position in the array.
The problem in your case is the newArray[i+1] which tries to access a position non-existent in your array.
I recommend editing the condition i < newArray.length-1 : There are, of course, other ways to fix this but this is the easiest.
Comment: i understand the exception but i did not think of this, thank you, it works now


How to reuse reviewed documents in further translations?

Question: Our instruction manual is in markdown format. We improve the manual daily or weekly and then we would like to translate to other languages. Until now, this process is manual and we use TRADOS (a assisted translation software)
We are studying to improve the process. What we want to do is to translate it using Microsoft translator and then a human reviewer do the fine tune. The problem is how we can reuse the corrected document in Microsoft Translator for the next translation.
Many times we only change 2 or 3 words of a topic and then the translator would create a complete new translation, doing the reviewer work very tedious if the translation is not accurate.
I know that we can train the model, but I think that there is not a 100% of probabilities that the translator uses the review. Also, it seems very time consuming to maintain the distortionary after reviewing the document.
I was wondering if somebody has solved this kind a problem.
Answer: We can automate the translation of the document using Microsoft Flow. In Microsoft flow we can use the SharePoint service to store the file which we need to translate and then we can create a flow of operation.

Need to create a folder in SharePoint and mention the site address
Mention the folder name and to which language you need to translate it when the file is available in the SharePoint folder
Give the destination folder. Again, it can be a SharePoint folder.

Note: Can't assure that the meaning after translation will be the same as the original statement.
Answer: You are looking for a translation memory system (TMS). A TMS will store your human edits to documents and reapply them to future translations of documents where a paragraph is repeated. A TMS will also help your human translator find close matches of a new segment with a previously translated one, highlighting the change the human will have to perform.
Most TMSes integrate machine translation systems like Microsoft Translator and others as a suggestion to the human editor, who can then approve or edit the suggestion.
https://en.wikipedia.org/wiki/Translation_memory
When selecting a TMS here are some features to consider:

Integration with the content management system (CMS) your business uses for storing, maintaining and publishing documents
Collaboration: Multiple people working on a shared set of documents
Workflow management: Initiate a translation job, track the progress of it, and execute payments to the collaborating humans
Ease of use and translator acceptance of the human-facing CAT component of the TMS
Pretranslate with your favorite machine translation system from inside the TMS

Once you have collected a significant amount of domain-specific human translations, you can train a custom translation system directly from the content of your TMS, tuning future machine translations in the direction of the terminology and style that are exemplified by your human translations.
Answer: You said you already use Trados.  So why don't you create a Translation Memory in Trados, and save your corrected work to that Translation Memory.  Then the next time you create your project in Trados, presumably also using the MS Translator plugin that is freely available from the RWS AppStore you will pre-translate using your translation memory AND MS Translator.  Any work you translated before and is in your translation memory will be used in preference to the machine translation result.
If you have the professional version of Trados you can also use Perfect Match.  If you do this then when you receive your updated document with only a few words to change you match it against the bilingual file from your previous translation.  Everything that remains the same receives a Perfect Match status and is optionally locked making it simple to identify what needs to be changed by the translator.


A cool integral: $\int^{\ln{\phi}}_{0}\ln\left(e^{x}-e^{-x}\right)dx=-\frac{\pi^2}{20}$

Question: I was looking at the equation $\ln{e^{x}-e^{-x}}$ and found that the zero was at $x=\ln{\phi}$ where $\phi$ is the golden ratio. I thought that was pretty cool so I attempted to find the integral. I am currently at the beginning of Calculus BC so it is definitely over my skill level. Here was my attempt:
$$\int^{\ln{\phi}}_{0}\ln\left(e^x-e^{-x}\right)dx$$
$$\int^{\ln{\phi}}_{0}\ln\left(\frac{e^{2x}-1}{e^x}\right)dx$$
$$\int^{\ln{\phi}}_{0}\left(\ln\left(e^{2x}-1\right)-\ln\left(e^x\right)\right)dx$$
$$\int^{\ln{\phi}}_{0}\left(\ln\left(e^{2x}-1\right)-x\right)dx$$
$$\int^{\ln{\phi}}_{0}\ln\left(e^{2x}-1\right)dx-\frac{\phi^2}{2}$$
$$\int_{0}^{\ln\phi}\ln\left(e^{x}+1\right)dx+\int_{0}^{\ln\phi}\ln\left(e^{x}-1\right)dx-\frac{\phi^2}{2}$$
I can't figure out how to solve these two integrals I am left with (integration by parts doesn't seem to work). Wolfram Alpha says to use polylogarithms but I was hoping there would be a method that there would be an approach to solving it that I could understand.
Comment: It's more cool writing down like this: $\displaystyle \int_0^{\ln\varphi}\ln(2\sinh x)dx$
Answer: \begin{align}J&=\int^{\ln{\phi}}_{0}\ln\left(\text{e}^{x}-\text{e}^{-x}\right)dx\\
&\overset{u=\text{e}^x}=\int_1^\varphi \frac{\ln\left(u-\frac{1}{u}\right)}{u}du\\
&=\underbrace{\int_1^\varphi \frac{\ln(u^2-1)}{u}du}_{z=u^2-1}-\int_1^\varphi \frac{\ln u }{u}du\\
&=\boxed{\frac{1}{2}\underbrace{\int_0^{\varphi}\frac{\ln z}{z+1}dz}_{=A}-\frac{1}{2}\ln^2\varphi}\end{align}
On the other hand,
\begin{align}J&=\int_1^\varphi \frac{\ln(u^2-1)}{u}du-\frac{1}{2}
\ln^2\varphi\\
&=\underbrace{\int_1^\varphi \frac{\ln(u-1)}{u}du}_{z=u-1}+\underbrace{\int_1^\varphi \frac{\ln(u+1)}{u}du}_{\text{IBP}}-\frac{1}{2}
\ln^2\varphi\\
&=\int_0^{\frac{1}{\varphi}}\frac{\ln z}{1+z}dz-\int_1^{\varphi}\frac{\ln z}{1+z}dz+\frac{3}{2}\ln^2\varphi\\
&=\int_0^1 \frac{\ln z}{1+z}dz-\underbrace{\int_{\frac{1}{\varphi}}^1\frac{\ln z}{1+z}dz}_{w=\frac{1}{z}}-\int_1^{\varphi}\frac{\ln z}{1+z}dz+\frac{3}{2}\ln^2\varphi\\
&=\int_0^1 \frac{\ln z}{1+z}dz+\int_1^{\varphi}\frac{\ln z}{z(1+z)}dz-\int_1^{\varphi}\frac{\ln z}{1+z}dz+\frac{3}{2}\ln^2\varphi\\
&=\int_0^1 \frac{\ln z}{1+z}dz-2\int_1^{\varphi}\frac{\ln z}{1+z}dz+2\ln^2\varphi\\
&=3\underbrace{\int_0^1 \frac{\ln z}{1+z}dz}_{=-\frac{\pi^2}{12}}-2\int_0^{\varphi}\frac{\ln z}{1+z}dz+2\ln^2\varphi\\
&=\boxed{2\ln^2\varphi-\frac{\pi^2}{4}-2A}\\
\end{align}
Therefore,
\begin{align}4J+J&=\left(2A-2\ln^2\varphi p\right)+\left(2\ln^2\varphi-\frac{\pi^2}{4}-2A\right)=-\frac{\pi^2}{4}\\
J&=\boxed{-\frac{\pi^2}{20}}
\end{align}


$\pi (x) = -1 + \pi(\sqrt x) + \sum \mu (d)\lfloor \frac {x}{d}\rfloor$,

Question: Sorry about the title i didn't know what to call this other than "analytic number theory"
I am asked to show that $\pi (x) = -1 + \pi(\sqrt x) + \sum \mu (d)\lfloor \frac {x}{d}\rfloor$, where the sum is over all d for which ever prime factor is less or equal to $\sqrt x $
The furthest right hand part of the equation looks like a mobius inversion but im not sure how to do it over root x and the rest i am completely lost on.
Comment: "Analytic number theory" is the part where you use analytic functions of a complex variable, like Riemann zeta. Everything else is called "elementary number theory", though most of it is very far from being elementary in the usual sense of the word. And no, that's not Moebius inversion, though it's expressing the same principle of inclusion/exclusion.
Answer: This should be Legendre's formula for computing $\pi(x)$:
$$
\pi(x)=-1+\pi(\sqrt{x})+\lfloor x \rfloor-\sum_{p_i\le a}\left\lfloor \dfrac{ x }{(p_i)}\right\rfloor+\sum_{p_i<p_j\le a}\left\lfloor\dfrac{ x}{(p_ip_j)}\right\rfloor-\sum_{p_i<p_j<p_k\le a}\left\lfloor \dfrac{x}{(p_ip_jp_k)}\right\rfloor+\dots
$$
This is proved there.
Comment: thanks for the post i actually did get the argument already thanks.
Answer: I don't believe this is true. Take $x=25$.
$\pi(x)=9$, $\pi(\sqrt{x})=3$.
The relevant $d$s are $2, 3, 5$ together with their square-free multiples, that is $6, 10, 15, 30$. The factor $\lfloor \frac {x}{d}\rfloor$ kills the participation of $15$ and $30$.
For the rest we get $$9=-1+3+(-12-8-5+4+2)$$
which is wrong, right?
Comment: You forgot 1! That's +25 And the floor of 25/15 is one
Comment: @Faust Yes, the numbers 2, 3, 5, 6, 10, 15, 30 are those only made of the primes 2, 3, 5, and also square free otherwise $\mu$ is $0$ and there is no contribution.
Comment: @Faust Silly me :)


How to setup a base URL and where do I declare it?

Question: I am confused as to where I should setup a base URL. Currently I am calling the URL and its extensions as they are:
For example:
$(document).on("pageinit", "#login", function () {
    $("#form2").on("submit", function (event) {
        $.ajax({
            type: "GET",
            url: "http://www.websiteurl.com/public/account/login/", //the full url
            data: $("#form2").serialize(),
            success: function (data) {
                if (data.loggedIn) {
                    alert("logged");
                } else {
                    alert("not logged");
                }
            }
        });
    });
});

From my understanding base URL is a string and I just concatenate information to that string such as:
var baseUrl = "http://www.websiteurl.com/";

$(document).on("pageinit", "#login", function () {
        $("#form2").on("submit", function (event) {
            $.ajax({
                type: "GET",
                url: baseUrl + "public/account/login/", //using baseUrl
                data: $("#form2").serialize(),
                success: function (data) {
                    if (data.loggedIn) {
                        alert("logged");
                    } else {
                        alert("not logged");
                    }
                }
            });
        });
    });

But I believe I am doing it wrong and some sites talk about using PHP to declare baseurl. can I get some advice on how to do that and where should I declare the base URL string.
As a <base> at the HTML page or as a String on the js file? Thanks.
Comment: http://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag
Comment: you can use  or your second example var baseUrl to set it. No need to declare nothing in php. Or just use the full url, baseUrl is not mandatory
Answer: You don't need to specify the full base url.
change:
url: baseUrl + "public/account/login/",

to:
url: "/public/account/login/",

and it should continue to work.

consider the following: http://localhost/test.php
test.php
<?php

// GET Handler
if (isset($_GET['loadData']))
{
    exit('Got your request');
}

?>

Comment: It doesn't work. Where should I place the baseurl. As you can see I am currently declaring that as a normal string.
Comment: This may not work if the `baseURL` is something like `http://www.websiteurl.com/test/`.
Comment: And to be honest I don't see any real difference between declaring full url and baseurl + extension.
Comment: I've updated my answer with example scenario. It does work without specifying the base url and using `/` (site root path)
Comment: I have never used fully-qualified URLs in AJAX requests unless I need content from another domain.  As long as you want content from the same domain that is running the script, you can use relative URLs as this answer is demonstrating.
Answer: I am developing a large application and have quickly learned that there are great benefits to keeping your path in one location and using variables and/or constants everywhere else. The reason is pretty simple: Flexibility, DRY, etc.
If you have a PHP application that also uses Javascript, as I do, you may want to consider doing something like this:
File: constants.php
<?php
define("WEB_ADDRESS","http://www.somewebsite.com");
//...
?>

And now, to put it into every JS page, while I do not know your specific architecture and whether you are using a bootstrap or not, I assume you have one or more files from which you bootstrap and load headers/footers, or you use a template program. If not, you may want to look into it. In any case, the concept is that you simply declare it at the start of your page text for each page you load before including any other JS.
File: header.php (called in your web page you are loading).
//No Javascript above.
echo '';
//Now you can put in your Javascript.

The end purpose is that each Javascript file you include or any Javascript you call after this point is going to have access to the variable WEB_ADDRESS. If you need to change that path for any reason you can easily do so without breaking any links, in PHP and Javascript.
Answer: I am not sure, but as far as I understand,it is like

here the $_SERVER["HTTP_HOST"] part is the host name, say, www.example.com
then in your ajax request you can use that baseUrl js var and can concatenate your url
url: baseUrl + 'account/login'

Comment: Might be silly question but which part of your code do I replace it with my base url for example if my baseurl is "www.aaa.com/user".
Comment: @Trevor_zam I updated a little the answer, if ur base url contains smth more than the host name, than u should add that, so it will be ``


npm not running scripts in package.json

Question: The problem is that when I do npm start OR npm run customScriptCommand npm just not doing anything with the project and quickly just return new line in the terminal.
I've tried removing node and npm from my machine and then do brew installation for node and npm, but it does not fix the problem.
Then I tried removing node and npm from the brew installation and installing it again from nvm, but it also does not fix the problem.
NPM Details
npm -v -> 6.11.3
which npm -> /usr/local/bin/npm

NodeJS Details
node -v -> v12.12.0
which node ->/usr/local/bin/node

Scripts in package.json
"scripts": {
    "start": "node ./bin/www",
    "devstart": "DEBUG=app-name:* nodemon ./bin/www", //I've changed my actual app name to "app-name"
  },

If I do node ./bin/www OR DEBUG=app-name:* nodemon ./bin/www it will work:

Update

I've tried on other project that does not have problem on my colleague's machine, with git clone do npm install and tried to run the project, but it still failed
Even with fresh project which I just did npm init -y it fail,

{
   "name": "test"
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
   },
   "keywords": [],
   "author": "itsme",
   "license": "ISC"
}

Comment: Can you post your whole package.json? The bits you've shown look right.
Comment: even with new project which I just did `npm init` it still failed.

```
mkdir test
cd test && npm init -y
```

the resulted package.json:
```
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "nrajan",
  "license": "ISC"
}
```
Answer: npm config set ignore-scripts false would do the trick for you.
The struggle is real my friend, not following random tutorials from now.
https://github.com/npm/cli/issues/541
Comment: thank you, funny that I did re-install the node installation several times did not encounter this variable setup.

hope that other people will be helped with this
Answer: Installing npm install --save-dev nodemon and running npm start did the magic for me
Answer: You can install yarn and it works; just run yarn start. As to what caused the problem I have no idea.
Comment: This should be a comment not an answer.

npm not running scripts in package.json


Android e requisição HTTP campo X-auth-token

Question: Eu estou tentando enviar um token, através de uma aplicação Android no campo 'X-auth-token' do header. Esta requisição é enviada para um servidor PHP, no qual uso CodeIgniter.
Android
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL_PATH);
    httpPost.setHeader("X-auth-token", token);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("nome", this.nome_value));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    httpPost.setEntity(urlEncodedFormEntity);
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
          //...
        }

Server
...
$res = $CI->input->request_headers()['X-auth-token'];
...

Problema: $res não está setado, como se o campo 'X-auth-token' não existisse.
1 - Como posso enviar o campo do header 'X-auth-token' no Android?
2 - Eu estou usando o campo 'X-auth-token' porque eu li que é mais seguro do que um campo de post normal, para enviar dados confidencias.
Comment: Existe a possibilidade de você usar uma biblioteca? Eu passo um token mas não uso o `HttpClient`. Se existir eu posso te mostrar como faço no meu caso
Answer: Boa tarde.
Cara, encontrei o mesmo problema com o Authorization.
Fiz uma regra pra reescrevê-lo  no .htaccess conforme segue:
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Creio que, se tu simplesmente alterar HTTP:Authorization e HTTP_AUTHORIZATION:%1, deverá funcionar.


For $V = \sum_{s=1}^{t} A_s A_{s}^T$ to be non-singular $(A_s)_{s=1}^{t}$ needs to span $R^d$

Question: I am reading a book on bandits algorithm and inside a proof it says the following:
Let $(A_s)_{s=1}^{t}$ be sequence of vectors in $R^d$. Construct a matrix $V$ such that:
$$ V =  \sum_{s=1}^{t} A_s A_{s}^T$$
Now for $V$ to be non-singular, $(A_s)_{s=1}^{t}$ must span $R^d$ and $t$ must be at least $d$.
I can see why $t$ needs to be at least $d$ but I am not sure how to prove that $(A_s)_{s=1}^{t}$ must span $R^d$.
Any help in understanding this would be much appreciated.
Answer: For $V$ to be non-singular, it has to have rank $d$. That means that the rows (or columns, whichever you prefer) span all of $R^d$. Taking a close look at these columns, you will see that every single column is a linear combination of the $A_s$. Hence, the rows of $V$ span at most the same space as the $A_s$.


hts in R: Convert data.frame into a gts object

Question: I'm  a month-old user of RStudio.
Currently, I'm working with hierarchical time series analysis with the hts package. After reading my .csv data below,
<code>      WEEKNUM     SITE   OPERATIONS    ATTRITION
 1    201502      DAVAO   PRODUCTION         0
 2    201503      DAVAO   PRODUCTION         3
 3    201504      DAVAO   PRODUCTION         8
 4    201505      DAVAO   PRODUCTION         6
 5    201506      DAVAO   PRODUCTION         9
 6    201507      DAVAO   PRODUCTION         4
 7    201508      DAVAO   PRODUCTION         9
 ...
 592  201623      WM      TRAINING           0
</code>
I've tried creating the matrix out of it with these codes:

Then a matrix was successfully created, however the values were rnorm generated:

How do I replace them with the original grouped series values?
Or how do I start hts better, with my data import?
Thanks and more power! :)
Answer: It's not a statistics but a program topic....Supposition in this example: There are four SITE and two OPERATION.
(if not, you'll modify each number in below code.)
<code># example data as .csv data (you needn't)
df <- data.frame(WEEKNUM=rep(c(201502:201552, 201601:201623), 8),
                 SITE = rep(LETTERS[1:4], each=74),
                 OPERATIONS = rep(LETTERS[11:12], each=296),
                 ATTRITION = rnorm(592))

# If undone, you'll sort the data (1st key is SITE, 2nd is OPERATIONS, last is WEEKNUM).
df <- df[order(df$SITE, df$OPERATIONS, df$WEEKNUM),]
df$test <- paste(df$SITE, df$OPERATIONS, seq=" ") # make the row to check

matrix(df$test, nrow=74)        # checking. If you succeed, each column consist of one factor.
abc <- ts(matrix(df$ATTRITION, nrow=74), start=c(2015,2), frequency=52)   # creating time-series objects
SITE <- rep(levels( df$SITE ), each=2)        # each=2; the number of OPERATIONS
OPERATIONS <- rep(levels( df$OPERATIONS ), 4) # 4; the number of SITE
gc <- rbind(SITE, OPERATIONS)                 # a matrix consists of strings
rownames(gc) <- c("SITE", "OPERATIONS")
x <- gts(abc, groups = gc)                    # finish
</code>
Comment: Thanks crayfish44, but the formed gts object still prints negative values. :(
How do I replace them with the original series?
Comment: or are they some sort of standardized?
Comment: `df <- read.csv(your file)` and you'll do all lines under # If undone, you~.


Adapting the simple Open VPN example to get multiple client

Question: The sample OpenVPN configuration in Debian documentation https://wiki.debian.org/OpenVPN gives the following code.
Server /etc/openvpn/tun0.conf:
dev tun0
ifconfig 10.9.8.1 10.9.8.2
secret /etc/openvpn/static.key

Client /etc/openvpn/tun0.conf:
remote your-server.org
dev tun0
ifconfig 10.9.8.2 10.9.8.1
secret /etc/openvpn/static.key

My question: how to adapt this to handle more than one client? Without hard coding IPs on the clients?
Comment: Scroll down further on that page.  There is a perfectly good example. https://wiki.debian.org/OpenVPN#TLS-enabled_VPN
Comment: This part is about using TLS which is not what I want to do. A shared static key is ok for me.
Comment: I need this too! An open-vpn-server without any encryption and key-infrastructure... and authentication.
Comment: @raiserle do you mean a proxy?
Comment: No. The simple question is: How do I get Windows (no server) to make NAT.
Answer: I am another such lazy and inexperienced person. I can't use wireguard or vxlan tunnels because I don't know up front all my VPN clients (to predeclare point-to-point tunnels) and my clients don't share an l2 segment with the VPN server (that would allow for multicast vxlan). Moreover, I can't easily tunnel through NAT with vxlan. Finally, I might want to connect from a macOS computer. So, OpenVPN it is.
Server config
Create the certificates. Public certificate for the server is sufficient. You can either use easy-rsa, or you can do it on your own with openssl. I prefer openssl.
On RHEL 9, do this
dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
dnf install -y openvpn easy-rsa openssl

When using easy-rsa, that got installed into
/usr/share/easy-rsa/3.0.8/easyrsa

When using openssl, create certificate authority and server certificate.
Use the -nodes parameter for openssl to avoid having to specify password for the generated certificates.
openssl req -nodes -x509 -newkey rsa:4096 -sha256 -days 3650 -keyout ca-key.pem -out ca-cert.pem -subj "/CN=TestCA"

openssl req -nodes -newkey rsa:4096 -keyout server-key.pem -out server-csr.pem -subj "/CN=localhost"
openssl x509 -req -in server-csr.pem -CA ca-cert.pem -CAkey ca-key.pem -out server-cert.pem -days 365

openssl dhparam -out dh.pem 2048

Create config following the sample in https://github.com/OpenVPN/openvpn/blob/master/sample/sample-config-files/server.conf
proto udp
dev tun
ca ca-cert.pem
cert /root/server-cert.pem
key /root/server-key.pem
dh /root/dh.pem
verify-client-cert none
auth-user-pass-verify /bin/true via-env
script-security 3
server 188.8.131.52 255.255.255.0
push "route 188.8.131.52 255.0.0.0"
push "redirect-gateway local"
topology subnet
explicit-exit-notify 1

Now run server with
# openvpn --config openvpn.config
2023-07-20 23:32:55 WARNING: Compression for sending and receiving enabled. Compression has been used in the past to break encryption. Allowing compression allows attacks that break encryption. Using "--allow-compression yes" is strongly discouraged for common usage. See --compress in the manual page for more information
2023-07-20 23:32:55 --cipher is not set. Previous OpenVPN version defaulted to BF-CBC as fallback when cipher negotiation failed in this case. If you need this fallback please add '--data-ciphers-fallback BF-CBC' to your configuration and/or add BF-CBC to --data-ciphers.
2023-07-20 23:32:55 WARNING: POTENTIALLY DANGEROUS OPTION --verify-client-cert none|optional may accept clients which do not present a certificate
2023-07-20 23:32:55 OpenVPN 2.5.9 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Feb 16 2023
2023-07-20 23:32:55 library versions: OpenSSL 3.0.7 1 Nov 2022, LZO 2.10
2023-07-20 23:32:55 WARNING: --keepalive option is missing from server config
2023-07-20 23:32:55 NOTE: the current --script-security setting may allow this configuration to call user-defined scripts
2023-07-20 23:32:55 TUN/TAP device tun0 opened
2023-07-20 23:32:55 net_iface_mtu_set: mtu 1500 for tun0
2023-07-20 23:32:55 net_iface_up: set tun0 up
2023-07-20 23:32:55 net_addr_v4_add: 126.96.36.199/24 dev tun0
2023-07-20 23:32:55 Could not determine IPv4/IPv6 protocol. Using AF_INET
2023-07-20 23:32:55 UDPv4 link local (bound): [AF_INET][undef]:1194
2023-07-20 23:32:55 UDPv4 link remote: [AF_UNSPEC]
2023-07-20 23:32:55 Initialization Sequence Completed

Client config
Copy ca-cert.pem to all clients. Then configure clients in the NetworkManager GUI for KDE.

Don't forget to enable "Use only for resources on this connection", from https://serverfault.com/a/469131/116739, otherwise all your traffic will go through the VPN by default, which you may not want.
Answer: Try
server 10.9.8.0 255.255.255.0

on the server, and
client

on the clients.  The server should take the first address in the range (10.9.8.1) for itself, then hand out the others to the clients; the clients should accept those assignations.
Comment: Thanks for the advice, unfortunately `Options error: --server and --secret cannot be used together (you must use SSL/TLS keys)`
Comment: It's mostly laziness and inexperience, I'm trying to pick the simplest way. In my case, this VPN will be setup between VM instances to connect to another network, if one VM is compromised, the whole image should be trashed. The static key could have been enough in terms of security.
Comment: Then it's clear that, by design, you can't use a single-shared-secret to connect more than two endpoints; if you want more than a simple ad-hoc network, a proper key infrastructure is unavoidably imposed upon you.  Are there good business reasons not to like such a prospect?
Comment: The simplest way is probably public-key - it's so well-documented that it's really quite painless to set up.


Gradient of the form $(\textbf{x}-\textbf{x}_k)^TA(\textbf{x}-\textbf{x}_k)$

Question: In the context of a convex optimization problem I came across with the following function:
$$f_1(\textbf{x})=(\textbf{x}-\textbf{x}_k)^T\textbf{A}(\textbf{x}-\textbf{x}_k) - t^2$$
EDIT
$f_1$ is a real-valued function and $t$ is a positive real number. Also $\textbf{A}$ is positive definite.
and I am trying to take its gradient following the rules I found here.
Starting from the given form I get:
\begin{eqnarray*}
f_1(\textbf{x})&=&\textbf{x}^T\textbf{A}\textbf{x}-\textbf{x}^T\textbf{A}\textbf{x}_k-\textbf{x}_k^T\textbf{A}\textbf{x}+\textbf{x}_k^T\textbf{A}\textbf{x}_k-t^2\\
&=&\textbf{x}^T\textbf{A}\textbf{x}-2\textbf{x}_k^T\textbf{A}\textbf{x}+\textbf{x}_k^T\textbf{A}\textbf{x}_k-t^2\\
&=&\textbf{x}^T\textbf{A}\textbf{x}-2\textbf{q}^T\textbf{x}+\textbf{x}_k^T\textbf{A}\textbf{x}_k-t^2\\
\end{eqnarray*}
where in the last line I have considered a row vector $\textbf{q}^T=\textbf{x}_k^T\textbf{A}$
So what I get is:
$$\nabla f_1(\textbf{x})=\textbf{A}\textbf{x}-2\textbf{q}=\textbf{A}\textbf{x}-2\textbf{A}\textbf{x}_k=\textbf{A}(\textbf{x}-2\textbf{x}_k)$$
But looking at my notes I see that the result is:
$$\nabla f_1(\textbf{x})=2\textbf{A}(\textbf{x}-\textbf{x}_k)$$
Am I doing something wrong? Also, does it matter if $\textbf{A}$ is positive definite or not?
Comment: Where is your $-t^2$ term coming from?
Comment: @mathcounterexamples.net Please see the edit. Thanks for pointing this out.
Answer: Assuming $A$ is positive definite, i.e. $A+A^T$ is SPD. Then expanding the quadratic form we have
$$f_1(\mathbf{x}) = \mathbf{x}^TA\mathbf{x} - \mathbf{x}_k^T(A+A^T)\mathbf{x} + \mathbf{x}_k^T A \mathbf{x}_k - t^2.$$
The second-last term should have a positive sign although it has no effect in calculating the gradient.
In calculating the gradient of $\mathbf{x}^TA\mathbf{x}$, using the formula there we should have
$$\nabla \mathbf{x}^TA\mathbf{x} = (A+A^T)\mathbf{x}, $$
and therefore
$$\nabla f_1 = (A+A^T)\mathbf{x} - (A+A^T)\mathbf{x}_k = (A+A^T)(\mathbf{x}-\mathbf{x}_k).$$
In particular, if $A$ is SPD, then
$$ \nabla \mathbf{x}^TA\mathbf{x} = 2A\mathbf{x}, $$
and
$$\nabla f_1 = 2A(\mathbf{x}-\mathbf{x}_k).$$
Comment: Thanks for your reminder. I messed up the orders since I thought SPD is given as a condition when I first wrote the answer.
Comment: The remark after "in particular" should come first, because the term $-2 \mathbf{q}^T \mathbf{x}$ is obtained using $A = A^T$.
Comment: @S.W.Cheung So what you are saying is that I also need to impose on $\textbf{A}$ to be symmetric?
Comment: @koursaros Yes. In fact, as pointed out by A.P., you have imposed the condition $A$ is symmetric in simplifying the second line in the expansion of the quadratic form to $2\mathbf{x}_k^T A \mathbf{x}$. Please read the edited answer for a more detailed explanation.


Proving the rectangle theorem using Green's theorem

Question: Question 1
I want to prove that given $ f:\mathbb{C}\to\mathbb{C} $ and rectangle $ R $ with boundary $\gamma $ anti-clockwise, the line integral over $ f $ would be $ 0 $.
I'm pretty sure with my way but I cannot find my mistake. Here's what I have tried:
Assume that $ f\left(x,y\right)=\left(u\left(x,y\right),v\left(x,y\right)\right) $ (we will recognize $\mathbb{C} $ with $\mathbb{R}^2$, and assume $ \gamma\left(t\right)=\left(x\left(t\right),y\left(t\right)\right),\thinspace\thinspace\thinspace a\leq t\leq b $
Then,by definition we have:
$$ \intop_{\gamma}fdz=\intop_{a}^{b}f\left(\gamma\left(t\right)\right)\cdot\dot{\gamma}\left(t\right)dt $$
$$ =\intop_{a}^{b}\left[\left(u\left(x\left(t\right),y\left(t\right)\right),v\left(x\left(t\right),y\left(t\right)\right)\right)\right]\cdot\left[\left(\dot{x}\left(t\right),\dot{y}\left(t\right)\right)\right]dt $$
$$ =\intop_{a}^{b}\left[u\left(x\left(t\right),y\left(t\right)\right)\dot{x}\left(t\right)+v\left(x\left(t\right),y\left(t\right)\right)\dot{y}\left(t\right)\right]dt $$
$$ =\intop_{\gamma}u\left(x,y\right)dx+v\left(x,y\right)dy\underset{\text{Green's Theorem}}{=}\intop_{R}\left(v_{x}-u_{y}\right)dxdy $$
I used Gree'ns theorem as it stated in wikipedia
What I actually need in those parenthesis is $ \left(u_{x}-v_{y}\right) $ so I can use Cauchy-Riemann equations and claim that the integrand is $0$, but seems like I was wrong somewhere
Any help and clarifications would be very helpful and I would highly appreciate it.
Thanks in advance.
Comment: What do we know about $f$.  For example, if $f$ is holomorphic, then yes, you can show that the integral around the rectangle is zero.  Otherwise, usually $\int_\text{rectangle} f(z)\, dz \ne 0.$
Answer: We regard $f \colon \mathbb{R}^2 \to \mathbb{C}$. Your first one is just not the definition of contour integration. It gives you a real number, so is definitely not correct. Your second one is correct. The first  integral you computed is (with $f = u + iv$)
$$\int_{\partial R}u\,dx + v\,dy,$$
while the definition of the contour integral is
$$\int_{\partial R}f\,dz := \int_{\partial R}f(dx + i\,dy) = \int_{\partial R}f\,dx + if\,dy.$$
Green's theorem applies to functions from $\mathbb{R}^2$ to $\mathbb{C}^2$ too (this follows easily from the real version of Green's theorem), so applying Green's theorem to $(f, if)$ gives
$$\int_{\partial R}f\,dx + if\,dy = \int_{R}(if_x - f_y)\,d(x, y).$$
If $f$ is holomorphic, then $if_x - f_y = 0$, which yields your result.
Edit: The contour integral is defined as the line integral of the vector field $(f, if)$, a complex valued vector field. The integral of such a vector field is defined componentwise. That means it is really two real integrals. We can expand to see them
\begin{align}
f\,dz &= (u + iv)\,(dx + i\,dy) \\
&= u\,dx - v\,dy + i(u\,dy + v\,dx). \\
\end{align}
So
$$\int_{\partial R}f\,dz = \int_{\partial R}(u\,dx - v\,dy) + i\int_{\partial R}(v\,dx + u\,dy).$$
Comment: Can you write the correct definition of the contour integral without involving $\mathbb{C} $? (assuming $\mathbb{C} = \mathbb{R}^2 $. I want to know how could I solve it in the first way
Comment: @FreeZe The contour integral is a complex number (i.e. a pair of real numbers). I expanded it to show what those two real numbers are.


Rails 3.1.0, geokit, with error acts_as_mappable

Question: I am getting the
undefined local variable or method `acts_as_mappable'

error when using geokit, and after tons of Goggling and attempts, I cannot seem to be able correct the problem.
Basically, I have the following gems installed:
geokit (1.6.0, 1.5.0)
geokit-rails31 (0.1.3)

and have the following in my model
class House < ActiveRecord::Base
  acts_as_mappable
end

and Gemfile:
gem 'geokit', '>= 1.5.0'
gem 'geokit-rails31'

I get the error with or without doing the following in my local app.
rails plugin install git://github.com/jlecour/geokit-rails3.git

Answer: Okay - Here is the solution for anyone that needs help on how I got it to work...
Make sure your project Gemfile does not contain any geokit info of any kind.
install geokit
> gem install geokit

> gem list geo
*** LOCAL GEMS ***
geokit (1.6.0, 1.5.0)

uninstall geokit-rails3 and geokit-rails31
> gem uninstall geokit-rails31 geokit-rails3

in your project, at the root level:
> rails plugin install git://github.com/jlecour/geokit-rails3.git

edit the spec
> vi vendor/plugins/geokit-rails3/geokit-rails3.gemspec

change rails dependency line to be
s.add_runtime_dependency 'rails', '>= 3.1.0'

now, edit the Gemfile to include the gem
gem 'geokit-rails3', :path => 'vendor/plugins/geokit-rails3'

Note, the Gemfile only contains an entry for the geokit-rails3, and no entries for normal geokit gem. i.e. there is not a "gem 'geokit', '>= 1.5.0'" entry
then in your application root, do a
bundle install

It should be setup, and you can now follow a typical tutorial - as described in the git instructions
https://github.com/jlecour/geokit-rails3


Trouble getting duplicity + cron + shell script to play nicely together

Question: I'm not sure if this is more appropriate here or over in Stackexchange so sorry if I got it wrong.
I was wondering if I could get some help: So I'm trying to use cron to run my shell script which consists of multiple duplicity calls (so I can back up different things without it all being jumbled together in a mess)
In my crontab
09 15 * * * /home/backup.sh

in my home/backup.sh
duplicity --no-encryption --exclude /home/itq/anotherOne /home/itq file:///media/backup/backup/tester/Ian

duplicity --no-encryption /media/ab file:///media/backup/backup/tester/ab

The problem that I'm getting is that
Command line error: Expected 2 args, got 1
Enter 'duplicity --help' for help screen.
/home/backup.sh: 2: /home/backup.sh: file:///media/backup/backup/tester/Ian: not found
Command line error: Expected 2 args, got 1
Enter 'duplicity --help' for help screen.
/home/backup.sh: 5: /home/backup.sh: file:///media/backup/backup/tester/ab: not found

even though it works just fine when I run it from terminal (outside of the script). It's probably worth noting that /media/backup is a harddrive that I've mounted to the system (it's called backup, and is the first backup file after media) so IDK if that changes anything.
Answer: I'm not familiar with duplicity, but your description about difference between running the script in terminal and by cron would suggest that tasks run by cron could be using a different interpreter.
Try adding the following line to the very start of your script file.
#!/bin/sh

Comment: Thanks! Silly question, but is it also possible to get it to stop posting an update to /var/mail/root ? I'm scheduling it as sudo (setting up the backup system for a research lab and I don't have ownership of all their files)
Comment: It is.
If you want to disable it for all cron jobs, edit your crontab file by `crontab -e` and add to the top of the file `MAILTO=""`. This _should_ disable the mail alerts.
If you want to do it just for the one cron task, it looks something like this:
`0 1 10 10 * /path/backupscript.sh >/dev/null`
But i'm not sure on the specifics from top of my head.


Under what conditions does local concavity imply global concavity?

Question: I have the following result:
Assume $U:\mathbb{R}^+\to\mathbb{R}^+$ is continuous and strictly increasing. Further, for every $a>0$ there exists a neighborhood (interval) $S$ of $a$ such that $U$ is concave on $S$.
Now I want to show that $U$ is concave on all of $\mathbb{R}^+$. I was thinking about using the fact that $U$ has a non-increasing right derivative on $int S$ (famous result by Stolz)- by continuity on $S$. However, I don't really know how to incorporate this.
Consider the following result:
A function $f:I\to\mathbb{R}$ is concave if and only if for $x,y,z\in I, x<z<y$ it holds
$$\frac{f(x)-f(z)}{x-z} \geq \frac{f(x)-f(y)}{x-y} \geq \frac{f(z)-f(y)}{z-y}.$$
My intuition is the following. For any $x<z<y$ in $\mathbb{R}^+$ I know that around each of these points, $U$ is concave. Further, for any points in between $x,z,y$, the same situation holds. Hence, I use overlapping intervals, around the points in between, to show the above inequalities using Stolz result. However, I have the feeling that considered intervals need not necessarily overlap?!
What's your opinion on this?
Comment: This is similar to your proposed solution, but do you know that each concave function is (locally) absolutely continuous, where the (almost everywhere existent) derivative is nonincreasing (and vice versa)?
Answer: More generally, the result is true in any convex subset $D$ of a topological vector space: if $f: D \to \mathbb R$ is continuous and every $a \in D$ has a neighbourhood on which $f$ is concave then $f$ is concave on $D$.
Proof:  Suppose not.  Then there exist $a,b \in D$ and $t \in (0,1)$ such that
$f(t a + (1-t) b) < t f(a) + (1-t) f(b)$.  Define $g: [0,1] \to \mathbb R$ by
$g(s) = f(sa + (1-s) b) - s f(a) - (1-s) f(b)$.  Then $g$ is continuous, and
every $s \in [0,1]$ has a neighbourhood on which $g$ is concave.  Note that
$g(0) = g(1) = 0$ while $g(t) < 0$.  Let
$y = \min\{g(s): s \in [0,1]\} < 0$, and $p = \max\{s: g(s) = y\} \in (0,1)$.
But $g(s) > g(p)$ on $(p,1]$ while $g(s) \ge g(p)$ on $[0,p)$, so there is no
neighbourhood of $p$ on which $g$ is concave.
Comment: +1 I am just not fluent enough in this stuff. I have to read it carefully and slowly, instead of instantly thinking "oh, yes". I guess the problem is I am not currently using it much ... No, that is a feeble excuse!
Comment: The reason that there is no neighborhood of p on which g is concave is that g(p) lies below the secant between any two points in the neighborhood of p?
Comment: Yes (for any two points where one is on one side and the other is on the other).
Answer: Just a little addition to Robert Israel's great proof.
I had to think about why every $s\in[0,1]$ has a neighborhood on which $g$ is concave a little and came up with the following reasoning - for those who are interested.
Let $s\in[0,1]$ and consider the point $z(s):=s x + (1-s)y$. By assumption, $f$ is concave on an interval around $z(s)$ whose points can be described by convex combinations of $x$ and $y$. Hence, for $s_1,s_2$ around $s$ such that
$$z(s_1) = s_1 x + (1-s_1)y, \quad z(s_2) = s_2 x + (1-s_2)y$$
lie in the interval on which $f$ is concave, by midpoint concavity the following holds
\begin{align*}
f\left(\frac{1}{2} z(s_1) + \frac{1}{2} z(s_2)\right) &\geq \frac{1}{2} f(z(s_1)) + \frac{1}{2} f(z(s_2))\\
\Leftrightarrow\quad\quad\,\,\, f\left(\frac{1}{2} z(s_1) + \frac{1}{2} z(s_2)\right)&\geq\frac{1}{2} f(s_1 x + (1-s_1)y) + \frac{1}{2} f(s_2 x + (1-s_2)y)
\end{align*}
\begin{align*}
&\Leftrightarrow\quad f\left(\frac{1}{2} z(s_1) + \frac{1}{2} z(s_2)\right) - \left(\frac{1}{2}s_1 + \frac{1}{2}s_2\right) f(x) - \left(1-\frac{1}{2}s_1 - \frac{1}{2}s_2\right) f(y)\geq\\
&\qquad\qquad\qquad\frac{1}{2} f(s_1 x + (1-s_1)y) + \frac{1}{2} f(s_2 x + (1-s_2)y) - \left(\frac{1}{2}s_1 + \frac{1}{2}s_2\right) f(x) \\
&\qquad\qquad\qquad\quad - \left(1-\frac{1}{2}s_1 - \frac{1}{2}s_2\right) f(y)\\
&\Leftrightarrow\qquad\qquad\qquad\, g\left(\frac{s_1+s_2}{2}\right) \geq \frac{1}{2} g(s_1) + \frac{1}{2} g(s_2),
\end{align*}
since
$$f\left(\frac{1}{2} z(s_1) + \frac{1}{2} z(s_2)\right) = f\left(\left(\frac{1}{2}s_1 + \frac{1}{2}s_2\right)x + \left(1-\frac{1}{2}s_1 - \frac{1}{2}s_2\right) y\right).$$
Hence, for every $s\in[0,1]$  there exists a neighborhood on which $g$ is concave.


Difficulties using parent class constructors in subclass

Question: I have a Contractor subclass that extends of it's parent class Staff.
    Test Class

    Date macHireDate = new Date(2016, 1, 5);
    Staff mac = new Staff("Mac", 66222222, macHireDate);
    System.out.println(mac);

    Staff bob = new Contractor("Bob", new Date(2012,10,10), new Date(2013,4,11))
    System.out.println(bob);

I want the output to be Bob (ID: None) ...
But I'm not sure how to make the ID a String. I don't want to change anything in my Test Class
public class Contractor extends Staff {
private Date contractEnds;

This is my Contractor classes constructor
public Contractor(String name, Date hireDate, long employementID, Date contractEnds) {
    super(name, employementID, hireDate);
    this.contractEnds = contractEnds;
}

and it's extending off of
public Staff(String name, long employementID, Date hireDate) {
super();
this.name = name;
this.hireDate = hireDate;
this.employementID = employementID;
}

Bob only has a String, Date, Date. So I'm having difficulties on how to make bobs ID "None" without changing anything in Test Class.
Answer: If you change the constructor of Contractor to be
public Contractor(String name, Date hireDate, Date contractEnds) {
    super(name, 0, hireDate);
    this.contractEnds = contractEnds;
}

then also change your toString method of Staff so that if employementID is 0 then it will print None
Answer: Use a combination of a super() constructor, and any other additional parameters that need to be initialized, to instantiate the object.
public Contractor(String name, Date hireDate, Date contractEnds, int employmentID ) {
    super(name, employmentID, hireDate);
    this.contractEnds = contractEnds;
}

The super() constructor inherits all of the superclass's constructor code, and initializes all of the corresponding variables in the subclass
you can also write custom code in your methods by adding the @Override annotation before it
Example:
@Override
public String toString(){...}

Answer: Add a constructor to Contractor that does not require the ID. Use "this" to call the main constructor with a default ID:
[Warning - untested code ahead]
public Contractor(String name, Date hireDate, Date contractEnds) {
    this(name, hireDate, 0, contractEnds);
}

You will need to pick some value of type long to represent a non-existent ID. I used 0.
Answer: The following code:
public class JavaApplication23
{
    public static void main(String[] args)
    {
        Date macHireDate = new Date(2016, 1, 5);
        Staff mac = new Staff("Mac", 66222222, macHireDate);
        System.out.println(mac);

        Staff bob = new Contractor("Bob", new Date(2012,10,10), 1234L, new Date(2013,4,11));
        System.out.println(bob);

        Staff bob2 = new Contractor("Bob2", new Date(2012,10,10), new Date(2013,4,11));
        System.out.println(bob2);
    }

}

class Contractor extends Staff
{
    private Date contractEnds;

    public Contractor(String name, Date hireDate, long employementID, Date contractEnds)
    {
        super(name, employementID, hireDate);
        this.contractEnds = contractEnds;
    }

    public Contractor(String name, Date hireDate, Date contractEnds)
    {
        super(name, hireDate);
        this.contractEnds = contractEnds;
    }

    @Override
    public String toString()
    {
        String out = super.toString();
        return out + "ContractEnds: " + contractEnds + "\n";
    }
}

class Staff
{
    private String name;
    private long employementID;
    private boolean idIsOK;
    private Date hireDate;

    Staff(String name, long employementID, Date hireDate)
    {
        //super();
        this.name = name;
        this.hireDate = hireDate;
        this.employementID = employementID;
        idIsOK = true;
    }

    Staff(String name, Date hireDate)
    {
        //super();
        this.name = name;
        this.hireDate = hireDate;
        this.employementID = -1;
        idIsOK = false;
    }

    @Override
    public String toString()
    {
        String out = "Name: " + name + "\n";
        out += "HireDate: " + hireDate + "\n";
        out += "EmployementID: " + ((idIsOK) ? employementID : "None") + "\n";
        return out;
    }
}

returns:
Name: Mac
HireDate: Sat Feb 05 00:00:00 CET 3916
EmployementID: 66222222

Name: Bob
HireDate: Sun Nov 10 00:00:00 CET 3912
EmployementID: 1234
ContractEnds: Sun May 11 00:00:00 CEST 3913

Name: Bob2
HireDate: Sun Nov 10 00:00:00 CET 3912
EmployementID: None
ContractEnds: Sun May 11 00:00:00 CEST 3913


Should you return to the original key?

Question: So I've begun writing several orchestral pieces (forgive me if I use incorrect names, I didn't study orchestrastion or composition beyond my GCSEs).
When writing a piece, you often change the key part way through to inject some flavour and keep the piece interesting. Should you return to the original key when ending the piece?
I've found that it sounds finished regardless of whether I go back to the original key or stay in the new key to the end. Are there any hard and fast "rules" that say you should or shouldn't return to the original?
Answer: Music that deals in key relationship as a structural device - which could be considered a definition of the Classical style - almost inevitably returns to the original key (or possibly the tonic or relative major if it started in a minor key).   Yes, of course you can ignore this 'rule'.  I suspect, however, that you will grow into appreciating the reason for it.
Do you know the song 'Unforgettable' by Nat King Cole?   It ends in the subdominant key.  If you choose to start in G, it will end in C. It's a great song, but for me the key structure is a negative feature.
Comment: Unforgettable is a tad awkward to go round two or three times, in that it sounds like it changes key for the next time round, which in a way it does.
Comment: Yup.  I wondered if there was a lost verse in the same key as the end of the chorus, but apparently not.   He went where the music took him, but it wasn't an altogether satisfactory journey!   It's interesting to see what arrangers have done with it.  Nat's recording has an interesting series of modulations, one into an instrumental half-chorus another into the final vocal. Have a listen.
Comment: I have, many times - and played it in many guises. Still can't work out exactly where the mod occurs, though...
Comment: Sometimes it's hard to define just when you stop visiting and actually set up house!   Maybe only in the very last few bars in this case.  But it's pretty clear where it starts and where it ends.
Answer: The answer as Lawrence and Tim have stated is that music prior to the Twentieth Century most often did. However, beginning roughly at the start of the 20th Century, the harmonies and progressions matured to the point that any relatively strong cadence will sound completed. By using other musical elements such as tempo, dynamics, etc., you even get away with a dissonant cadence, such as at the end of Ravel's 'Bolero'.
Bach's continually rising canon ends one whole step up on each iteration.
If you are writing music in the style of the common practice period, the final cadence for the piece as a whole should end in the key it began on in general. However, if you have musical reasons for ending on a half cadence, dissonance, a chord in a foreign key, etc, and it sounds convincing, then go ahead and do it.
I would strongly suggest reading the chapters on Tonality and Cadences in Leon Dallin's book "Twentieth Century Composition" 3rd edition, 1974 published by WM. C. Brown.
Answer: If it's modulated a good few bars before the end, then playing that I harmony will sound like it's arrived back at home, even though, technically, it hasn't. It's what sounds best that is the best. If it's just modulated somewhere away from the original key shortly before the end, then it'll sound better to either prolong that ending in the new key, or return to a key that sounds final. I say 'a key', as that may indeed not be the original at all.
So, to sum up, whatever chord sounds like it signifies the end in that the piece has come to rest, permanently, rather than temporarily, will be the most convincing, be it the original key or the one it last modulated to. No hard and fast rule. As usual, ears are best judges.

Should you return to the original key?


DatagridViewButtonColumn Text Displaying Only in Editing Mode? Why?

Question: In my Datagridview, I have a button column. I want to display text on my button. It displays text only when I enter a text into another row of the datagridview. It does not display it when the form is run.
I use this code to assign text to the button.
DataGridViewButtonColumn dgv_col22 = new DataGridViewButtonColumn();
dgv_col22.Text = "delete";
dgv_col22.UseColumnTextForButtonValue = true;

Is there another way to do that?
I use Visual Studio 2013 Windows Forms.
Answer: Try this
DataGridViewButtonColumn dgv_col22 = new DataGridViewButtonColumn()
{
    dgv_col22.Text = "delete",
    dgv_col22.UseColumnTextForButtonValue = true
}
dataGridView1.Columns.Add(dgv_col22);


CheckBox desaparecendo quando clica

Question: Estou fazendo uma checkbox personalizada e quando clica, ela desaparece. Quero que, ao clicar nela, apareça True ou False sem que ela desapareça.
Quando eu retiro o evento onClick() a checkBox não desaparece, mas também não aparece True ou False.
Aqui está o código:

    Tabela

    Boolean

 True
   <input type="checkbox" checked="checked" id="check" onclick="myCheck()"></input>

Comment: Ta muito bagunçado o **Html** você abre uma tag `label` e fecha ela com uma tag `input`, tem `td` e `tr` sem fechamentos, etc..
Comment: É verdade, corrigi esses detalhes, mas ainda permanece o erro.
Answer: Fiz alguns ajustes e parece estar funcionando do jeito que deveria.

O HTML estava quebrado (por exemplo, </input> aonde deveria ser ,
 sem fechar, etc).
A função myCheck() estava trocando o texto mas não o estado da checkbox.

function myCheck() {
  var checkBox = document.getElementById("check");
  if (checkBox.checked == true){
    document.getElementById("check").checked = false;
    document.getElementById("lblBool").innerHTML = "False";
  } else {
    document.getElementById("check").checked = true;
    document.getElementById("lblBool").innerHTML = "True";
  }
}
#customers {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  margin-left: 5px;
  margin-top: 5px;
}

#customers td, #customers th {
  border: 1px solid #ddd;
  padding: 8px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #4CAF50;
  color: white;
}

/* The container */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 4px;
  cursor: pointer;
   font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default checkbox */
.container input {
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

/* Create a custom checkbox */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
  background-color: #2196F3;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  }

 input[type=text], select {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

input[type=submit] {
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

table{
   top: inherit;
             width: 310px;
             height: 350px;
             overflow: auto;
             display: inline-block;
             margin-left: 5px;
             margin-top: 5px;
}

    Tabela

    Boolean

        True
        <input type="checkbox" checked="checked" id="check"  />

CheckBox desaparecendo quando clica


Por que função de remover javascript não funciona?

Question: Fiz uma função em javascript para apagar linha da tabela quando o usuário apertar o botão, porém ela não está funcionando.

(function($) {

RemoveTableRow = function(handler) {
var tr = $(handler).closest('tr');

tr.fadeOut(400, function(){
  tr.remove();
});

return false;
  };

var counter = 1;
jQuery('a.add').click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('
'+
                            '<input class="form-control" name="cod_Produto" type="text" disabled/>	'+
                            'Update software	'+
                            'wd	'+
                            'wd	'+
                            'efe	'+
                            'ewf	'+
                            'wefwe	'+
                            'wef	'+
                            'ewfe	'+
                            '<button class="btn btn-danger" type="button" onClick="newRow.remove()"></button>	'+
                        '
');
    jQuery('table.table-bordered').append(newRow);
});

})(jQuery);

Itens

<buttom class="btn btn-success"></buttom>

                              Cód
                              Produto
                              UN
                              Volume
                              Peso
                              Unitário
                              Total
                              Desconto
                              Líquido
                              Excluir

                                <input class="form-control" name="cod_Produto" type="text" disabled/>
                                Update software
                                wd
                                wd
                                efe
                                ewf
                                wefwe
                                wef
                                ewfe

Comment: qual é o erro? esse código do snippet não está faltando o `html`?
além disso, na linha onde é criada a `td` com o `button`, tem muitas aspas duplas que estão provavelmente dando erro, de uma olhada nesses pontos
Comment: Não está acusando erros aqui
Comment: Edite sua pergunta inclua o html para que possamos simular seu problema.
Comment: Olha ai, editei ai
Answer: Alterei o seu código de forma que o <button> criado dinâmicamente chamará uma função passando this (o próprio botão) como parâmetro.
onClick="RemoveLinha(this);"

E criei a função abaixo para remover a linha mais próxima utilizando o método  closest() do jquery:
function RemoveLinha(btn){
   $(btn).closest("tr").remove();
}

Segue exemplo abaixo:

var counter = 1;

jQuery('a.add').click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('
'+
      '<input class="form-control" name="cod_Produto" type="text" disabled/>	'+
      'Update software	'+
      'wd	'+
      'wd	'+
      'efe	'+
      'ewf	'+
      'wefwe	'+
      'wef	'+
      'ewfe	'+
      '<button class="btn btn-danger" type="button" onClick="RemoveLinha(this);"> Remover</button>	'+
      '
');

    jQuery('table.table-bordered').append(newRow);
});

function RemoveLinha(btn){
   $(btn).closest("tr").remove();
}

Clique para adicionar
Answer: Na sua pergunta original estava assim:
'... onClick="$(this).parents("tr").remove()" ....'+

Tudo o que você precisava fazer era trocar o "tr" (aspas duplas) por 'tr' (aspas simples, que é o delimitador da string que você está concatenando) e fazer o escape das aspas:
'... onClick="$(this).parents(\'tr\').remove()" ....'+

Veja exemplo:

var newRow = jQuery('
'+
'<input class="form-control" name="cod_Produto" type="text" disabled/>	'+
'Update software	'+
'wd	'+
'wd	'+
'efe	'+
'ewf	'+
'wefwe	'+
'wef	'+
'ewfe	'+
'<button class="btn btn-danger" type="button" onClick="$(this).parents(\'tr\').remove()">Remover linha</button>	'+
'
');
jQuery('table.table-bordered').append(newRow);


Vector/linear algebra Plane Question english explanation

Question: I am not a native English speaker but I study a vector/linear algebra course in English. I am having trouble understanding what this particular question actually means. I have seen the solution and I know how to get there but I am not sure what I am actually doing or what the question wants me to do. I managed to solve this by following calculations of a similar example question.
"In Exercises 73-76, find a point-normal form of the equation of the plane passing through P and having n as a normal"
P(2,3,-4) n=(1,-1,2)
Comment: Do you know what "point-normal" means?
Comment: What do you mean by a *point-normal form*?
Comment: I know that normal is a orthogonal vector to the plane, I do not know what point normal mean
Comment: A simple internet search for "point-normal form" turns up [this](http://mathonline.wikidot.com/point-normal-form-of-a-plane), [this](https://socratic.org/questions/what-is-the-point-normal-form-of-the-equation-of-a-plane), [this](https://ocw.mit.edu/courses/mathematics/18-02sc-multivariable-calculus-fall-2010/1.-vectors-and-matrices/part-b-matrices-and-systems-of-equations/session-12-equations-of-planes-ii/MIT18_02SC_notes_5.pdf) and many other sources.
Answer: If $(x_0,y_0,z_0)$ is a point in the plane and $\vec{n}=\langle n_x,n_y,n_z\rangle$ is normal to the plane, then the point-normal equation for the plane is
$$
n_x(x-x_0)+n_y(y-y_0)+n_z(z-z_0)=0.
$$
Answer: Pick a point $(x,y,z)$ in the plane, then the vector $(x-2,y-3,z+4)$ is a vector in the plane. Therefore the dot product of the vector and the normal vector is $0$ so we get $(x-2)-(y-3)+2(z+4)=0$(This is the point normal form) which is the same as $x-2-y+3+2z+8=0$ which is the same as $x-y+2z=-9$.
Answer: Consider the equation of the plane: ax+by+cz=c. This is of the form f(x,y,z)=c, which is level to the the function f(x,y,z). Since the gradient $\nabla$f(x,y,z) is always perpendicular to the level of a function. So that means that the normal is $<a,b,c>$. Do you know how to find the equation of the plane?


Application of Dynkin's formula

Question: Let $x\in\mathbb{R}^d, (W_t)_{t\geq0}$ be a $d$-dim. Brownian motion. I have the following processes
$$
Z_{t, x} = b(Z_{t, x})dt + \sigma(Z_{t, x})dW_t, \qquad Z_{0, x} = x \\
V_{t, v} = \nabla b(Z_{t,x})V_{t,v}dt + \nabla \sigma(Z_{t,x})V_{t,v}dW_t, \qquad V_{0, v} = v\\
U_{t, v, v'} = (\nabla b(Z_{t,x})U_{t, v, v'} +  \nabla^2b(Z_{t, x})[V_{t, v'}]V_{t,v})dt \\ + (\nabla \sigma(Z_{t,x})U_{t, v, v'} +  \nabla^2\sigma(Z_{t, x})[V_{t, v'}]V_{t,v})dW_t, \qquad U_{0, v, v'}=0,
$$
i.e. a stochastic process and its first and second variation process, formally derived by differentiating $Z_{t, x}$ in direction $v\in\mathbb{R}^d$, and then $v'\in\mathbb{R}^d$.
Let $(P_t)_{t\geq0}$ denote the transition semigroup, i.e. $(P_tf)(x)=\mathbb{E}[f(Z_{t,x})]$. Can someone explain, why Dynkin's formula would lead to
$$
\mathbb{E}\left[ (P_tf)(x) \int_0^t\langle \sigma^{-1}(Z_{s,x})U_{s, v, v'}, dW_s \rangle \right] = 0?
$$
To my knowledge, letting $\mathcal{A}$ denote the infinitesimal generator, Dynkin's formula reads
$$
(P_tf)(x) = \mathbb{E}[f(Z_{t,x})] = f(x) + \mathbb{E}\left[\int_0^t(\mathcal{A}f)(Z_{s,x})ds\right] \\
= f(x) + \mathbb{E}\left[\int_0^t \langle b(Z_{s,x}), \nabla f(Z_{s,x}) \rangle +  \langle \sigma(Z_{s,x})\sigma^T(Z_{s,x}), \nabla^2 f(Z_{s,x}) \rangle_{\mathrm{F}} ds\right],
$$
where $\langle \cdot, \cdot \rangle_F$ denotes the Frobenius scalar product. I don't see how that helps here...
Comment: My word the notation is complicated. Can you provide the PDF/textbook/paper/talk video  where you saw these expressions and reasoning? I am asking you just in hope that there's some intuition regarding $Z,V,U$ and so on, because at the moment they seem so arbitrary to me! I still think your problem is down to putting notation properly and doing the computation carefully, which I'm willing to do provided everything is a little clearer to me than at present.
Comment: @TeresaLisbon This is the [paper](https://arxiv.org/pdf/1611.06972.pdf). The process $Z$ is defined on p. 5, $V$ and $U$ on p.28, the cited eqn. is on p.31 (starting with $\mathbb{E}[J_{3, x}]=~...$). I think the solution is easy, though, and as you said I was indeed not seeing the forest for the trees. $(P_tf)(x)$ is deterministic, so it factors out of the expectation, and then we're left with a sum over expectations of integrals w.r.t. to a brownian motion, which is zero? Does that make sense?
Comment: Let me have a look and get back. The paper you have attached seems a nice read, so I will go through all the material and make sure that you are correct. +1 to your question, for participating and otherwise putting in MathJax.
Comment: Thanks a lot. If my comment is correct, I'd still be wondering why the authors claim to use Dynkin's formula here...
Comment: I am actually trying to figure out that as well. I have an explanation for the whole $E[J_3(x)]$ simplification somewhat ready, but I feel that it is incomplete until I find out what Dynkin's formula has to do with it. No clue till now.
Comment: You are right , however, about the forest from the trees. Indeed, that term is zero because the $P_tf(x)$ slips out, and then the expectation of a stochastic integral is $0$. Don't know what this has to with Dynkin's formula then. I am not able to get out of the second line, though.
Comment: I have solved the entire expression, and I don't see Dynkin's formula used anywhere. To see a concrete use of Dynkin's fomula, we see page 32 for usage of Dynkin's formula on both $V_{t,v}$ and $U_t$, where clearly derivative terms and so on are seen. So I think there's a typo, since only the Ito formula $(29)$ (and the fact that the stochastic integral) gets used to simplify $E[J_3(x)]$ . Can you suggest what would be a good answer to this question, now that we have this observation?
Comment: I think your last comment together with the fact that $(P_tf)(x)$ can be drawn out and the expectation of the stochastic integral is $0$ can serve as an answer. I'm happy to accept that if you want to post that as an answer. Thanks for your help!
Comment: Thank you so much for clarifying that. I will take my time, and in addition add a few more things I need to, so that this answer can be of help to others than just you. Thank you once again.
Answer: Introduction to the paper
This answer focuses on the paper attached here. The paper measures sample quality using diffusions. The main idea for this is the idea of Stein's discrepancy method, a powerful idea in probability theory which allows the upper bounding of usual probabilistic distances by an appropriate Stein discrepancy. The Stein discrepancy involves the use of Ito diffusions, and in order to ensure that the Stein operator is well behaved, one needs good bounds on the behaviour of the underlying semigroup of the Ito diffusion, which we call $P_t$. The Ito diffusion will be called $Z_{t,x}$, the initial point being $x$ and time being $t$. We have $P_t f(x) = \mathbb E[f(Z_{t,x})]$.
On the use of Dynkin's formula
The main reference for stochastic calculus of the paper is Avner Friedman, Stochastic Differential Equations And Applications. As per the paper , equation (7.10) of the text has the following statement :

Dynkin's formula : Under suitable integrability conditions ,
$$
\mathbb Eu(\xi(t),t) - \mathbb Eu(\xi(0),0) = \mathbb E\int_0^\tau Lu(\xi(s),s)ds
$$
where $u(\psi(t),t)$ is a suitable function, $d\xi(t) = A(t)dt + B(t)dw(t)$ is an Ito diffusion and $L = \frac{1}{2}\sum_{i,j} (B^TB)_{ij} \frac{\partial^2}{\partial x_i\partial x_j} + \sum_{i} A_i\frac{\partial}{\partial x_i} + \frac{\partial}{\partial t}$ is the associated semigroup operator of $\xi$.

It is clear, that the use of Dynkin's formula must involve differentiation of a certain kind, since $L$ involves the same.
For a clear use of Dynkin's formula, we witness page number $32$ of the paper, where we see that in both applications of Dynkin's formula, derivatives clearly appear on the functions $\sigma$ and $b$.
The story of $\mathbb E[J_3(x)]$
To compute $\mathbb E[J_3(x)]$, nowhere is Dynkin's formula used, unlike what the author says. Indeed, what is used is equation $(29)$ at the end of page number $30$.
$$
f(Z_{t,x}) = (P_tf)(x) + \int_0^t \langle \Delta (P_{t-s}f)(Z_{s,x}) ,\sigma(Z_{s,x}) dW_s\rangle
$$
which is derived by applying the Ito formula to $(s,x) \to P_{t-s}f(x)$, a $C^2$ function.
From there, we have :
\begin{align}
\mathbb E[J_3(x)] & = \frac{1}{t} \mathbb E\left[f(Z_{t,x}) \int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right]  \\ &= \frac{1}{t} \mathbb E\left[\left((P_tf)(x) + \int_0^t \langle \Delta (P_{t-s}f)(Z_{s,x}) ,\sigma(Z_{s,x}) dW_s\rangle\right) \int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right] \\ &= \frac 1t \mathbb E\left[P_tf(x)\int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right] \\ &+ \mathbb E\left[\int_0^t \langle \Delta (P_{t-s}f)(Z_{s,x}) ,\sigma(Z_{s,x}) dW_s\rangle\int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right]
\end{align}
Of these, the first term vanishes since the $P_tf(x)$ comes outside the integral and we are left with the expectation of a stochastic integral, which is a martingale starting at $0$ hence has constant expectation equal to $0$. For the second term, we observe the form of Friedman's Ito theorem statement and how it was translated here, and obtain by expansion a result which I find bewildering but definitely true :
$$
\left\langle\Delta (P_{t-s}f)(Z_{s,x}) ,\sigma(Z_{s,x}) dW_s \right\rangle= \sum_{l=1}^n \sum_{i=1}^m [\Delta (P_{t-s}f)(Z_{s,x})]_i  \sigma(Z_{s,x})_{il} (dW_s)_l \\ = \sum_{l=1}^n (\Delta P_{t-s}f(Z_{s,x})\sigma(Z_{s,x}))_l (dW_s)_l =\left\langle \Delta (P_{t-s}f)(Z_{s,x}) \sigma(Z_{s,x}), dW_s   \right\rangle
$$
which is kind of saying that the $\sigma$ term can come from right to left side. I don't know why it was kept on the right in the first place, this could have even been a typo for all I know.
Anyway, now we come to :
$$
\mathbb E\left[\int_0^t \langle \Delta (P_{t-s}f)(Z_{s,x})\sigma(Z_{s,x}), dW_s\rangle\int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right]
$$
and are in the "covariance of Ito-Integrals" territory. Indeed, by equation (7.1) of Friedman applied coordinatewise, we get :
$$
\mathbb E\left[\int_0^t \langle \Delta (P_{t-s}f)(Z_{s,x})\sigma(Z_{s,x}), dW_s\rangle\int_0^t \left\langle \sigma^{-1}(Z_{s,x})U_{s,v,v'},dW_s\right\rangle\right]
 \\ = \mathbb E\left[\int_0^t \left\langle \Delta (P_{t-s}f)(Z_{s,x})\sigma(Z_{s,x}), \sigma^{-1}(Z_{s,x})U_{s,v,v'}\right\rangle ds\right]$$
whence we can again use the same coordinatewise expansion logic we applied last time in the Ito integral form, for this expression to bring the $\sigma^{-1}$ over to the left of the $\sigma$ and cancel out, to get :
$$
\mathbb E\left[\int_0^t \left\langle \Delta (P_{t-s}f)(Z_{s,x}), U_{s,v,v'}\right\rangle ds \right]
$$
which is the final expression obtained by the authors of the paper as well.
Final thoughts
I feel that the paper skips many steps, and struggles to integrate its notation with that of the standard reference. However, the use of the Stein discrepancy in this particular instance is very nice, and I would suggest going through the paper without really looking at the details and just understanding the flow and what is happening in general, because it should not take too much effort for an expert to fill in details if and when required.
Comment: Congrats on your taxicab answer! :)
Comment: @LightYagami Apologies, I don't know what that means. Are you referring to the Ramanujan incident , where Hardy tells him he came in a taxi numbered 1729? I don't recall having written an answer based off that. This answer is correct, I think the downvote is scattered. I do, however, mildly regret reading that paper. It is very very poorly written. It is almost like they want to cover the intuition, and just want to brush the details under the carpet so kept the details very terse and poorly jointed.
Comment: Yes I was referring to [Taxicab numbers](https://en.wikipedia.org/wiki/Taxicab_number#:~:text=In%20mathematics%2C%20the%20nth%20taxicab,%3D%2093%20%2B%20103.). I don't have to say anything related to this answer because I don't understand this, I am preparing for JEE.
Comment: @LightYagami Oh, it's my 1729th answer! On the exact day that I celebrate my fifth anniversary on Stack Exchange as well! It is extremely rare that I get downvoted, mostly scatter, so I'm a little unhappy at the end of the day, but well, that was nice! Thank you for pointing it out.
Comment: @LightYagami I hope you read the answer before doing so. I don't want this to look rigged , that's the point.But thank you! If you like, I'll run you basically through what's going on in the paper. Keeping in mind the JEE background, of course. Not today, I'm too sleepy. But on a good day, maybe tomorrow you can pop in [here](https://chat.stackexchange.com/rooms/119549/teresa-lisbon-senior-agent-cbi) to ask for it.
Comment: I don't even know what stochastic even means... can I understand that?
Comment: @LightYagami I will explain everything about this answer, considering your background. The simplest possible explanation will come. Of course, on another day that suits us.
Comment: Sure, I will ask tomorrow then!
Comment: @LightYagami I'm sure we are on the same time zone, so : good night!
Comment: @LightYagami Ready?
Comment: @LightYagami Actually, maybe another day. Probably a weekend, because I am not free unfortunately right now. If you are preparing for the JEE we will do this once you are a little free, I am sure your schedule will be up and down due to these factors. Please reply when you'd like to hear, I am sure you will like it.
Comment: yes, that is why I didn't ask today. I have my JEE MAINS day after tomorrow. So after that, sure!
Comment: @LightYagami Good luck for the same. Hope to see some good questions from there on the site, hopefully good quality well written questions.
Comment: I am done now with my exam. Now you can explain this answer whenever you get time... BTW I am also a great fan of THE MENTALIST..it is my favourite show!!!

Application of Dynkin's formula


Determining the limit $\lim_{x\to a}\frac{x^3-a^3}{x-a}$ with variables

Question: How can I figure out the following limit:

$$\lim_{x\to a}\dfrac{x^3-a^3}{x-a}$$

I always seem to get that the limit is zero but it isn't.
Thanks in advance!
Comment: You need to show us your working : we will tell you what is wrong
Comment: Use $(x^3-a^3)=(x-a)(x^2+ax+a^2)$
Answer: One may use derivative definition
$$\lim_{x\to a}\dfrac{x^3-a^3}{x-a}=(x^3)'\Big|_{x=a}=3a^2$$
or using identity
$$\lim_{x\to a}\dfrac{x^3-a^3}{x-a}=\lim_{x\to a}\dfrac{(x-a)(x^2+ax+a^2)}{x-a}=3a^2$$
even l'Hospital rule works here
$$\lim_{x\to a}\dfrac{x^3-a^3}{x-a}=\lim_{x\to a}\dfrac{3x^2}{1}=3a^2$$
Answer: Let $x=a+h$.
$$\lim_{h\to0}\frac{(a+h)^3-a^3}h=\lim_{h\to0}\frac{3a^2h+3ah^2+h^3}h=\lim_{h\to0}(3a^2+3ah+h^2).$$
You can conclude.
Answer: In the numerator, you have a difference of two cubes.
$$x^3-a^3 = (x-a)(x^2+xa+a^2)$$
Simply rewrite the limit using the factored form.
$$\lim_{x \to a} \frac{x^3-a^3}{x-a} \implies \lim_{x \to a} \frac{(x-a)(x^2+xa+a^2)}{x-a}$$
Now, just cancel out $x-a$ and simplify.
$$\lim_{x \to a} x^2+xa+a^2 = a^2+a(a)+a^2 = 3a^2$$


Can a player receive a direct red card after receiving the second yellow card?

Question: On 13th August 2017, Cristiano Ronaldo was sent off in win over Barcelona:

He was given a first yellow card for removing his shirt during the celebration of a goal.
A couple of minutes later, he got the second yellow card for diving to attempt to win a penalty.

The second yellow card made him be sent off. After receiving the red card he pushed the referee. Such action normally involves a direct red card, but he had already received it.
So my question is:
After receiving a second yellow card, can a player get an "extra" red card for a blatant bad behaviour?
My impression is that a player in that situation is already out of the game, so any actions involving suspension will just be written down by the referee in the "certificate" of the game, so the federation will study it after the game and, eventually, penalise the player. However, I don't know if this is what rules say.
Answer: The situation you are interested in is not explicitly mentioned in Laws of the Game or specifically in Disciplinary Code of Royal Spanish Football Federation (PDF in Spanish, page 56).
Showing a direct red card after showing a red card for two accumulated yellow cards is redundant. Because what is more important, as you have already guessed, is what the referee wrote in the post-match protocol.
And here comes the most entertaining part: what has Ricardo de Burgos Bengoetxea mentioned in his protocol? Below you can see the original protocol, published by MARCA:

Which states:

Cautions:
79th minute. Player #7 Cristiano Ronaldo was cautioned for the
  following reason: removing off the shirt during goal celebration.
82th minute. Player #7 Cristiano Ronaldo was cautioned for the
  following reason: foul simulation.
Dismissals:
82th minute. Player #7 Cristiano Ronaldo has been sent off for the
  following reason: second yellow card.
Other incidents:
Once shown the red card Cristiano Ronaldo pushed me slightly in a sign
  of disagreement.

As a result of this incident, Cristiano Ronaldo was banned for five games. So, this decision has been made because the referee mentioned it in the protocol and regardless whether Ronaldo received direct red card or not.
Answer: gdrt's answer provides an excellent summary of what occurred in the incident you provided as an example.
In general, a player cannot receive multiple "red cards" in the same match. The reasoning behind this becomes apparent when you refer to the sanction as a sending-off, rather than a "red card". The card is only a signal of the sanction.
Law 12 - Fouls and Misconduct, Section 3 - Disciplinary Action:

The yellow card communicates a caution and the red card communicates a sending-off.

It is obvious that a player cannot be sent-off more than once in a match. The Laws do not explicitly state this, but it is implied in Laws 3 and 12.
Law 12 - Fouls and Misconduct, Section 3 - Disciplinary Action:

A player, substitute or substituted player who has been sent off must leave the vicinity of the field of play and the technical area.
...
Only a player, substitute or substituted player may be shown the red or yellow card.

In Law 3 - The Players, Section 7 - Extra Persons on The Field of Play, the following language is used:

... a team official, substitute, substituted or sent off player ...

In Law 12 - Fouls and Misconduct, Section 4 - Restart of Play After Fouls and Misconduct, the following language is used:

...  opposing player, substitute, substituted or sent off player, or team official ...

The distinction is made, as:

when a player, substitute or substituted player is sent off, they become a sent off player
only players, substitutes and substituted players can be sent off
therefore, players who are already sent off cannot be sent off again - the red card or yellow card is not shown for subsequent sending-off or cautionable offences committed by a player after they have been sent off.

As happened in this case, if a player commits further misconduct (e.g. cautionable or sending-off offences) after having been sent-off, it is simply noted in the referee's report and the competition's disciplinary administrator or committee makes a determination on the matter.
Answer: Based on the language used, some responders appear to believe that merely showing the second yellow is a dismissal.  This is incorrect.  After the second yellow and before the restart of play, the referee must actually SHOW the red card following the display of the second yellow card.  As others have correctly noted, once this occurs, the player (or substitute) becomes a dismissed player and therefore cannot be shown any further cards of any color for any reason.  Any behavior that might be cautionable or warrant a dismissal is simply included in the match report and left to the discretion of the competition authority.
Comment: @fedorqui In 2004 world cup Graham Poll showed Croatia's Josip Simunic three yellow cards before sending him off. That means Simunic stayed in the pitch for some time however brief that is.
Comment: This is interesting. What if the referee does not show the red card  following the display of the second yellow card? Would the player still be able to remain in the field?
Comment: Yes, and Poll resigned as a result of this grievous error (but for this event, he had been a well-respected official -- after all he was at the WC!).  He explained later that he had misidentified Simunic for the first yellow (put another player's name down in his book) and thus, in the heat of the 2nd yellow, did not realize it was indeed a 2nd until an AR advised him of this upon the issuance of the 3rd yellow.  Actually, the rest of Poll's crew have to share at least some of the blame for the mistake as (especially at this level) backup tracking of such things is a standard pregame topic.
Answer: The Laws of the Game do account for such situations:

[The referee] has the authority to take disciplinary action from
  entering the field of play for the pre-match inspection until leaving
  the field of play after the match ends

(Laws of the Game, 2016-2017, Law 05: The Referee, point 3. Powers and duties, Disciplinary action)
The next bullet clarifies that this includes showing yellow or red cards. Yet, I do not know about actually displaying a second red card - that is probably redundant as gdrt said in their reply.


Databases "Synchronized / In Recovery" after adding server to SQL Avaylability Group

Question: I have an SQL AlwaysOn Availabilty Group configured with 2 nodes. The AG works without any problem with this 2 nodes and I can do a failover to/from any of them (this servers are on the same network).
Recently, I added another server to the AG, but this one is an Azure VM. I successfully added it to the AG, with seeding mode 'automatic', and configured as a "Readable secondary". All the databases get created on the Azure VM, but they stay in "Synchronized/In Recovery" mode, I have restarted the server, remove the database and added it again, but always all the databases stays on that mode. On the on-premise secundary replica, all databases are in "Synchronized" mode and I can access to all databases for read only operations.
How can I take those databases out of the "In Recovery" state?
Regards.
Answer: I found the problem, I was using a newer version of SQL (SQL 2017) on the new replica, but the primery was SQL 2016. After installing SQL 2016 on the new replica, all databases in "Syncronized" and available for read-only access.


Proving differentiable mapping is onto

Question: Let $f: \mathbb{R}^n \rightarrow \mathbb{R}^n$ be a differentiable mapping such that there is a $C > 0$ satisfying $C|x-y| \leq |f(x) - f(y)|$ for all $x,y \in \mathbb{R}^n$.  Prove that $\det f'(x) \neq 0$ for all $x \in \mathbb{R}^n$ and then deduce that $f(\mathbb{R}^n) = \mathbb{R}^n$.
I am really stuck on this, but it's a problem I've been working on for a while.  I have used the first inequality to show that $f$ is one-to-one.  Am I on the right track, or is there something additional I can determine from this inequality?
Answer: 1) If $\det f'(x) = 0$, then there is a vector $h$ such that $f'(x)h = 0$. What happens now, from the definition of the derivative?
2) The easiest way I can see to do this is use invariance of domain. Since you've shown $f$ is 1-1, you know that $f(\mathbb{R}^n)$ is an open set. (I suppose you secretly don't need invariance of domain, only the IFT.) Now, I claim you can also show it's closed, using your condition. (Recall some facts about Cauchy sequences for this.) Hence it must be all of $\mathbb{R}^n$.
Comment: Thank you, this was very helpful

Proving differentiable mapping is onto