Changing JavaScript object definition style causes canvas to stay blank

Question: I'm making an HTML5 game using the canvas tag and I'm trying to change the way I define a class I have created in JavaScript and I had it working with one definition style and when I tried to define it in another style it stopped working.  I am not sure what I did wrong as I am just getting familiar with JavaScript.  When I tried the other style of defining, my canvas just doesn't work and nothing appears on the screen.
Essentially in the version that is not working, I am trying to create the object Player() and then create a new player object with so that I can use the rest of the player.doThis() calls I make throughout the rest of the script.
var player = new Player();

WORKING DECLARATION
var player = {
    color: "#00A",
    x: 10,
    y: playerLocation,
    width: 32,
    height: 32,
    speed: (10/1830) * CANVAS_WIDTH,
    zone: [0, 0],
    //sprite: Sprite("player.png"),
    //spriteImage: new Image(),
    //spriteImage.src =  "player.png",

    draw: function() {
        canvas.fillStyle = this.color;
        canvas.fillRect(this.x, this.y, this.width, this.height);
    },

    drawDebug: function() {
        canvas.font = "normal 7pt Arial";
        //canvas.fillText("Cosine: " + transition , this.x, (this.y-55));
        canvas.fillText("In Zone " + this.zone[0] + " of " + this.zone[1], this.x, (this.y-45));
        //canvas.fillText("Zones " + this.zone[1], this.x, (this.y-55));
        canvas.fillText("X: " + this.x , this.x, (this.y-35));
        canvas.fillText("Y: " + this.y , this.x, (this.y-25));
    },

    determineZones: function(numberOfZones) {
        //this sets the boundaries of the zones
        zoneLocations[0] = 0;
        var gap = CANVAS_WIDTH - (infoBoundaries * 2) - infoWidth;
        for (var i = 1; i < numberOfZones; i++)
        {
            zoneLocations[i] = (gap / (numberOfZones - 1)) * i;
        }
    },

    update: function() { //all of the controls are placed in here
        if ((keydown.left) || (keydown.a))
        {
            this.x -= this.speed;
        }
        if ((keydown.right) || (keydown.d))
        {
            this.x += this.speed;
        }
        this.x = this.x.clamp(0, CANVAS_WIDTH - this.width);

        if(scene == SCENES.length)//this would added controls for perhaps that last boss levels
        {
        }
    },

};

NOT WORKING DECLARATION (that I am trying to get working)
function Player()
{
    this.color = "#00A";
    this.x = 10;
    this.y = playerLocation;
    this.width = 32;
    this.height = 32;
    this.speed = (10/1830) * CANVAS_WIDTH;
    this.zone = [0, 0];
    //sprite: Sprite("player.png"),
    //spriteImage: new Image(),
    //spriteImage.src =  "player.png",

    function draw()
    {
        canvas.fillStyle = this.color;
        canvas.fillRect(this.x, this.y, this.width, this.height);
    }

    function drawDebug()
    {
        canvas.font = "normal 7pt Arial";
        //canvas.fillText("Cosine: " + transition , this.x, (this.y-55));
        canvas.fillText("In Zone " + this.zone[0] + " of " + this.zone[1], this.x, (this.y-45));
        //canvas.fillText("Zones " + this.zone[1], this.x, (this.y-55));
        canvas.fillText("X: " + this.x , this.x, (this.y-35));
        canvas.fillText("Y: " + this.y , this.x, (this.y-25));
    }

    function determineZones(numberOfZones)
    {
        //this sets the boundaries of the zones
        zoneLocations[0] = 0;
        var gap = CANVAS_WIDTH - (infoBoundaries * 2) - infoWidth;
        for (var i = 1; i < numberOfZones; i++)
        {
            zoneLocations[i] = (gap / (numberOfZones - 1)) * i;
        }
    }

    function update()
    { //all of the controls are placed in here
        if ((keydown.left) || (keydown.a))
        {
            this.x -= this.speed;
        }
        if ((keydown.right) || (keydown.d))
        {
            this.x += this.speed;
        }
        this.x = this.x.clamp(0, CANVAS_WIDTH - this.width);

        if(scene == SCENES.length)//this would added controls for perhaps that last boss levels
        {
        }
    }
}
var player = new Player();

Anyways, if there is something I am doing incorrectly for defining this javascript class please let me know.
Comment: You need to do `this.update = function() { ... }` instead of `function update() { ... }`
Comment: @KyleStacey Check your console (ctrl+shift+j in chrome). Any errors?
Comment: ...or pull the method definitions out of the constructor function and define them afterwards on the prototype with `Player.prototype.update = function() { ... }`.
Comment: I wish either of those worked but still no change in the page.  This is the page I am trying to get working http://game.kstacey.com/testing.html and it works here http://game.kstacey.com/
Comment: Getting closer to it now.  Current error: Unable to get property of 'x' of undefined or null reference
Comment: My player doesn't show up but thanks to all of your guys' help it is back to a state where I can continue debugging on my own.  Thanks so much guys!
Comment: It's all working now!  Thanks guys!
Answer: The problem is you are creating methods using function functionName() {} instead of this.functionName = function() {} (note the this part, it's important). Unfortunately, you can't do function this.functionName() {} because that's a syntax error.
You could see this by doing console.log(player.update), and you would see that it is undefined.
The solution: use this when creating your functions.
this.draw = function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
}

this.drawDebug = function() {
    canvas.font = "normal 7pt Arial";
    //canvas.fillText("Cosine: " + transition , this.x, (this.y-55));
    canvas.fillText("In Zone " + this.zone[0] + " of " + this.zone[1], this.x, (this.y - 45));
    //canvas.fillText("Zones " + this.zone[1], this.x, (this.y-55));
    canvas.fillText("X: " + this.x, this.x, (this.y - 35));
    canvas.fillText("Y: " + this.y, this.x, (this.y - 25));
}

// So on

this.update = function() { //all of the controls are placed in here
    if ((keydown.left) || (keydown.a)) {
        this.x -= this.speed;
    }
    if ((keydown.right) || (keydown.d)) {
        this.x += this.speed;
    }
    this.x = this.x.clamp(0, CANVAS_WIDTH - this.width);

    if (scene == SCENES.length) //this would added controls for perhaps that last boss levels
    {}
}

Alternatively, you could attach functions to the prototype object. For example:
function Player() {
  // Non function declarations here
}
Player.prototype.draw = function() {
  // Whatever
}
Player.prototype.drawDebug = function() { // etc.
}

The advantage is you save memory, especially since you probably won't be reassigning to these properties (that is, you won't write player.draw = function() { /* New function here */ } will you? It's okay if you do that, even with the prototype method, it just won't save memory.
The (possible) disadvantage is that player.hasOwnProperty("draw") or player.hasOwnProperty("drawDebug") will return false (even though player has that property). Another disadvantage is that those functions won't be able to directly access any var declarations in the constructor.


Understanding function of diminished chord in Paganini's 4th caprice

Question:
I'm trying to understand this simple progression in the middle of Paganini's 4th caprice.
This seems like I-?-I-V7-I in Eb major, but I am unable to figure out what the function of the second chord is. I know it is Ebdim7 (or Adim7 or Gbdim7 or Cdim7).
My attempts:

There is some nice voice leading from the A-nat to the B-flat in the third chord, which suggested it is a secondary leading chord of some sort, but the third chord is Eb, which doesn't make sense: io7 - I??
Perhaps the second chord could be viio7/V7, but this doesn't seem to make sense if there is a I chord between the viio7/V7 and the V7.
Comment: You offered some interesting reflections on this progression in your points under "My Attempts".  Hidden in your attempts lies the real music theory: an open-ended investigation of the question you posted. All too often our "answers" on these forums miss the real truth under the guise that short and common understandings equate to truth. Thank you for that.
Comment: Yes, this is - like you assume - a secondary viio7, you can say it resolves to I 46.
Comment: @Ootagu Yes, it is nice to see that my two attempts were not too far off: my first attempt is heading toward the "common-tone diminished" idea in Aaron's answer, and my second attempt is related to the "secondary leading chord to the dominant" idea in Albercht Hügli and Dekkadeci's answers.
Answer: This is basically a better-phrased version of Albrecht Hügli's answer, but I'd treat the chord progression as this, with the diminished chord in bold:
Isus4 - I - vii°7/V - I6/4 - V7 - I
Yes, I'd treat the diminished 7th chord as a secondary dominant, especially since it resolves its root by step to I6/4, then V7. The I6/4 chord is so strongly associated with the V chord and resolves into a version of it so often that some textbooks (including one I learned from) call it V6/4 instead.
Comment: It's an endless and fruitless discussion whether this is V64 (dominant with suspension) or the 2nd inversion of the tonic. I wrote I 46 as in German it is called  a *fourth-sixth* chord. The dim 7 can be considered as #IVdim7 or vii dim7/V.
Answer: This is a "common-tone diminished seventh chord". It's used, in this case, as an elaboration of the I chord. You can read more about it and see examples in a few SE questions:

Diminished chord constructed over the tonic degree?
A chord progression from Leavitt: how to analyze it correctly
How does this Bdim7 resolves to F/C?
Is this a harmonic sequence?
What's going on functionally/structurally in these four bars of Rachmaninoff's 3rd piano concerto?
Where does the Eb diminished 7 in I Wanna Be Around come from and how to play over it?
Answer: A,C,Eb,Gb (=vii o7) -> Bb,Eb,G (=I46) (resp. V46
The secondary  VIIdim to the dominant (also interpreted as #IVdim) usually in a I46 chord - like in your example.
e.g.:
Very common in Bach's recitatives!
Comment: It does resolve - to V. The 'I64' shouldn't be thought of as  chord I but as chord V with dissonant 4 which resolves to 3, dragging 6 to 5 in the process
Comment: This is a good example of the *opinion based* side of music theory. I can live with both interpretations while others make a dogmatic arguing. The theory is derived of historical evolution and development of harmony and counterpoint.
Comment: I think keeping the distinction between I64 based on 'morphology' and V64 as 'function' is worthwhile in thinking about much 19C Western Classical music (and earlier). In Paganini's time it was unquestioned that a perfect fourth above the bass was *always* dissonant and needed to resolve to a consonance. In the OP's example the E-flat in the third chord is a perfect fourth above the bass, hence dissonant, hence not part of 'the chord'. Opinion yes, but the opinion of Paganini's contemporaries, so relevant to theory, if only in historical context.
Comment: What is the functional purpose of a secondary dominant that doesn't resolve?


Constructing Simultaneous Equation for This Problem

Question: Suppose we have a rating system where a "thumbs up" equals +1 and a "thumbs down" equals - 1. We know the total number of votes cast and the current score. For example a score of +3 with 5 votes cast.
How can we determine how many "thumbs up" and "thumbs down" there are?
I imagine this would be some sort of simultaneous equation....
Comment: Let $u$ be the number of ups and $d$ the number of downs. Then in your example $u-d=3$, $u+d=5$. Solve.
Answer: $x$: number of up votes
$y$: number of down votes
Now solve
$$x+y=5$$
$$x-y=3$$
Answer: Let the number thumbs up be $u$, let the total number of votes be $n$, and let the total score be $t$. Then we can say that the number of thumbs down votes must be $n-u$, so we can write:$$u-(n-u)=t$$$$\therefore 2u-n=t$$$$\therefore u=\frac{t+n}{2}$$


Calculate the expectation of games won by a team

Question: I've come across this problem on a forum, seems interesting.
Assume a soccer team has played $N$ soccer games and has scored 0 goals and also has conceded 0 goals. Therefore we know the team won't be able to win any of the games. Now if the soccer team has scored $N$ goals and has also concede $N$ goals, what is the expectation of the games won by this team?
Comment: The answer can be anything between $0$ and $N-1$ games won.
Answer: Let me first rephrase the question:
Let A and B be two soccerteams that have played exactly $N$ games against each other. It is known that after all these games, each team scored exactly $N$ goals. What is the expected number of games won by team A?
I will assume the following: if we consider, say, team A and one goal scored by that team, the probability that goal has been scored is the same for every game played and does not depend on the other goals scored. I think this is the most natural way to think about the problem, but it of course depends on the precise mathematical interpretation of something belonging to the real world.
Now for the solution: If $N_A$ is the expected number of games won by team $A$ and similarly for $B$ then by symmetry, $N_A= N_B$. Also, if $N_D$ is the expected number of draws, then $N_A + N_B + N_D = N$, so $N_A = \frac12 (N-N_D)$.
By symmetry again, $N_D = N \times P$, where $P$ is the probability the first match will be a draw. Then let $P[i]$ denote the probability that the number of goals scored by team $A$ in the first game equals $i$. (In particular $P[0] + \dots + P[N] = 1$.) By symmetry again, the same probabilities apply to team B and in particular, $P = \sum_{i=0}^N P[i]^2$, i.e. a draw occurs when both teams happen to score the same amount of goals in the first match. So we try to determine $P[i]$.
$P[i]$ is given by the number of "good combinations" / the total number of combinations. Here a "combination" is a sequence of $N$ numbers ranging from $1$ to $N$, such that the $k$'th number records in which match the $k$'th goal was scored. (E.g. for $N=3$ the sequence 1-2-1 would mean that of the 3 goals scored by team A, the first was scored in the first game, the second in the second game, the thirth in the first game.) There are of course $n^n$ possible combinations. The ones that contain exactly $i$ times $1$ are "good". To find these combinations, we may determine $\binom{N}{i}$ positions first and then fill in the other positions in $(N-1)^{N-i}$ ways with the remaining numbers from $2$ to $N$. This gives us
$$ P[i] = \frac{ \binom{N}{i} (N-1)^{N-i} }{N^N}. $$
Therefore the answer is given by
$$ N_A = \frac{N}2 \left[1 - \sum_{i=0}^N \left( \frac{\binom{N}{i}(N-1)^{N-i}}{N^N}\right)^2  \right].$$
Presumably this can further be simplified, and quietly I'm hoping there is a clever combinatorial argument that counts this number in another way, meanwhile simplifying this equation, but I'll leave it just here.
Comment: Fairly nice analysis. Thanks!


É possível acessar a chave através do valor:

Question: Em dicionários, em Python, é possível acessar uma chave através do valor? Há algum método que inverta chave/valor?
Answer: O dict não possui nenhum método nativo para isso. Mas existe uma manobra que pode ser feita.
Você pode utilizar o método values, que retornará uma list. Daí você pega o índice dessa lista e obtém os valores da outra lista gerada pelo método keys.
Confuso? Então vamos a um exemplo:
valores = {"valor_16" : 16, "valor_17" : 17}

valores.keys()[valores.values().index(16)]; // "valor_16"

Resposta original no SOEN
Comment: Muito obrigado!


Book for starting classical guitar player?

Question: Please excuse my ignorance, I have zero knowledge/experience:
In my mind I have two categories of guitar playing: Strumming (associated with rock) and picking (associated with classical sounding music, jazz, etc.).
I do not want to learn about strumming at all, and in the picking category I do not want to learn any jazz, hip-hop, or modern-sounding music in general; I only want to learn classical-sounding music. Is there a book you would recomend for absolute beginners? I know how to read notes on a score but that's about it.
Answer: While I can't recommend a specific book, I suggest that you look into the beginner and self-instruction guides by Frederick M. Noad. Noad authored several instructional guitar books, many focusing on classical guitar playing for beginners.


Default value of user id in MQ message header

Question: In my application, I am sending message out to a Websphere MQ queue. Here in the application, users have the flexibility to set the user id in the message. However my problem is, since the parameter is configurable in my application, if users does not set it, from where the value will be taken?
I have gone through the below links, but got little idea about what value will be set for user id if it is not set at application level.

http://www-01.ibm.com/support/knowledgecenter/SSFKSJ_7.0.1/com.ibm.mq.csqzaw.doc/jm41030_.htm
How to set MQMD ApplicationID field via JMS API?

Any help is appreciated.
Answer: The MQMD.UserIdentifier field is set by the queue manager to the user ID associated with the connection (hConn) that put the message. You can see what this user ID is by looking at DISPLAY CONN or the Applications... display in MQ Explorer.
If your application is running using local bindings, that is, it is on the same machine as the queue manager and it chose not to use a socket, then the user ID that the queue manager will discover is the user ID that the application process is running with.
If your application is running using client bindings, that is, it is using a network conncetion to the queue manager, then the user ID that the queue manager will use is the one assigned to the MCAUSER of the channel connection which can be set by CHLAUTH rules, or security exits, or flowed from the client etc.
If your application is going to set the user ID in the MQMD of the message then the application must tell the queue manager it is going to do this, or whatever is in the MQMD.UserIdentifier field will be over-written with the above. To tell the queue manager it wants to do this, the application must use an additional option when it opens the queue, MQOO_SET_IDENTITY_CONTEXT and when it puts the message, MQPMO_SET_IDENTITY_CONTEXT. The open option also requires you to have the authorization to be allowed to do so, +setid when using setmqaut
Further reading:

Message Context
Controlling context information
Comment: Thank you for the response. +1 for clear explanation.


Vertical align Glyphicons with text CSS

Question: I'm getting an issue in my navbar between my tab and the associated glyphicons.
I would like to align vertically both elements to the center but I don't overcome to do that. I tried some things : text-align, vertical-align but I think the issue is with my
 and
elements.
This is my HTML/CSS part :

span.glyphicon {
  font-size: 1.7em;
  vertical-align: middle;
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 Accueil

I would like to shift glyphicons to the middle of each tab name.
Thank you !
Comment: You applied text-align to `span.glyphicon`, which is of course nonsense - that inline element is only as wide as its content demands it, so that "centering" that content is a fruitless endeavor. You want to apply it to the parent element, so that the (text and inline) content of that element gets centered.
Answer: You can try using flexbox..

span.glyphicon {
  font-size: 1.7em;
}

li {
  list-style: none;
}

li a {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

 Accueil

Comment: I tried your answer which seems to work in your case, but it doesn't work in my script.
Answer: This should work, text-align: center should be added to the parent element because span is an inline element and does not have a width.

span.glyphicon {
  font-size: 1.7em;
}

li {
  list-style: none;
  text-align: center;
}

li a {
  display: inline-block;
}
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

 Accueil

Answer: text-align:center will do the trick:

span.glyphicon {
  font-size: 1.7em;
}

li {
  list-style: none;
}

li a {
  text-align:center;
  display:inline-block;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

 Accueil

Vertical align Glyphicons with text CSS


Existence of solution to dynamical system

Question: How can I prove that there exists a solution to dynamical system presented below?
$$
\dfrac{dT}{dt} = \lambda - \alpha T + rT\bigg(1 - \dfrac{T+I}{T_{max}}\bigg) - kVT \\
 \dfrac{dI}{dt} = kVT - \beta I \\
 \dfrac{dV}{dt} = N \beta I - \gamma V \\
$$
Answer: Your right side is polynomial, thus continuous, so the local existence theorems apply.
As it is also locally Lipschitz, any solution of an initial value problem is unique.


On the $w^{\ast}$ Convergence of a Sequence of Measures

Question: Assume that $(\nu_{j})$ is a sequence of positive Radon measures supported in a compact set $K\subseteq\mathbb{R}^{n}$ and
\begin{align*}
\sup_{x\in{\mathbb{R}}^{n},r>0}\dfrac{1}{r^{n-\lambda}}\int_{B(x,r)}|M_{\alpha}\nu_{j}(y)|^{p}dy\rightarrow 0,
\end{align*}
where $0<\lambda,\alpha<n$, and
\begin{align*}
M_{\alpha}\nu_{j}(y)=\sup_{s>0}\dfrac{1}{s^{n-\alpha}}\nu_{j}(B(y,s)).
\end{align*}
The author claims that there is a subsequence of $(\nu_{j})$ that $w^{\ast}$ converges to a measure $\nu$ which supported in $K$.
I fail to see why it must be the case.
Apparently the author resorts to the Banach-Alaoglu Theorem of the sequential $w^{\ast}$ compact property regarding to the space of all positive Radon measures which supported in $K$.
Therefore we are to bound $(\nu_{j}(K))$. But how does one bound the quantity $\nu_{j}(K)$ in terms of the integral with respect to the fractional maximal function?
Answer: Assume that $K\subseteq B(0,M)$ for some $M>0$. Then for $y\in B(0,1)$ we have $B(y,M+1)\supseteq K$ and hence
\begin{align*}
\sup_{x\in{\mathbb{R}}^{n},r>0}\dfrac{1}{r^{n-\lambda}}\int_{B(x,r)}|M_{\alpha}\nu_{j}(y)|^{p}dy&\geq\int_{B(0,1)}|M_{\alpha}\nu_{j}(y)|^{p}dy\\
&\geq\int_{B(0,1)}\left(\dfrac{1}{(M+1)^{n-\alpha}}\nu_{j}(B(y,M+1))\right)^{p}dy\\
&\geq\dfrac{1}{(M+1)^{p(n-\alpha)}}\int_{B(0,1)}\nu_{j}(B(y,M_1))^{p}dy\\
&\geq\dfrac{1}{(M+1)^{p(n-\alpha)}}\int_{B(0,1)}\nu_{j}(K)^{p}dy\\
&=\dfrac{v_{n}}{(M+1)^{p(n-\alpha)}}\nu_{j}(K)^{p},
\end{align*}
so $\lim_{j\rightarrow\infty}\nu_{j}(K)=0$ and hence the sequence $(\nu_{j}(K))$ is bounded.


Inverse function of $x+\ln(x)$

Question: How can I find the inverse function of $$f(x)=x+\ln(x).$$
This function has an inverse function (I can prove it) but I couldn't find it.
Help please!
Comment: The inverse function of $f$ is just that; you can't express it in terms of elementary functions.
Comment: Start by identifying the domain and range of $f(x)$.  What do you expect to find in the way of an inverse of $f(x)$?
Answer: $y=x+lnx$
$y=ln(e^x)+ln(x)$
$y=ln(xe^x)$
$e^y=xe^x$
Here, you can use the Lambert W Function
$x=W(e^y)$

Inverse function of $x+\ln(x)$


Finding the minimum length of multiple lists

Question: I have three lists of different lengths.
For example
List1 is of length 40
List2 is of length 42
List3 is of length 47

How can I use the Python inbuilt min() or any other method to find the list with the minimum length?
I tried:
 min(len([List1,List2,List3]))

but I get TypeError: 'int' object is not iterable
Answer: You need to apply len() to each list separately:
shortest_length = min(len(List1), len(List2), len(List3))

If you already have a sequence of the lists, you could use the map() function or a generator expression:
list_of_lists = [List1, List2, List3]
shortest_length = min(map(len, list_of_lists))  # map function
shortest_length = min(len(l) for l in list_of_lists)  # generator expr

To find the shortest list, not the shortest length, use the key argument:
list_of_lists = [List1, List2, List3]
shortest_list = min(list_of_lists, key=len)

Answer: Use generator expression
min(len(i) for i in [List1,List2,List3])


post commit failed on SVN tortoise

Question: I get a SVN post commit failed:
Error msg is :
post-commit hook failed (exit code 255) with no output.
I tried few different scenerios:
1) Login putty as root and run the cmd in post-commit manually, able to execute the cmd successfully.
2) Login using user xxxx and run the same cmd, the cmd run failed.
So, i thought is the permission issue. but my question is that, whenever we SVN commit using SVN tortoise, are we committing as a xxxx user ? or as a root?
Note: I had included the user xxxx in the conf/passwd.
=============
My cmd in post-commit is :
#!/bin/sh
svn checkout svn://mmmm.my/mstardev /home/mmmm/public_html/mstardev

Comment: Post-commit hook runs on server side, so mentioning Tortoise in the title is misleading.
Comment: Also, it appears that you are using SVN as poor man's deployment tool. SVN is not meant to be used like that. Use proper deployment tool.
Comment: I was thinking that, after SVN commit from local to web server,then the post-commit in web server will execute that post-commit cmd. Is this not a correct use of SVN? I mention SVNTortoise was refering to the client I use to commit file to server.
Answer: 255 exit code in SVN hooks is (usually) "Permission problem" or "File not found"
You may be victim of both:

Hooks are executed in empty environment, thus - plain svn without full path to it may be (must be) problematic
Hooks executed under user, which runs used SVN-server and svnserver-user may have not rights for writing into /home/mmmm/public_html/mstardev

If you'll redirect stdout of checkout to stderr (/usr/bin/svn co --username ... --password ... 1>&2), you'll see results of svn co attempt

post commit failed on SVN tortoise


derivation of the cubic formula

Question: In my research I came across the following derivation of the cubic formula that was almost complete. However at the end it says to make  the substitution $u=z^3$ which would determine the roots. I am not quite sure how to do this and then how to determine the roots and I am looking for some help.
A general form for the cubic equation is,
$$ax^3+bx^2+cx+d=0 \tag{1}$$
To find the roots of this equation we first try to get rid of the quadratic term $x^2$. The substitution $x=y-\dfrac{b}{3a}$ helps in achieving our goal. This results in, $$ay^3+\left(c-\dfrac{b^2}{3a}\right)y+\left(d+\dfrac{2b^3}{27a^2}-\dfrac{bc}{3a}\right)=0\tag{2}$$ which we transform into the following, $$y^3+\dfrac{1}{a}\left(c-\dfrac{b^2}{3a}\right)y+\dfrac{1}{a}\left(d+\dfrac{2b^3}{27a^2}-\dfrac{bc}{3a}\right)=0\tag{3}$$ Upon assuming $e=\dfrac{1}{a}\left(c-\dfrac{b^2}{3a}\right)$ and $f=\dfrac{1}{a}\left(d+\dfrac{2b^3}{27a^2}-\dfrac{bc}{3a}\right)$ we get the equation as, $$y^3+ey+f=0\tag{4}$$ We reduce this equation by the substitution $y=z+\dfrac{s}{z}$ and choosing $s=-\dfrac{e}{3}$ we obtain the simplified equation as, $$z^6+fz^3-\dfrac{e^3}{27}=0\tag{5}$$ What only remains is to make the substitution $u=z^3$.
Comment: You would just have $$u^2+fu-e^3/27=0$$, which you can solve using the quadratic formula.
Comment: so then there is only 2 roots?
Comment: No. You would only have one from the quadratic formula, and because you do $u=z^3$, you need to take a cube root, and cube roots have three roots, analogous to how square roots have two roots. For example, $z^3=1$ has 3 roots: see http://www.math-only-math.com/the-cube-roots-of-unity.html
Comment: In fact, I asked a very similar question https://math.stackexchange.com/questions/2358214/cubic-formula-derivation-check-and-questions
Answer:
We start with the substitution  $z^3=u$ and obtain a quadratic  equation in $u$
  \begin{align*}
z^6+fz^3-\frac{e^3}{27}&=0\\
u^2+fu-\frac{e^3}{27}&=0\tag{1}
\end{align*}
We solve the quadratic equation (1) and get
  \begin{align*}
u_{0,1}=-\frac{f}{2}\pm\sqrt{\frac{f^2}{4}+\frac{e^3}{27}}\tag{2}
\end{align*}
Since $z^3=u$ we obtain from (2)
\begin{align*}
z_{0,1}=\sqrt[3]{-\frac{f}{2}\pm\sqrt{\frac{f^2}{4}+\frac{e^3}{27}}}
\end{align*}

We are free to select either $z_0$ or $z_1$ and we choose $z_0$. Since $z^3=u$ we know  there are three solutions
\begin{align*}
z_0,z_0 e^{\frac{2\pi i}{3}},z_0 e^{\frac{4\pi i}{3}} \tag{3}
\end{align*}

From (3) we can calculate the three solutions for $x$ via
  \begin{align*}
y=z-\frac{s}{3z}\qquad\text{ and }\qquad x=y-\frac{b}{3a}
\end{align*}
We finally obtain with $\omega_1=e^{\frac{2\pi i}{3}}$
  \begin{align*}
x_0&=z_0-\frac{s}{3z_0}-\frac{b}{3a}\\
x_1&=z_0\omega_1-\frac{s}{3z\omega_1}-\frac{b}{3a}\\
x_2&=z_0\omega_1^2-\frac{s}{3z\omega_1^2}-\frac{b}{3a}
\end{align*}

[2017-11-05] Add-on: Let's make an example to see the formulas in action.
Find the solutions of
\begin{align*}
\color{blue}{x^3-7x^2+14x-8=0}
\end{align*}

Step 1: We consider $ax^3+bx^2+cx+d=0$ and calculate $x=y-\frac{b}{3a}$.
We set $x=y+\frac{7}{3}$ and obtain
  \begin{align*}
y^3-\frac{7}{3}y-\frac{20}{27}=0
\end{align*}
Step 2: We consider $y^3+ey+f=0$ and calculate $y=z-\frac{e}{3z}$.
We set $y=z+\frac{7}{9z}$ which gives
  \begin{align*}
729z^6-540 z^3+343=0
\end{align*}
Step 3: We substitute $z^3=u$ and solve the quadratic equation
\begin{align*}
729u^2-540 u+343=0
\end{align*}
We obtain
\begin{align*}
u_{1,2}=\frac{10}{27}\pm\frac{i}{\sqrt{3}}
\end{align*}
Step 4: The cubic roots $z_0,z_0\omega_1,z_0\omega_2$
We select $u_1=\frac{10}{27}+\frac{i}{\sqrt{3}}$ and calculate the three cubic roots:
\begin{align*}
z_0&=\sqrt[3]{\frac{10}{27}+\frac{i}{\sqrt{3}}}=\frac{1}{6}\left(5+i\sqrt{3}\right)\\
z_0\omega_1&=z_0e^{\frac{2\pi i}{3}}=\frac{1}{3}\left(-2+i\sqrt{3}\right)\\
z_0\omega_2&=z_0e^{\frac{4\pi i}{3}}=-\frac{1}{6}\left(1+3i\sqrt{3}\right)\\
\end{align*}
Step 5: The solutions $x_0,x_1,x_2$
Finally we can calculate the solutions from $z_0,z_1,z_2$ via
  \begin{align*}
x=y-\frac{b}{3a}=z-\frac{e}{3z}-\frac{b}{3a}
\end{align*}
We obtain
  \begin{align*}
\color{blue}{x_0}&=z_0+\frac{7}{9z_0}+\frac{7}{3}\color{blue}{=4}\\
\color{blue}{x_1}&=z_0\omega_1+\frac{7}{9z_0\omega_1}+\frac{7}{3}\color{blue}{=1}\\
\color{blue}{x_2}&=z_0\omega_2+\frac{7}{9z_0\omega_2}+\frac{7}{3}\color{blue}{=2}\\
\end{align*}
  and conclude
  \begin{align*}
\color{blue}{x^3-7x^2+14x-8=(x-1)(x-2)(x-4)=0}
\end{align*}

Note: Working with the conjugate complex $u_2=\overline{u_1}=\frac{10}{27}-\frac{i}{\sqrt{3}}$ instead of $u_1$ gives the complex conjugates $\overline{z_1},\overline{z_1}e^{-\frac{2\pi i}{3}}$ and $\overline{z_1}e^{-\frac{4\pi i}{3}}$ and leads (of course) to the same results $x_0=4,x_1=1$ and $x_2=2$.
Comment: the part where it says from 3 the solutions to x via y and x, do you mean subsiting those two equations in?
Comment: @mt12345: Correct. I did the same in the example too.
Comment: @MarkusScheuer When you are solving example, you come to a "Step 4" where you select $u_1$ over $u_2$ and completely forget about $u_2$. Why is this possible? I mean why is it possible to ignore one half of the solution?
Answer: The cubic formula was derived from a series of substitutions. It's probably better to memorize the process of deriving the formula, rather than memorizing the actual formula.
Starting with the general cubic, make a substitution such that the squared term is removed. Let's denote the depressed cubic as$$x^3+qx+r=0$$Now, set $x=y+z$. Expanding and factoring gives$$y^3+z^3+(3yz+q)(y+z)+r=0$$Setting $3yz+q=0$ gives $$y=-\frac q{3z}$$If we substitute that in, we get a quadratic in $y^3$. Using the quadratic formula, we get the roots of $y^3$ and $z^3$ respectively. Therefore, we have the solution as$$x_1=\color{blue}{\left\{-\frac r2+\sqrt{\frac {r^2}4+\frac {q^3}{27}}\right\}^{\tfrac 13}+\left\{-\frac r2-\sqrt{\frac {r^2}4-\frac {q^3}{27}}\right\}^{\tfrac 13}}$$

The other solutions can be found using the cube roots of unity.$$\omega=-\frac 12+\frac {i\sqrt{3}}2\qquad\omega^2=-\frac 12-\frac {i\sqrt3}2$$So$$\begin{align*} & x_2=\color{blue}{\omega\left\{-\frac r2+\sqrt{\frac {r^2}4+\frac {q^3}{27}}\right\}^{\frac 13}+\omega^2\left\{-\frac r2-\sqrt{\frac {r^2}4+\frac {q^3}{27}}\right\}^{\frac 13}}\\ & x_3=\color{blue}{\omega^2\left\{-\frac r2+\sqrt{\frac {r^2}4+\frac {q^3}{27}}\right\}^{\frac 13}+\omega\left\{-\frac r2-\sqrt{\frac {r^2}4+\frac {q^3}{27}}\right\}^{\frac 13}}\end{align*}$$

derivation of the cubic formula


Sending many dynamically-generated emails with php

Question: I have a script: invoice.php?id=12 that generates an invoice in pdf and emails it to a customer with id = $_GET['id'].
Now, after sales are closed, Id like to send an email to all customers at once and I have no idea how to do that.
Generating one pdf and sending it by email takes about 3-4 seconds and there will be hundreds or even thousands of customers.
I'm using SwiftMailer PHP library, if that's relevant.
Any idea how I could do it?
Is there a way to loop through ajax requests for several hours?
Or is there a simpler solution?
Thanks!
Answer: If I understand your question correctly, you are initiating an AJAX request for every email you would like to send. It would be a lot more efficient to send 1 email addressed to a lot of people, by specifying multiple receivers in the mail header as follows:
$email_to = "firstname.lastname@example.com,email@example.com,firstname.lastname@example.com";

For SwiftMailer try this:
$message = Swift_Message::newInstance('Wonderful Subject')
    ->setFrom(array('email@example.com' => 'John Doe'))
    ->setTo(array('firstname.lastname@example.com', 'email@example.com' => 'Name'))
    ->setBody('Here is the message itself')
;

Comment: It would be more efficient, but sadly not possible: the pdf invoice is different for every customer. Is there a way to send ajax requests one after another indefinitely?
Comment: Hmmm... can't help you with that, sorry.


Why does this bound of integration become pi/4?

Question: Perhaps it is something easy that I am not seeing but I cannot seem to understand why, in this integral, a changes to $\frac\pi4$
3$\int_0^a$$\frac {dx}{\sqrt {a^2+x^2}}$
I was able to solve the integral but am stuck on why I needed to change a to $\frac\pi4$. Is it assumed a=1? Thanks
Edit: This integral is solved using trig substitution. My question was only about why the upper bound a is changed to $\frac\pi4$ instead of another value after doing the trig sub. The question was answered by Travis below.
Comment: You question is not clear at all. You do not need to change $a$ to anything in general
Comment: Are you using some change of variable?
Comment: Presumably you are approaching the integral via $u$-substitution.  When changing from an integral $\int f(g(x))g'(x)dx$ to $\int f(u)du$, the original limits were in terms of $x$ values, and the limits of the new form will be in terms of $u$ values.
Comment: $x=a\tan u$, $0<x<a$, hence $0<u<\pi/4$.
Answer: Perhaps because a change of variable was done:
$$x=a\tan u\implies dx=\frac a{\cos^2u}du\;,\;\;\begin{cases}x=0\implies u=0\\{}\\x=a\implies\tan u=1\implies u=\frac\pi4\end{cases}$$
so that
$$3\int_0^a\frac{dx}{\sqrt{a^2+x^2}}=3\int_0^{\pi/4}\frac{du}{\cos^2u}\cdot\frac{1}{\sqrt{1+\tan^2u}}=3\int_0^{\pi/4}\frac1{\cos u}du=$$
$$=\frac32\int_0^{\pi/4}\left(\frac{\cos u}{1-\sin u}+\frac{\cos u}{1+\cos u}\right)du=\frac32\,\log\left|\frac{1+\sin u}{1-\sin u}\right|_0^{\pi/4}=...$$
Comment: There's an error in the last step: careful, it's $\sqrt{1+\tan^2u}$ (with the square root), so that you should obtain $$3\int_0^{\pi/4}\frac{\mathrm{d}u}{\cos(u)}.$$
Comment: @gniourf_gniourf Thank you very much, you're right. Edit now.
Answer: Presumably the substitution made in the given solution is the standard trigonometric substitution $$x = a \tan \theta, \qquad dx = a \sec^2 \theta \,d\theta ,$$ which eliminates the radical from the integrand. At the lower limit, we have $x = 0$, and since $\theta = 0$ solves $0 = a \tan \theta$, we can take the lower limit to be $0$. At the upper limit, we have $x = \frac{\pi}{4}$, and to write the upper limit with respect to $\theta$, we must solve $a = a \tan \theta$, or $\tan \theta = 1$, which has solution $\frac{\pi}{4}$. Hence, with respect to $\theta$, we write the integral as
$$\int_0^{\pi / 4} \cdots d\theta .$$
(This explanation brushes under the rug a technical point, namely that once we've picked the lower limit, we must pick a suitable upper limit, that is, we cannot pick any solution to $\tan \theta = 1$ for the upper limit. Since $\tan \theta$ is increasing and continuous on the interval $(-\frac{\pi}{2}, \frac{\pi}{2})$, and that interval contains the chosen lower limit $0$, we should take the unique solution to $\tan \theta = 1$ in that interval.)
Comment: That's what I was looking for, thanks.
Comment: You're welcome, I'm glad you found it useful.


Adding months to a date and insert into database

Question: i'm trying to add X month to a date taken from my database
$sql_batch = "SELECT * FROM mgm_subscription WHERE status = '1'"
$query_batch = mysql_query($sql_batch);
$row_batch = mysql_fetch_array($query_batch);

$addMonth = 3;
$startDate = $row_batch['start_month'];
$endDate = strtotime('+'.$addMonth.' month', $startMonth);  // add number of days from form
$endDate = date('m/d/y H:i:s', $endDate );

$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startDate."','".$endDate."', '')";
$query_date = mysql_query($sql_date);

NULL was inserted into the end_month.
start_month and end_month is DATE type in the mysql
how do i fix this? tq.
Comment: Is $startMonth a string or numeric value?
Comment: if data type is `date` , then from your example you are trying to insert `datetime` , Also valid mysql datetime format is `Y-m-d H:i:s`
Comment: i inserted the value of $end_month into a varchar data type field. and it inputs 04/01/70 01:33:34
Answer: If I understood your question, your $endDate should be
$endDate = date('Y-m-d', strtotime($startDate.' +'.$addMonth.' months'));

So this will equate to:
$endDate = $startDate + 3 months /* in Y-m-d format */

EDIT: Just saw that your column datatype is Date. This would mean that you can't store timestamp in your date. It has to be Y-m-d format only as that is the valid mysql format supported.
Answer: You insert $endMonth a value(number of days from form) then you try to replace it ($endMonth) and you call back your replaced variable..

$endMonth = strtotime('+'.$addMonth.' month', $startMonth);  // add number of days from form
      $endMonth = date('m/d/y H:i:s', $endMonth);

It will return null value.. My suggestion, try to put other variable to prevent duplicate value or missing data
Comment: even i use a different var, it still inserts NULL inside my db. I think the problem is on the format of the value sent to the db.
Comment: You change it to $endDate but $endMonth in $endDate = date('m/d/y H:i:s', $endMonth); still did't have a value
Comment: i change it. and it still the same, it inserted 04/01/70 01:33:34 when i put it in a varchar field
Comment: if your format of date is 5/1/2014 12:00:00 AM.. so i suggest you change to $endMonth = strtotime('+'.$addMonth.' month', $startMonth); $endDate = date('n/j/Y H:i:s', $endMonth);
Answer: You only mention adding X months. Maybe I misunderstood your question, but if all you care about is the month, I would do the following:
if ($startMonth === 'January') {
    $monthNumber = 1;
} else if ($startMonth === 'February') {
    $monthNumber = 2;
} //Up to November then finish with {
else {
    $monthNumber = 12;//December
}

$newMonthNumber = $monthNumber + $addMonth;

if ($newMonthNumber % 12 == 1) {
    $endMonth = 'January';
} else if ($newMonthNumber % 12 == 1) {
    $endMonth = 'February';
} //Up to November then finish with {
  else {
    $endMonth = 'December';
}

$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startMonth."','".$endMonth."', '')";
$query_date = mysql_query($sql_date);

Comment: tq for replying, but i think u misunderstood the problem, adding the month is determined for $addMonth. In this case is 3, so i need to add 3 months from the $startMonth date and insert it into the DB
Comment: What is inserted into the database? A month only, or a date? The variable names $endMonth and $startMonth suggest months and not dates.
Comment: sorry, it's a full date. like this 5/1/2014 12:00:00 AM .. sorry for the bad programing. i change it already to avoid confusions


What rectangle does this statement convey?

Question: What rectangle is this talking about?
The rectangle: $$\{(x,y)\mid 0 \leq x \leq 2 , 0 \leq y \leq 1 \}$$
How does this convey a rectangle?
Please help me out. Thank you.
Answer: The one with corners at (0,0), (2,0), (0,1), and (2,1).
Comment: Why not something in between??
Comment: Yes, it's the full area with the corners mentioned, inclusive of the edges.
Comment: Can you explain to me what that statement means in words? Please.
Comment: @arihant In words: "The set of all $(x, y)$ pairs such that $x$ is between $0$ and $2$ (inclusive) *and* $y$ is between $0$ and $1$ (again inclusive)".
Comment: Thanks pjs. I got it now. So there arr infinitely many points (x,y) here.
Answer: It's this rectangle:

Notice that the corners are at $(0,0)$, $(0,1)$, $(2,0)$, and $(2,1)$.  The rectangle is just all of the points $(x,y)$ such that $0\le x\le 2$ and $0\le y\le 1$.


using System.Collections.Generic in WinRT (windows app)

Question: I am making a Windows 8 App to put on the store.
Some .NET assemblies seem to not be accessible (like some WPF graphics classes), while some ordinary, default assemblies (like System.Collections.Generic) are no longer added by default.
I want to use the List class, but I'm afraid there's some hidden cost to using it (after all, why isn't it enabled by default on XAML apps?). Would my future users get an extra .NET DLL for WinRT they'll have to download? Will their computers explode in a loud, concussive blast? Ok, maybe that won't happen.
Am I bothering about nothing?
Comment: Should be fine according to MSDN.
Answer: Most of the classes in System.Collections.Generic namespace are supported in Windows Store apps (the green suitcase icon in the first column). This means that they are availabe on Windws RT systems. So you don't need to worry about anything. There is no hidden cost or anything in using them.


need explanation for PayPal recurring options: BILLINGPERIOD, BILLINGFREQUENCY, TOTALBILLINGCYCLES

Question: https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECRecurringPayments/
I understand that setting BILLINGPERIOD to MONTH and BILLINGFREQUENCY to 1 will charge the user once a month.
But according to the above link, TOTALBILLINGCYCLES is optional and is set to 0 by default. So if I don't include that option, will the user be charged once a month forever or stopped after charging for the first year (12 times)?
Also, I want to charge the user for the first year only. What should i do? Should i set TOTALBILLINGCYCLES to 1 to achieve it?
Please advise.
Thanks
Comment: This sounds like a question for paypal customer support, and has nothing to do with programming.
Comment: I'm voting to close this question as off-topic because it should be addressed to PayPal, and because it is not primarily about computer programming.
Comment: Then where should i ask? [the community](https://developer.paypal.com/developer/support) link is pointed to this site. and also i find some similar [questions](http://stackoverflow.com/questions/9278615/paypal-createrecurringpaymentsprofile-billing-frequency) like this (just that they are not exactly what i'm looking for.)
Comment: If you want to bill for just 1 year then to stop, set cycles=1 period=year or cycles=12 period=month etc
Answer: Please find TOTALBILLINGCYCLES in the link below:
https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
For the regular payment period, if no value is specified or the value is 0, the regular payment period continues until the profile is canceled or deactivated.
If you want to charge the user for the first year only, TOTALBILLINGCYCLES depends on your billing period.
If you set BILLINGPERIOD=Month and BILLINGFREQUENCY=1, you should set TOTALBILLINGCYCLES=12 to charge one year.
If you set BILLINGPERIOD=Year and BILLINGFREQUENCY=1, you should set TOTALBILLINGCYCLES=1 to charge one year.


Obter hora minutos e segundos em javascript

Question: Gostaria de sabe como faço em Javascript para obter a hora? Um número que representa a data e hora e segundos atual. Sei que conseguimos o objeto para data e hora e segundos através de:
const data = new Date();

Não entendi muito bem isto.
Answer: Em JavaScript podes guardar uma data num objeto (instância) Date. Essa instância tem métodos a partir dos quais podes extrair os seus componentes como data, ano, horas, etc...
Podes ler mais sobre isso aqui na MDN, mas para dar um exemplo com horas podes extrair e criar uma array que depois convertes em string com os dois pontos a separar os valores:

const data = new Date(); // momento atual
const horas = data.getHours();
const minutos = data.getMinutes();
const segundos = data.getSeconds();

const hhmmmss = [horas, minutos, segundos].join(':');
console.log(hhmmmss);

Porém, para esse tipo de representação podes também usar o toLocaleTimeString que te dá exatamente isso formatado para o locale que quiseres:

const data = new Date(); // momento atual
console.log(data.toLocaleTimeString('pt-BR'));
Comment: Entendi, obrigado


One SSL Certificate for two servers?

Question: we have set up one productive server and a testing environment, which are two VMs with different internal IP addresses.
Our public DNS server points software.example.com to our public IP address.
If you want to use the productive server you would type in https://software.example.com and if you want to access the server for testing you would use https://software.example.com:10443.
Our firewall would then redirect the request to the right internal IP.
This is sufficient for external use, as we can use the same SSL certificate for two servers (as they use the same FQDN).
But we need to use the internal IP for the productive server, because it should be available even when the internet connection is down.
So I used an A record to the internal IP of the productive server.
Now we can not open the testing website using the DNS name, because software.example.com points to the productive server internally, we just can use the internal IP like 192.168.1.10:10443, which results in a SSL certificate error.
Do you know a way around this?
I would like to find a way to make the address software.example.com work internally for both servers. I wouldn't like to make the website accessible through the internet connection only.
I could use a different certificate for the testing environment, but I would have to go with let's encrypt, a way to use our paid certificate from our provider would be better.
Thanks for your suggestions.
Answer: You have a couple of options:

Install a load balancer / reverse proxy internally in front of the two servers, and point the domain software.example.com to the IP of the reverse proxy, that way you can use the same setup as you're using externally. This can be done using for example NGINX, MS IIS or an F5.
You can also use the web server running the production environment to forward requests internally to the testing environment. This of course requires that the web server on the production server supports a reverse proxy configuration. This has the added benefit of saving you an extra server.
Set up a different domain, say software-testing.example.com, for the testing environment and install a different certificate on that server. This is in my opinion the cleanest option, since you're not sharing any infrastructure, and an SSL certificate is rather cheap compared to running extra servers and maintaining them.
Comment: Thanks for your suggestions.
Answer: To directly answer the question in the title, you would use the SAN (Subject Alternate Name) field when creating your CSR or ordering your certficate.  SAN allows a single certificate to be valid for two (or more) host names.
Looking at the body of the question, though, you seem more interested in having a single name which will always reach your internal server, even when external networking is unavailable, rather than a single certificate which is valid for multiple names.  There are several ways this can be done.  Here are the first few to mind:

Set up an internal DNS server which is private to your network and returns the internal IP address for internal machines (e.g., 192.168.1.10 for software.example.com) and forwards the request to an external DNS server (e.g., your ISP or 18.104.22.168) for non-internal names.  This is the "most correct" solution and the easiest if you already have an internal DNS server, but, if you don't already have one, you'll have to set one up and reconfigure all your internal machines to use it.
Configure a "hosts file" (/etc/hosts on Linux, check google for locations on Windows, OS X, or other operating systems) on all your internal machines to tell them that software.example.com is at 192.168.1.10 without going through DNS.  This has the same general effect as #1, but it's a lot more work to set up and maintain.  Its only advantage is that it avoids having to set up an internal DNS server.
Tell your internal users to use the IP address or an alternate name for internal access at all times, regardless of whether your internet is up or down.  If you don't have the corresponding SAN on your certificate, they can "accept the risk and continue" when their browser complains about the certificate being invalid.  If you don't have the SAN, this is a very "not-correct" solution (because it involves ignoring browser security warnings), but it's the easiest to implement if you don't have the networking infrastructure already in place for any of the other solutions.
If you have a configurable router handling your internal network's traffic, you can set it to send traffic for your server's external IP address directly to the server without routing it out the internet connection and back.  This keeps the internally-visible IP address the same regardless of whether the connection is up or down, but it's the most esoteric solution, so it should be well-documented if you do this to avoid confusing someone (quite likely yourself) who has to debug a routing problem sometime in the future.  It also might not help anyhow if you aren't able to access external DNS servers when your connection goes down - which brings us back to "set up an internal DNS and use solution #1."
Comment: Thanks you for your resonse.
I like method number 4, I'm going to try this out.

One SSL Certificate for two servers?


How to load data from one project's bucket into another project's table in python?

Question: I have two projects. I store data in project_A and build tables in project_B. I have created a service_account.json for both of them, but I don't know how to use  both files at the same time when I need to load the data from project_A and build the tables in project_B.
The data is stored in URI:
gs://project_A//*

The table will live in project_B table name huge_table
from google import storage, bigquery

proj_a_client =  storage.Client.from_service_account_json(service_acct_A.json)
proj_b_client = bigquery.Client.from_service_account_json(service_acct_B.json)

dest_table = proj_b_client.dataset('DS_B').table('huge_table')
uri = 'gs://project_A//*'

job_config = bigquery.LoadJobConfig()
load_job = proj_b_client.load_table_from_uri(uri,
                                         dest_table,
                                         job_config=job_config)

But I get the error:

google.api_core.exceptions.Forbidden: 403 Access Denied: File
  gs://project_A/: Access Denied
Comment: At which point are you getting the error? By the looks of your code, it seems that the service account from Project B is the one trying to access the Cloud Storage bucket, could you please confirm this? Also, a full trace of it would be greatly appreciated.
Answer: You have to make sure service_acct_B has storage access to project_A:
In project_A,

go to IAM & admin
add member service_acct_B with (at a minimum) Storage Object Viewer role

As a matter of fact, you don't use/need a service_acct_A here so
proj_a_client =  storage.Client.from_service_account_json(service_acct_A.json) is redundant.


Help with a factorisation problem. Completely factor $4(a^2)(c^2) - (a^2 - b^2 + c^2)^2$

Question: The questions asks to completely factor the following polynomial:
$4a^2c^2 - (a^2 - b^2 + c^2)^2$
The closest I can get to completely factoring it is (and I am not sure if this is even correct):
$2c^2(a^2 + b^2) - c^4 - a^4 - b^4 $
However the solution given is:
$(a+b+c)(a+b-c)(a-b+c)(-a+b+c)$
This is a maths problem from the book Precalculus Mathematics for Calculus (7th) Stewart, Lothar, Saleem Watson, page 35, exercises 1.3, number 133.
Thanks for any help in advance.
Comment: What are you asking exactly? Expand the solution and you will have the original expression.
Answer: Squares difference: $\;x^2-y^2=(x-y)(x+y)\;$ :
$$\overbrace{4a^2c^2}^{=(2ac)^2}-(a^2-b^2+c^2)^2=(2ac-(a^2-b^2+c^2))(2ac+(a^2-b^2+c^2))=$$
$$=\left(b^2-(a-c)^2\right)\left(-b^2+(a+c)^2\right)=(b-(a-c))(b+(a-c))(a+c-b)(a+c+b)$$
Now do some order inside with the parentheses.
Comment: Thanks for the help. You answer and Angel really helped me.
Answer: Use the factorization for the difference of two squares:
\begin{align*}
4a^2c^2-(a^2-b^2+c^2)^2&=(2ac+a^2-b^2+c^2)(2ac-a^2+b^2-c^2)\\
&=(a^2+2ac+c^2-b^2)(b^2-a^2+2ac-c^2)\\
&=\left[(a+c)^2-b^2\right]\left[b^2-(a-c)^2\right]\\
&=(a+c+b)(a+c-b)(b+(a-c))(b-(a-c))\\
&=\color{blue}{(a+b+c)(a-b+c)(a+b-c)(-a+b+c)}
\end{align*}
Comment: Thanks for the help. I understood the steps you took to solve the equation. Really appreciate it.


How can I export all results from Blazegraph into a file?

Question: I would like to export the results of my SPARQL query from Blazegraph into a file. However, it exports only the first page of the results. When I try to display all results, my browser crashes.
How can I fix this?
I'm running Blazegraph 2.1.2 on a local cluster.
Comment: How did you do the export? And what did you try to display all results? Such information might help readers in order to help you. Please consider [editing](http://stackoverflow.com/posts/38437787/edit) your question in order to provide some details.
Answer: To export results you can rely on curl and query your SPARQL endpoint through command line like this:
curl -X POST http://localhost:9999/bigdata/namespace/YOUR_NAMESPACE/sparql --data-urlencode 'query=SELECT * WHERE{ ?s p ?o } LIMIT 1' --data-urlencode 'format=json' > outputfile

You have to specify your endpoint's address of course and your query as you want. This is just an example but it may give you an idea.
Also you can modify your expected output format (CSV, XML, JSON, etc) and include headers if you want.
Here you can read more about it.
Comment: Thanks aquiros, that works! Blazegraph's web interface does provide an export-results feature (at least mine does).
Comment: I haven't tried yet the 2.1.2 version so maybe that's it. I'm updating my answer. If it worked for you please consider accepting it. @Fabian_G
Answer: If you want to download all your graph you should use a CONSTRUCT query:
curl --X POST \
  --url 'https://{host}/bigdata/namespace/{namespace}/sparql' \
  --data-urlencode 'query=CONSTRUCT { ?s ?p ?o } where { ?s ?p ?o }' \
  --header 'Accept: application/x-turtle' > outputfile.ttl

In this case I am exporting it in a turtle format.


I have a question on how to prove an inequality holds true.

Question: How do I prove that for $a < b< c$ and $n \geq 3$ then the inequality $$b^n+c^n > a^n$$ holds true.
I tried setting $c =b+n$ but I don't know we're to go from here !
Comment: I think you need also that $0a^n$ and that $c^n>0$?
Comment: I can  b > a so lnb>lna so nlnb > nlnb therfore 2 more steps we get $b^n$ > $a^n$.  $c^n$ will be always postive if c>0. However I was looking for a proof for all a,b,c. Thanks to all who disproved this inequality.
Answer: Hint
(assuming the numbers are positive)
Use the fact that $$x > y > 0 \implies x^n > y^n$$ and $$x > y, z > 0 \implies x+z > y$$


How does - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view work

Question: I've been using that kind of methods on and off but never really understood how they behaved.
Every time I try to use them, I find myself poking in the dark as I try different aspect and it never seem to do what I expect it to.
For the sake of argument, I'm trying to convert the frame I get from UIKeyboard's notification.
In landscape mode, I get this NSRect:
UIKeyboardFrameEndUserInfoKey = NSRect: {{406, 0}, {362, 1024}}

Now I want to convert it to the proper rect (swap x/y, width and height) so I do
CGRect compatibleRect = [self convertRect:[[[notif userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil];

But the rect becomes:
compatibleRect = CGRect: {{406,406}, {362, 1024}}

Any help would be appreciated :)
Answer: You are using it wrong. It basically does a coordinate conversion. I'm assuming it starts by converting the rect from the starting view to window coordinates and then converting back from window coordinates to the coordinate system of the second view. Here's an example.
You have two subviews in your window, one with a frame of {{25,0}, {100, 100}}, The other with a frame of {{50, 50}, {200, 200}} You want to translate the following rect {{50, 50}, {50, 50}} from the first subview to the second subview. Here's how it might work.

convert the rect from the first subview's coordinated to window coordinates:
Since the subview we are starting from has an origin of {25,0} we need to translate it to window coordinates. This can be done by adding the origin of the subview to the origin of the rect, so the new rect in window coordinates is {{75, 50}, {50, 50}}
convert the new rect from window coordinates to the second subview's coordinates: We start with the rect {{75, 50}, {50, 50}}, The frame of the second subview is {{50, 50}, {200, 200}}. Now we subtract the origin of the second subview to the rect to do our translation. So we end up with a translated rect of {{25, 0}, {50, 50}}
Comment: In your case you want to use convertRect:fromView: not convertRect:toView: so [self convertRect:rect fromView:nil] will take the bounds, that is in screen coordinates and convert it to your local view coordinates.
Comment: I understand how conversions work. However, I'm trying to understand how those specific method works. I used [self.window convertRect:[[[notif userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromWindow:nil]; in order to make it work.

If you check out the following link http://developer.apple.com/iphone/library/documentation/uikit/reference/UIWindow_Class/UIWindowClassReference/UIWindowClassReference.html#//apple_ref/occ/instm/UIWindow/convertRect:fromWindow:

It mentions how it behaves, but it's not very clear on what really is happening


Overdispersed and zero-inflated count data

Question: I have a dataset with social media posts and like to predict the number of likes a post receives.
So I fit a Generalised Linear Model (GLM). I am relatively new to GLMs but find them super cool. Inspecting the data, I think that they are overdispersed, but am not so sure about zero-inflation. This stack exchange post differentiates the two concepts. Here is my approach to check for overdispersion and zero-inflation.
The dependent variable number of likes ranges from 0 to 37,659. Out of the 8000 posts, 4359 posts (or roughly 54%) receive no likes. 3641 posts (46%) received at least one or more likes. The majority of posts that receive a like receive around 5 likes.
Comparing these numbers to a simulated quasi-poisson distribution based on this tutorial for R for 8000 data points, the range of number of likes should be 0 to 43 likes. Out of 8000 data points, 2415 (or 30%) should receive a like and 5585 (70%) should not receive a like.
Here a basic plot comparing both distributions.
I read around a bit what the options are for overdispersion and zero-inflation.

GLMs with the family set to 'quasi-poisson' deal with overdispersion
Negative binomial regression also deal with overdispersion

--> which one to use?
--> From what I understand the glm() function with family set to 'quasi-poission' in R automatically corrects for the degree of overdispersion?
--> What if a comparison of both models show a similar root mean-square error?

Zero-inflated Poisson (ZIP) deal with excessive zeros, but I am not sure that this is the problem here? Also, I have no a priori rationale for the two processes that underlie ZIPs.

Any thoughts highly appreciated.

Fitting a GLM with a quasi-poisson distribution gives me results that I can "sell", but I want to make sure I pick a robust model that fits the data well.
Comment: if you want to deal simultaneously with zero inflation and overdispersion, something to try would be a hurdle model (https://search.r-project.org/CRAN/refmans/pscl/html/hurdle.html). What's nice about these is they try to explain *why* you're seeing zeros (or nonzeros).
Comment: hurdle models are a logistic regression and some other GLM combined. You first have a logistic regression which decides if a datapoint going to be zero or not, and then a GLM that decides what the nonzero distribution is. So you end up with two sets of regression coefficients.
Comment: Have you considered an ordinal regression model?
Comment: You aren't going to find any (meaningful) distribution that has a 54% probability of zero and a 1/10,000 probability of > 30,000; that's a staggering amount of skew.   I'd probably model it in two stages:  P(like = 0) vs P(like > 0) and then P(like | like >= 1).  A quick experiment with the zeta distribution on the latter indicates a parameter in the vicinity of 1.7 would give you a 1/4000 chance of an observation > 30,000, but that hardly qualifies as anything but "extremely rough cut, almost to the point of worthless"  analysis.
Comment: @jbowman Just make a mixture of a dirac delta distribution with a uniform distribution; nicely characterizes the "L" shape of the data ;-)
Comment: @JohnMadden thank you for the suggestion. Heard of them and will look into them.
Comment: @Simone Surely you mean "Hurd of them" :).  And I meant to mention: to account for overdispersion, make sure to use the dist="negbin" option.
Comment: @JohnMadden yup :-) is a vanilla regression similar to hurdle models? a colleague mentioned them and now I am left to google.... ^^
Answer: A few thoughts:
First, while in this case the difference in distributions is blatantly obvious, in general, if you want to compare two distributions a QQ plot is much better than two histograms. In one of his books, William S. Cleveland disparages histograms saying "longevity and ubiquity are not guarantees of utility" and never uses them again.
Second, you've already had recommendation for a hurdle model. That's a good idea.
Third, you clearly have both zero inflation and over-dispersion and it's pretty easy to figure out why you have both. Zero inflation because a lot of posts don't get any likes at all. Heck, a huge number of social media posts don't get any views, or get very few. Over-dispersion -- well, almost every set of count data I've seen has this.  In context, though, anyone who looks at social media knows that some posts get a TON of likes. E.g. posts by celebrities.
Finally, an alternate to hurdle models is zero-inflated negative binomial models. I did some research comparing ZINB to Hurdle models, but I did it back in grad school, around 25 years ago. Doubtless there is much more now. Maybe someone here is up-to-date on the differences; or you can do some research on which is preferred where. Back then, I found the main difference was by field of research. IIRC, psychology preferred ZINB and economics preferred hurdle, probably because James Heckman, who did a lot of work on hurdle models, is an economist.
Comment: Thanks for the suggestions, I'll look into both. ZINB seem relatively easy to implement in R according to [UCLA](https://stats.oarc.ucla.edu/r/dae/zinb/). Will also check what the differences are between the two asides from preferences from different research disciplines.


Failing to recover true parameters in simulations of multinomial logit

Question: I am trying to understand how multinomial logistic regression works. In the first round, I am using the following model representation:
$$
P(Y=k|X_1=x_1,X_2=x_2)=\frac{\exp(\beta_{k0}+\beta_{k1}x_2+\beta_{k2}x_2)}{\color{red}1+\sum_{j=\color{red}2}^K \exp(\beta_{j0}+\beta_{j1}x_2+\beta_{j2}x_2)}
$$
where $k$ is the category of $Y$, and it can be any value between $1$ and $K$.
I simulate data according to the model and then estimate the model with the R function multinom from the nnet package. Unfortunately, I am getting parameter estimates that are far away from the true values.
The simulation code in R for an examples with 3 categories and two independent variables is given below.
# An auxiliary function that takes regressors and coefficients and produces probabilities according to the multinomial logit model
mnlogitgen1=function(X,Beta){
 if(is.null(dim(X))) X=t(X)
 p=cbind(1,exp(X%*%Beta))/(1+rowSums(exp(X%*%Beta)))
 return(p)
}

# Set parameter values of the data generating process (DGP)
n=1e4 # sample size
beta10= 0.5; beta11=2; beta12=-2;   beta1=c(beta10,beta11,beta12)
beta20=-0.5; beta21=2; beta22=-2;   beta2=c(beta20,beta21,beta22)
beta30= 0.5; beta31=1; beta32= 1;   beta3=c(beta30,beta31,beta32)

# Generate random variables x1, x2
set.seed(1); x1=rnorm(n); set.seed(2); x2=rnorm(n)

# Generate the probabilities
p=mnlogitgen1(X=cbind(1,x1,x2),Beta=cbind(beta2,beta3))
# Generate an auxiliary random variable u that is uniformly distributed between 0 and 1
set.seed(0); u=runif(n,min=0,max=1)

# Determine categories of Y based on probabilities
u1=which(u<=p[,1])
u2=which((u>p[,1])&(u<=p[,1]+p[,2]))
u3=which(u>p[,1]+p[,2])

# Generate y
y=rep(NA,n)
y[u1]=1; y[u2]=2; y[u3]=3
# Encode y as factor to reflect the numbers mean categories
y=factor(y)

And here is the fitting bit:
# Fit a multinomial logistic regression
library(nnet)
m1=multinom(y~x1+x2)
print(m1)

with the following result:
> m1
Call:
multinom(formula = y ~ x1 + x2)

Coefficients:
  (Intercept)        x1        x2
2  -0.5247573 1.9761060 -1.937964
3   0.5011046 0.9772012  1.028550

The estimated coefficients turn out to be similar to beta2 and beta3 -- so far so good.

In the second round, I try another representation of the multinomial logit model:
$$
P(Y=k|X_1=x_1,X_2=x_2)=\frac{\exp(\beta_{k0}+\beta_{k1}x_2+\beta_{k2}x_2)}{\sum_{j=\color{red}1}^K \exp(\beta_{j0}+\beta_{j1}x_2+\beta_{j2}x_2)}.
$$
In this case I swap the line
p=mnlogitgen1(X=cbind(1,x1,x2),Beta=cbind(beta2,beta3))

with the line
p=mnlogitgen2(X=cbind(1,x1,x2),Beta=cbind(beta1,beta2,beta3))

and the function mnlogitgen1 with mnlogitgen2:
mnlogitgen2=function(X,Beta){
 if(is.null(dim(X))) X=t(X)
 p=exp(X%*%Beta)/rowSums(exp(X%*%Beta))
 return(p)
}

When I fit the model, the coefficients do not resemble the true values:
> m1
Call:
multinom(formula = y ~ x1 + x2)

Coefficients:
  (Intercept)           x1          x2
2 -1.03717237 -0.008854468 -0.00652646
3  0.01580405 -0.973528437  2.91347034

Questions:

What mistake am I making?
How should I modify the procedure to obtain estimates close to the true parameter values?
Answer: Consider the second model
$$p_k = \frac{\exp(\beta_{k0} + x_1\beta_{k1} + x_2\beta_{k2})}{\sum_j \exp(\beta_{j0} + x_1\beta_{j1} + x_2\beta_{j2})}$$
Divide all these probabilities with a constant $c$ in numerator and denominator
$$p_k = \frac{\exp(\beta_{k0} + x_1\beta_{k1} + x_2\beta_{k2})/c}{\sum_j \exp(\beta_{j0} + x_1\beta_{j1} + x_2\beta_{j2})/c}$$
trivially getting the same probabilities ... Now let the constant be
$$c = \exp(\beta_{10} + x_1\beta_{11} + x_2\beta_{12})$$ the numerator of the first alternative then the probabilities become
$$p_k = \frac{\exp(\beta_{k0}-\beta_{10} + x_1(\beta_{k1}-\beta_{11}) + x_2(\beta_{k2}-\beta_{12}))}{\sum_j \exp(\beta_{j0}-\beta_{10} + x_1(\beta_{j1}-\beta_{11}) + x_2(\beta_{j2}-\beta_{12}))}$$
which with proper choice of definitions becomes
$$p_k = \frac{\exp(\lambda_{k0} + x_1\lambda_{k1} + x_2\lambda_{k2})}{1+\sum_{j=2}^K \exp(\lambda_{k0} + x_1\lambda_{k1} + x_2\lambda_{k2})}$$
for $k>1$ and then
$$p_1 = \frac{1}{1+\sum_{j=2}^K \exp(\lambda_{k0} + x_1\lambda_{k1} + x_2\lambda_{k2})}$$
The point is that the choice frequencies observed only identifies through the probabilities, so same probabilities gives the same likelihood value, but the probabilities are kept the same when deviding with the clever chosen constant, even though 3 parameters were removed from the model. Hence since the likelihood is the same these parameters are not identified. That is also why the estimation code only gives you estimates of coefficients for TWO alternatives even though there are THREE alternatives in the model.
So the mistake you are maken is to include non-identified parameters in your model (and expect that you can recover them).
You correct the mistake by setting all params of one alternative to 0, which is what you did in the first case.
Let us assume you estimate under standard assumption that $\beta_{10},\beta_{11},\beta_{12}$ are all $0$ but in reality they were not when you simulated then the estimates are (i suspect)
$$\hat\lambda_{k0}=\beta_{k0}-\beta_{10} , \hat \lambda_{k1}=\beta_{k1}-\beta_{11} , \hat \lambda_{k2} =\beta_{k2}-\beta_{12}$$
so just add the parameters of alternative 1 to the estimates to recover original "true" values.
Comment: Thanks for a great answer! A quick additional question (disclosure: I am just being too lazy to work out the details myself): in my second approach, do you see a quick way in R of recovering the "canonical" parameters from my specified parameters, so that I can anticipate what R will be estimating and compare the estimates to these "canonical" values?
Comment: I have a hunch, see the edit
Comment: Thank you very much!


How do I store node form data between form steps using ajax?

Question: I want to turn a node form into a multi-step form using ajax. I've added ajax-enabled submit buttons and some logic in a hook_form_alter (see below) to handle inc- and decrementing steps, and showing and hiding form items based on the current step. The stepping back and forth works great, in terms of rendering the correct elements.
The problem is, if I enter some data in one step, go forward or backward, and then return to the original step, the data I entered is gone from the form. If I check the value of the item for which I entered data using FormStateInterface::getValue(), the data is there when my alter hook runs when leaving the original step, but gone on subsequent next/back transitions. This problem also does not apply to data that is already in the form (e.g. when editing an existing node).
Clearly, I need to store the incoming values somewhere, but where? And then, how do I restore them to the form elements on the appropriate step?
My code (minimal example):
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_ajax_test_form_alter(&$form, $form_state) {
  // Define steps. Each child array is a step, and each string in the
  // a child array is a field that should be present on that step.
  $steps = [
    ['title'],
    ['body'],
  ];
  // Add wrapper.
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  // If the step is not set, this is step 0.
  if (!$form_state->has('step')) {
    $form_state->set('step', 0);
  }
  // Get the current step.
  $step = $form_state->get('step');
  // If we have a triggering element, increment or decrement step as
  // appropriate.
  if ($trigger = $form_state->getTriggeringElement()) {
    switch ($trigger['#name']) {
      case 'next':
        $form_state->set('step', ++$step);
        break;

      case 'back':
        $form_state->set('step', --$step);
        break;
    }
  }
  // Show elements in the current step, hide others. Always show the
  // `actions` element, and all `form_*` elements.
  foreach (Element::children($form) as $element) {
    $form[$element]['#access'] = (
      in_array($element, $steps[$step])
      || $element == 'actions'
      || strpos($element, 'form') === 0
    );
  }
  // Show the back button if this is not the first step.
  $form['actions']['back'] = $step > 0 ? ajax_button('back') : NULL;
  // Show the next button if this is not the last step.
  $is_last_step = $step == count($steps) - 1;
  $form['actions']['next'] = !$is_last_step ? ajax_button('next') : NULL;
  // Show the submit button if this is the last step.
  $form['actions']['submit']['#access'] = $is_last_step;
}

/**
 * Return a render array for an ajax step button.
 */
function ajax_button($name) {
  return [
    '#type' => 'button',
    '#value' => $name,
    '#name' => $name,
    '#ajax' => [
      'wrapper' => 'ajax-form-wrapper',
    ],
  ];
}

Answer: This code is quite impressive. I did not think it was possible to build a multi-step entity form with a few lines in a form alter hook. To keep it this simple you can try to use the entity object to store the values, because the form object is serialized and cached between the steps and a method to build such an entity from the submitted values is part of the entity form class:
  if ($trigger = $form_state->getTriggeringElement()) {
    $form_object = $form_state->getFormObject();
    $new_entity = $form_object->buildEntity($form, $form_state);
    $form_object->setEntity($new_entity);

Comment: Thanks for the compliment! I posted my own answer with the full code, but this is exactly the solution I discovered after many hours of research.
Answer: Well, I figured it out. (This was before @4k4's answer, which is very close to what I ended up with).
I needed to build the entity using the submitted form values and then set the form to rebuild (which puts the values from the entity into the form) in a submit handler. Here's how I did it:
<?php
/**
 * Return a render array for an ajax step button.
 */
function ajax_button($name) {
  return [
    // Changed from 'button', buttons don't invoke submit handlers,
    // submits do.
    '#type' => 'submit',
    '#value' => $name,
    '#name' => $name,
    // Set the submit handler.
    '#submit' = ['my_module_ajax_form_submit'],
    '#ajax' => [
      'wrapper' => 'ajax-form-wrapper',
    ],
  ];
}

/**
 * Build entity using submitted form data and rebuild form.
 */
function my_module_ajax_form_submit($form, $form_state) {
  // Get the NodeForm object.
  $form_object = $form_state->getFormObject();
  // NodeForm::buildEntity() maps form values into the entity object
  // and returns it.
  $entity = $form_object->buildEntity($form, $form_state);
  // NodeForm::setEntity() stores the entity in the form object which
  // is used to populate form fields when the form rebuilds.
  $form_object->setEntity($entity);
  // Set the form to rebuild.
  $form_state->setRebuild()
}

I got here by following very closely the various implementations of ::buildEntity() and ::buildForm() in NodeForm and its ancestors ContentEntityForm and EntityForm.
Answer: I think you need to use the symfony sessions
Set session variable
$session = \Drupal::request()->getSession();
$session->set('mymodule_variable', 'value');

Later on you can get this variable like this
$session = \Drupal::request()->getSession();
$value = $session->get('mymodule_variable', 'default_value');

Symfony sessions are equivalent to php $_SESSION
Answer: It seems that the correct way todo this is with PrivateTempStore, if you go to see the CommentAdminOverview in Core you will see this:
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
      ...
      $info = [];
      /** @var \Drupal\comment\CommentInterface $comment */
      foreach ($comments as $comment) {
        $langcode = $comment->language()->getId();
        $info[$comment->id()][$langcode] = $langcode;
      }
      $this->tempStoreFactory
        ->get('comment_multiple_delete_confirm')
        ->set($this->currentUser()->id(), $info);
      $form_state->setRedirect('comment.multiple_delete_confirm');
    }
  }

In this page you collect the comment id that you want to delete and made a redirect, and the comment deletion happens in comment.multiple_delete_confirm (ConfirmDeleteMultiple) that have the following code:
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->commentInfo = $this->tempStoreFactory->get('comment_multiple_delete_confirm')->get($this->currentUser()->id());
    if (empty($this->commentInfo)) {
      return $this->redirect('comment.admin');
    }
    /** @var \Drupal\comment\CommentInterface[] $comments */
    $comments = $this->commentStorage->loadMultiple(array_keys($this->commentInfo));
  ...
  }

Views also works with PrivateTempStorage, this is why when you return to a view that is not saved you can see again the changes.


Need Order data after specific order number using zfr-shopify package

Question: I have used below package to get shop order from shopify.
https://github.com/zf-fr/zfr-shopify
Now I got all orders data of store and stored in my DB. Now I need orders after specific order number.
Suppose,In my db last order number was 123 then I get all orders after order number 123.
Sample Code :
<code>$shopifyClient = new ShopifyClient([
    'private_app'   => false,
    'api_key'       => 'YOUR_API_KEY',
    'access_token'  => 'MERCHANT_TOKEN',
    'shop'          => 'merchant.myshopify.com',
    'version'       => '2019-04'
]);
$orders = $shopifyClient->getOrders();
</code>
Now, I don't know how to pass argument inside that function and achieve my above requirement.
Thanks.
Answer: In the repository README, it says that you pass arguments as a first parameter, in a type of array.
So try this to get orders after a specific ID:
<code>$orders = $shopifyClient->getOrders([
  'since_id' => 123
]);
</code>
Comment: yes it is working. @Vladimir. Thanks :)
My i know is there any proper documentation for above query builder. If so then can you please provide me its link. I will really appreciate your help.
Comment: I believe you can pass there any arguments that Shopify API accepts. If I were the package owner I would do this way. The `GET /orders` endpoint reference you can find here: https://shopify.dev/docs/admin-api/rest/reference/orders/order?api[version]=2020-04#index-2020-04. Just try to use parameters listed there.


Simple DoS protection with mod_security?

Question: I have mod security2 in ubuntu 14.04 LTS server.
I saw the below tutorial:
http://blog.cherouvim.com/simple-dos-protection-with-mod_security/
The above sadly do not work on me apache error :
 * Restarting web server apache2                                                                                [fail]
 * The apache2 configtest failed.
Output of config test was:
AH00526: Syntax error on line 226 of /etc/modsecurity/modsecurity.conf:
ModSecurity: No action id present within the rule
Action 'configtest' failed.

The Apache error log may have more information.
Can you recommend something similar?
Answer: https://launchpad.net/ubuntu/trusty/+source/modsecurity-apache
Ubuntu has ModSecurity 2.7+ which requires [1]

Added Rules must have ID action and must be numeric.

So best would be to add ID's to those rules and that will do the trick.
For instance rule
SecRule ip:block "@eq 1" "phase:1,deny,log,logdata:'req/sec: %{ip.requests}, blocks: %{ip.blocks}',status:403"

should be
SecRule ip:block "@eq 1" "id:12345,phase:1,deny,log,logdata:'req/sec: %{ip.requests}, blocks: %{ip.blocks}',status:403"

Or some other ID which is not already used by some other rule.
[1] https://github.com/SpiderLabs/ModSecurity/blob/master/CHANGES


QML anchors to ApplicationWindow via id not work

Question: I test a simple QML(Qt sdk version 5.3.2) program like this
import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    id: appWin

    Text {
        text: qsTr("Hello World")
        anchors.bottom: parent.bottom
    }
}

I want the text will be layed on the bottom of application window, that's work. But if I change anchors.bottom: parent.bottom to anchors.bottom: appWin.bottom (via id), anchors not work anymore, is this a bug?
Answer: ApplicationWindow does not ultimately derive from Item, so it does not have an anchors property that's why using the window's id does not work.  So why does using parent?  Because the children you define in an ApplicationWindow become children of an intermediate Item called contentItem:

If you assign an Item to the data list, it becomes a child of the
  Window's contentItem, so that it appears inside the window. The item's
  parent will be the window's contentItem, which is the root of the Item
  ownership tree within that Window. ... It should not generally be
  necessary to refer to the data property, as it is the default property
  for Window and thus all child items are automatically assigned to this
  property.
Answer: This looks like a bug, but it can be by design according following docs:

For performance reasons, you can only anchor an item to its siblings
  and direct parent

It's not really clear how we can specify direct parent when anchoring. QML translator may only accept parent to reference parent qml item.
Comment: It is not a bug, and you can specify the direct parent by it's `id` or by using `parent`.


What's a good practice to call an action from another action of the same model in mobx-state-tree?

Question: I am trying to wrap multiple functions inside one.
I have a model like this:
const CookModel = types.actions(self =>({
  talkToSousChefs:() => {
    // talk to sous-chefs
  },
  talkToWaiters: () => {
    // business logic
  },
  talkToVendors: () => {
    // business logic
  },
  runTalkRoutine: () => {
    // current code

    const root = getRoot<typeof CookModel>(self)

    root.talkToSousChefs()
    root.talkToVendors()
    root.talkToWaiters()

    // what's the best practice?
  }
}))

What's the best way to wrap those actions in runTalkRoutine?
Answer: That would do it but I would use self directly
  runTalkRoutine: () => {
    self.talkToSousChefs()
    self.talkToVendors()
    self.talkToWaiters()
  }

If any of your actions are async you can use yield
If you want autocomplete you can move the runTalkRoutine to another actions block
const CookModel = types.actions(self =>({
  talkToSousChefs:() => {
    // talk to sous-chefs
  },
  talkToWaiters: () => {
    // business logic
  },
  talkToVendors: () => {
    // business logic
  }
})).actions(self => ({
  runTalkRoutine: () => {
    // here you will have autocomplete on self
    self.talkToSousChefs()
    self.talkToVendors()
    self.talkToWaiters()
  }
}))


Extrair posição de valores em uma matriz no R

Question: Tenho os seguintes dados:
numbers <- c(303, 2107, 35000)
matriz <- matrix(1:90000, nrow = 300, ncol = 300, byrow=T)

Preciso da posição dos valores na matriz. Estou tentando com o seguinte código:
linha <- function(mat, vetor){
  aux <- which(apply(mat, 1, function(mat) all.equal(mat, vetor)) == "TRUE")
for (r in 1:nrow(matriz)) {
    for (c in 1:ncol(matriz)) {
       print(paste("Row", r, "and column",c, "have values of", matriz[r,c]))
  } }}

linha(matriz, numbers)

Porém, ele está retornando a posição de todos os 90000 valores.
Alguém sabe me dizer onde estou errando? Ou possui outra sugestão?
Answer: Não estou certo do que pretende com a primeira linha da sua função, mas confira a ajuda para all.equal. Juntamente com uso de apply para as linhas da matriz, ela provavelmente não está fazendo o que espera. E de qualquer maneira, o objeto aux não está sendo usado posteriormente. O que tem são dois loops que circulam por todas as linhas e colunas da matriz, e é isso que está sendo exibido.
Para localizar o índice de um valor em uma matriz, pode usar which com a opção arr.ind = TRUE. Por exemplo:
which(matriz == 4, arr.ind = TRUE)
#>      row col
#> [1,]   1   4

Pode usar isso dentro de um loop que percorra todos os valores do vetor de números:
linha <- function(mat, vetor) {
  for (valor in vetor) {
    rc <- which(mat == valor, arr.ind = TRUE)
    print(paste("Row", rc[1], "and column", rc[2], "have value of", valor))
  }
}

linha(matriz, numbers)
#> [1] "Row 2 and column 3 have value of 303"
#> [1] "Row 8 and column 7 have value of 2107"
#> [1] "Row 117 and column 200 have value of 35000"

Se precisa armazenar o resultado, pode usar *apply ao invés de um loop e unir o resultado em um data.frame:
resultado <- as.data.frame(do.call("rbind", lapply(numbers, function(x) which(matriz == x, arr.ind = TRUE))))
resultado$value <- numbers

resultado
#>   row col value
#> 1   2   3   303
#> 2   8   7  2107
#> 3 117 200 35000

Comment: Muitíssimo obrigada! Resolveu a minha questão! :D


Check wether a set of data already exists in current worksheet

Question:  I have a large table filled with data. What I want to do is check wether a set of data already exists within this table. I have inserted the data I am looking for in a separate worksheet. The Range with the table items I am looking for I called "SearchedData" and the Area where I am checking wether it holds the data I am looking for I called "SearchArea".
My code only shows me the data would exist but in the worksheet I am working on it doesn't so there must be something wrong with my code. Any help on this would be very much appreciated!
Sub CheckWetherDataExists()

    Dim SearchedData As Variant
    Dim SearchArea As Variant

    SearchedData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value
    SearchArea = ThisWorkbook.Worksheets("Tabelle1").Range("A:E").Value

    If SearchArea = SearchedData Then
    MsgBox ("Searched Data already exists")

    Else: MsgBox ("Searched Data is missing")
    End If

End Sub

Comment: `Range("C5:G8").Value` will result in an array of values but you cannt compare arrays like `SearchArea = SearchedData` you must loop. Also your ranges are different in size so you cannot compare them directly. What is the aim of this? Do you want to check if the **complete** data range `C5:G8` exists **anywhere** in columns `A:E`? Or do you want to check each cell on it's own? Please be more specific here or give a screenshot for explanation.
Comment: Simply use `match()` formula to check. If match formula return any number then data is exist otherwise it will give you error.
Comment: @Harun24HR `match` would not work with a range as criteria. Not that simple.
Comment: @Pᴇʜ excacrly, I want to check wether the complete data in range(C5:G8) in worksheet "Tabelle2" exists in the table in worksheet "Tabelle1"
Comment: and yes if it exists anywhere in the worksheet "Tabelle1". "Tabelle1" contains a large amount of data and what I want to do is checking wether a certain piece of the table already exists somewhere in this table.
Comment: @Pᴇʜ yes, I am looking wether the table items in the exact order of range(C5:G8)  exist.
Comment: Use a table of matches to check each individual cell in the range.. if just one is an error then the data is not identical...
Comment: I just added screenshots of an exemplary table to clearify what I am trying to do
Answer: This is a way more complicated to solve.
Imagine Tabelle2 as following:

And Tabelle1 as following:

I suggest to use the Range.Find method to find the first occurenc of the first cells data here this is represented by 11. And then check if the rest of the data is right/below there too. Do this in a loop until all occurences are checked.
So in Tabelle1 the yellow areas will be ckecked but the only full match is at A14:E17 which will be considered as duplicate.
Option Explicit

Public Sub CheckIfDataExists()
    Dim wsSearch As Worksheet
    Set wsSearch = ThisWorkbook.Worksheets("Tabelle1")

    Dim SearchRange As Range
    Set SearchRange = wsSearch.Range("A1", wsSearch.Cells(wsSearch.Rows.Count, "A").End(xlUp))

    Dim SearchData() As Variant 'data array
    SearchData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value

    Dim FoundData() As Variant

    'remember first find to prevent endless loop
    Dim FirstFoundAt As Range
    Set FirstFoundAt = SearchRange.Find(What:=SearchData(1, 1), After:=SearchRange.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

    If Not FirstFoundAt Is Nothing Then
        Dim FoundAt As Range
        Set FoundAt = FirstFoundAt
        Do
            Set FoundAt = SearchRange.Find(What:=SearchData(1, 1), After:=FoundAt, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
            If Not FoundAt Is Nothing Then
                FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Select
                FoundData = FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Value
                If AreArraysEqual(SearchData, FoundData) Then
                    MsgBox "data found at " & FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Address
                    Exit Sub
                End If
            End If
        Loop Until FoundAt Is Nothing Or FirstFoundAt.Row >= FoundAt.Row
    End If

    MsgBox "data not found"
End Sub

Private Function AreArraysEqual(Arr1 As Variant, Arr2 As Variant) As Boolean
    Dim iRow As Long, iCol As Long

    'default
    AreArraysEqual = True

    For iRow = LBound(Arr1, 1) To UBound(Arr1, 1)
        For iCol = LBound(Arr1, 2) To UBound(Arr1, 2)
            If Arr1(iRow, iCol) <> Arr2(iRow, iCol) Then
                AreArraysEqual = False
                Exit Function
            End If
        Next iCol
    Next iRow
End Function

Answer: I believe this code will do what you want reasonably fast.
Sub CheckWetherDataExists()

    Dim SearchedData As Variant
    Dim SearchArea As Variant
    Dim LookFor() As String
    Dim LookIn() As String
    Dim R As Long, C As Long

    SearchedData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value
    LookFor = MergedRows(SearchedData)

    With ThisWorkbook.Worksheets("Tabelle1")
        SearchArea = .Range(.Cells(2, 1), .Cells(.Rows.Count, 5).End(xlUp)).Value
    End With
    LookIn = MergedRows(SearchArea)

    For R = 1 To UBound(LookIn)
        If LookIn(R) = LookFor(1) Then
            If R < UBound(LookIn) - 2 Then
                For C = 2 To UBound(LookFor)
                    If LookIn(R + C - 1) <> LookFor(C) Then Exit For
                Next C
                If C > UBound(LookFor) Then
                    MsgBox "Match found in Row " & R
                    Exit For
                End If
            End If
        End If
    Next R
End Sub

Private Function MergedRows(RngVal As Variant) As String()

    Dim Fun() As String
    Dim R As Long, C As Long

    ReDim Fun(1 To UBound(RngVal))

    For R = 1 To UBound(RngVal)
        For C = 1 To UBound(RngVal, 2)
            Fun(R) = Fun(R) & "," & RngVal(R, C)
        Next C
    Next R
    MergedRows = Fun
End Function

The code creates merged strings of 5 cells of both the SearchedData and the SearchArea data. This job is done by the Function MergedRows. In the process the SearchedData turn into array LookFor(1 To 3) and LookIn(1 To LastRow). Next the first element (representing a row) of LookFor is compared to each element (representing a row) of LookIn. If a match is found the other two rows are also compared. When all three elements (rows) match a message is issued and the search is terminated.
Comment: My code was tested and worked. In order to test it on your data one would have to step through the code line by line (F8) and check why it fails. Toward this end I have added a description of the code's action to my answer.
Comment: Thank you. But this code doesn't do anything. I have inserted the data I was searching for in the worksheet that the macro runs on (Tabelle1) but it doesn't show the Messagebox that indicated that the data was found..
Comment: Thanks for your help!


Windows 7 Trust issues

Question: Like many people my network has been getting the dreaded "The trust relationship between this workstation and the primary domain failed" error.  I remove the computer from the domain rejoin it to the domain after changing the computer name and everything is back working.  I have a 2008 R2 DC, how can I prevent this from happening?  Is there a group policy or script i can push?
Comment: Why did you change the computer name?
Answer: There are a few common reasons why this happens.

A computer with a duplicate name was joined to the domain. This will cause the original to no longer have a trust relationship with the domain, since its computer account is now effectively the account for the new machine with the duplicate name.
Time sync is screwed up. You won't be able to log in if the time is more than 5 minute off. Kerberos relies on time being at least in the same ballpark on the clients and servers. Make sure that your DC holding the PDC Emulator role is set as a reliable time source and that all of your other DCs sync from it. Also make sure that there are no alternate time sources configured for your clients via GPO or local policy. The clients should sync time from the logon server.
The computer account was reset or the password came out of sync. Computers log into AD just like users do, and they have a password. This password is changed at a regular interval behind the scenes. If you have replication problems and a computer changes the password on one DC and then later tries to log into another and replication failed for whatever reason, your machine won't be trusted for logon on, since the computer password differs between the client and logon server.

There are, of course, other edge cases why this happens. These are the most common and are where your troubleshooting should begin. There's no script, GPO, or magic fairy dust to sprinkle, since there isn't a normal reason for this to happen.
Comment: Another common reason: the network is broken.  (You'd think this was self-evident, but apparently not.)
Answer: If it happens more than every once in a blue moon, you need to track down the root cause to determine what's breaking the trust relationship.  There's no magic policy or script to do it for you.
You'll want to make sure it's not some script or other administrator deleting these machines form the domain, that the machines aren't being "tombstoned," and that your AD is healthy (dcdiag, etc).  Your basic AD administration/troubleshooting steps, in other words.
Comment: Tombstoned objects would have nothing to do with this. When an object is "deleted" from AD, what actually happens is that most of its attributes are removed abd it is moved to CN=Deleted and renamed. That object is now a tombstone. There is a job that periodically runs (every 30 days, I believe - maybe longer) that removes tombstoned objects from the directory. Tombstone lifetime really doesn't factor into this question at all.

Windows 7 Trust issues


Perspective on 3D objects

Question: I am updating one of our older apps from vb6 to c# and in the process have to recreate a custom control that the original programmer designed.  The control simply took the dimensions of an object, rectangular or conical, and placed an outline sketch of the object in 3D (2.5D technically I think).  Of course, the code for the control or the algorithim is nowhere to be had.
Knowing nothing about this before hand I have gotten pretty much everything replicated except the perspective.  I am using this code that I found on another answer here.
<code>        }
        double w = 400;
        double h = 250;
        double t = 0.6; // tilt angle
        double X = w / 2 - x;
        double Y = h / 2 - y;
        double a = h / (h + Y * Math.Sin(t));
        double u = a * X + w / 2;
        double v = a * Y * Math.Cos(t) + h / 2;
        }
</code>
The last piece I need help with though is turning the perspective about 30 degrees left-to-right so I'm not looking at straight on.
Thanks for any help.
Comment: If i understood what you want to do, you need to use __rotation__ matrix.
http://en.wikipedia.org/wiki/Transformation_matrix
And yes, the best way to understand this all is to read about openGL transformations
http://www.songho.ca/opengl/gl_transform.html
Answer: As the commenter says: You should use matrices to make your live easy.
Rotation could be easily done by multiplying the 2 matrices, a rotation matrix and a perspective matrix this way:
<code>// We don't have a view matrix here
Matrix4x4 modelProjection = Matrix4x4.Perspective(400, 250, Math.PI / 4) * Matrix4x4.RotationX(degree);
// Get a specifics point position, use x and y to determine the screen position and z for the z-order
Vector3 screenPosition = modelProjection * myPosition; // myPosition is a Vector3
</code>
For running the code you have to do some things:
Implement a C# matrix, or get it from anywhere else. Here is a excellent source for implementing matrices.

Perspective on 3D objects