Is there an elegant/insightful way to understand this linear regression identity for multiple $R^2$?

Question: In linear regression I have come across a delightful result that if we fit the model
$$E[Y] = \beta_1 X_1 + \beta_2 X_2 + c,$$
then, if we standardize and centre the $Y$, $X_1$ and $X_2$ data,
$$R^2 = \mathrm{Cor}(Y,X_1) \beta_1 + \mathrm{Cor}(Y, X_2) \beta_2.$$
This feels to me like a 2 variable version of $R^2 = \mathrm{Cor}(Y,X)^2$ for $y=mx+c$ regression, which is pleasing.
But the only proof I know is not in anyway constructive or insightful (see below), and yet to look at it it feels like it should be readily understandable.
Example thoughts:

The $\beta_1$ and $\beta_2$ parameters give us the 'proportion' of $X_1$ and $X_2$ in $Y$, and so we are taking respective proportions of their correlations...
The $\beta$s are partial correlations, $R^2$ is the squared multiple correlation... correlations multiplied by partial correlations...
If we orthogonalize first then the $\beta$s will be $\mathrm{Cov}/\mathrm{Var}$... does this result make some geometric sense?

None of these threads seem to lead anywhere for me.  Can anyone provide a clear explanation of how to understand this result.

Unsatisfying Proof
\begin{equation}
R^2 = \frac{SS_{reg}}{SS_{Tot}} = \frac{SS_{reg}}{N} = \langle(\beta_1 X_1 + \beta_2 X_2)^2\rangle
 \\= \langle\beta_1^2 X_1^2\rangle + \langle\beta_2^2 X_2^2\rangle + 2\langle\beta_1\beta_2X_1X_2\rangle
\end{equation}
and
\begin{equation}
\mathrm{Cor}(Y,X_1) \beta_1 + \mathrm{Cor}(Y, X_2) \beta_2 = \langle YX_1\rangle\beta_1 + \langle Y X_2\rangle \beta_2\\
=\langle \beta_1 X_1^2 + \beta_2 X_1 X_2\rangle \beta_1 + \langle \beta_1 X_1 X_2 + \beta_2 X_2^2\rangle \beta_2\\
=\langle \beta_1^2 X_1^2\rangle + \langle \beta_2^2 X_2^2 \rangle + 2\langle \beta_1 \beta_2 X_1 X_2\rangle
\end{equation}
QED.
Comment: Doesn't your top result only hold if X1 & X2 are perfectly uncorrelated?
Comment: You must be using standardized variables, for otherwise your formula for $R^2$ is not guaranteed to lie between $0$ and $1$.  Although this assumption comes out in your proof, it would help to make it explicit at the outset. I am puzzled over what you are really doing, too: your $R^2$ clearly is a function of the *model* alone--having nothing to do with the data--yet you start out mentioning that you have "fit" the model to something.
Comment: @gung I don't think so - proof at bottom seems to say it works regardless.  This result surprises me too, hence wanting a "clear understanding proof"
Comment: @whuber I'm not sure what you mean by "function of the model alone"?  I simply mean the $R^2$ for simple OLS with two predicter variables.  I.e. this is the 2 variable version of $R^2 = Cor(Y,X)^2$
Comment: I cannot tell whether your $\beta_i$ are the parameters or the estimates.
Comment: @whuber, they are the fitted (estimated) values, and the $Cor(Y_, X_i)$ are the sample estimates.
Comment: "This feels to me like a 2 variable version of $R^2=Cor(Y,X)^2$ for y=mx+c regression" - the multiple regression equivalent is that $R^2 = Cor(Y, \hat{Y})^2$.
Comment: See also https://stats.stackexchange.com/q/123651/3277
Answer: The hat matrix is idempotent.
(This is a linear-algebraic way of stating that OLS is an orthogonal projection of the response vector onto the space spanned by the variables.)

Recall that by definition
$$R^2 = \frac{ESS}{TSS}$$
where
$$ESS = (\hat Y)^\prime \hat Y$$
is the sum of squares of the (centered) predicted values and
$$TSS = Y^\prime Y$$
is the sum of squares of the (centered) response values.  Standardizing $Y$ beforehand to unit variance also implies
$$TSS = Y^\prime Y = n.$$
Recall, too, that the estimated coefficients are given by
$$\hat\beta = (X^\prime X)^{-} X^\prime Y,$$
whence
$$\hat Y = X \hat \beta =  X (X^\prime X)^{-} X^\prime Y = H Y$$
where $H$ is the "hat matrix" effecting the projection of $Y$ onto its least squares fit $\hat Y$.  It is symmetric (which is obvious from its very form) and idempotent.  Here is a proof of the latter for those unfamiliar with this result.  It's just shuffling parentheses around:
$$\eqalign{H^\prime H = H H  &=\left( X (X^\prime X)^{-} X^\prime\right)\left(X (X^\prime X)^{-} X^\prime \right) \\ &= X (X^\prime X)^{-} \left(X^\prime X \right) (X^\prime X)^{-} X^\prime \\ &=  X (X^\prime X)^{-} X^\prime = H.
}$$
Therefore
$$R^2 = \frac{ESS}{TSS} = \frac{1}{n} (\hat Y)^\prime \hat Y = \frac{1}{n}Y^\prime H^\prime H Y = \frac{1}{n}Y^\prime H Y = \left(\frac{1}{n}Y^\prime X\right) \hat \beta.$$
The crucial move in the middle used the idempotence of the hat matrix.  The right hand side is your magical formula because $\frac{1}{n}Y^\prime X$ is the (row) vector of correlation coefficients between $Y$ and the columns of $X$.
Comment: @amoeba: Yes, this notation appears elsewhere, including in the classical texts by Graybill on the linear model.
Comment: @amoeba Penrose, in his original paper (*A Generalized Inverse for Matrices*, 1954) used the notation $A^\dagger$. I like neither that nor the $A^{+}$ notation because they are too easily confused with conjugates, transposes, or conjugate transposes, whereas the $A^{-}$ notation is so suggestive of an inverse the casual reader can get away with thinking of it as $A^{-1}$ if they like. You're just too good a reader--but thanks for noticing.
Comment: @amoeba It's a [generalized inverse](http://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse), put there to handle the cases where $X^\prime X$ may be singular.
Comment: Interesting and compelling motivation, but may I ask if this notation is something that is occasionally used elsewhere or is it your own invention?
Comment: (+1) Very nice write-up. But why `^{-}` instead of `^{-1}` everywhere?
Comment: Ah! Funny, I have never seen this notation, I am used to `^+` (used also in the wiki article you link to), so plus instead of minus...
Comment: That's just the sort of explanation I was looking for.  Interestingly this suggests that the result hold for many predictors, not just 2.
Comment: That is correct. I'm pretty sure that with some care it can be proven for Hilbert space projections, too, effectively extending it to a countable infinity of predictors!
Answer: The following three formulas are well known, they are found in many books on linear regression. It is not difficult to derive them.
$\beta_1= \frac {r_{YX_1}-r_{YX_2}r_{X_1X_2}} {\sqrt{1-r_{X_1X_2}^2}}$
$\beta_2= \frac {r_{YX_2}-r_{YX_1}r_{X_1X_2}} {\sqrt{1-r_{X_1X_2}^2}}$
$R^2= \frac {r_{YX_1}^2+r_{YX_2}^2-2 r_{YX_1}r_{YX_2}r_{X_1X_2}} {\sqrt{1-r_{X_1X_2}^2}}$
If you substitute the two betas into your equation
$R^2 = r_{YX_1} \beta_1 + r_{YX_2} \beta_2$, you will get the above formula for R-square.

Here is a geometric "insight". Below are two pictures showing regression of $Y$ by $X_1$ and $X_2$. This kind of representation is known as variables-as-vectors in subject space (please read what it is about). The pictures are drawn after all the three variables were centered, and so (1) every vector's length = st. deviation of the respective variable, and (2) angle (its cosine) between every two vectors = correlation between the respective variables.

$\hat{Y}$ is the regression prediction (orthogonal projection of $Y$ onto "plane X"); $e$ is the error term; $cos \angle{Y \hat{Y}}={|\hat Y|}/|Y|$, multiple correlation coefficient.
The left picture depicts skew coordinates of $\hat{Y}$ on variables $X_1$ and $X_2$. We know that such coordinates relate the regression coefficients. Namely, the coordinates are: $b_1|X_1|=b_1\sigma_{X_1}$ and $b_2|X_2|=b_2\sigma_{X_2}$.
And the right picture shows corresponding perpendicular coordinates. We know that such coordinates relate the zero order correlation coefficients (these are cosines of orthogonal projections). If $r_1$ is the correlation between $Y$ and $X_1$ and $r_1^*$ is the correlation between $\hat Y$ and $X_1$
then the coordinate is $r_1|Y|=r_1\sigma_{Y} = r_1^*|\hat{Y}|=r_1^*\sigma_{\hat{Y}}$. Likewise for the other coordinate, $r_2|Y|=r_2\sigma_{Y} = r_2^*|\hat{Y}|=r_2^*\sigma_{\hat{Y}}$.
So far it were general explanations of linear regression vector representation. Now we turn for the task to show how it may lead to $R^2 = r_1 \beta_1 + r_2 \beta_2$.
First of all, recall that in their question @Corone put forward the condition that the expression is true when all the three variables are standardized, that is, not just centered but also scaled to variance 1. Then (i.e. implying $|X_1|=|X_2|=|Y|=1$ to be the "working parts" of the vectors) we have coordinates equal to: $b_1|X_1|=\beta_1$; $b_2|X_2|=\beta_2$; $r_1|Y|=r_1$; $r_2|Y|=r_2$; as well as $R=|\hat Y|/|Y|=|\hat Y|$. Redraw, under these conditions, just the "plane X" of the pictures above:

On the picture, we have a pair of perpendicular coordinates and a pair of skew coordinates, of the same vector $\hat Y$ of length $R$. There exist a general rule to obtain perpendicular coordinates from skew ones (or back): $\bf P = S C$, where $\bf P$ is points X axes matrix of perpendicular ones; $\bf S$ is the same sized matrix of skew ones; and $\bf C$ are the axes X axes symmetric matrix of angles (cosines) between the nonorthogonal axes.
$X_1$ and $X_2$ are the axes in our case, with $r_{12}$ being the cosine between them. So, $r_1 = \beta_1 + \beta_2 r_{12}$ and $r_2 = \beta_1 r_{12} + \beta_2$.
Substitute these $r$s expressed via $\beta$s in the @Corone's statement $R^2 = r_1 \beta_1 + r_2 \beta_2$, and you'll get that $R^2 = \beta_1^2 + \beta_2^2 + 2\beta_1\beta_2r_{12}$, - which is true, because it is exactly how a diagonal of a parallelogram (tinted on the picture) is expressed via its adjacent sides (quantity $\beta_1\beta_2r_{12}$ being the scalar product).
This same thing is true for any number of predictors X. Unfortunately, it is impossible to draw the alike pictures with many predictors.
Please see similar pictures in this great answer.
Comment: @Corone, I added some "insight" which you might take.
Comment: +1 nice to see it constructed this way as well, but this doesn't add as much insight compared to whuber's answer
Comment: +1 Really cool (after the update). I thought that invoking "general rule" of converting between coordinates is a bit of an overkill (and for me was only confusing); to see that e.g. $r_1 = \beta_1 + \beta_2 r_{12}$ one only needs to remember the definition of cosine and look at one of the right triangles.
Comment: Really cool edit, switched accepted.


What is the keyboard shortcut for adding a new file to a project in Visual Studio 2022?

Question: I used to be able to press shift+alt+c to add a new file to a project, but my Visual Studio updated and I seem to have lost this keyboard shortcut.
If i go to Tools -> options... -> Environment -> Keybord, I can see a huge list of commands that can have keybord shortcuts assigned to them. What is the command for adding a new item to a project?
I know there is a new shift+F2 shortcut that lets you quick add a new class., but I'm interested in the full Add New Item menu.
Comment: Shortcut keys are displayed on the menu to the right of the menu text.  So Ctrl+N for a new file, Shift+Alt+A for an existing file.
Answer: So the shift+alt+c shortcut for adding new items to projects is apparently gone in new versions of Visual Studio. I found a mapping of commands and keyboard shortcuts from before the update here.
The shift+alt+c shortcut used to be linked to the command Project.AddClass.
So If you navigate to Tools -> options... -> Environment -> Keybord, and then search for Project.AddClass, you can re-add the shift+alt+c keyboard shortcut and use the shortcut as befor.


How to get rid of lag when working with multi threading

Question: Refer to: How to animate a spinner while performing a workload via threading
I am working with a Delphi xe5 Application for iOS. While performing a SQL query, I have a TAniIndicator spinning. I am using threads - for specific code, see article stated above.
Everything works, however, when using the code I was helped with in the previous question, I've noticed added lag. When ran under the debugger, the application hangs between the lines:
Thread.DoTerminate;
Thread.FFinished := True;

under the ThreadProc Function of System.Classes Unit
Any clue as to why ? Or what I can do to prevent that added 5 second lag? Thank you
Update reply to TLama:
procedure TForm_Login.WorkIsDone(Sender : TObject);
begin
  Form_Login.LoadSpinnerFrame.visible := False;
  Form_Login.LoadSpinner.Visible := False;
  Form_Login.LoadSpinner.Enabled := False;
  Form_Login.btnLogin.Text := 'Logout';
  Form_Login.btnLogin.Enabled := True;
  if GoodLogin = 1 then
    Main_Form.show;
end;

My onTerminate() is linked to the above procedure.
Comment: @norgepaul says there is a "known" bug in the spinner in XE5 for iOS. It has to do with the spinner being active when a `OnTerminate` call is made. QC is #117572. There is also #118973.
Comment: So the best thing to do is to emulate a spinning component, at least until this bug is fixed. It could probably be done with a timer and an image with alternating icons.
Comment: Found this component in the FMX library, [`FMX.Ani.TBitmapListAnimation`](http://docwiki.embarcadero.com/Libraries/XE5/en/FMX.Ani.TBitmapListAnimation). Seems to do the animation nicely.
Comment: Do you have any code in the `OnTerminate` event method of your thread ?
Comment: Question Updated, Thank you
Comment: You sure you took out that `Sleep(5000)`?
Comment: @MarcusAdams: the `Sleep()` was in the thread's `Execute()` method, not in its `OnTerminate` event handler.
Comment: @RemyLebeau, I saw that, but who knows where the OP put it while testing/debugging.
Comment: yes @Marcus, that was the first thing I checked.. lol
Comment: Is the lag same if `GoodLogin` is 1 and <> 1?
Comment: Yes, and the 5 seconds is more like... 30 seconds too..
Comment: QC #118973 is just a duplicate of #117572.
Comment: Seems to b independent of TAniIndicator. I still experience a lag time even when using a TBitmapListAnimation.
Answer: TThread.DoTerminate() calls TThread.Synchronize() to fire the TThread.OnTerminate event handler in the main thread. TThread is then blocked until the main thread processes that request - which does not happen instantaneously as the main thread has to detect and process new messages first - and the OnTerminate handler exits.  Only then is control returned to TThread so it can finish its logic.  So if you are encountering a 5s lag in DoTerminate(), then it mean the main thread is taking 5s to detect and process the Synchronize() request.
Comment: So is there anything I can do about that, or no ?
Comment: For other answer-seekers regarding this question. Review comments above in replies to the OP


Can we read SQL results as is into a variable instead of string

Question: I have two database - SRC and TGT having table TAB1. I need to verify that the data in both tables is same. The table has data set of types int, varchar, date etc..
When I read the result set in to arraylist, its converted to string. Because of this my comparison failing due to the fact that DATE columns in both SRC and TGT tables are yielding different formats as they are converted to string.
My SQL and results are as below:
Select * from TAB1:
Sl No | Name | DOB        | Age | Salary
1     | ABC  | 09/02/2000 | 18  | 100.20
2     | XYZ  | 02/02/2000 | 18  | 200.40

We are using below piece of java code:
Statement stmt = databaseDBconn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from TAB1");
ResultSetMetaData rsmd = rs.getMetadata();
int colnum = rsmd.getColumnCount();
String[] str = new string[colnum];

while (rs.next()) {
    for (int i=1;i<=colnum;i++) {
        str[i-1] = rs.getstring(i);
        tablearray.table1.add(str[i-1]);
    }
}

we have used same above code for TAB1 in both SRC and TGT database.
Even though the data in both tables is same, we are getting error message because of the DATE column value is getting converted to string.
Is there a way we can have DATE as is without getting this converted to string for comparison?
Comment: It's converted into a string because you tell it to be converted to a string (`getstring`). If you don't want that behavior, then do not implement it[.](http://roboter-basteln.de/)
Comment: Have you considered `ResultSet`'s four versions of the `getDate()` method?  Alternatively, `getObject()` ought to give you a `java.sql.Date` (probably) or `java.sql.Timestamp` (maybe), too, when the SQL column type is `DATE`.
Comment: @JohnBollinger The two-arg `getObject` methods will give you a `java.time.LocalDate` when you ask them to, freeing you from the outdated `Date` and `Timestamp` classes.
Comment: By the way, you might find a database migration tool to be useful in keeping your database structures intact, such as [*FlyWay*](http://www.FlywayDB.com/) or *LiquiBase*.
Answer: I would do it like this:
while(rs.next) {
  int slNo = rs.getInt("Sl No");
  String name = rs.getString("Name");
  Date dob = rs.getDate("DOB");
  int age = rs.getInt("Age);
  BigDecimal salary = new BigDecimal(row.getString("Salary"));
}

That way each column is stored in an appropriate datatype.
Comment: Correct answer, but the `Date` class is long outdated. Better: `LocalDate dob = rs.getObject("DOB", LocalDate.class);` (using `java.time`, just requires a JDBC 4.2 compliant driver, which you're likely to have already and can get if not).
Comment: Right, I still maintain a Java 6 project when I use the JDBC stuff, I'm out of date!
Comment: @Matt For Java 6 & 7, use the [*ThreeTen-Backport*](http://www.threeten.org/threetenbp/) project, back-porting much of the *java.time* functionality. Virtually the same API. Later, when you move to Java 8 or 9 or later, you'll need do little more than change your `import` statements. In the back-port, you can convert between legacy and modern classes via the [`DateTimeUtils`](http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html) class, in Java 8 and later use new conversion methods added to the legacy classes.


Flutter WebView doesn't work on canvas for web

Question: I am building a cross platform application for web, android and mobile using WebView feature but I want to use the canvas implementation but the WebView doesn't work in canvas what should be done.
Comment: did you solve this problem?
Comment: Yes check the answer below
Answer: In fact you can use the HtmlElementView
Heres an example
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

void main() {
  // ignore: undefined_prefixed_name
  ui.platformViewRegistry.registerViewFactory(
      'hello-html',
      (int viewId) => IFrameElement()
        ..width = '640'
        ..height = '360'
        ..src = 'https://www.youtube.com/embed/xg4S67ZvsRs'
        ..style.border = 'none');

  runApp( Padding(
        padding: EdgeInsets.all(25),
        child: SizedBox(
          width: 640,
          height: 360,
          child: HtmlElementView(viewType: 'hello-html'),
      ),
    ),
  );
}

Check it out here:
https://codepen.io/riccio85/pen/wvMeaMe


View test result of BrowserTestBase based test?

Question: How can I setup my Drupal config to be able to view the results of failed tests using the new BrowserTestBase class in 8.2.x?
I don't see any files generated and the phpunit.xml config does not seem to be getting respected:

    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/testing" />

The command I am using is:
vendor/bin/phpunit -c core/phpunit.xml --group tvi

I have some failing tests but I can't see what the test sees.
Answer: Figured it out. Before calling parent::setUp(), I set:
$this->htmlOutputEnabled = true;


Predicting point forecast using Random walk model coefficients

Question: I have created a random walk model ARIMA(0,1,0) in R. The coefficients and R output is as shown below:
arima(x = Y, order = c(0, 1, 0), xreg = Indp_varbl)
Coefficients:
          t2       t3
      9.1993  18.0351
s.e.  0.4921   7.7715

I wanted to ask how I can forecast points using these coefficients through an equation? I have gone through papers but was not able to find exact equation using regressors as well:
Yt = Yt-1 + mean error

is generally used. How can I get the equation for the same?
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: Let $y$ denote the dependent variable and $x_1$, $x_2$ denote the independent ones. Then
$$ \Delta y_t = 9.1993 x_{1,t} + 18.0351 x_{2,t} + u_t $$
For example, if you have values for $y_{t-1}$, $x_{1,t}$ and $x_{2,t}$, the point prediction of $y_t$ will be
$$ \hat y_t = y_{t-1} + 9.1993 x_{1,t} + 18.0351 x_{2,t} + 0 $$
(as $\hat u_t=0$).


Is there easier way to calculate the limit of this function?

Question: $$
\lim_{K\rightarrow\infty}\frac{(1-\epsilon)^K}{1+(1-\epsilon)^K}\frac{\sum_{i=1}^{\frac{K-1}{2}}\left(\begin{array}{l}
         K \\
         i \end{array}\right)\left[\left(\frac{2\epsilon-\epsilon^2}{(1-\epsilon)^2}\right)^i-\left(\frac{\epsilon}{1-\epsilon}\right)^i\right]}{(1-\epsilon)^K\left[1+\sum_{i=1}^{\frac{K-1}{2}}\left(\begin{array}{l}
         K \\
         i \end{array}\right)\left(\frac{2\epsilon-\epsilon^2}{(1-\epsilon)^2}\right)^i\right]+\left[1+\sum_{i=1}^{\frac{K-1}{2}}\left(\begin{array}{l}
         K \\
         i \end{array}\right)\left(\frac{\epsilon}{1-\epsilon}\right)^i\right]}=?
$$
where $1>\epsilon>0$. I wonder especially when $\epsilon\rightarrow 0$ but $\epsilon\neq 0$
I even dont know if this is a difficult or an easy question for a mathematician. If you could comment on this matter, I will be happy.
Comment: Oh, sorry, I thought it was $\lim\limits_{\epsilon\to0^+}$. Then I would just "reverse-use" the binomial theorem.
Comment: @SeyhmusGüngören  $p^i q^{n-i}=q^n(p/q)^i$ and the first multiplier does not depend on $i$ so...
Comment: @anon: That's what I thought too, but he says $\epsilon \ne 0$...
Comment: yes it cannot be zero but can be a very small positive real number.
Comment: yes I saw the theorem: $(1+x)^n=\sum_{k=0}^{n}\left(\begin{array}{l}
         n \\
         k \end{array}\right)x^k$
Comment: If an individual factor has a non-zero, non-infinite limit, then it is safe to apply the limit to that factor. So for instance, the first denominator of $1+(1-\epsilon)^K$ approaches $1$ as $K\to\infty$, and therefore may be omitted from the expression.
Comment: yes but still it has a little help)
Comment: @SeyhmusGüngören perhaps remembering the binomial distribution http://en.wikipedia.org/wiki/Binomial_distribution and de Moivre–Laplace theorem could help here. In this case the function erf could appear in the answer.
Comment: binomial distribution has two terms p and q. I cannot see that I will get a nice solutions easily in this way.
Answer: An idea which leads directly to the solution is to write the sums involved as (multiples of) probabilities of events involving some binomial random variables $X_K$ and $Y_K$ with respective parameters $(K,\eta)$ and $(K,\epsilon)$, where $\eta=2\epsilon-\epsilon^2$. To wit, the ratio of interest $R_K$ can be rewritten as
$$
R_K=\frac{(1-\epsilon)^K}{1+(1-\epsilon)^K}\cdot\frac{A_K-B_K}{(1-\epsilon)^K\cdot A_K+B_K},
$$
with
$$
A_K=\sum_{i=0}^{\frac{K-1}{2}}{K\choose i}\left(\frac{\eta}{1-\eta}\right)^i=(1-\eta)^{-K}\cdot\mathrm P(X_K\leqslant\tfrac12(K-1)),
$$
and
$$
B_K=\sum_{i=0}^{\frac{K-1}{2}}{K\choose i}\left(\frac{\epsilon}{1-\epsilon}\right)^i=(1-\epsilon)^{-K}\cdot\mathrm P(Y_K\leqslant\tfrac12(K-1)).
$$
If $\eta\lt\frac12$, then $\epsilon\lt\frac12$ and, by the (weak) law of large numbers, $\mathrm P(X_K\leqslant\tfrac12(K-1))\to1$ and $\mathrm P(Y_K\leqslant\tfrac12(K-1))\to1$ when $K\to\infty$.
Thus,
$$
(1-\epsilon)^{2K}\cdot A_K=(1-\eta)^{K}\cdot A_K\to1,\qquad
(1-\epsilon)^{K}\cdot B_K\to1.
$$
Finally, for every $\epsilon$ such that $\eta=2\epsilon-\epsilon^2\lt\frac12$, that is, for every $\epsilon\lt1-\frac{\sqrt2}2=0.393$,
$$
\lim\limits_{K\to\infty}R_K=\tfrac12.
$$
Comment: Thanks alot for the solution. I have one more question named "maximum of the function at limit" in this question the first part is always $1$ if $\theta <0.5$. but the second part is diverging from 1 if $\theta<0.5$ but very close to $0.5$. For example if $\theta=0.49$ then I have $(1-t)^K f=0.7364$ and the first part is $1$ and the difference is $0.2636$. I took $K=999$. I guess K is not enough since $\theta$ is very close to $0.5$ although less than that of. Then the answer for my other question should be $0$? then it seems strange to me because this question was general of the other one..


How to speed Indexing process of Magento eCommerce website?

Question: I have a Magento eCommerce website in which multiple cron jobs running that are updating the 30,000 products on here.  The indexing speed is horrible....I can't even update at the same rate as my supplier.   Inventory is being updated on 2 hour intervals when it should be 1 hour intervals.   Other cron jobs that should be run daily are being run weekly.  Are these things can be fix?  In addition I need to add about 3 more suppliers so I wanted know how to integrate it ?
I want this website to handle 100K+ products from many suppliers.   As it relates to adding additional suppliers with the same and different SKUs. Please suggest me possible ways to achieve this ?
Answer: At my shop the only way to get batch-operation inventory or catalog scripts to run quickly was to turn indexing off before the script started, and turn it back on and let the indexes rebuild after the updates were done.
This probably still works:
UPDATE index_process SET mode = 'manual';

Then run your update code, then:
UPDATE index_process SET mode = 'real_time';

Although you may want to be more selective about which indexes you disable/re-enable.


Conditional expectations of $X$ with respect to a filtration converges to $X$

Question: Let $\mathbb F = \left( \mathcal F_n\right)_{n \in \mathbb N}$ be a filtration, and let $\mathcal F_\infty = \sigma\left(\mathcal F_n : n \geq 1\right)$. I want to try proving the following result:

If $X \in \mathcal L^1\left(\mathcal F_\infty\right)$, then $\mathbb E\left[X|\mathcal F_n\right] \to X$ as $n \to \infty$ almost surely.

It's easy to show that $\left(\mathbb E\left[X|\mathcal F_n\right]\right)_{n \in \mathbb N}$ is a martingale with respect to $\mathbb F$, and since $X$ is integrable, one can show that
$$
\sup_{n \geq 1} \mathbb E\left[\mathbb E\left[X|\mathcal F_n\right]^+\right] \leq \mathbb E[|X|] < \infty
$$
So by the martingale convergence theorem, $\left(\mathbb E\left[X|\mathcal F_n\right]\right)_{n \geq 1}$ converges almost surely, say to the random variable $\tilde X$. But why does $X = \tilde X$ a.s.? How can I show that $\left| X - \mathbb E\left[X|\mathcal F_n\right]\right| \to 0$? I'm wondering if there's a functional analytic reason, considering the projections $\mathbb E\left[\cdot|\mathcal F_n\right] : \mathcal L^1\left(\mathcal F_\infty\right) \to \mathcal L^1\left(\mathcal F_n\right)$, but I haven't gotten very far with this approach. Or is there an obvious reason for this that I'm just overlooking?
Comment: If you are working in $L^2$, you can use the projection method: you only have to use that the conditional expectation is the orthogonal projection on the subspace of $\mathcal{F}_n$- measurable functions.  Otherwise, I think that it is more of a measure-theoretic proof using measure-theoretic induction.
Answer: Let $X_n=\mathbb{E}\left[X\mid\mathcal{F}_n\right]$. This is a closed martingale so it converges in $L^1$ and almost surely to $\tilde{X}$. For all $n\geq 1$ and $A\in\mathcal{F}_n$, the convergence in $L^1$ together with the continuity of the conditional expectation give
$$\mathbb{E}\left[\mathbf{1}_AX\right]=\mathbb{E}\left[\mathbf{1}_AX_n\right]=\mathbb{E}\left[\mathbf{1}_A\tilde{X}\right]$$
This equality holds for any $A\in\bigcup_{n=1}^\infty\mathcal{F}_n$. If we can show that it holds for $A\in\mathcal{F}_\infty$ we are done because both $X$ and $\tilde{X}$ are $\mathcal{F}_\infty$-measurable. Now, the set $\bigcup_{n=1}^\infty\mathcal{F}$ is stable by finite intersection and the class $$\mathcal{G}=\left\{A\in\mathcal{F}_\infty:\mathbb{E}\left[\mathbf{1}_AX\right]=\mathbb{E}\left[\mathbf{1}_A\tilde{X}\right]\right\}$$
is a monotone class. Since $\bigcup_{n=1}^\infty\mathcal{F}_n\subset\mathcal{G}$ the monotone class lemma implies $\mathcal{F}_\infty\subset\mathcal{G}$.
Comment: Thank you! It took me a bit to work through this solution because my reference text doesn't explicitly prove that $\mathbb E[X|\mathcal F_n]$ is uniformly integrable, and hence $L^1$-convergent.
Comment: Great! A neat property about martingales that might be useful to you is that the following conditions are equivalent: (i) $X_n$ converges a.s. and in $L^1$ (ii) $(X_n)_{n\geq 0}$ is closed, in the sense that there is some $Z\in L^1$ such that $X_n=\mathbb{E}\left[X\mid\mathcal{F}_n\right]$ and (iii) $(X_n)_{n\geq 0}$ is uniformly integrable


In what order are the countries during the Olympics Opening Ceremony?

Question: Shortly after the beginning of the Olympics Opening Ceremony, the Parade of Athletes occurs where the athletes enter the stadium by country.  It usually seems to be alphabetical, but some countries are out of order.  How is it determined which order the teams are in when they enter the stadium?
Answer: During the Parade of Athletes, the first team to enter the stadium is always Greece, in honor of the fact that the Olympics has its origin in ancient Greece.  The last team in is the host country.  The rest of the teams enter the stadium in alphabetical order, according to the language of the host country.  This is why teams are in a different order in each Olympics.
In 2004, when the Olympics were held in Athens, Greece, the Greek flag bearer, weightlifter Pyrros Dimas, entered the stadium first alone, leading the parade.  The rest of the Greek athletes entered as the last team in the parade.
The International Olympic Committee has published a factsheet outlining the elements of the opening ceremony.


In Angular, what is the proper way to send query parameter to a GET endpoint

Question: I have build an Angular service which is responsible to retrieve datas from a REST endpoint.
It works but I need to know if

There is other ways to do it ?
And even more importantly. If there is, which way is the proper one ?

Thank you for your help.

Here is my code:
<code>@Injectable()
export class XXXService {
  private static ENDPOINT = "./api/XXX/YYY/rate";

  constructor(private http: HttpClient) {
  }

  public getRateDatas(): Observable<IRate[]> {
    const httpParams = new HttpParams()
      .set('paramId', 's1')
      .set('paramCode', 'r1')
      .set('paramNumber', '2');
    return this.http.get<IRate[]>(XXXService.ENDPOINT, {params: httpParams});
  }
}
</code>
Comment: Using `httpClient` is going to be your best bet. For Reference: https://angular.io/guide/http
Comment: See this this answer... https://stackoverflow.com/questions/45470575/angular-4-httpclient-query-parameters
Answer: You can use like this way to call your APIs
<code>  //in your service
  Call_GetTypeApi(id){
    this._Url = 'your_API_url?id=' +id;
    return (<Observable<IRate[]>>this.getData(this._Url));
  }

 Call_PostTypeApi(jsonData: string) {
    this._Url = "your_API_url";
    return (<Observable<IRate[]>>this.postData(this._Url, jsonData));
  }

 //Common function for get and post method
  getData(_Url: string) {
    return this.http.get(_Url);
  }

  postData(_Url: string, jsonData?: any) {
    return this.http.post(_Url, jsonData,
      {
        headers: new HttpHeaders().set('Content-Type', 'application/json'),
      });
  }
</code>
I hope it is helpful for you. :)


A classe Model padrão MVC no PHP

Question: Estou estudando MVC, criei a classe Model abstrata para servir de "molde" para as demais que poderão herdá-la. Gostaria de uma avaliação do código como, pontos positivos e negativos, qual a melhor forma de melhorá-lo, etc.

abstract class Model {

private $sql;

protected function setSql($sql_query) {

    return isset($sql_query) ? $this -> sql = $sql_query : false;
}

public function getAll() {

    $query = $this -> db -> prepare($this -> sql);
    try {
        $query -> execute();
        return $query -> fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());
    }
}

public function getById($id) {

    $query = $this -> db -> prepare($this -> sql);
    $query -> bindValue(1, $id);

    try {
        $query -> execute();
        return $query -> fetch(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());
    }
}

public function getBySearch($search_term) {

    $query = $this -> db -> prepare($this -> sql);
    $query -> bindValue(1, $search_term);

    try {
        $query -> execute();
        return $query -> fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());

    }

}

public function deleteById($id) {/*será implementada*/}
public function updateById($id) {/*será implementada*/}
public function insert() {/*será implementada*/ }

}
E esta seria a chamada numa classe filha:
public function getUserById($id) {

    $this -> setSql("SELECT * FROM XXX WHERE id = ?");
    return $this -> getById($id);

Comment: Esta pergunta está sendo discutida do Meta: http://meta.pt.stackoverflow.com/questions/1510/devemos-aceitar-pedidos-de-melhoramento-de-c%C3%B3digo
Comment: Recomendo utilizar o Doctrine. É uma excelente ferramenta de abstração e mapeamento dos relacionamentos. Dê uma conferida na [documentação](http://docs.doctrine-project.org/en/latest/)
Answer: Pontos Positivos

A sua classe Model está lembrando muito as classes DAO (Data Access Object), o que separa a responsabilidade de resgatar os objetos (resultados) da responsabilidade de representar o objeto.

Pontos Negativos

Seria legal abstrair o resultado (cada linha do banco de dados) ao invés de retornar um array associativo
Você está usando SQL, se você criar um Objeto para Representar o critério da consulta você vai ter uma independência de banco de dados SQL e NoSQL.

Exemplo
Acredito que tudo deveria ser abstraido, para tornar o desenvolvimento mais natural, por exemplo ao invés de:
echo $model['first_name'].' '.$model['last_name']

você poderia digitar
echo $model->full_name;

A função iria cuidar de juntar transformar os dados em informações mais úteis.
A mesma coisa se aplica para a consulta, ao invés de
$person = $personModel->getBySearch("SELECT * FROM person WHERE name = 'Joe'");

Você poderia usar
$person = Person::$objects->filter(array('name'=>'Joe'))->first();

Ou ainda
$person = Person::$objects->byName('Joe')->first();

No rails, por exemplo, ele cria métodos para filtrar cada atributo (automaticamente)
Comment: Obrigado pelas dicas, sou um pouco novo nisso, eu entendi e não entendi ao mesmo tempo rs, quais padrões de projeto que eu deveria estudar?

A classe Model padrão MVC no PHP


Pooling data from two different samples: Does the scale of the sampling weights matter?

Question: Background
A colleague recently came to me with a problem.  He was tasked with comparing health service utilization indicators in two secondary datasets:

The first dataset is a Demographic and Health Survey (DHS) dataset,
which has around 9,000 observations and is a nationally
representative sample of women 15-49 in Country X.  Individuals were
sampled using stratified two-stage cluster sampling.  The strata for
this sample were the province of residence and whether the cluster
was in an urban area or rural area.
The survey instrument for the second dataset was modeled after the DHS. The same sampling strategy used by the DHS Program was used here. It has around 2,000 observations and is a representative sample of women 15-49 in 3 of the 11 provinces in Country X.  As with the DHS, the strata were the province of residence and whether the cluster was in an urban or rural area.

Both datasets contain sampling weights, but the scales are different.  For the first dataset, the party that processes the data generally multiplies the weight by 100,000 to preserve decimal places.  The documentation urges users to divide the weight variable that is shipped with the dataset by 100,000 before using.  For the second dataset, the party that processes the data did not transform the weight variable further, so that the variable could be used as-is.
Problem
The "scale" of the weight--whether divided by 100,000 first or used as is--doesn't really matter when working within a single survey for point estimates of proportions, means, or parameters, as this kind of transformation only affects the "effective" number of observations (i.e. 1,000/1,000,000 is equivalent to 0.01/10).  What I am not sure about is whether the weights necessarily need to be re-scaled when the data are pooled.  The DHS documentation for sampling states that when pooling DHS datasets, the weights need to be "de-normalized" before using (ICF International, 2012, p. 28) by  multiplying the weight by the target population and dividing this by the number of completed cases (in other words, sum of the weights), for each survey, because the given sampling weights are country-time specific.  My inclination is that once the weights are de-normalized, it is not necessary to ensure that they are the same scale, as he is only interested in the differences in proportions between the two datasets.  Is this correct, or will having variables of different scales be a problem when doing regression?
Reference

ICF International. 2012. Demographic and Health Survey Sampling and
Household Listing Manual. Calverton, Maryland, USA: ICF
International.
http://dhsprogram.com/pubs/pdf/DHSM4/DHS6_Sampling_Manual_Sept2012_DHSM4.pdf
Answer: What DHS does with weights is beyond me. I think their intent with division by 100,000 is to make weights sum up to the nominal sample size of 9,000. But this is an awkward scale of weights. The proper scale should be the population of the country (or, rather, as DHS surveys the specific population of women in their fertile ages, total number of women aged 15-49). ICF computes the weights properly stringing the probabilities of selection, but chooses to destroy the scale. Ah well. So as your first step, you would need to scale the weights in the DHS sample up so that they sum up to the population total. (My guess though is since that total is usually not known very accurately, DHS sweeps the issue under the carpet, and just makes a poker face with the weights that sum up to the sample size.)
Likewise, your additional sample should be scaled so that the weights sum up to the target population in your three provinces.
Once that is done, you can combine the weights using a version of the single frame estimation method (Lohr 2009). Since weights are inverse probabilities of selection, the combined weight should be the inverse of the combined probability of selection:
$$
w_i^c = 1/\pi_i^c = 1/[1-(1-\pi_1^1)(1-\pi_i^2)] \approx 1/(\pi_i^1 + \pi_i^2) = 1/(1/w_i^1 + 1/w_i^2)
$$
for the observations in the three provinces that were sampled twice, while the observations in the remaining provinces just retain their DHS weight.


Struggle with OSGi dependencies for Pellet and OWL-API

Question: I wrote a facade for the owl-api paired with the pellet reasoner to easily access an ontology. It worked quiet well. Then I tried to pack it as an OSGi Bundle and use it via an TrackerService from other services. The owl-api bundle needs guava and trove to run. For trove there is no bundle. Even after reloading the target platform, the pellet jars were not recognized as bundle in eclipse (I took them from jpm4j). So I thought about just take all the jar- stuff and squeeze it into the bundle.
I read a lot of how-to's for packaging third-party jars with a bundle. I use the maven-bundle-plugin and after reading some documentation from this plugin and bndtools I decided to use conditional-package, because here it was described that all entries in the pom are passed to the bndtools. After the compilation, no jar was packaged with my bundle :(. Then I used embed-dependencies. It didnt't work because the transient dependiencies were not available at runtime. So I used the embed-transient tag (I already read that this is bad style). The Import-Package part was filled automatically with all transient dependencies, so I overwrote it by hand to ged rid of the errors regarding the unsolved imports. This worked and I was able to use the owl-api to insert new properties,individuals, etc (yeah).
When I tryed to start the pellet reasoner, I got the error message below at runtime. I think it is about the dependency-mess in my project again. I already know that the current way is the wrong one, but I was not able to find a better one. Please help me to get this dependency management in OSGi right.
Cheers,
Stephan
ERROR MESSAGE:
!ENTRY org.apache.felix.configadmin 4 0 2015-11-16 11:28:45.218
!MESSAGE [org.osgi.service.cm.ManagedService, id=28, bundle=7/initial@reference:file:..vdg.iCar.service]: Unexpected problem updating configuration vdg.iCar.service
!STACK 0
java.lang.Error: javax.xml.datatype.DatatypeConfigurationException: Provider for class javax.xml.datatype.DatatypeFactory cannot be found
at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:892)
at javax.xml.bind.DatatypeConverter.initConverter(DatatypeConverter.java:140)
at javax.xml.bind.DatatypeConverter.parseFloat(DatatypeConverter.java:243)
at com.clarkparsia.pellet.datatypes.types.floating.XSDFloat.getValue(XSDFloat.java:81)
at com.clarkparsia.pellet.datatypes.types.floating.XSDFloat.getCanonicalRepresentation(XSDFloat.java:58)
at com.clarkparsia.pellet.datatypes.DatatypeReasonerImpl.getCanonicalRepresentation(DatatypeReasonerImpl.java:365)
at org.mindswap.pellet.ABox.createLiteral(ABox.java:1746)
at org.mindswap.pellet.ABox.addLiteral(ABox.java:1725)
at org.mindswap.pellet.KnowledgeBase.addPropertyValue(KnowledgeBase.java:974)
at com.clarkparsia.pellet.owlapiv3.PelletVisitor.visit(PelletVisitor.java:1103)
at uk.ac.manchester.cs.owl.owlapi.OWLDataPropertyAssertionAxiomImpl.accept(OWLDataPropertyAssertionAxiomImpl.java:119)
at com.clarkparsia.pellet.owlapiv3.PelletVisitor.visit(PelletVisitor.java:699)
at uk.ac.manchester.cs.owl.owlapi.OWLOntologyImpl.accept(OWLOntologyImpl.java:1516)
at com.clarkparsia.pellet.owlapiv3.PelletReasoner.refresh(PelletReasoner.java:967)
at com.clarkparsia.pellet.owlapiv3.PelletReasoner.<init>(PelletReasoner.java:345)
at com.clarkparsia.pellet.owlapiv3.PelletReasoner.<init>(PelletReasoner.java:304)
at com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory.createReasoner(PelletReasonerFactory.java:71)
at de.dlr.vdg.ontology.osgi.impl.util.ReasonerUtil.getInferredOntology(ReasonerUtil.java:56)
at de.dlr.vdg.ontology.osgi.impl.util.ReasonerUtil.getInferredRelations(ReasonerUtil.java:304)
at de.dlr.vdg.ontology.osgi.impl.OntologyServiceImpl.startReasoning(OntologyServiceImpl.java:106)
at de.dlr.vdg.iCar.osgi.impl.iCarServiceImpl.start(iCarServiceImpl.java:67)
at de.dlr.vdg.iCar.osgi.Activator.updated(Activator.java:65)
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.updated(ManagedServiceTracker.java:189)
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.updateService(ManagedServiceTracker.java:152)
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.provideConfiguration(ManagedServiceTracker.java:85)
at org.apache.felix.cm.impl.ConfigurationManager$ManagedServiceUpdate.provide(ConfigurationManager.java:1444)
at org.apache.felix.cm.impl.ConfigurationManager$ManagedServiceUpdate.run(ConfigurationManager.java:1400)
at org.apache.felix.cm.impl.UpdateThread.run(UpdateThread.java:103)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.xml.datatype.DatatypeConfigurationException: Provider for class javax.xml.datatype.DatatypeFactory cannot be found
at javax.xml.datatype.FactoryFinder.findServiceProvider(FactoryFinder.java:304)
at javax.xml.datatype.FactoryFinder.find(FactoryFinder.java:268)
at javax.xml.datatype.DatatypeFactory.newInstance(DatatypeFactory.java:145)
at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:890)
... 28 more
Caused by: java.util.ServiceConfigurationError: javax.xml.datatype.DatatypeFactory: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not a subtype
at java.util.ServiceLoader.fail(ServiceLoader.java:239)
at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:376)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
at javax.xml.datatype.FactoryFinder$1.run(FactoryFinder.java:297)
at java.security.AccessController.doPrivileged(Native Method)
at javax.xml.datatype.FactoryFinder.findServiceProvider(FactoryFinder.java:292)
... 31 more

POM-File (important parts):
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>3.0.1</version>
            <extensions>true</extensions>
            <configuration>
                <manifestLocation>META-INF</manifestLocation>
                <instructions>
                    <Private-Package>${bundle.namespace}.*</Private-Package>
                    <Export-Package>${bundle.namespaceShared}</Export-Package>
                    <Bundle-SymbolicName>${bundle.symbolicName}</Bundle-SymbolicName>
                    <Bundle-Version>${project.version}</Bundle-Version>
                    <Bundle-Activator>${bundle.namespace}.Activator</Bundle-Activator>
                    <Bundle-RequiredExecutionEnvironment>JavaSE-1.8</Bundle-RequiredExecutionEnvironment>
                    <Embed-Dependency>*;scope=compile|runtime</Embed-Dependency>
                    <Embed-Transitive>true</Embed-Transitive>
                    <Import-Package>org.osgi.framework;version="[1.6,2)",org.osgi.se
                    rvice.cm;version="[1.4,2)",org.slf4j;version="[1.7,2)"</Import-Package>
                    <Bundle-ClassPath>.,{maven-dependencies}</Bundle-ClassPath>
                </instructions>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.osgi</groupId>
        <artifactId>org.osgi.core</artifactId>
        <version>4.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.osgi</groupId>
        <artifactId>org.osgi.compendium</artifactId>
        <version>4.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.owlapi</groupId>
        <artifactId>owlapi-distribution</artifactId>
        <version>3.5.2</version>
        <type>bundle</type>
    </dependency>
    <dependency>
        <groupId>com.github.ansell.pellet</groupId>
        <artifactId>pellet-owlapiv3</artifactId>
        <version>2.3.6-ansell</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>com.github.ansell.pellet</groupId>
        <artifactId>pellet-query</artifactId>
        <version>2.3.6-ansell</version>
        <type>jar</type>
    </dependency>
</dependencies>

Answer: After an additional day of research I came across this thread at oracle.
The pellet-api references the xerces and xml-api libs and due to the transient inclusion of dependencies, these libs were included in my bundle. But these libs are already present in the java runtime environment. Therefore I excluded them in the Embed-Dependency section and everything works.
<Embed-Dependency>*;scope=compile|runtime;inline=false;groupId=!xml-apis|xerces</Embed-Dependency>


How do you do a keyword search the Services.msc (mmc) window in Windows 7?

Question: When you want to run a service, you have very limited capabilities, in all current Windows versions, as far as I can tell.
I usually start Services by typing "services.msc" into the Start->Run box, on most versions of Windows, this works.  I know how to click the "Name" column in the MMC view of Windows Services. If you know what the first few characters of a service name is, you can usually sort by the name, and type the prefix to scroll the list down (find Windows Search for example).
This seems pretty weak to me, so I spent some time searching the interwebs for tools that do a better job of managing services.  Usually I have a keyword that I know "fooWare" might be the keyword, and I need to find the (usually badly named) service and start it and stop it. This is often WAY too hard.
The best I could do is "NET SERVICES" from the command line, and maybe add a grep in there, but that doesn't list every service, only a few of them.
And the MMC snap-in in Win7 now has an Export List button, exporting to csv text file feature which I have used from time to time, to export and then search.   I have thought of writing my own tool. I'm hoping a better "service manager" utility exists out there that sysadmins use.  I'd like a search box at the top right corner, kind of the same way that the Add-Remove-Programs dialog in Win7 and Vista has a search facility.
Does such a services utility exist out there?
Comment: I was wondering myself why this isn't a basic feature of services.msc. All the answers in this thread are helpful, but it would be more convenient if Microsoft implemented a simple search function in services.msc, and I really wonder why they don't :(
Answer: sc.exe at the command prompt OR the *-service set of PowerShell tools.
At the command line, sc can do a bit of service frobbing and you can combine that with outputting to a text file or messing about with find. But really, you should be using PowerShell these days so Get-Service (as well as Start-Service, Restart Service, Set-Service, etc.) combined with the myriad of PowerShell supplied formatting and parsing tools is your best bet.
Here's an example in PowerShell:
$t = '*mana*';Get-Service | Where {($_.Name -like "$t" -or $_.DisplayName -like "$t") -and $_.StartType -ne "Disabled"}

it filters in both name and display name and ignores disabled services.
You could put this into a script Find-Service.ps1 with a single parameter.
 param(
 [string]$term
 )

 $term = "*" + $term + "*"
 Get-Service | Where-Object {($_.Name -like "$term" -or $_.DisplayName -like "$term") -and $_.StartType -ne "Disabled"}

Comment: Builtin. Exactly what I was looking for.
Answer: xnet.exe available from a few locations (e.g. http://www.netware.se/en/downloads/) can list all the services running - you can then use something else to search the output.  Handlily xnet also reports the short name of a service, which can be used to manage it.
Answer: HKLM\System\CurrentControlSet\Services can give you a lot of info that you might want.  Tread with caution.
Answer: I also wonder the same :-(
Even in Windows 10 still nothing about the search function in the MMC view of Windows Services.
Anyway I found this utility Serviwin at the following link:
http://www.nirsoft.net/utils/serviwin.html
It shows all the info about the services and has the search function too.
I hope this helps and also hope that Microsoft implements the search box in the MMC view of Windows Services.
I found also this utility ServiceBouncer and it is very good indeed.
https://github.com/PaulStovell/ServiceBouncer


Crash on nested ForEach inside a LazyHStack

Question: I have two nested ForEachs inside a LazyHStack
LazyHStack {
    ForEach(items) { item in
        ForEach(item.urls, id: \.self) {
            Text($0.absoluteString)
        }
    }
}

This snippets compiles, but it immediately crashes with the following error

Fatal error: each layout item may only occur once: file SwiftUI, line 0

I read online that this might be due to ForEach not distinguishing correctly the elements of the collection, even if there're all identifiable. In my case, the items in the outer ForEach are all identifiable, while the inner ForEach is looping through an array of optional URL? objects. I tried to make an URL identifiable using its absolute string (that should be unique, I think), but it did not work.
extension URL: Identifiable {
    var id: String? { absoluteString }
}

I should add that the same code snippet works fine with a standard HStack. How can I solve this problem?
Comment: I don't count this as a problem, rather the app being smart on runtime... What do you want to achieve? Without some kind of stack in the middle of the two for each s, it make sense that the app crashes because it doesnt know how to layout the second for each well
Comment: You might have more than one of each `absoluteString`.
Comment: Try just `var id: UUID { UUID() }`
Comment: In addition to @MahdiBM 's comment, you also identified the `urls` with `\.self`, instead of `\.id` or leaving the `id` parameter empty.
Answer: It's up to you exactly how the UI is laid out, but this answer creates a horizontally-scrolling list of URLs which are vertically stacked as part of each item.
Working code:
ScrollView(.horizontal) {
    LazyHStack {
        ForEach(items) { item in
            VStack {
                ForEach(item.urls) {
                    Text($0.absoluteString)
                }
            }
        }
    }
}

Changes:

Wrapped LazyHStack in a ScrollView, so the items off screen can be scrolled to be seen.
Inserted a VStack in between the ForEachs, to determine the layout for each item.
Removed id: \.self from the second ForEach, because you created a custom id already for the URL. Either use id: \.id or don't include the id parameter in the ForEach.

Result:

Another possibility would be to set a unique ID for every element. Basically, if multiple URLs are the same (therefore have the same ID), then the LazyHStack has an issue that the IDs aren't all unique. Link to similar answer here. This is the alternate fix which wouldn't require the VStack in between:
Text($0.absoluteString)
    .id(item.id.uuidString + ($0.id ?? ""))

Edit to support optional URLs
Structure of the data (only difference here is URL was replaced with URLItem so we can hold an optional value):
struct Item: Identifiable {
    let id = UUID()
    let urls: [URLItem]
}

struct URLItem: Identifiable {
    let id = UUID()
    let url: URL?

    init(_ url: URL?) {
        self.url = url
    }
}

New example data:
let items: [Item] = [
    Item(urls: [
        URLItem(URL(string: "https://www.google.com")), URLItem(URL(string: "https://www.stackoverflow.com"))
    ]),
    Item(urls: [
        URLItem(URL(string: "https://www.stackoverflow.com")), URLItem(URL(string: ""))
    ])
]

This means that we can now have Identifiable optional URLs. The code should now look like this:
ForEach(item.urls) {
    if let url = $0.url {
        Text(url.absoluteString)
            .id($0.id)
    } else {
        Text("Bad URL")
            .id($0.id)
    }
}

You can handle your own cases now where $0.url is nil.
Comment: @Dree What would you like to do with the optional URLs? Would you like to not display them, display some alternate text such as "No URL", or another way? Can you instead guarantee that these URLs are not nil? For example, if you just don't want to display `nil` URLs, you could have `.compactMap { $0 }` after `item.urls` to remove `nil` values. If there is a problem with the `Text`'s ID, you can just do `.id(UUID())` instead.
Comment: Thank you for this answer. A nested stack is a good solution for my use case, but I still have problems because the `URL` array contains optional values. In this case the compiler returns this error: *Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'URL?' conform to 'Identifiable'*.
Comment: Well, inside the `ForEach` there isn't just a simple `Text` view, but instead another view which is in charge to handle the *nil* case for the URLs. Unfortunately I cannot just drop *nil* values using `compactMap`.
Comment: @Dree Code is now updated to support optional URLs.
Answer: It is working, you had some mistake in code:
for example you should use self in your extension
also you used 2 ForEach inside together for no reason, I would say bad coding, I am not going advice to use 2 ForEach inside together, it bring down the system and your app, use 1 ForEach! However here is your answer:

 struct ContentView: View {

    @State private var items: [[URL]] = [[URL(string: "www.apple.com")!, URL(string: "www.amazon.com")!, URL(string: "www.google.com")!], [URL(string: "www.Tesla.com")!]]

    var body: some View {

        LazyHStack {

            ForEach(items, id: \.self) { item in

                ForEach(item) { url in
                    Text(url.absoluteString)
                }

            }

        }

    }

}

extension URL: Identifiable {
    public var id: String { self.absoluteString }
}


Como salvar dados Console Application usando EntityFramework

Question: Fiz uma aplicação console usando o Entity Framework, só que estou tendo dificuldades para implementar os métodos da minha classe de repositório que herda de uma interface,fiz minhas classes de interface e minha classe concreta de repositório dessa maneira:
public interface IBaseRepositorio<TEntity> where TEntity : class
{
    //Métodos para obter todos contatos e obter por Id
    List<Contato> ObterTodosContatos();
    Contato ObterContatoId(int id);

    //Métodos de inserção,atualização,exclusão
    bool IncluirContato(Contato contato);
    bool AtualizarContato(Contato contato, String colunaAtual);
    bool DeletarContato(int id);
}

Minha InterfaceBase.
Aqui minha Interface que herda da Interface base:
 public interface IContatoRepositorio:IBaseRepositorio<Contato>
 {

 }

Mas aqui na minha classe concreta de repositório eu não consigo realizar as operações para rodar meu CRUD,segue a classe:
public class ContatoRepositorio : IContatoRepositorio<Contato>
{
    protected ProjectTestsContext Db = new ProjectTestsContext();

    public Contato ObterContatoId(int id)
    {
        return this.Db.Contatos.SqlQuery("Select * From Contato where Contatoid = @Contatoid", new { Id = id }).FirstOrDefault();
    }

    public List<Contato> ObterTodosContatos()
    {
        return this.Db.Contatos.SqlQuery("Select * From Contatos").ToList();
    }

    public bool IncluirContato(Contato contato)
    {
        try
        {
            string sql = "INSERT INTO Contato(Nome,Sobrenome,Empresa,Titulo) values(@Nome,@Sobrenome,@Empresa,@Titulo);SELECT CAST(SCOPE_IDENTITY() as int)";
            var returnId = Db.Contatos.SqlQuery(sql, contato).SingleOrDefault();
            contato.Contatoid = returnId.ToString();
        }
        catch (Exception)
        {

            return false;
        }
        return true;
    }

    public bool AtualizarContato(Contato contato, string colunaAtual)
    {
        string query = "Update Contato set " + colunaAtual + " =@" + colunaAtual + "Where Contatoid=@Contatoid";
        var count = Db.Execute(query, contato);
        return true;

    }

    public bool DeletarContato(int id)
    {
        // var affectdrowns = Db.Execute("Delete From Contato where Contatoid = @Contatoid", new { Contatoid = id });
        //   return affectdrowns > 0;
        return true;
    }

}

No método de atualizar contato, o trecho Db.Execute, não acha a ação que ele teria que fazer,achei somente o Entry,mas não consigo fazer a atualização.
Se alguém puder me ajudar como realizar da melhor maneira esses métodos,agradeço,até para eu dar sequência no raciocínio.
Obrigado
Comment: você esta criando seu DbSet ?no seu ProjectTestsContext
Answer: Se você tive criado seus DbSet, você pode criar um CRUD mais simples com o Entity Framework.
Veja como ficaria.
public class ContatoRepositorio : IContatoRepositorio<Contato>
{
    protected ProjectTestsContext Db = new ProjectTestsContext();

    public Contato ObterContatoId(int id)
    {
        return this.Db.Contatos.FirstOrDefault(x => x.Id = id );
    }

    public List<Contato> ObterTodosContatos()
    {
        return this.Db.Contatos.ToList();
    }

    public bool IncluirContato(Contato contato)
    {
        try
        {
            Db.Contato.Add(contato);
            Db.SaveChanges();
        }
        catch (Exception)
        {

            return false;
        }
        return true;
    }

    public bool AtualizarContato(Contato contato, string colunaAtual)
    {
        Db.Entry(contato).State = EntityState.Modified;
        Db.SaveChanges();
        return true;
    }

    public bool DeletarContato(int id)
    {
        var obj = ObterContatoId(id);
        Db.Categorias.Remove(obj);
        Db.SaveChanges();
        return true;
    }
}

Veja um exemplo funcional aqui.


MANOVA application

Question: Need to check whether it is mandatory to have at least one continuous DVs in MANOVA, also does sample size of 2 groups matters much, i am planning to check whether recruits from campus or off-campus have significant difference in 4 selected DVs. sample size for campus is 23K & off campus is 14K?
Please advise accordingly, can any other statistical technique be applied here say, MLR?
Answer:
Is it mandatory to have at least one continuous DVs in MANOVA?

Yes, Manova is a multivariate technique. You need to have more than one continuous response variables (and no categorical response).

Does sample size of 2 groups matters much?

You should have an adequate sample size. Although the larger your sample size, the better; for MANOVA, you need to have more cases in each group than the number of dependent variables you are analysing.
In your case, you've large sample size, so it's not an issue.

MANOVA application


Tinker giving exception in Laravel 5.8

Question:

Exception: Writing to /home/vishu/.config/psysh is not allowed.
at /usr/share/nginx/html/example/vendor/psy/psysh/src/ConfigPaths.php:228
 @\mkdir($dir, 0700, true);
         }

         if (!\is_dir($dir) || !\is_writable($dir)) {
           \trigger_error(\sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE);

             return false;
         }

Comment: Did you check file permission? And you should try to give more detail info about question, not just paste code/log/images, see [Help Center > Asking](https://stackoverflow.com/help/how-to-ask).
Comment: sudo chmod -R 777 storage
Comment: Solution suggested by bernhardh on github is modification of the location by setting the following to .env                                                      XDG_CONFIG_HOME=/path/to/new/location             but I am not getting setting of the path thing in Vendor/../Xdg.php
Comment: You're only checking if dir is writable and if it's a dir but not if you have permissions to modify it.
Comment: I have permission to write it.                                                                                -rw-rw-r-- 1 vishu www-data /usr/share/nginx/html/example/vendor/psy/psysh/src/ConfigPaths.php
Answer: If the project is in development state, you can change the whole storage directory permission to 777:
sudo chmod -R 777 storage/

Comment: Giving  permission 777  is a bad idea even though it is in development stage.
Comment: I have changed permissions for Log  to 775.Now Error is  Writing to /home/vishu/.config/psysh is not allowed.

  at /usr/share/nginx/html/example/vendor/psy/psysh/src/ConfigPaths.php:228
Comment: this did not work for me.

Tinker giving exception in Laravel 5.8


How can I display all levels in Simple hierarchical select

Question: I created select hierarchy ( taxonomy with 3 level), but in default it shows only one level , how can I display all 3 level in default page? : -Any- + -Any- + -Any-
I do not want it to automatically generate other fields.I want to display by default all the select input
Comment: I am looking for the same Question's answer.
Answer: I had the same problem and found the answer was to create a custom module and not use SHS. Here's how I did it with Drupal 8 ... and some info on how done with D7: https://drupal.stackexchange.com/a/269296/18513
Comment: This is another alternative (still in sandbox) https://github.com/bmcclure/drupal-views_selective_filters
Answer: In Drupal 8 you will need to use the "business rules" module to add hierarchical select...


How can I create a redux selector for a state that does not exist yet

Question: I'm finding my way around the Redux echosystem, and I came across the following sutuation: Suppose I have a React component which should be connected to a redux state part using a selector, but this part does not exist yet (undefined). So, when running it I get a "get on undefined" error. Is it possible to somehow define and connect the selector to the component, even though the state part does not exist yet?
I'm using reselect for creating the selector, this is a workaround I've used to avoid throwing the error:
import { createSelector } from 'reselect';

const selectLogin = (state) => state

const loginDataSelector = () => createSelector(
  selectLogin,
  (authState) => authState.get("auth")?
   authState.get("auth").get('loginData'):undefined
);

export {
  loginDataSelector
};

By this way, the selectLogin selector seems to monitor the entire state tree. Is there a better way to do this, or is there a best practise for selectors with an undefined (=not set yet) state part?
Comment: what if you set that piece of state to some default value initially?
Comment: This means that I should use a reducer for this state part, right? This seems a little too much to me, since I only need to read the state part, and not write it (from this component). Also, there is a reducer for this state part in another component, is has just not been called yet.

A related question that arises is if there is a way to connect an already existing component to a state part AFTER it has been initialized/rendered, etc. This would avoid the "non existing state" problem.
Answer: You can use ES6 default values to work around this issue.
Also not the use of getIn that allows you to safely access deep properties
import { createSelector } from 'reselect';
import { Map } from 'immutable';

const selectLogin = (state) => state

const loginDataSelector = createSelector(
  selectLogin,
  (authState = Map()) => authState.getIn(["auth", "loginData"])
);


Compute the sum $\sum_{i=0}^n 5^{i+1}-5^i$

Question: Compute the sum:
$$\sum_{i=0}^n 5^{i+1}-5^i$$
with the hint, "start by writing out (and expanding) the sum."
So I did and got
$$4 + 20 + 100...$$
with the appearance of going to infinity. Is infinity a valid answer?
Comment: Factor out $5^i$; what do you get?
Comment: Actually even better: follow the hint: Write it out without doing the subtractions.
Comment: Infinity is not a valid answer, because there is an upper limit to the sum, which is therefore finite.
Comment: WOW. SO IT WOULD BE -1. WOW. QUESTION MARK.
Comment: No, it is not $-1$ because the $5^{n+1}$ doesn't cancel.
Answer: The person who wrote the hint didn't quite get her meaning across. Expand it without simplifying:
$$
\sum_{i=0}^n 5^{i+1}-5^i = (5^1-5^0) + (5^2-5^1) + (5^3-5^2) + \cdots + (5^{n+1}-5^n).
$$
We see immediately that almost all of the terms cancel out. The sum is
$5^{n+1}-1$. This is an example of a telescoping sum.
Answer: According to the hint $$\begin{align*}\sum_{i=0}^n  (5^{i+1}-5^i)&=(5^1-5^0)+(5^2-5^1)+(5^3-5^2)+\ldots+(5^{n}-5^{n-1})+(5^{n+1}-5^{n})=\\&=-5^0+(5^1-5^1)+(5^2-5^2)+\ldots+(5^{n-1}-5^{n-1})+(5^{n}-5^{n})+5^{n+1}=\\\\&=5^{n+1}-5^0=5^{n+1}-1 \end{align*}$$


VB6 - IIF (ISNULL(rs),"TRUE",Replace())

Question: why i cannot use :
<code>     rep8_bc = IIf(IsNull(rs(8)), "null", Replace(rs(8), "'", "''"))
</code>
it say " Invalid use of Null"
but if i remove replace, it's work. And then get error because record have an apostrophe character, so i change the code into this :
<code> rep8_bc = "null"
 If IsNull(rs(8)) = False Then rep8_bc = Replace(rs(8), "'", "''")
</code>
or this :
<code> If IsNull(rs(8)) = False Then
     rep8_bc = Replace(rs(8), "'", "''")
 else
     rep8_bc = "null"
 end if
</code>
Comment: Use .Net instead ;) I can not compile VB6 on my system, as I do not have the tools installed. I am not familiar with the inline if-statement of VB6. But the syntax looks ok to me
Comment: So you're trying to achieve what?
Comment: alright.. this is so old.. :P
just asking, maybe someone know the answer hehehe... xD
Answer: Mostly likely compiler doesn't short circuit within IIF() statement. Compiler takes it as a whole statment (both values) before returning one. That's where you get the error. So breaking into pieces of proper conditional statemetns would be the key here. So you have any achieved that with your answer.
To further add, IIF() is much slower in execution than the IF-ELSE statments.
Comment: In your case, single line IF and multi-line IF both stay at relatively same speed. Unless you have some other operators(arithmatic etc) in one answer and not in the other. Then the IF statement with additional math operator seem to take more time/resources. [Check this post out](http://www.aivosto.com/vbtips/not-optimize.html)
Comment: Correct, `IIf` does not short-circuit (in [VB6](http://msdn.microsoft.com/en-us/library/aa445024(v=vs.60).aspx) or VB.Net).
Comment: in my answer have 2 way for running, which one is better? "1. insert null then check if", or "if , else?" .. first for save my line... xD

VB6 - IIF (ISNULL(rs),"TRUE",Replace())


Method to trick ASP.NET to process HTTP PUT as POST?

Question: I have a web cam that can send an image via HTTP PUT to a web server. I'd like to process this in ASP.NET MVC, but it doesn't natively support PUT. Is there any way to trick it into treating the request as a POST? I'm looking to get the Request.Form and Request.Files properties populated.
Comment: The top answer by Arjan does not actually address the issue I'm asking about. I'm trying to get ASP.NET to populate the File and Form properties, which it does not do by default for PUTs.
Answer: ASP.NET MVC supports PUT requests by putting the HttpPut attribute on the action.
(In earlier versions you might need to use the AcceptVerbs attribute...)
Comment: It supports PUT for routing actions, but does not populate the Request objects like it does for POST requests.
Answer: Are you sure it doesn't support HTTP Put? I see that it is listed within the HttpVerbs Enumeration: http://msdn.microsoft.com/en-us/library/system.web.mvc.httpverbs.aspx
All you should have to do is ensure that you have decorated your action appropriately.
Answer: This does not appear to be possible. I've just used the Request.InputStream to read in a bitmap directly.


Axis Rotation to determine new points

Question: I am looking at this answer .
https://math.stackexchange.com/a/62248/474907, but the formula
<code>c = cos(a); // compute trig. functions only once
s = sin(a);
xr = xt * c - yt * s;
yr = xt * s + yt * c;
</code>
differs from the wikipedia entry. So, I am a little confused, which one is correct.
$R_{z}(\theta )={\begin{bmatrix}\cos \theta &\sin \theta &0\\[3pt]-\sin \theta &\cos \theta &0\\[3pt]0&0&1\\\end{bmatrix}}$
https://en.wikipedia.org/wiki/Rotation_of_axes#Generalization_to_several_dimensions
EDIT:
AFter answer from @caverac
If not changing the axis
$\vec{new} = R_{active} * \vec{old}$
$R_{z}(active)={\begin{bmatrix}\cos \theta &-\sin \theta &0\\[3pt]\sin \theta &\cos \theta &0\\[3pt]0&0&1\\\end{bmatrix}}$
If changing the axis
$\vec{new} = R_{passive} * \vec{old}$
and
$R_{z}(passive)={\begin{bmatrix}\cos \theta &\sin \theta &0\\[3pt]-\sin \theta &\cos \theta &0\\[3pt]0&0&1\\\end{bmatrix}}$
The angle is just negated ( clockwise or counter-clockwise ). Is my understanding correct?
Answer: If you're referring to the sign difference, this seems to be the key sentence in the SE answer:

In 2D graphic libraries the x-axis goes to the right and the y-axis goes down

The wikipedia entry is based on the y-axis going up. The formula is slightly different depending on whether you consider the angle to be clockwise (as in the SE answer) or counter-clockwise (as in the wikipedia page).
Answer: That's the difference between an active and a passive transformation, in an active vectors are rotated, while in the passive the basis vectors are rotated
Comment: thanks, have a look at my edit please
Comment: @infoclogged Just need to fix the order: passive in place of active and *vice versa*
Comment: done....................

Axis Rotation to determine new points


Sample space for discrete random variables

Question: Can discrete random variables be defined in a continuous sample space?

Continuous sample space is a non countable sample space!
Comment: Could you tell us what you mean by "continuous sample space"?  "Continuous" is a term that doesn't ordinarily apply to sample spaces.
Answer: For simplicity, let us assume that by "continuous sample space" you mean the real line $\mathbb R$.

The corresponding probability space is $(\Omega, \mathcal F, P)$ where $\mathcal F$ is the $\sigma$-algebra of events defined on $\Omega$ and $P$ is the probability measure that specifies the probability of each event in the $\sigma$-algebra. For the sample space $\mathbb R$, one can take the $\sigma$-algebra to be generated the intervals $(-\infty, x]$ and use any continuous nondecreasing function $F$ with limiting values $0$ as $x\to -\infty$ and value $1$ as $x \to \infty$ to define the probability of $(-\infty, x]$ to be $F(x)$.

If the highlighted paragraph above is gobbledygook to you, just ignore it, and concentrate on what follows next.
It is straightforward to define a discrete random variable on this sample space $\Omega = \mathbb R$. For example, one could define a discrete random variable $X$ as one that maps the outcome $\omega \in \Omega$ (this outcome is a just an ordinary real number) to $1$ if $\omega \leq 0$ and to $0$ if $\omega > 0$.  $X$ is then just a Bernoulli random variable with parameter $p= P(\omega \leq 0)$.

The gobbledygook in the highlighted paragraph above just says that it makes sense to talk about the probability that the outcome $\omega$ is no larger than $0$, or more generally, the probability that the outcome
  $\omega$ is no larger than a specified real number $x$, and that this probability $P(\omega \leq x)$ is just the value of the function $F$ at $x$.  In whuber's answer, he has chosen $F$ to be $\Phi$, the cumulative probability distribution function (CDF) of the standard normal random variable.
Answer: Part of what makes a set a "sample space" is that we designate certain subsets and call them "events."  Not every subset of a sample space can have a probability: only events have probabilities.  This restriction is needed to avoid paradoxes when extending the concept of probability from a finite sample space to uncountably infinite sample spaces.
Unless the sample space is trivial--which means it and the empty set are the only events--there will be some event $\mathcal E$ that is neither empty nor the whole space.  The probability axioms assure us that the complement of $\mathcal E$--let's call it $\mathcal F$--is also an event.

Define the random variable $X$ to have the value $1$ for all elements of $\mathcal E$ and otherwise have the value $0.$

(This is known as the indicator function of $\mathcal E.$)  $X$ is discrete because it takes on only two values, $0$ and $1.$  Indeed, the probability that $X=1$ is the probability of $\mathcal E$ and the probability that $X=0$ is the remaining probability (the two probabilities must sum to $1.$)

As an example, consider the sample space of the real numbers with its usual events (determined by the half intervals $(-\infty, a]$) and endow it with a standard Normal probability, so that for all numbers $a,$
$$\Pr((-\infty, a]) = \Phi(a) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^a e^{-x^2/2}\,\mathrm{d}x.\tag{1}$$
Pick an event, such as $\mathcal E = (-\infty,0].$  In the foregoing construction, $X(\omega)=1$ for all non-positive numbers $\omega$ and otherwise $X(\omega)=0$ for positive numbers.  $X$ is a random variable.  It has a Bernoulli$(1/2)$ distribution (it's a "fair coin") because the chance that $X=1,$ according to formula $(1),$ is $\Phi(0)=1/2.$

Every discrete distribution corresponds to some random variable that is constructed with a generalization of this approach.
When you can find a finite or countable number of nonoverlapping events $\mathcal{E}_1, \mathcal{E}_2, \ldots$ whose probabilities sum to $1$ (which is always possible in the preceding example of the real numbers with a standard Normal probability function), you may assign an arbitrary value $x_1$ to all the elements of $\mathcal{E}_1,$ another (or even the same) value $x_2$ to all the elements of $\mathcal{E}_2,$ and so on.  This almost defines a random variable $X.$  There may be a few elements not contained in any of the $\mathcal{E}_i.$  Let the set of all such elements be called $\mathcal{E}_0.$  The axioms of probability imply $\mathcal{E}_0$ has zero probability. You can assign any values you like to the elements of $\mathcal{E}_0.$  This effectively defines a whole class of random variables that equal $X$ "almost everywhere."  They all have the same (discrete) probability distribution.


Proposition 1.33 in Hatcher's Book

Question: Recall the following proposition in Hatcher's Algebraic Topology:

Proposition 1.31 The map $p_* : \pi_1(\widetilde{X},\widetilde{x}_0) \to \pi_1(X,x_0)$ induced by a covering space $p : (\widetilde{X}, \widetilde{x}_0) \to (X,x_0)$ is injective. The image subgroup $p_*(\pi_1(\widetilde{X},\widetilde{x}_0))$ in $\pi_1(X,x_0)$ consists of the homotopy classes of loops in $X$ based at $x_0$ whose lifts to $\widetilde{X}$ starting at $\widetilde{x}_0$ are loops.

I am currently working through the proof of following proposition:

Proposition 1.33 Suppose a given covering space $p : (\widetilde{X},\widetilde{x}_0) \to (X,x_0)$ and a map $f : (Y,y_0) \to (X,x_0)$ with $Y$ path-connected and locally path-connected. Then a lift $\widetilde{f} : (Y,y_0) \to (\widetilde{X},\widetilde{x}_0)$ of $f$ exists iff $f_*(\pi_1(Y,y_0)) \subseteq p_*(\pi_1(\widetilde{X},\widetilde{x}_0))$

Here is the proof Hatcher gives in his book:

In the first paragraph, why does Hatcher say that $h_0$ is path homotopic to a loop at $x_0$ which lifts to a loop in $\widetilde{X}$ at $\widetilde{x}_0$? This seems unnecessary. If $[h_0] \in p_*(\pi_1(\widetilde{X},\widetilde{x}_0)$, then $h_0$ itself lifts to a loop in $\widetilde{X}$ at $\widetilde{x}_0$. It seems unnecessary to talk of a homotopy between $h_0$ and $h_1$.
My next two questions concern the second paragraph. I'm having trouble following the proof that $\widetilde{f}$ is continuous. It appears that he does this by proving continuity at an arbitrary point $y \in Y$. Usually these sorts of proof start out as follows:

Let $y \in Y$ be arbitrary, and let $\mathcal{O}_1$ be an open set about $\widetilde{f}(y)$. We need to find an open set $\mathcal{O}_2$ about $y$ such that $\widetilde{f}(\mathcal{O}_2) \subseteq \mathcal{O}_1$

As you may see, he shows that we can find an open set $V$ about $y$ such that $\widetilde{f}(V) \subseteq \widetilde{U}$. But $\widetilde{U}$ was not arbitrarily selected at the beginning. How do we know we can fit it in an arbitrarily chosen neighborhood about $y$?
My next question is, why is $\widetilde{(f \gamma )} \cdot \widetilde{(f \eta)}$ a lift of $(f \gamma ) \cdot(f \eta)$? Is he implicitly using the following: if $\alpha$ is a path in $X$ from $x_0$ to $x_1$, $\beta$ a path from $x_1$ to $x_2$, then $\widetilde{\alpha \cdot \beta} = \widetilde{\alpha} \cdot \widetilde{\beta}$? I tried proving this, but I don't think it is true since the end point of $\widetilde{\alpha}$ may be different from the starting point of $\widetilde{\beta}$.
Answer: For the first question : $[h_0]=p_*[\gamma]$ doesn't tell you that there is $\delta$ such that $h_0 = p\circ \delta$, it tells you that $h_0$ and $p\circ \gamma$ are homotopic. A priori there is no reason to believe that $h_0$ should itself be the projection of a loop.
The sentence that follows explains why a posteriori it is actually the case that $h_0$, too, is the projection of a loop.
For the second question, $\tilde{U}$ is not arbitrary but it is picked among a basis of neighbourhoods, so it is enough. That it is enough is a point-set topology basic fact, that we may for instance state as

Let $f:X\to Y$ be a function between two topological spaces; let $x\in X$ and let $\mathcal{V}$ be a basis of neighbourhoods of $f(x)$. Then, if for each $U\in \mathcal{V}$ there is $V\subset X$ a neighbourhood of $x$ such that $f(V)\subset U$, $f$ is continuous at $x$.

For your last question, Hatcher is not being very precise here, in the sense that $\widetilde{\gamma}$ in this last section is not the same as the one at the beginning which specifically denoted a lift with starting point $\widetilde{x_0}$; here it denotes some lift, with the starting point "obvious from context", as is often the case.
In particular, a claim that is true is that if $\widetilde{\alpha},\widetilde{\beta}$ are lifts of $\alpha,\beta$ that can be put after another, then so can $\alpha, \beta$, and $\widetilde{\alpha}\widetilde\beta$ is a lift of $\alpha\beta$. It is then your job here to figure out which specific lifts are meant here, but that shouldn't be a problem.
Comment: But $[h_0] \in p_*(\pi_1(\widetilde{X},\widetilde{x}_0))$, so why doesn't proposition 1.31 tell us directly that $h_0$ lifts to a loop?
Comment: Proposition 1.31 tells us that $[h_0]$ is the class of *a* loop that lifts to a loop, the sentence that comes afterwards tells you why it follows that all elements of that class actually lift to a loop
Comment: Why $\tilde U$  a neighborhood base for $f(y)$?

Proposition 1.33 in Hatcher's Book


Is it possible to set widget options dynamically in R Shiny?

Question: As a minimal working example,
# An app with a datatable whose pagination option we can toggle with a button
library(shiny)
runApp(list(
    ui = basicPage(
        actionButton("button", label = "Toggle paginate"),
        dataTableOutput("table")
    ),
    server = function(input, output) {
        output$table <- renderDataTable(
            data.frame(x = 1:100, y = input$button),   # Some dummy data
            options = list(
                bPaginate = as.logical(input$button %% 2)
            )
        )
    }
))

The corresponding browser output:

I should be able to dynamically switch the option bPaginate on and off just by clicking the "Toggle paginate" button.
However, this does not work - the table is never paginated. What's going wrong?
Answer: I also struggled with the data table widget. Neither renderDataTable nor DT::renderDataTable appear to recognize and re-render output when options are given as a simple list.
Yihui's answer works for the base Shiny renderDataTable, but I would never guess this as a solution and I can't see why a function would work and a plain list wouldn't. I assume it is some internal implementation issue with the underlying Javascript, but this seems like an implementation detail that should not leak out into the R api.
I can't, however, make Yihui's answer work for the DT version of the DataTable package. Perhaps this is just my error, but I eventually figured another way to get user input to affect table options without using a function for options. Doing so requires one extra (reactive) variable layer and uses the datatable() function. (Note that the latest DataTable version this is all based on uses different option names, and I'm using a slightly different ui than the question above. None of that should change the basic problem or its solution.)
# An app with a datatable whose pagination option we can toggle with a button
library(shiny)
runApp(list(
   ui = fluidPage(
      sidebarLayout(
         sidebarPanel(
            checkboxInput("paging", "Paginate table")
         ),
         mainPanel(
            DT::dataTableOutput("table")
         )
      )
   ),
   server = function(input, output) {
      # Create a new table when input$paging changes
      makeTable <- reactive({
         DT::datatable(
            { data.frame(x= 1:100, y = input$paging)},   # Some dummy data
            options= list(
               paging = input$paging
            )
         )
      })
      # Render the datatable returned by the reactive function
      output$table <- DT::renderDataTable( makeTable() )
   }
))

Answer: You can use a function to return the DataTable options, e.g.
options = function() {
  list(
    bPaginate = as.logical(input$button %% 2)
  )
}

Note this requires shiny >= 0.9.0.
Answer: Thanks Stuart. Your example works right off the bat.
Here is your code for a flexdashboard:
---
title: "Datatable Pagination"
output: flexdashboard::flex_dashboard
runtime: shiny
---

Inputs {.sidebar}
-------------------------------------

```{r}
# shiny inputs defined here
checkboxInput("paging", "Paginate table")
```

## Column

### Data Table

```{r}

makeTable <- reactive({
    DT::datatable(
        { data.frame(x= 1:100, y = input$paging)},   # Some dummy data
        options= list(
            paging = input$paging
        )
    )
})
# Render the datatable returned by the reactive function
output$table <- DT::renderDataTable( makeTable() )

DT::dataTableOutput("table")

```


Google Fit Custom Data Type

Question: I am creating one Google Fit compatible App. My objective is to store Google Fit data using HistoryApi, and provide kind of Back Up- Restore functionality to user. If user buys new Android devices then he/she should be able to BackUp(sync) old data using his/her account.
I need to use Custom Data Type, as Public Data Types doesn't meet my requirements.
Everything works perfect, I am able to insert data and read data using History Api.
But When I try to read data from Another Android device using same Google Account then data is not available to read there.
My problem seems similar to this Custom DataTypes not synching between devices
This statement from Google Fit Document is not clear to me.

Custom data types are not available to use in other apps. Only the app
  that creates a custom fitness data type can use it

source : CustomDataType
Q-1) What does it really means ? If I have an app GoogleFitDemo installed on multiple Android devices, then is it possible to sync data between this same app between multiple Android devices ?
Q-2)Is it improper way to store and backup data using Google fit ?
Update:
Finally, I found that Custom Data Type can also be synced normally, same as other Public Data Types. I had the sync issue as mentioned by @Ifor. Sync functionality is still buggy. In some scenarios sync stops working, and sometimes synced data is inconsistent across multiple devices.
Answer: 1). My understanding is that same app same account but different devices it should work.  Having said that sync is notoriously slow (hours days...) and has been buggy so it may be hard to tell if you have it right or not.
2) There are better backup methods...  But if the data fits in with the rest of the stuff Google Fit is about and is not too big then it's probably ok.
Comment: Unfortunately, I am not able to sync data created using custom data types. But, document doesn't clearly mention that you can not sync custom data type across multiple devices.
Comment: Best to ask on the G+ Google Fit developers community the fit developers do look at issues reported there.  https://plus.google.com/u/0/communities/103314459667402704958
Comment: Thank you for your guidance.
Comment: You were right. It was sync issue. I have updated question with clarification.

Google Fit Custom Data Type


Maximo: Use script to update work order when a related table is updated

Question: I have an automation script in Maximo 220.127.116.11 that updates custom fields in the WORKORDER table.
I want to execute the automation script when the LatitudeY and LongitudeX fields (in the WOSERVICEADDRESS table) are edited by users.
What kind of launch point do I need to do this?

Edit:
For anyone who's learning automation scripting in Maximo, I strongly recommend Bruno Portaluri's Automation Scripts Quick Reference PDF. It doesn't have information about launch points, but it's still an incredibly valuable resource.
I wish I'd known about it when I was learning automation scripting...it would have made my life so much easier.
Answer: You can create an attribute action launch point on the latitudeY field and another on the longitudeX field. These will trigger whenever each field is modified, so it will fire once when the latitudeY field was changed, again if the longitudeX field is changed, again if the longitudeX field is changed again, and so on. This is also all before the data is saved, so the user may choose to cancel their changes, but the scripts will still have fired.
You could also make an "on save" object launch point for WOSERVICEADDRESS (if that's what is actually being updated via the map). This will run any time data in the object is saved, so you would have to do the extra checks of seeing if either of those fields have changed and then do your logic, but at least it would run once and only if the user commits to their changes.
Comment: There is an "isModified()" method on the MboValue field class (which you can get from the Mbo record class with "getMboValue"), but that will just tell you that someone changed the value in the field at least once. If they changed it from X to Y and then back from Y to X, Maximo will still tell you it was modified.
https://developer.ibm.com/static/site-id/155/maximodev/7609/maximocore/businessobjects/psdi/mbo/Mbo.html
Comment: From that MboValueData class, there is also a "getInitialValue" method that you could compare against instead, to make sure it really is different. https://developer.ibm.com/static/site-id/155/maximodev/7609/maximocore/businessobjects/psdi/mbo/MboValue.html
    I think if you bind the field the automation script settings that you get an implicit "_initial" variable that also gives you that initial value to compare against. Beware that in both cases that gives you MaxType class back, not a String. So you have to worry about nulls and you have to get the String from the class.
Comment: @User1973 No, it will return whether it was modified since instanciation (loaded in memory). Regarding your solution, I'd lean towards the SAVE event.
Comment: Then, Maximo asks you at which point _during_ those selected saves do you want the script to trigger. During/before the "action" phase and when the data is still changeable (before the save method)? After the "action" phase and when the data should be static/unchanging (after save)? Or after the data has been committed to the database?
Comment: Thanks Dex. Regarding this point: *"...you would have to do the extra checks of seeing if either of those fields have changed and then do your logic..."* --- Do you know how I could perform this check?
Comment: So the `isModified()` method is really an indication of whether the record has *ever* been modified since it's original creation (or not)?
Comment: @JPTremblay In a dead-simple test, I'm trying to use an automation script to update a WORKORDER field after the WO is created or updated. I can get it to work where `Events = Save; Save = Add`. But none of the other combinations of `Save` are working for me. For example, I can't get `Save = Add, Update; AfterSave` to work. Any tips? https://i.stack.imgur.com/OUygB.png
Comment: If you want your script to be triggered on `Add` and `Update`, you need to check both boxes.
Comment: The "before save" part on the right is independent of the add and update on the left. You first select which kinds of save you want this to trigger on. Only when a *new* record is saved? Only when an existing record update is saved? When either save happens? Select all that are appropriate.
Answer: Related:
Populates WORKORDER.WOSAX and WORKORDER.WOSAY (custom fields) from the values in WOSERVICEADDRESS.LONGITUDEX and WOSERVICEADDRESS.LATITUDEY.
woMbo=mbo.getOwner()
longitudex=mbo.getString('longitudex')
latitudey=mbo.getString('latitudey')
if woMbo is not None:
  wosax=woMbo.getString('WOSAX');
  wosay=woMbo.getString('WOSAY');
  if longitudex!=wosax:
      woMbo.setValue('WOSAX',longitudex)
  if latitudey!=wosay:
      woMbo.setValue('WOSAY',latitudey)

The launch points are Attribute Launch Points, not Object Launch Points.


mustache Handlebars.js partial get all objects in list

Question: I have a list of objects (this list structure needs to stay the same)
I want to pass to my html partial all the data for example title intro and the rest from ranges
My partial within my html is
{{> range-list range-list-page.ranges}}

I need to get all data from the object list (ranges), this works if I remove bigbob2 and bigbob3 however I need them to call in bigbob2 bigbob3
 later in a different partial.
when I change my partial to be
{{> range-list range-list-page.ranges.bigbob2}}
I get the data for bigbob2as expected, however I need to get the data from bigbob2 and bigbob3 how would I do this?
so all I need is to call bigbob2 and bigbob3. for example.
{{> range-list range-list-page.ranges.bigbob2,bigbob3}}

my json array
"ranges": {
  "bigbob": [
    {
      "title": "brain patter",
      "intro": "fghtfhthd ",
      "slider": {
        "slides": [
          "//train-pool.jpg"

        ],
        "thumbnails": [
          "//train-blue.jpg"
        ]
      },
      "price": "xxx",
      "promo": [
        "xxx"
      ],
      "colors": [
        {
          "color": "#FFFFFF",
          "label": "Ice",
          "bordered": true,
          "href": "/jjhj.html"
        },
        {
          "color": "#A1ABAA",
          "label": "Azure",
          "href": "/kkkkjjj.html"
        },
        {
          "color": "#726B65",
          "label": "Graphite",
          "href": "/ppp.html"
        }
      ]
    }
  ],
  "bigbob2": [
    {
      "title": "hill",
      "intro": "ojhuohiuphipj.",
      "slider": {
        "slides": [
          "//image/two.jpg"
        ],
        "thumbnails": [
          "//my-image-bee.jpg"
        ]
      },
      "price": "xxx",
      "promo": [
        ""
      ],
      "colors": [

        {
          "color": "#f4eef0",
          "label": "grey",
          "href": "/gg.html"
        },
        {
          "color": "#d8d7d5",
          "label": "blue",
          "href": "/tt.html"
        }
      ]
    }
  ]

},

Answer: You can use the withBefore handlebar helper.
{{#withBefore range-list-page.ranges 3}}
  {{>range-list this}}
{{/withBefore}}

Also if you want to use the partial with every pair from the array, you can use the withGroup handlebar helper. Like this:
{{#withGroup range-list-page.ranges 2}}
  {{#each this}}
    {{>range-list .}}
  {{each}}
{{/withGroup}}


Calculating an integral

Question:
Let $r>0$. Show that $$\frac{1}{\sqrt{4\pi t}}\int\limits^{-r}_{-\infty} \exp \left(-\frac{x^{2}}{4t}\right) dx=\frac{1}{2}\left[1-\text{erf}\left(\frac{r}{\sqrt{4t}}\right)\right]$$
  where $\text{erf}$ is the  error function

I calculated this using software, but I can't prove .... somebody can help me please.
Comment: You may want to google the keyword *error function*.
Comment: A [related problem](http://math.stackexchange.com/questions/503643/is-there-only-numerical-method-to-find-this-defenite-integral-or-any-other-way).
Comment: @sos440 What error? I dont understand ...
Comment: This function is related to what is known as the error function. http://en.wikipedia.org/wiki/Error_function
Comment: @Wmmoreno: just google the words as sos440 said.
Comment: @user71352 hann ... ok tnks XD
Comment: You're welcome.
Answer: Since the integrand is even, we have
$$\begin{align}
\frac{1}{\sqrt{4\pi t}}\int\limits^{-r}_{-\infty} \exp \left(-\frac{x^{2}}{4t}\right) dx
&= \frac{1}{\sqrt{4\pi t}}\int\limits^{\infty}_{r} \exp \left(-\frac{x^{2}}{4t}\right) dx.
\end{align}$$
Then, making the $u$-substitution $u=x/(2\sqrt{t})$, we get
$$\begin{align}
\frac{1}{\sqrt{4\pi t}}\int\limits^{-r}_{-\infty} \exp \left(-\frac{x^{2}}{4t}\right) dx
&= \frac{1}{\sqrt{\pi}}\int\limits^{\infty}_{r/(2\sqrt{t})} \exp \left(-u^2\right) du\\
&= \frac{1}{2}\left(\frac{2}{\sqrt{\pi}}\int\limits_0^\infty\exp \left(-u^2\right) du -  \operatorname{erf}\left(\frac{r}{2\sqrt{t}}\right) \right)\\
&= \frac{1}{2}\left[1-\operatorname{erf}\left(\frac{r}{2\sqrt{t}}\right)\right].
\end{align}$$

Calculating an integral


slur or tie to no note in Lillypond

Question: I am trying to have a slured note to 'nothing' in a musical example in my paper, like this:

Any tie (~) or slur () I put in Lilypond (actually Frescobaldi), nothing happens.
This is the code I am using:
\version "2.18.2"
  global = {
  \key bes \major
  \numericTimeSignature
  \time 6/8
}

violin = \relative c'' {
  \global
  % Music follows here.
  c ees f~
}

\score {
  \new Staff \violin
  \layout { }
}

Any help is appreciated!
Comment: That apart - 6/8 doesn't normally group notes like that.
Answer: Use \laissezVibrer instead of ~.  Cf the notation manual.
Answer: You can tie the note to a hidden note.
{ \time 6/8 \relative c'' {
  c4 e f~ | \once \hideNotes f c b
} }

Comment: You can hide the barline if you want. `c4 e f~ \bar "" \hideNotes f`

slur or tie to no note in Lillypond