number of ordered pairs and sets

Question: I got 2 questions(truth or false with explanation) which I found confusing a bit and I would like to know what the different approach should be and if my approach is right .
we are working with the set A={1,2,3,4,5,6}
the first question is the number of sets {B,C} that B,C⊆A , $|B|$=$|C|$=$3$ and $B∩C=∅$ is equal to the number of words that their length is $6$ and each of the digits $0,1$ shows $3$ times in it
My way was that I looked at the set {1,2,3,4,5,6} and i took {1,2,3} for A and {4,5,6} for B which are different so we got for the first option  ${6 \choose 3}$ which is 20 and for the second we got  ${3 \choose 3}$ which is 1 , so total its equal to 20. as for the words we got 3 times '1' and 3 times '0' so total 6  and 3 of each so we got $\left(\frac{6!}{3!*3!}\right)$ which is also 20 so the first one is true but the second question is
the number of ordered pairs $<B,C>$ that $B,C⊆A$ , $|B|$= $2$ $|C|$=$3$ and  $B∩C=∅$ is equal to the number of words that their length is 6 and each of the digits are shown $0$ one time , $1$ two time , $2$ three times
The thing that got me confused the most here is when they said ordered pairs. So I know that for the number (0,1,2) it will be ${6 \choose 1}$ * ${5 \choose 2}$ * ${3 \choose 3}$ which is 60 and for B,C it would be ${6 \choose 2}$ * ${4 \choose 3}$  also = $60$
My question is , is it right to do that? Is there really no difference in solving just normal sets or ordered pairs? Because i did it in the same way but it feels wrong as then why would they state that they are ordered sets .
Thanks for any type of help , and I am sorry if there are some translation mistakes.
Answer: In the first question you can think of a word of lenght 6 in witch 0 and 1 appears 3 times in this way: given such a word (for example 001011) you can take the set $\{1,2,3,4,5,6\}$ and put in the set $B$ all the numbers that correspond to the position of a $0$ in the word (in this case $1,2,4$) and in the set $A$ all the numbers that correspond to the position of a $1$ in the word (in this case $3,5,6$).
Viceversa, given such a couple of sets you can construct a word representing that partition  in the same way: the first digit is a $0$ if $1 \in B$ and is a $1$ if $1 \in B$ and so on with the other digits.
In the second question you can apply the same method of the first answer by creating a new set $D$ such that, all the numbers who are not in $B$ or $C$ are in $D$. In this way, given $B$ and $C$, you can create $D$ and then a word in the same way putting a $0$ for elements in $D$ , a $1$ for elements in $C$ and a $2$ for elments in $B$. Viceversa, also in this case, you can construct a word representing that partition in the same way:  the first digit is a $0$ if $1 \in D$, is a $1$ if $1 \in C$ and is a $2$ if $1 \in B$ and so on with the other digits.
P.S. There is no difference in the second question between ordered pairs and not ordered one becaus you can distinguish the two sets just by looking at their cradinality.

number of ordered pairs and sets


Differentiate a matrix trace in Kalman filter

Question: I have a problem about differentiating a matrix with trace as
$\frac{d T[KHP]}{dK}$,
where $T$ is the trace operation, K, H and P are three matrices and $P^{\top} = P$
In Kalman filter derivation, the result for this is
$(HP)^{\top}$
(refer to equation 11.24 and 11.25 in Here).
I am not quite understand it, and why the result is not $HP$. Thank you
Answer: I've heard some people scorn it but The Matrix Cookbook is full of useful information. For example, in the derivatives of traces section, one can see that
$$
\frac{\partial}{\partial {\bf X}}\text{Tr}({\bf XA}) = {\bf A}^\text{T}
$$
Note that a trace is a linear operator so it commutes with the derivative. To prove the above relation, you could differentiate ${\bf XA}$ and then take the trace to arrive at the same result.
Comment: Thank you. I will read the book and have a look.
Comment: Just so you know, it's not really a book, just a long list of identities.


suphp error Directory / is not owned by admin

Question: I'm trying to run a test phpinfo page from:
/home/admin/testdomain.com
But it displays such error:
Internal Server Error

Directory / is not owned by admin
suPHP 0.7.1

My /etc/suphp.conf is like this:
[global]
logfile=/var/log/httpd/suphp_log
loglevel=info
webserver_user=apache
docroot=/
env_path=/bin:/usr/bin
umask=0022
min_uid=500
min_gid=48

; Security options
allow_file_group_writeable=true
allow_file_others_writeable=false
allow_directory_group_writeable=true
allow_directory_others_writeable=false

;Check wheter script is within DOCUMENT_ROOT
check_vhost_docroot=false

;Send minor error messages to browser
errors_to_browser=true

[handlers]
;Handler for php-scripts
x-httpd-php="php:/usr/bin/php-cgi"
; x-httpd-php52="php:/usr/local/lxlabs/ext/php/bin/php_cgi"
x-httpd-php52="php:/usr/local/lxlabs/ext/php/etc/lxphpcgi.sh"

;Handler for CGI-scripts
x-suphp-cgi="execute:!self"

Answer: A fix is simple:
chown root.root /

Comment: Please up my answer ;)
Comment: I don't know but it works ok ;)
Comment: First thanks a lot, the fix is indeed easy and quick! How come it happens? Why should the / permissions change? And why SuPHP talks about "not owned by user" while the / has to be owned by root ?
Comment: Cooool!!! But... why chown root.root / has resolved the problem? tell me, please :-D


Setting custom contrasts in R

Question: I have a data as follows.
data <- structure(list(Loc = structure(c(17L, 27L, 33L, 6L, 39L, 10L,
                                         9L, 11L, 36L, 4L, 2L, 5L, 34L, 45L, 18L, 15L, 29L, 31L, 14L,
                                         40L, 44L, 19L, 1L, 22L, 3L, 32L, 16L, 21L, 20L, 13L, 12L, 25L,
                                         35L, 8L, 24L, 41L, 30L, 23L, 7L, 37L, 42L, 26L, 28L, 38L, 43L,
                                         17L, 27L, 33L, 6L, 39L, 10L, 9L, 11L, 36L, 4L, 2L, 5L, 34L, 45L,
                                         18L, 15L, 29L, 31L, 14L, 40L, 44L, 19L, 1L, 22L, 3L, 32L, 16L,
                                         21L, 20L, 13L, 12L, 25L, 35L, 8L, 24L, 41L, 30L, 23L, 7L, 37L,
                                         42L, 26L, 28L, 38L, 43L), .Label = c("Hpan100786", "Hpan100794",
                                                                              "Hpan107006", "Hpan109517", "Hpan109543", "Hpan109546", "Hpan109549p",
                                                                              "Hpan109551", "Hpan109552", "Hpan109553", "Hpan109556", "Hpan112828",
                                                                              "Hpan113401", "Hpan114525", "Hpan116055", "Hpan14479", "Hpan25167",
                                                                              "Hpan2573", "Hpan34342", "Hpan36372", "Hpan39020", "Hpan39039",
                                                                              "Hpan4496", "Hpan6103", "Hpan61434", "Hpan65773", "Hpan76756",
                                                                              "Hpan93602", "Hpan95269", "Hpan95278", "Lpan15539", "Lpan16561",
                                                                              "Lpan16823", "Lpan21755", "Lpan24060", "Lpan24994", "Lpan25763",
                                                                              "Lpan3", "Lpan501186", "Lpan501220", "Lpan501263", "Lpan501286",
                                                                              "Lpan501468", "Lpan501493", "Lpan501531"), class = "factor"),
                       Class = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                           1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                           2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                           3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                           1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                           2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                           3L, 3L, 3L, 3L, 3L), .Label = c("Good", "Medium", "Poor"), class = "factor"),
                       Rep = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                         1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                         1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                         1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                         2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                         2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                         2L, 2L, 2L, 2L, 2L), .Label = c("R1", "R2"), class = "factor"),
                       y = c(1202, 686, 921, 705, 1060, 642, 996, 1154, 1195, 692,
                             1045, 1008, 1107, 1195, 1267, 703, 1371, 1122, 992, 1721,
                             989, 503, 1023, 740, 1169, 716, 625, 1403, 783, 1182, 1411,
                             851, 1191, 1444, 1643, 1185, 1635, 1525, 1162, 1472, 626,
                             575, 721, 849, 867, 1178, 703, 845, 689, 1011, 659, 1022,
                             1203, 1202, 716, 1004, 1004, 1082, 1176, 1248, 719, 1328,
                             1185, 966, 1685, 1050, 510, 998, 721, 1173, 718, 614, 1392,
                             767, 1035, 1430, 902, 1225, 1451, 1615, 1157, 1659, 1506,
                             1151, 1466, 618, 583, 736, 885, 876)), .Names = c("Loc",
                                                                               "Class", "Rep", "y"), class = "data.frame", row.names = c(NA,
                                                                                -90L))

I am trying to do ANOVA with planned contrasts in R using aov. The 45 Loc belong to 3 different Class. I want to compare the Loc in one class with those in another Class. I am trying to follow A (sort of) Complete Guide to Contrasts in R steps for "Running Fewer than J-1 Contrasts for J Groups".
#Creation of contrast matrix
# reorder the levels of `Loc` according to `Class`
data$Loc <- factor(data$Loc, levels = unique(data[order(data$Class), "Loc"]))

c1 <- c(rep(1/15, 15), rep(-1/15, 15), rep(0, 15)) # Good vs Med
c2 <- c(rep(1/15, 15), rep(0, 15), rep(-1/15, 15)) # Good vs Poor
c3 <- c(rep(0, 15), rep(1/15, 15), rep(-1/15, 15)) # Med vs Poor

# Specify the contrasts
mat <- cbind(c1, c2, c3)

options(contrasts = c("contr.helmert", "contr.poly"))
m1 <- aov(y ~ Loc, data = data)
summary(m1)
            Df  Sum Sq Mean Sq F value Pr(>F)
Loc         44 8547697  194266   292.3 <2e-16 ***
Residuals   45   29910     665
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

m2 <- aov(y ~ Loc, data = data, contrasts=list(Loc = mat))
summary.aov(m2, split=list(Loc=list("Good Vs Med"=1,
                                     "Good Vs Poor" = 2,
                                     "Med Vs Poor"=3)))

                    Df  Sum Sq Mean Sq F value Pr(>F)
Loc                  2  483311  241656   2.597 0.0802 .
  Loc: Good Vs Med   1    1363    1363   0.015 0.9039
  Loc: Good Vs Poor  1  481948  481948   5.180 0.0253 *
  Loc: Med Vs Poor   1
Residuals           87 8094296   93038
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The third contrast is missing.
Also the contrast c3 effect is missing
names(m2$coefficients)
[1] "(Intercept)" "Locc1"       "Locc2"       "Locc3"
names(m2$effects)
 [1] "(Intercept)" "Locc1"       "Locc2"       ""            ""            ""
 [7] ""            ""            ""            ""            ""            ""
[13] ""            ""            ""            ""            ""            ""
[19] ""            ""            ""            ""            ""            ""
[25] ""            ""            ""            ""            ""            ""
[31] ""            ""            ""            ""            ""            ""
[37] ""            ""            ""            ""            ""            ""
[43] ""            ""            ""

How to get the appropirate comparisons here? What am I doing wrong in specifying the contrast matrix?
In SPSS I can do the comparisons using the following syntax
UNIANOVA y BY Loc
/METHOD=SSTYPE(3)
/INTERCEPT=INCLUDE
/CRITERIA=ALPHA(0.05)
/LMATRIX = "Good_vs_Med" y -15, 15, -15, 15, 15, 15, 0, 0, 15, 15, 15, 0, -15, -15, -15, -15, 15, 15, -15, -15, -15, -15, 0, 0, 0, 0, 15, 0, -15, 0, -15, -15, 15, 15, 0, 15, 0, 0, 15, -15, 0, 0, 0, -15, 15;
/LMATRIX = "Good_vs_Poor" y 0, 15, 0, 15, 15, 15, -15, -15, 15, 15, 15, -15, 0, 0, 0, 0, 15, 15, 0, 0, 0, 0, -15, -15, -15, -15, 15, -15, 0, -15, 0, 0, 15, 15, -15, 15, -15, -15, 15, 0, -15, -15, -15, 0, 15;
/LMATRIX = "Med_vs_Poor" y 15, 0, 15, 0, 0, 0, -15, -15, 0, 0, 0, -15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, -15, -15, -15, -15, 0, -15, 15, -15, 15, 15, 0, 0, -15, 0, -15, -15, 0, 15, -15, -15, -15, 15, 0;
/PRINT = TEST(LMATRIX)
/DESIGN=y

Comment: You have only 2 degrees of freedom. 3 groups, 1 grand mean, 2 degrees of freedom. Are you testing the hypothesis $\mu_1=\mu_2=\mu_3$ (sane) or $\mu_1=\mu_2=\mu_3=0$ (not clear).
Comment: @AdamO There are 45 levels in Loc, so 44 df (as is clear in `m1`). Something is going wrong when aov() estimates `m2`. Interesting problem!
Comment: A related post on SO (unfortunately without a useful answer): [https://stackoverflow.com/questions/31818174/custom-contrasts-in-r-contrast-coefficient-matrix-or-contrast-matrix-coding-s](https://stackoverflow.com/questions/31818174/custom-contrasts-in-r-contrast-coefficient-matrix-or-contrast-matrix-coding-s)
Comment: @Crops then the 2 level ANOVA is correct for hypothesis one, and Tukey post hoc for the next hypotheses. 2-4 are redundant.
Comment: At a guess R insists on only using 2 df for comparing 3 groups and SPSS does not. You might get better answers on an R site.
Comment: Is it because the contrast effect `Locc3` is missing in model (`names(m2$effects)`)
Comment: @AdamO  The hypothesis to be tested would be (1)$\mu_1 = \mu_2 = .......= \mu_{45}$; (2)$\mu_{Good} = \mu_{Medium}$;
(3)$\mu_{Good} = \mu_{Poor}$ and (4)$\mu_{Medium} = \mu_{Poor}$
Comment: I'm the author of the tutorial you're using, by the way. :) I'm glad it's still getting some use! Perhaps I'll update it with some follow-up information on this issue.
Comment: @RoseHartman 2 *numerator* degrees of freedom. The denominator is irrelevant until the issue of contrasts is resolved.
Answer: Interesting problem! The issue is that you're basically re-coding Loc into a variable with three levels (corresponding to your three levels of Class in this case), which leaves it with only 2 degrees of freedom. R can't estimate three contrasts for a factor with three levels in a model with an intercept.
You can see this because you get 44 df in m1 when R uses its automatic contrasts, but only 2 when you specify your own contrast matrix in m2. The problem is that the contrasts you're specifying create a singular matrix:
> contrasts(data$Loc) <- mat
Error in `contrasts<-`(`*tmp*`, value = c(0.0666666666666667, 0.0666666666666667,  :
  singular contrast matrix

If you modify your contrast matrix so it's not a complete coding scheme for three levels, R will go back to filling in the missing df with complementary orthogonal contrasts to the ones you specify:
c4 <- c(rep(0, 5), rep(1/15, 15), rep(-1/15, 15), rep(0, 10)) # made up c4
mat <- cbind(c1, c2, c3, c4)
m2 <- aov(y ~ Loc, data = data, contrasts=list(Loc = mat))
summary.aov(m2, split=list(Loc=list("Good Vs Med"=1,
                                    "Good Vs Poor" = 2,
                                    "Med vs Poor"=3)))

Results:
                    Df  Sum Sq Mean Sq F value Pr(>F)
Loc                  3  683581  227860   2.482 0.0663 .
  Loc: Good Vs Med   1    1363    1363   0.015 0.9033
  Loc: Good Vs Poor  1  481948  481948   5.250 0.0244 *
  Loc: Med vs Poor   1  200270  200270   2.182 0.1433
Residuals           86 7894026   91791
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Note that when you specify the contrasts within the model call (aov), it limits the df for the predictor to the number of contrasts you ran - 1, and any additional SS goes into the residual SS. Above, I used a pretty gross hack to get 3 df (so we could see all of your comparisons) by specifying 4 contrasts.
If you specify your contrasts as an attribute of the variable Loc before running the model, R will attempt to auto-fill the rest of the contrast matrix out to the full 44 df, but it still can't in this case because the matrix is singular.
A better approach
It sounds like you're actually trying to get comparisons among the levels of Class, not Loc, but you want all three possible comparisons so you're trying to get Loc to do it for you since Class can't. Instead of running contrasts, you should be looking at pairwise comparisons for Class. You can do that with pairwise.t.test from the stats package, but I prefer the lsmeans package for nicer formatting and more flexibility.
m3 <- aov(y ~ Class, data = data)
library(lsmeans)

You can then use lsmeans functions to compare your different classes on y. The default output gives you the estimated marginal means (which is the same as the raw means, in this case, since you don't have any covariates) with 95%CI around them:
> lsmeans(m3, ~ Class)
 Class     lsmean       SE df  lower.CL upper.CL
 Good    987.2333 55.68898 87  876.5454 1097.921
 Medium  996.7667 55.68898 87  886.0788 1107.455
 Poor   1147.2333 55.68898 87 1036.5454 1257.921

You can see all pairwise comparisons by wrapping that with the pairs function:
> pairs(lsmeans(m3, ~ Class))
 contrast         estimate       SE df t.ratio p.value
 Good - Medium   -9.533333 78.75612 87  -0.121  0.9920
 Good - Poor   -160.000000 78.75612 87  -2.032  0.1107
 Medium - Poor -150.466667 78.75612 87  -1.911  0.1418

P value adjustment: tukey method for comparing a family of 3 estimates

It defaults to a sensible post hoc adjustment (Tukey's HSD), but you can change that with the adjust argument if you want. If you turn off the adjustment for multiple comparisons, you'll see that one of your comparisons is significant with uncorrected p-values:
> pairs(lsmeans(m3, ~ Class), adjust = "none")
 contrast         estimate       SE df t.ratio p.value
 Good - Medium   -9.533333 78.75612 87  -0.121  0.9039
 Good - Poor   -160.000000 78.75612 87  -2.032  0.0452
 Medium - Poor -150.466667 78.75612 87  -1.911  0.0594

This is a much more sensible way to compare each of the three classes in your data.
Comment: How do I set c4? Is it arbitrary? If I am using `c4 <- c(rep(-1/15, 15), rep(1/30, 30))`, again it is a singular matrix.
Comment: If I am using each contrast individually, I am getting the sum of squares as in SPSS. `mat <- cbind(c3)
m2 <- aov(y ~ Loc, data = data, contrasts=list(Loc = mat))
summary.aov(m2, split=list(Loc=list("Good Vs Med"=1,
                                    "Good Vs Poor" = 2,
                                    "Med vs Poor"=3)))`
Comment: @Crops as long as you include c1, c2, and c3 as you have them, you'll end up with a singular matrix. Adding an arbitrary c4 will get R to print results for you, but the F-ratios will depend on the residual and so may change depending on the c4 you create --- not ideal. I don't recommend you test the comparisons with contrasts. Instead, use pairwise comparisons.
Answer: My advice is to forget contrasts in aov and use the lsmeans or multcomp packages instead.  They allow you to run as many contrasts as you would like without being limited by degrees of freedom.  They also allow you to run a test on contrasts that span more than one line.
The follow page has examples. http://rcompanion.org/rcompanion/h_01.html. (Caveat:  I am the author of this page.)

Setting custom contrasts in R


Unit testing presence of mat-error after touching and untouching mat-input

Question: How would I test that the mat-error is present in the DOM when I haven't touched the input, and also when I have touched and untouched the input without entering any text?
I am testing using Jest
HTML
<mat-form-field>
  <input matInput formControlName="someInput"/>
  <mat-error id="my_error">* required</mat-error>
</mat-form-field>

Test
it('Should not show error', () => {
  const myEl = fixture.debugElement.query(By.css('#my_error'));

  expect(myEl).toBeUndefined();
});

it('Should show error', () => {
  const myEl = fixture.debugElement.query(By.css('#my_error'));

 // code to touch and untouch the element

  expect(myEl).not.toBeUndefined();
});

Answer: Maybe something like:
const input = fixture.debugElement.query(By.css("[formControlName='someInput']"));
const errors = fixture.debugElement.queryAll(By.css("mat-error"));

input.nativeElement.dispatchEvent(new Event("input"));
fixture.detectChanges();

expect(errors.length).toEqual(1);
expect(errors[0].nativeElement.innerHTML.trim()).toMatch("* required");


Different results, why?

Question: I have code for print MAC address from Java, the code is
InetAddress ip;
try {
    ip = InetAddress.getLocalHost();
    System.out.println("Current IP address : " + ip.getHostAddress());

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

    System.out.print("Current MAC address : ");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
         sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
    }
    System.out.println(sb.toString());

} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (SocketException e){
    e.printStackTrace();
}

but I has curiosity about this, and I'm trying to print directly with
System.out.print("Current MAC address : ");
for (int i = 0; i < mac.length; i++) {
         System.out.print(mac[i]);
              if (i < mac.length - 1)
                   System.out.print("-");
              else
                   System.out.print("");
}

but it doesn't work.
The results are
Current MAC address : 08-00-27-96-40-39
Current MAC address : 8-0-39--106-64-57

why?
Thank's in advance for your help!!
Answer: String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "") produces 2 hexadecimal digits for each element of the array.
On the other hand, your code prints the decimal representation of each element, so 27 (hex) becomes 39 (decimal), and so on.
If you replace
System.out.print(mac[i]);

with
System.out.print(Integer.toString (mac[i] & 0xff,16).toUpperCase ());

you'll get (almost) the same result.
Note that & 0xff is required in order to get the positive value of the integer whose 8 lowest bits are the same as the original byte. Without it the negative valued bytes (such as -106 in your example) will be printed as negative numbers.
For example, take the 4th byte, which your code prints as -106 :
First we want to get its unsigned value 150. Converting 150 from decimal to hexadecimal gives 96.
After that change the output of the 2 snippets is :
Current MAC address : 08-00-27-96-40-39
Current MAC address : 8-0-27-96-40-39

Note that the second snippet is still lacking the leading 0s for small numbers.
Comment: @Holloway That's because the OP is printing a negative byte value "-106"
Comment: I don't get the double hyphen between 39 and 106 though. Any idea what's going on there?

Different results, why?


Vue js component interaction using shared store pattern with vue-loader

Question: I am following this SO answer to achieve sibling-sibling data sharing(communcation).
Here is my ComponentA.vue:
<template>
    <input id="ca" type="text" v-model="localvarA" placeholder="localvarA">
    {{localvarA}}

        thisdiv
        {{sharedvar}}

</template>

CompoinentB.vue:
<template>
    <input type="text" v-model="localvarB" placeholder="localvarB">
    {{localvarB}}

        thisdiv2
        <input type="text" v-model="sharedvar" placeholder="sharedvar">

</template>

And here is my App.vue:
<template>
    <component-a></component-a>
    <component-b></component-b>
</template>

Here is my application/index.js (the shared module):
export default {
    sharedvar: 'sharedval'
};

In above, the shared variable sharedvar when updated in ComponentB does not update its value in div in ComponentA.
I have tried best to replicate in vue-loader the jsfiddle in that SO answer, but not sure why this is not working.
Here is the github repo if someone needs to try this out: https://github.com/rahulserver/vueshared-vue-loader
So where am I doing it wrong and how do I make it work?
Comment: I had similar problem to check does it same could you change this in both components `sharedvar: remoteservice.sharedvar` to this `sharedvar: remoteservice`.Then in componentB assign v-model to input like this `sharedvar.sharedvar` - I think this should work
Answer: You are declaring data items that are being initialized with the value in remoteservice.sharedvar. Because sharedvar is a simple value and not an object, they're just separate copies of a value.
In the fiddle example, hub.state is an object. If you assign it to a variable, and then reference some member of that variable, you are referencing a member of hub.state. In each of their components, they do:
hubState: hub.state

and then use
<input v-model="hubState.message">

To parallel that, you should be doing
sharedvar: remoteservice

and then using
 <input type="text" v-model="sharedvar.sharedvar" placeholder="sharedvar.sharedvar">

(or change the names to be more sensible). The trick is that you have to work with an object.


Bézier curve approximating the intersection between a cone and a plane.

Question: I've been trying to fine a nice way to visualise projecting a parabola to a circular arc, but I realise I don't actually know how to derive the functions necessary to show projecting a parabola through its plane onto the base plane of the conic it lies on...
I started with the following geometric setup:

In this, we have a 3D space with an origin $P_2=(0,0,0)$, and a cone with base radius $r$ and height $h$, effecting a conic angle $\phi$. There is a plane at the same angle, shifted along the x-axis by $d$, and as such the intersection of the plane and the cone is a parabolic conic section, with points $A$ and $C$ the intersection points of the plane and the conic base and point $B$ the parabola's extremum.
From the geometry, it is clear that every point on the parabola can be projected from $P_2$ through the parabolic plane onto the conic base plane to yield a circular arc (after all, the cone itself is that projection) but I have no idea how to turn this into the form of a function.
I figured I could represent the parabola as a 3D rational quadratic Bezier curve, with start point $A$ and end point $C$, and a control point $B'=\{ 0, r-d, \frac{r-d}{r}h \}$, and then vary the rational weight for point $B$ to "slide" the parabola along the cone, but that does not appear to be what happens when you adjust that value.
So my question is: given this geometry, and given the parabola as a Bezier curve, how would I go about turning that into a "projective" Bezier curve function that takes the coordinates $A$, $B$, and $C$, and the angle $\phi$, yielding the conic section described by the intersection of the cone and a plane passing through $A-C$ at angle $\phi$?
(E.g. at $\phi=0$ this would be a circular arc, at $\phi=\frac{\pi}{2}$ a triangle, and anywhere in between some form of non-parabolic elliptical arc)
Comment: So you have a 2D equation of a parabola as a Bézier curve and want to have a 3D version? Or something else? And what has the semi-circle to do with all that? I think you should make your problem more clear.
Comment: No? I have a 3d equation of a parabola, which I can represent as a 3d bezier curve, and I want to transform it into other "all the other 3d elliptical arcs" that pass through A and C (think of it as rotating the plane on intersection about A--C if that helps). The special case circular arc is still a 3D curve, even if it has the same value for all z coordinates (technically, all conic sections are 2D in their plane of intersection, but 3D in terms of "world coordinates")
Comment: The type of function I'm looking for, though, is one that explicitly models these curves in terms of a transformed Bezier expression (similar to how the rational Bezier function can model a circular arc up to a semi circle - that same arc is trivially expressed using a parametric sinoidal function, but that's not the form I'm looking for)
Comment: Now I see what you want: a parametric equation for the arc of conic section $ABC$, with $AC$ fixed and $B$ any point along the mid generatrix. This, of course, cannot be a Bézier curve, apart the particular case of a parabola, but you need a Bézier approximating that curve.
Comment: I edited the title to make the question clearer. I'd suggest you to edit your question, especially the first part with a misleading request for a projection.
Comment: Another thing is not clear: you used the same name $\phi$ to denote both the conic angle and the dihedral angle formed by the cutting plane with a plane perpendicular to the axis of the cone. But I presume you want to keep the cone fixed while the cutting plane (and thus $B$) varies, right?
Comment: It cannot be a Bezier curve, but it can be a function _based_ on a Bezier curve (in the same way a rational Bezier curve is not a Bezier curve, but is equivalent to a circular conic section, as long as the correct ratio values are specified for each Bezier hull coordinate). So I'm _not_ looking for a true Bezier, but for the function that "contains" the parabolic Bezier, with the projection along the cone applied to it. I'll try to edit my question to make this clearer. Good catch on the $\phi$, that should indeed be a free parameter for the projection, not the same as used by the cone.
Answer: One reason why your idea might not have panned out is that the point $B'$ in your question is the parabola's vertex, so it doesn't even work as the control point for a Bézier parameterization of the original parabola: even for a rational Bézier  curve the middle control point never lies on the curve. The correct middle control point for a Bézier parameterization of the parabola can be found by intersecting the tangent planes to the cone at $A$ and $C$ with the plane that generates the parabola. We can thus find that with $$A = \left(2\sqrt{d(r-d)},r-2d,h\right) \\ B = \left(0,r,\frac hr(r-2d)\right) \\ C = \left(-2\sqrt{d(r-d)},r-2d,h\right)$$ the Bézier curve $$(1-t)^2A+2t(1-t)B+t^2C \tag1$$ matches the parabola. For $0\le t\le1$, we get the arc through the vertex with endpoints $A$ and $C$. (This orientation might not match your diagram exactly.)
Going back to your idea of projecting the parabola onto a variable plane through $A$ and $C$, we observe that since the center of the projection is the origin, if a point $P$ has a finite projection onto the plane then it is a scalar multiple of $P$ and so can be expressed as $P'=c(P)P$. Note that this scalar $c$ depends on $P$, and, of course, on the image plane. By construction, $A$ and $C$ are their own images, so the projection of the curve (1) is $$(1-t)^2A+2t(1-t)c(B)B+t^2C. \tag2$$ Comparing the rational Bézier parameterization $${(1-t)^2w_1P_1+2t(1-t)w_2P_2+t^2w_3P_3 \over (1-t)^2w_1+2t(1-t)w_2+t^2w_3}$$ to (2) suggests setting $w_1=w_3=1$ and since we'd like the control point to lie on the curve's plane, $w_2=1/c(B)$ seems like a reasonable guess, leading to $${(1-t)^2A + 2t(1-t)B'/c(B)+t^2C \over (1-t)^2+2t(1-t)/c(B)+t^2}. \tag3$$
Parameterizing the variable plane by the angle $\phi$ between its normal and the positive $z$-axis, we have for an equation of the plane $$y\sin\phi+z\cos\phi=h\cos\phi+(r-2d)\sin\phi$$ and we can find $$B' = {r(h\cos\phi+(r-2d)\sin\phi) \over h(r-2d)\cos\phi+r^2\sin\phi}B.$$ I'll leave verifying that using these values of $B'$ and $w$ do indeed produce a parameterization of the intersection curve, which involves some tedious but straightforward algebra.
Observe that, instead of sliding the vertex along the cone as you proposed, we are effectively sliding the parabola's control point $B$ along the line through it and the origin. Parameterizing this family of curves by $c(B)$ as in (3) instead of the plane's normal angle makes this relationship more transparent, I think.
Here, for example, is what results with $h=3$, $r=1$, $d=1/4$ and $\phi=\pi/4$:

The black arc is the above rational Bézier curve for $0\le t\le1$.
Comment: @Mike'Pomax'Kamermans Glad I could help. It was a fun problem to work on.
Comment: @Mike'Pomax'Kamermans The white fringe at the top of the cone is just GeoGebra fading the image out. I suppressed the $z=h$ plane to reduce clutter. $A$ and $C$ are fixed at $z=h$, in this case $3$.


Nomenclature of variables: What do the names mean?

Question: I see different names for variables in different contexts and I am confused. Can you help me understand the differences between:

Variable
Predictor
Covariate
Explanatory Variable
Independent variable

Are these different and if so how? Also, do these have different meanings in different analysis (e.g., ANOVA, Regression)?
For example to my confusion:
From Factor Analysis:

In this context (ANOVA), the covariate is always continuous, always a control
  variable, and always observed (i.e. observations weren't randomly
  assigned it's values, you just measured what was there).

Can an independent variable be the same as covariate? it sounds the opposite.
Answer: The word "variable" is a vague term in the field of statistics. Too vague to be regarded as synonymous with any of the other terms you listed. You're more likely to see that used as an adjective rather than a noun. As for the other terms, they all refer to the same thing. Namely, the data which is usually denoted by X. They can all be used in just about any regression context (ANOVA included).
It's also worth noting that the usage frequency of these terms often depends on the context. "Independent variable" and "explanatory variable" are used to emphasize different aspects of X - often in introductory settings. X is certainly intended to explain Y. However, if X is helpful in prediction, it will not be independent of Y. Instead, the practitioner typically would hope that X and Y "covary." That's why X is often referred to as a covariate. So, why then is X called an independent variable? In many problems, X can be chosen (or sampled, or collected) according to any means. X might be chosen through stratified sampling or perhaps just data collector's whim. In either case, we can expect (in some sense) to make the same inference regarding the prediction of Y.
Predictor and covariate are better and more general-purpose terms to refer to X. They're also shorter and equally descriptive. "Regressor" is another good synonym. And "feature" is yet another term which is typically used in Machine Learning contexts but means the exact same thing. Lastly, "factors" or "factor-variables" are specific types of predictors which are often used in ANOVA models. The specification for factors is that they must take on one of a set number of "levels" or categories.
Answer: From Wikipedia on Covariates

The alternative terms explanatory variable, independent variable, or
  predictor, are used in a regression analysis.

Also worth looking at Wikipedia on Dependent variables
Your last four terms are the same. All of them are names for the variables that are used to predict another variable.  You use independent variables (or Predictors or Covariates or Explanatory Variables) to predict the dependent variable (also called the response variable).


Tensor product of point-determined algebras

Question: We say a (commutative, associative, unital) $\mathbb{R}$-algebra $A$ is point-determined if for every nonzero $a\in A$ there is an $\mathbb{R}$-algebra homomorphism $\chi:A\to\mathbb{R}$ such that $\chi(a)\ne0$.
I'm having trouble showing that if $A,B$ are two point-determined $\mathbb{R}$-algebras, so is their tensor product $A\otimes_{\mathbb{R}} B$. This is an exercise from the book Smooth manifolds and observables by Jet Nestruev.

My thoughts: if I have a nonzero pure tensor, then everything is easy. However, given a general tensor $\sum_ia_i\otimes b_i\ne0$, there is not much I can say about each individual $a_i\otimes b_i$, since in general one cannot tell if a tensor is zero or not. Therefore, I can't produce $f,g$ such that $\sum_if(a_i)g(b_i)\ne0$.

Any help would be appreciated. Thanks!
Answer: We need to check that if $u\in A\otimes B$ is a non-zero tensor, there exists an $\mathbb{R}$-algebra homomorphism $\psi:A\otimes B\to \mathbb{R}$ such that $\psi(u)\neq 0$. Note that if $\alpha:A\to \mathbb{R}$ and $\beta:B\to \mathbb{R}$ are $\mathbb{R}$-algebra homomorphisms, then $\alpha\otimes \beta:A\otimes B\to \mathbb{R}$ given by $$(\alpha\otimes \beta)(\sum_{i=1}^n a_i\otimes b_i)=\sum_{i=1}^n \alpha(a_i)\beta(b_i)$$ is a  well-defined $\mathbb{R}$-algebra homomorphsim. We're going to look for $\psi$ of the form $\alpha\otimes \beta$, which OP already knows.
To get around non-uniqueness of representation, we will let $n$ be the minimum non-negative integer $m$ such that there exist $a_1',\ldots, a_m'\in A$ and $b_1',\ldots, b_m'\in B$ such that $u=\sum_{i=1}^m a_i'\otimes b_i'$. Since $u\neq 0$, $n\neq 0$.
With this fixed $n$, we can select some $a_{1},\ldots, a_{n}\in A$ and $b_1,\ldots, b_n\in B$ such that $u=\sum_{i=1}^n a_i\otimes b_i$.  Note that $a_1\neq 0$, otherwise $u=\sum_{i=2}^n a_i\otimes b_i$ is a representation of $u$ with fewer than $n$ elementary tensors. Fix an $\mathbb{R}$-algebra homomorphism $\chi:A\to \mathbb{R}$ such that $\chi(a_1)\neq 0$. Note that \begin{align*} u & =a_1\otimes b_1 + \sum_{i=2}^n a_i\otimes b_i = a_1\otimes b_1+\sum_{i=2}^n \Bigl[a_i-\frac{\chi(a_i)}{\chi(a_1)}a_1+\frac{\chi(a_i)}{\chi(a_1)}a_1\Bigr]\otimes b_i \\ & = a_1\otimes\Bigl[b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\Bigr] + \sum_{i=2}^n \Bigl[a_i-\frac{\chi(a_i)}{\chi(a_1)}a_1\Bigr]\otimes b_i.\end{align*}
Note that $b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\neq 0$, otherwise the first tensor in the expression above is zero, and we again have a representation of $u$ using at most $n-1$ elementary tensors, contradicting the minimality of $n$. Therefore there exists an $\mathbb{R}$-algebra homomorphism $\psi:B\to \mathbb{R}$ such that $$\psi\Bigl(b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\Bigr)\neq 0.$$  Then consider $\chi\otimes \psi:A\otimes B\to \mathbb{R}$ which is the unique $\mathbb{R}$-algebra homomorphism on $A\otimes B$ taking $a\otimes b$ to $\chi(a)\psi(b)$ for all $a\in A$ and $b\in B$.
Note that $$\chi\Bigl(a_i-\frac{\chi(a_i)}{\chi(a_1)}a_1\Bigr)=\chi(a_i)-\frac{\chi(a_i)}{\chi(a_1)}\chi(a_1)=0$$ for all $i=2,\ldots, n$. So \begin{align*} \chi\otimes \psi(u) & = \chi(a_1)\psi\Bigl(b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\Bigr) +\sum_{i=2}^n \chi\Bigl(a_i-\frac{\chi(a_i)}{\chi(a_1)}a_1\Bigr)\psi(b_i) \\ & = \chi(a_1)\psi\Bigl(b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\Bigr) +\sum_{i=2}^n 0\cdot \psi(b_i) \\ & =\chi(a_1)\psi\Bigl(b_1-\sum_{i=2}^n \frac{\chi(a_i)}{\chi(a_1)}b_i\Bigr) \neq 0.\end{align*}
Comment: Excellent proof! Do you mind sharing some motivation for how you came up with the argument?
Comment: Thanks! Of course. I chose the minimal $n$ because, after lots of time working with tensors, I found that this is often the most convenient way to deal with non-uniqueness of representation. So I started with that, and got lucky that it worked.
Comment: The other major part was we know that for any particular $a_i$, there exists $\chi$ such that $\chi(a_i)\neq 0$. But we only know how to choose these for one $a_i$ at a time (say, $a_1$). Then we want the action of $\chi$ on the other $a_i$ not to ruin the good behavior we get on $a_1$. So we want to modify each other $a_i$ to get something which has zero action under $\chi$ (a la Gram-Schmidt orthonormalization, biorthogonalization, etc.). Subtracting $\chi(a_i)/\chi(a_1)a_1$ is a common way to do this. Luckily in this case, the difference can be swept into the first term, and it works out.
Comment: Honestly, when I first split $a_i= a_i-\frac{\chi(a_i)}{\chi(a_1)}a_1+\frac{\chi(a_i)}{\chi(a_1)}a_1$, I wasn't quite sure it was going to go anywhere. Just kind of got lucky from there.
Comment: I agree that choosing the minimal expression for the tensor is a useful trick in dealing with tensor products.


Why (or when) can we neglect residuals mutual correlation?

Question: I've found in several books so far only a waving of hands explanation on why one can simply neglect the residuals mutual correlation, in a linear model context, and plot a QQ-graph to do a qualitative assessment on the distributional properties of the residuals.
In a comment to this other question of mine, there's a comment stating that  the average mutual correlation is $-1/(n-1)$ and I am not sure why ...
In this other question, StasK answer gives the following statement: "The reason I am saying that the off-diagonal values are small is because $\sum_{j≠i}h^2_{ij}+h^2_{ii}=h_{ii}$, and in fact either the diagonal or off-diagonal entries are roughly of order $O(1/n)$ although this is not a very strict statement that is easily thrown off by the high leverage points.»
I'm looking for two well laid out explanations of the two above statements, in simple terms, for a plain, simple man. And please, do include equations.
Comment: A similar question with no useful answer (at least to me) https://stats.stackexchange.com/questions/96144/why-doesnt-correlation-of-residuals-matter-when-testing-for-normality
Comment: Another similar question with no answer https://stats.stackexchange.com/questions/279105/why-check-normality-of-raw-residuals-if-raw-residuals-do-not-have-the-same-norma?rq=1
Answer: I would take a different approach from your other answers.
There are really 2 different sets of residuals:  The "true" residuals (epsilon's) from the "true" model: $y_i = \beta_0 + \beta_1 x_i + \epsilon_i$ and the observed residuals (the e's) from the computed model: $y_i = \hat\beta_0 + \hat\beta_1 x_i + e_i$.
The "true" residuals are the distance between the y-values and the "true", population, or theoretical model, what we would see if we had the entire population, an infinite sample size, or perfect knowledge of the true relationship.  These are parameters and in general are not ever observed, only estimated (like the betas).
The assumptions about independence, normality, equal variances (and any others) are about the "true" residuals, but since we do not have these values we use the observed residuals since they approximate the "true" residuals.  Tools like standardizing and studentizing the residuals are attempts to find better approximations of the "true" residuals.
Since Least squares regression is pretty robust to minor deviations from the assumptions, we really only care about major deviations (in the "true" residuals), which will also show up in the observed residuals, so they work well for the diagnostic purposes.  But we do not care about minor deviations because the assumptions are about the "true" residuals, not the observed ones.  Knowledge of the science behind the data is also needed to suggest the ways in which the assumptions may or may not hold.
Comment: This seems to just kick the answer down the line: *how* does one tell when the deviations will be "minor"?


2d Array containing objects

Question: This is an assignment for class that involves creating a hotel guest service. I created the 2d array below with 8 "floors", 20 "rooms", and populated them with Room objects. I am currently trying to use nested for-loops to go through each Room object and assign it a room number. For example, floor 1 would contain rooms 101-120.
The class below is a test class that I am using.
public class Test {

    public Test() {
    }

    public static void main(String[] args) {
        /**
          * Creates a two dimensional array with 8 rows and 20 columns
          */
        Room [][] hotelBuild = new Room[8][20];
        /**
          * populates the 2d array with Room objects
          */
        for (int floor=0; floor<hotelBuild.length; floor++) {
            for (int room=0; room<hotelBuild[floor].length; room++) {
                hotelBuild[floor][room] = new Room();
                /**
                 * used to print out contents of 2d array
                 */
                //System.out.print(hotelBuild[floor][room]=new Room());
            }
        }
    }
}

Below is class Room that contains the variables, setters, getters, as well as the toString() override method.
public class Room {

//Instance variables

    /**
     *the rooms number
     */
    private int roomNumber;

    /** is the room occupied or not
     *
     */
    private boolean isOccupied;

    /** name of guest
     *
     */
    private String guest;

    /** cost per day
     *
     */
    private double costPerDay;

    /** number of days guest is staying
     *
     */
    int days;

    //Constructors
    public Room(){
    }
    /** Construct a room with values above
     *
     */
    public Room(int room, boolean nonVacant, String guestName, double cost, int day) {
        roomNumber = room;
        isOccupied = nonVacant;
        guest = guestName;
        costPerDay = cost;
        days = day;
    }

    // getters

    /** gets roomNumber
     *
     */
    public int getRoomNumber(){
        return roomNumber;
    }

    /** gets isOccupied
     *
     */
    public boolean getIsOccupied(){
        return isOccupied;
    }

    /** gets guest
     *
     */
    public String getGuest(){
        return guest;
    }

    /** gets costPerDay
     *
     */
    public double getCostPerDay(){
        return costPerDay;
    }

    /** gets days
     *
     */
    public int getDays(){
        return days;
    }

    // setters

    /** sets isOccupied
     *
     */
    public void setIsOccupied(boolean full){
        this.isOccupied = full;
    }

    /** sets days
     *
     */
    public void setDays(int numDays){
        this.days = numDays;
    }

    /** sets guest name
     *
     */
    public void setGuest(String name){
        this.guest = name;
    }

    /** formats output depending if room is occupied or not
     *
     */

    public String toString(){
        if(isOccupied == true){
            return "Room number: " + roomNumber + "\n"+ "Guest name: "
                + guest + "\n"+ "Cost : " + costPerDay
                + "\n"+ "Days: " + days + "\n";
        }
        else{
            return "Room number " + roomNumber
                + " costs " + costPerDay + "\n";
        }
    }
}

How do I assign each Room object in the array a unique room number?
Comment: and your question is?
Comment: How do I assign each Room object in the array a unique room number?
Comment: Well you need a setter on room number if you only care about room number. If you specifically want the 1st floor to contain rooms 101-120 then you just have to calculate ((1+floor)*100)+1+room and set the value
Comment: If you want a way to put the numbers in the correct order then use auxiliar variables. Use a count for know what floor it is (it will be increased at the end of the first loop). Then room number is Floor * 100 + another variable you reset to 1 at the begining of the first loop.
Answer: You could do
for (int floor=0; floor<hotelBuild.length; floor++){
    for (int room=0; room<hotelBuild[floor].length; room++){
        Room r = new Room();
        r.setRoomNumber(
           cleverCalculationWithFloorAndRoomNr(floor, room));
        hotelBuild[floor][room]= r;

Answer: If you want a way to put the numbers in the correct order then use the varables you alredady have. Use a count for know what floor it is (it will be increased at the end of the first loop). Then room number is Floor * 100 + another variable you reset to 1 at the begining of the first loop. Just a hint to help you. Fill the gaps ;)
int floorNumber = 1;
int roomNumber = 1;
for (int floor=0; floor<hotelBuild.length; floor++){
        for (int room=0; room<hotelBuild[floor].length; room++){
            hotelBuild[floor][room]=new Room();

                            /**
                             * used to print out contents of 2d array
                             */
            //System.out.print(hotelBuild[floor][room]=new Room());
            //Add room number here.
            //Increase room number

        }
  //floorNumber increase
  //roomNumber reset
    }

Once you have achieved this you could try to use the variables you have in the loops (room and floor) with a few minor changes.
Answer: for (int floor=0; floor<hotelBuild.length; floor++){
    for (int room=0; room<hotelBuild[floor].length; room++){
        hotelBuild[floor][room]=new Room();
        // room number format: xxyy, x = floor, y = room
        // this assumes maximum 99 rooms per floor, it should be enough
        hotelBuild[floor][room].setNumber((floor + 1) * 100 + room + 1);
    }
}

Answer: You can pass it through the contructor for example or set with a setter in your class Room (classroom ahahah)
for example:
for (int floor=0; floor<hotelBuild.length; floor++){
        for (int room=0; room<hotelBuild[floor].length; room++){
            hotelBuild[floor][room]=new Room((floor+1)*100+room+1);
        }
    }

And in your Room class, you can add a constructor with only the room number as parameter
class Room{
  public Room(int roomNumber){
    this.roomNumber = roomNumber;
  }
...
}

Comment: class Room...classroom, I have sudden realization   8U

2d Array containing objects


Existe uma ferramenta para fazer manuais html de fácil atualização?

Question: Gostaria de saber se existe um ferramenta para fazer manuais tipo em HTML de fácil atualização e que desse pra customizar 100%.
Obrigado desde já!
Comment: Manuais da sua aplicação? Ou estás a criar manuais para qualquer produto? Se for a primeira opção, o [phpDocumentor](https://www.phpdoc.org) será teu amigo.
Answer: Além das opções informadas por Lacobus:  phpDocumentor ou o Doxygen ...  existem o ApiGen, o phpDox, o phpXRef, o PHPDoctor, o PHPSimpleDoc e outros.
O phpDocumentor possui templates.
O phpdox utiliza estilos CSS que facilitam a personalização.
Espero ter ajudado!
Answer: Além dos já citados doxygen e phpDocumentor.
Podemos incluir na lista:
Dexy
Apiary (pago)
Docco (coffeeScript)
Daux (muito bom)
Natural Docs
HelpNDoc
Espero ter ajudado.
Answer: Atualmente, existem novas propostas como o Doclets e o DAUX, ferramentas na nuvem que facilitam, e muito, a geração de manuais e documentação.
Answer: Que tal o phpDocumentor ou o doxygen ?
Comment: Vou dar uma olhada, vlw!
Answer: Aqui na empresa estamos usando o Gitbook, ótima ferramenta de manual, usando MARKDOWN, referências a páginas e arquivos externos funciona com versionamento.
Vale muito a pena.


JQuery slider doesn't interact with data drawn in vertical line with d3

Question: I am trying to get my data to interact with the jQuery slider.  My Data is represented with vertical lines in steelblue, but the jQuery slider only interacts with the lightgrey vertical lines xAxis since I set it up with the xAxis x.axis and its path. It only moves with slider, but not the actual vertical lines in steelblue.  I can't use d3 slider and I am stuck with this d3 v2.  I asked a question in regards to the vertical line: (How to interact JQuery slider with d3 vertical lines for every data point), but was recommended to ask a separate question to this slider issue :( Any input will help! Here is the code:

// define dimensions of graph
var m = [80, 80, 80, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 350 - m[0] - m[2]; // height

// create a simple data array that we'll plot with a line (this array represents only the Y values, X will just be the index location)
var data = [0];
for (var i = 1; i < 50; i++) {
  var sign = Math.random() > 0.5 ? +1 : -1;
  data.push(data[i - 1] + sign * Math.random());
}

// X scale will fit all values from data[] within pixels 0-w
var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
// Y scale will fit values from 0-10 within pixels h-0 (Note the inverted domain for the y-scale: bigger is up!)
var y = d3.scale.linear().domain([d3.min(data), d3.max(data)]).range([h, 0]);

// Add an SVG element with the desired dimensions and margin.
var graph = d3.select("#graph").append("svg:svg")
  .attr("width", w + m[1] + m[3])
  .attr("height", h + m[0] + m[2])
  .append("svg:g")
  .attr("transform", "translate(" + m[3] + "," + m[0] + ")");

// create yAxis
var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(3);
// Add the x-axis.
graph.append("svg:g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + h + ")")
  .call(xAxis);

// create left yAxis
var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
// Add the y-axis to the left
graph.append("svg:g")
  .attr("class", "y axis")
  .attr("transform", "translate(-25,0)")
  .call(yAxisLeft);

var circle = graph.selectAll("circle")
  .data(data);

circle.enter()
  .append("circle")
  .attr("cx", function(d, i) {
    return x(i)
  })
  .attr("cy", function(d) {
    return y(d)
  })
  .attr("class", "circle")
  .attr("r", 2)
  .attr("fill", "red");

var verticalLine = graph.selectAll(".vertical-line")
  .data(data);

verticalLine.enter()
  .append("line")
  .attr("x1", function(d, i) {
    return x(i)
  })
  .attr("x2", function(d, i) {
    return x(i)
  })
  .attr({
    y1: 0,
    y2: h,
    stroke: 'steelblue',
    class: 'vertical-line'
  });

function zoom(begin, end) {
  x.domain([begin, end - 1]);

  var t = graph.transition().duration(0);

  var size = end - begin;
  var step = size / 10;
  var ticks = [];
  for (var i = 0; i <= 10; i++) {
    ticks.push(Math.floor(begin + step * i));
  }

  xAxis.tickValues(ticks);

  t.select(".x.axis").call(xAxis);
  t.select('.path').attr("d", verticalLine);
}

$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 1000,
    values: [0, 1000],
    slide: function(event, ui) {
      var begin = d3.min([ui.values[0], data.length]);
      var end = d3.max([ui.values[1], 0]);
      console.log("begin:", begin, "end:", end);

      zoom(begin, end);
    }
  });
});
path {
  stroke: steelblue;
  stroke-width: 1;
  fill: none;
}

.axis {
  shape-rendering: crispEdges;
}

.x.axis line {
  stroke: lightgrey;
}

.x.axis .minor {
  stroke-opacity: .5;
}

.x.axis path {
  display: none;
}

.y.axis line,
.y.axis path {
  fill: none;
  stroke: #000;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />

Answer: I'd recommend using d3-brush, since it is essentially what you want, but built by the d3 team, for d3.
If you can't however, I've made it work below with your jQuery slider. You were fiddling with the axis ticks, but I recommend just redrawing the axis and letting d3 do that for you. Every tick I update the x.domain(), then call the draw() function to let the vertical lines and circles be redrawn` and redraw the x-axis. I've given all lines and circles outside the domain opacity 0 so they're hidden.

var m = [40, 80, 40, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 300 - m[0] - m[2]; // height

var data = [0];
for (var i = 1; i < 50; i++) {
  var sign = Math.random() > 0.5 ? +1 : -1;
  data.push(data[i - 1] + sign * Math.random());
}

var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
var y = d3.scale.linear().domain([d3.min(data), d3.max(data)]).range([h, 0]);

var graph = d3.select("#graph").append("svg:svg")
  .attr("width", w + m[1] + m[3])
  .attr("height", h + m[0] + m[2])
  .append("svg:g")
  .attr("transform", "translate(" + m[3] + "," + m[0] + ")");

var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(3);
var xAxisGroup = graph.append("svg:g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + h + ")");

var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
graph.append("svg:g")
  .attr("class", "y axis")
  .attr("transform", "translate(-25,0)")
  .call(yAxisLeft);

function draw() {
  var circle = graph.selectAll("circle")
    .data(data);

  circle.exit().remove();
  circle.enter()
    .append("circle");

  circle
    .attr("cx", function(d, i) {
      return x(i)
    })
    .attr("cy", function(d) {
      return y(d)
    })
    .attr("opacity", function(d, i) {
      return x.domain()[0] <= i && i <= x.domain()[1] ? 1 : 0;
    })
    .attr("class", "circle")
    .attr("r", 2)
    .attr("fill", "red");

  var verticalLine = graph.selectAll(".vertical-line")
    .data(data);

  verticalLine.exit().remove();
  verticalLine.enter()
    .append("line");

  verticalLine
    .attr("x1", function(d, i) {
      return x(i)
    })
    .attr("x2", function(d, i) {
      return x(i)
    })
    .attr("opacity", function(d, i) {
      return x.domain()[0] <= i && i <= x.domain()[1] ? 1 : 0;
    })
    .attr({
      y1: 0,
      y2: h,
      stroke: 'steelblue',
      class: 'vertical-line'
    });

  xAxisGroup.call(xAxis);
}

draw();

function zoom(begin, end) {
  x.domain([begin, end]);
  draw();
}

$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: data.length,
    values: [0, data.length],
    slide: function(event, ui) {
      var begin = d3.min([ui.values[0], data.length]);
      var end = d3.max([ui.values[1], 0]);
      zoom(begin, end);
    }
  });
});
path {
  stroke: steelblue;
  stroke-width: 1;
  fill: none;
}

.axis {
  shape-rendering: crispEdges;
}

.x.axis line {
  stroke: lightgrey;
}

.x.axis .minor {
  stroke-opacity: .5;
}

.x.axis path {
  display: none;
}

.y.axis line,
.y.axis path {
  fill: none;
  stroke: #000;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />

Comment: Ruben Helsloot, thank you again! this is a great solution! learning!


Why the change of the scrum verbal directions to "Crouch-Touch-Set"?

Question: Since I've watched Rugby in the late 90's, the referee's verbal directions for the scrum have been either:

Crouch-Pause-Engage

or for the last several years:

Crouch-Touch-Pause-Engage

I was watching the Six Nations games today, and the directions have changed to:

Crouch-Touch-Set

Unfortunately I live in a country where Rugby is not really watched.  Can someone explain to me why the directions have changed, and what the thinking is?
Comment: The Rugby Championship (Australia/New Zealand/South Africa/Argentina) just finished and they used a different set of commands again: crouch-bind-set. The players would bind together but not allowed to push until set. Seemed to keep the scrum from collapsing a bit better in the games I saw
Comment: @Greg - that sounds completely sensible, and kind of like the way that Rugby League scrums are set, but hopefully a bit more of the competition of a Union scrum.  I wonder whether the Six Nations will use it.
Comment: It was some of the best scrums I've seen in a while. Instead of being about the initial engagement it was about the ongoing pressure you could apply through the scrum. Also allowed the ref to make sure the ball was feed into the middle of the scrum
Answer: Law 20 of the International Rugby Board states the laws regarding the scrum, and 20.1 specifies the forming of the scrum. Amendment 21 to this section states the following:

CURRENT LAW
  20.1 Forming a scrum
(g)
The referee will call "crouch" then "touch". The front rows crouch
  and, using their outside arm, each prop touches the point of the
  opposing props outside shoulder. The props then withdraw their arms.
  The referee will then call "pause". Following a pause the referee will
  then call "engage". The front rows may then engage. The "engage" call
  is not a command but an indication that the front rows may come
  together when ready.
AMENDED LAW
  20.1 Forming a scrum
(g)
The referee will call "crouch" then "touch". The front rows crouch
  and, using their outside arm, each prop touches the point of the
  opposing prop's outside shoulder. The props then withdraw their arms.
  Following a pause the referee will then call "set" when the front rows
  are ready. The front rows may then engage. The "set" call is not a
  command but an indication that the front rows may come together when
  ready.

While the official page for the amendment does not have any information as to why this change was made, the wikipedia article on scrum claims that the change was to speed up the scrum:

"Pause" has been removed in order to speed up the scrum and to
  minimize resets due to collapsed scrums.

I found another article on "The Australian" which claims that the change in directions during scrum is one of the changes on trial basis for 2013, and that
the motivation was to decrease the risk of injuries as well as speeding up the game. The article features opinions from several professionals as well, good read.
Answer: The reason set replaces engage is because engage is a very awkward word to use. It has two syllables, and worse, the stressed syllable is the second one. The effect is like saying "ready, set,  g-Go" in a running race. Because scrummaging is time critical to a matter of milliseconds, a single syllable word is much more efficient.
Comment: This is a very good point. I had not considered that, particularly in pro games where as you say milliseconds count.
Comment: Additionally the teams used to go on the 1st syllable of the engage meaning that there was a potential timing issue.  So by bringing it to a single syllable its easier.   The words matter less as senior players tend to go on the 3rd sound from the referee rather than what it is.  Hence when standing a scrum up you always blow your whistle
Answer: Before 2013 the sequence was "crouch, touch, pause, engage". Typically that meant each team's pack would form up about a foot apart and hold back until the the referee said "engage", at which point the two packs would smash into each other. In the professional game the impact at "engage" kept getting bigger and bigger - the talk was of winning "the hit" - and it resulted in a lot of collapsed scrums and injuries.
Since 2013 the sequence has been "crouch, bind, set". The two front rows bind together before the scrum starts and the two packs start pushing against each other. The point is to reduce the impact by eliminating "the hit", making the scrum safer and more stable.


Completeness, Sufficiency and MLE of size n random samples of a joint distribution

Question: Let $(X_1, Y_1), (X_2, Y_2), \dots , (X_n, Y_n)$ be a random sample of size $n$ from the continuous distribution with joint pdf $f_{X, Y}(x, y|\theta) = \frac{1}{\theta y}e^{-\frac{x}{\theta y}}I(x)_{(0,\infty)}I(y)_{(0, 1)}I(\theta)_{(0,\infty)}$.
(1) Find a complete and sufficient statistic for $\theta$.
(2) Find the maximum likelihood estimator for $\theta$.
(3) Find the maximum likelihood estimator for $P(X < Y )$.
(4) Let $V = \frac{X}{\theta}$ and $W = Y$. Show the joint distribution of (V;W) does not depend on $\theta$.
(5) Define the statistic $S((X_1, Y_1), \dots,  (X_n, Y_n)) = \frac{\sum^n_{i=1}X_iY_i}{\sum^n_{j=1}X_j}$.
 Show that $S((X_1, Y_1), \dots,  (X_n, Y_n))$ is an ancillary statistic for the model $f_{X, Y}(x, y|\theta)$, taking note that I cannot claim I have a scale parameter family when I have a joint distribution. Thus, to show that S is ancillary, one has to show that its distribution does not depend on $\theta$.
For (1), I am showing sufficient by using Factorization Theorem, but I am having a bit of trouble with the completeness.
For (2), I think I am getting the wrong information trying to take the partial with respect to x and y and setting them equal to $0$ and then trying to find the determinant greater than $0$
For (3), (4) and (5) I am very confused on where to even begin.
Any assistance is greatly appreciated.
Comment: https://math.stackexchange.com/questions/299863/sufficient-statistics-and-maximum-likelihood?noredirect=1&lq=1
Answer: I believe for Part (1), you can just show that it's an exponential family, and then by the exponential family theorem, then the $\sum\limits_{i=1}^nt_{1}(X)$ is your complete and sufficient statistic.
For your part (2), you have to take the natural log of your likelihood function, and take the partial with respect to your parameter, then solve for your parameter, and that is your MLE of $\theta$. You should get $\frac{1}{n}*\sum\limits_{i=1}^n\frac{X_{i}}{Y_{i}}$
For part (3), you have to find a g($\theta$) = $Pr(X<Y)$, More complete answer here
For part (4), do a transformation, by taking your $g^{-1}(x)$ and your $g^{-1}(y)$ and plugging what you get into the original pdf and taking the determinant of the Jacobian matrix (which is just $\theta$), and cancelling, and you get a pdf of V's and W's that is free of $\theta$.
For part (5), see the link above for a more concise and complete response for your part (5).


Authorizing Client Acces to App Engine Backend

Question: I have a simple Google App Engine backend (written in Python) for an Android client. All the backend is responsible for is accepting a key and returning a value; it is a classifier in general, implemented simply by looking up the key in a Cloud SQL table, though this specific behavior will change in the future.
The backend and client communicate via Google Cloud Endpoints. I want to restrict access to my backend's API to only accept requests incoming from my client, and am wondering if OAuth 2.0 is really the way to do this.
I don't need any contextual or extra information from the user, and as such, don't want to have user action to grant any type of authorization. All I need to do is be certain the request came from my app. I was considering simply generating a static key and hardcoding it in my client and backend, but I thought there must be a more elegant way to do this.
TL;DR: How can I restrict access to my backend only to my client/app without needing user context/input, by OAuth 2.0 or otherwise?
Comment: Found a good explanation of this [here](http://stackoverflow.com/questions/21825175/how-do-i-restrict-google-app-engine-endpoints-api-access-to-only-my-android-appl?lq=1)
Answer: I don't know if the OP solved their problem but I am posting this here for others. I have wasted quite a few hours on this particular issue.
Steps :
1.Create an oAuth 2.0 client ID for your Android client.
2.Specify the Client IDs in the allowed_client_ids argument of the endpoints.api. In this case (Android), supply both its Android client ID and a web client ID in allowed_client_ids.
3.Supply the audiences argument as well in endpoints.api which is set to the web client ID.
4.Add a user check to the protected methods.
5.Redeploy the API backend.
6.Regenerate the client libraries.


Angular - Array chamando apenas primeiro item

Question: Estou tentando fazer um calculo de um Array para exibir o valor total ao adicionar um item ao meu carrinho.
Meu array está assim: Utilizo o Status para informar na view que o item foi adicionado ao carrinho.
public pastelData = [{
  name: 'Pastel de Calabresa',
  price: 7.50,
  status: 'false', }]

Dessa forma ao clicar eu executo o service que altera o Status para adicionado ao carrinho e também captura o preço.
addItems(pastelData) {
    this.sharedSerivce.setItemData(pastelData);
    pastelData.status = 'Adicionado';
    this.getPricePastel(this.pastelData);
}

Eu criei a seguinte função para pegar os preços dos pasteis:
getPricePastel(pastelData) {
    for (const index in pastelData) {
    }

    for (let i = 0; i < pastelData.length; i++) {
        console.log(pastelData[i].price);

        this.total += (pastelData[i].price);
        console.log(this.total);
        this.nextPastel.next(this.pastelData);
        return;
    }
}

Ela se comporta da seguinte forma:  SE eu deixo o return no final, ele pega em todas as chamadas de addItems apenas o primeiro preço. SE eu removo o return, todas as chamadas pegam o total dos price[]. E assim, não consigo chamar o preço equivalente ao item que o usuário adiciona ao carrinho
É um projeto para fins de estudos;
Comment: Ficou confusa sua pergunta, vc tem um array de objetos que possui uma propriedade com preços e quer saber o total dos preços é isso?
Comment: desculpe não ter sido muito claro.    Isso mesmo, porém, eu quero saber o total com base nos itens que eu chamei, e não o total de todos.

Por exemplo:

Meu array tem a seguinte composição:   [ A, preço:1  B, preço:2 C, preço:3]

Eu não quero chamar todos ao mesmo tempo. Porém, da forma que fiz ele chama somente o primeiro. Eu não estou conseguindo acessar as outras posições dele. Pois criei um carrinho, dentro dele tenho a função "add itens" que chama meu produto, valor etc.. porém ao somar o total não estou conseguindo chama certinho
Comment: está te retornando o primeiro por que há um `return`  no `for`. Com isso a primeira interação é finalizada. entenda sobre [Laços e iterações](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Loops_and_iteration)
Answer: Sobre o tal problema em for, há return assim na primeira interação ao chegar nele é finalizado a execução desse método.

sobre Laços e iterações

Pelo o que entendi, imagino que terá uma lista de pasteis pastelDataList no qual o usuário vai selecionando e assim o valor de cada vão sendo somados total. Bem, o código está confuso em entender para aprofundar melhor, porém vamos exatamente na dúvida sobre a variável total.
simplesmente você pode usar o forEach, exemplo:
interface pastelData {
  name: string;
  price: number;
  status: string;
}

//nomenclatura mudaria para setPricePastel
getPricePastel(pastelDataList: pastelData[]) {
  this.total = 0; //zerar
  this.pastelData.forEach((data)=>{
     this.total += data.price;
  })
  this.nextPastel.next(this.pastelData);
}

Answer: Você está parando o laço de repetição no primeiro índice já que tem um return isso para a execução do for.
Após remover o return calculará o valor total, poderia fazer o for assim:
let valorTotal: number = 0;
for (let i = 0; i < pastelData.length; i++) {
    console.log(pastelData[i].price);
    valorTotal += (pastelData[i].price);
    this.nextPastel.next(this.pastelData);
}
console.log(valorTotal)//Apenas para mostrar o valor a ser retornado
return valorTotal;


Lottery game with replacement

Question: A state lottery game is played by selecting three numbers between $0$ and $9$, inclusive, with replacement. The winning numbers are selected in the same way. You win if your numbers match the winning numbers in any order.
Find the total number of ways the winning numbers can be selected.
How is the answer not $10^3=1000$ different ways?
Comment: To me it sounds as if the question is just asking 'how many ways can the same three numbers be chosen?' Which would be six.
Comment: @cluelessatthis apparently the answer is 220...
Answer: A hint as to why the answer is not $10^3=1000$.
Suppose I pick $1,2,3$ as my numbers.
If the drawn numbers are $1,2,3$, I win.
If the drawn numbers are $1,3,2$, I win.
If the drawn numbers are $2,1,3$, I win.
If the drawn numbers are...
Edit: A calculation.
Of the $1000$ ordered draws:
$720$ contain three distinct numbers. (Example: $1,2,3$)
$270$ contain two numbers the same. (Example: $1,1,2$)
$10$ contain three numbers the same. (Example: $1,1,1$)
But for each category we need to eliminate equivalent draws:$$\frac{720}{6}+\frac{270}{3}+\frac{10}{1}=120+90+10=220.$$
Comment: @cluelessatthis Yes. The point is that these $6$ draws are equivalent so you count them only as $1$.
Comment: Right, so there are 6 ways to match the winning numbers. OP, however, is suggesting that the correct answer is 220.
Comment: right, I understand what you're suggesting now.
Comment: @nickgard I see how if the winning numbers are 1,2,3, then I have 6 ways to choose winning numbers, but my prof is telling me the answer is 220 and with the wording of this question (verbatim), I dont understand how.

Lottery game with replacement


AudioPlay Give error

Question: I am using below code to play audio file.
But it gives me error.
01-05 11:35:05.793: W/System.err(1739): java.lang.IllegalStateException
01-05 11:35:05.793: W/System.err(1739):     at android.media.MediaPlayer.prepare(Native Method)
01-05 11:35:05.793: W/System.err(1739):     at com.android.halfivrs.MyAudioControl.startAudio(MyAudioControl.java:22)
01-05 11:35:05.793: W/System.err(1739):     at com.android.halfivrs.HalfIVRSActivity.onCreate(HalfIVRSActivity.java:13)
01-05 11:35:05.793: W/System.err(1739):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-05 11:35:05.793: W/System.err(1739):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
01-05 11:35:05.793: W/System.err(1739):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
01-05 11:35:05.793: W/System.err(1739):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
01-05 11:35:05.793: W/System.err(1739):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
01-05 11:35:05.793: W/System.err(1739):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 11:35:05.793: W/System.err(1739):     at android.os.Looper.loop(Looper.java:123)
01-05 11:35:05.793: W/System.err(1739):     at android.app.ActivityThread.main(ActivityThread.java:4363)
01-05 11:35:05.793: W/System.err(1739):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 11:35:05.793: W/System.err(1739):     at java.lang.reflect.Method.invoke(Method.java:521)
01-05 11:35:05.793: W/System.err(1739):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-05 11:35:05.793: W/System.err(1739):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-05 11:35:05.793: W/System.err(1739):     at dalvik.system.NativeStart.main(Native Method)

Here is my Code.
public class MyAudioControl {

    private Context mContext;

    public MyAudioControl(Context con) {
        this.mContext = con;
    }

    private MediaPlayer player;

    public void startAudio() {
        try {
            player = MediaPlayer.create(mContext, R.raw.tabla);
            player.setLooping(false); // Set looping
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopAudio() {
        try {
            player.stop();
            player.reset();
            player.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Does any one has idea what's wrong with above code?
Thank You.
Answer: try this code :
public void startAudio() {
        player = MediaPlayer.create(ScaleTestActivity.this, R.raw.test30fps);
        player.setLooping(false); // Set looping
        player.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                // TODO Auto-generated method stub
                player.start();
            }
        });
}

hope useful to you...
Comment: check file you put on raw folder is it play on other player,because i am able to play .mp3 file like this way.
Comment: @Nirav, i think that there must be an error in your log if you can't play the file.
Answer:             player = MediaPlayer.create(this, R.raw.robotrock);
            player.setLooping(false); // Set looping

            playerButton = (Button) this.findViewById(R.id.play);

            playerButton.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                         player.start();

                    }
                });

AudioPlay Give error


Asynchronous Webscraping with beautiful soup, grequests

Question: I am trying to webscrape some information from a list of urls, and would like to do it asynchronously to save time. I am able to get the information I would like when I do so synchronously, and the relevant part of that code is essentially this:
links = [...] #list of links

for link in links:

   source_race = requests.get(link).text
   soup_race = BeautifulSoup(source_race,'lxml')

   contestant_names = []
   for contestants in soup_race.find_all('div',attrs={'data-automation-id':'racecard-outcome-name'}):
      contestant_names.append(contestants.text.replace('\xa0',' '))

This returns me a list of contestent names, which is exactly what I want.
Now when I try to do this asynchronously, I am testing it in a preliminary stage using the print fucntion, like so:
reqs = (grequests.get(link) for link in links)
resp = grequests.map(reqs)

for r in resp:
   soup = BeautifulSoup(r.text, 'lxml')
   results = soup.find_all('div',attrs={'data-automation-id':'racecard-outcome-name'})
   print(results)

but I am not getting the text items, I am simply getting an entire list of all of those specifics  on that page. The output looks like (I could not capture the entire output, but it is a long list, containing all of the information I want, but I am unable to pull out the specific text items I want, which I have circled, which are just names and a number in brackets):

when I try to put print(results.text), I am presented with the following error:

when I change my above code to find instead of find_all, and use print(results.text) I get exactly as I would expect (and would like), which is:

I just need a way to have all the runner names printed out.
I am brand new to asynchronous webscraping (and webscraping in general), so I am sorry if any of this is unclear.
Comment: You need to use asyncio for this.
Comment: Thanks for this. I did some research on this and have gotten it to work.
Comment: Unfortunately, I have gotten myself temporarily banned from accessing the website due to the quick fire nature of the requests.

It seems I will need to rotate through a bunch of IP addresses to solve this problem. would something like:

`conn = aiohttp.TCPConnector(local_addr=('127.0.0.1', 0), loop=loop)`
`async with aiohttp.ClientSession(connector=conn) as session:`

(obviously with a list of randomly chosen IP addresses) be the right path to take?
Comment: @TNoms did you try it out and what was the outcome?
Answer: You can use multiprocessing 10 links executed asynchronous.
My pseudo code:
from multiprocessing import Pool

def scrape(url):
   source_race = requests.get(url).text
   soup_race = BeautifulSoup(source_race,'lxml')

   contestant_names = []
   for contestants in soup_race.find_all('div',attrs={'data-automation-id':'racecard-outcome-name'}):
      contestant_names.append(contestants.text.replace('\xa0',' '))

links = []
p = Pool(10)
p.map(scrape, links)
p.terminate()
p.join()


How to auto unpublish a node after edit and later published by admin?

Question: I need to unpublish my node after edit. For this I created a rule. It's doing the unpublish of my node after editing. But after this I am not able to again publish this node.
I also need to fire a mail to admin after update.
Comment: What should happen when a brand node is created? Should your scenario also apply in that case?
Answer: Here's how you can do this:

Create a rule on node update event.
Add Condition where user role is not "Administrator/Moderator". (This will make sure that the content doesn't get unpublish when admin is updating it.)
If required, Add condition where content is of type "Article".
Add Action "Unpublish content" under node section and save.
Add another action "Send Mail" under System. Add required details to send email and save.

Above steps will unpublish content and notify site admin using email. After which site admin can navigate to "Admin => Content", review the content and approve. If you need to provide a custom/different UI, you can create a list using views and VBO module and allow site admin to Approve Content.
Comment: I set by default node unpublished for all user..
Comment: how to set this condition from rules Add Condition where user role is not "Administrator/Moderator ..
Comment: Under add action, select "User has role(s)", then in User Data selector set value as "**site:current-user**", select role as "**Administrator**", select Matching role as "**Any**" and lastly select **Negate** checkbox and click on save.
Answer: Your rule is firing for both node edits so you need to add conditions to your rules to check for the published status.
So for your unpublish rule, add a condition that the node is currently published.
The email to admin can be sent using a rules action.
Comment: not getting which event I need to select.. currently I am using After updating existing content of type Property event
Comment: Add a data comparison condition for the unupdated node's published field. Make it equal "published". The rule will only fire if that is true.
Answer: It will be better if you use  Work bench access module  .It provides various functionality and control over node publish.


How to count NULLS in one columns corresponding to every unique element in another column through MYSQL query?

Question: I have two columns in MYSQL table - something like this:
Col. 1   |  Col. 2
value1   |  yes
value1   |  yes
value2   |  NULL
value2   |  NULL
value3   |  yes
value3   |  NULL
value4   |  yes
value5   |  NULL

I want to find how many unique values in column 1 have atleast one NULL in column 2.
So, in this case the final answer would be 3 (value2, value3 and value5). There are no NULLS corresponding to value1 and value4.
Is there a way to write MYSQL query for something like this?
Answer: You can use count(distinct):
select count(distinct col1)
from t
where col2 is null;

Answer: Use COUNT(DISTINCT expr,[expr...])
SELECT COUNT(DISTINCT Col1)
  FROM MyTable
 WHERE Col2 IS NULL

Answer: you can use subquery
select * from table where col1 in (
 select col1  From table where col2 = null)


Object detection when two objects overlap

Question: I'm working on a project that needs to detect two different objects in a video. The idea is that when one object is on top of the other object, the system will trigger a controller to do something.
I'm using colors for detection, but I've no idea how to trigger the controller when two objects overlap, since then the system will not be able to detect the object underneath.
Does anyone have any idea or experience on this kind of stuff in computer vision? Thanks.
Edit:
https://www.youtube.com/watch?v=nvvaegox7PQ
I've attached a video here. The algorithm/method in the video is exactly what I expected. When objects overlap, vision system know there are two objects there.
Comment: Better add an image or code or something we can do something about.
Comment: @I.Newton Sorry for the confusion. I've added a video.
Answer: The general rule for this type of situation is that people won't disappear all of a sudden. So, if there is a group of pixels showing two people with an overlap, you can assume that they both are there, and calculate the groups of pixels that correspond to different persons. You can get a better idea of this kind of approaches from research papers on human tracking in video. I have seen one paper that use Gaussian mixture models to model people, and that works well.
Of course, these systems can be fooled. If they had a door at the place where the persons overlapped and one person slipped out from the back, the system won't detect that.
Comment: Thanks for the comment, I will look into that!


using jsonData as a key value to send mixed data in asp: Does not update the database with the values

Question: After trying to mix a fileupload and json data in postman i finally found a method where it is possible to send them both in the same request. Therefore, I have moved my json data to a Key in Postman, so that it becomes possible to send files as well using form-data (Picture below).

Within the value I have JSON data as following:
{
   "WorkshopEmail":"workshopemail",
   "WorkshopContactperson":"workshopcontactperson",
   "WorkshopCellphone":"workshopcellphone",
   "Service":[
      {
         "service":"Claim Airbag",
         "RequestTypeId":"1",
         "DamageDate":"2021-05-03",
         "DamageKilometerreading":"213",
         "LatestServiceDate":"2021-05-03",
         "LatestServiceKilometer":"1223",
         "WorkshopDiagnos":"diagnos workshop",
         "CarOwnerDescription":"carownerdescription",
         "CategoryId":"25",
         "works":[
            {
               "title":"arbete 1 airbag",
               "chargePerHour":"11",
               "hours":"12",
               "price":"132.00",
               "id":"13926"
            },
            {
               "title":"arbete2 airbag",
               "chargePerHour":"1",
               "hours":"2",
               "price":"2.00",
               "id":"13927"
            },
            {
               "title":"part1 airbag",
               "pricePerUnit":"100",
               "quantity":"1",
               "price":"100.00",
               "id":"13928"
            },
            {
               "title":"part2 airbag",
               "pricePerUnit":"100",
               "quantity":"2",
               "price":"200.00",
               "id":"13929"
            }
         ]
      },
      {},
      {},
      {},
      {},
      {}
   ]
}

The empty {} just contains more service types. Now when I send the request in Postman i get a 200 OK and when i debug i can see the following (sorry if the picture is blurry):

¨
However, my database does not get updated with these values. Here's the class for inserting data into the tables:
public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
    bool CreateRequest = true;
    int requestID = 0;
    int claimID = 0;
    //bool country = true;

    //First Create the Request
    foreach (Service item in model.Service)
    {
        //First Create the Request
        if (CreateRequest)
        {

            var parameters = new DynamicParameters();
            parameters.Add("WorkshopEmail", model.WorkshopEmail);
            parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
            parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
            parameters.Add("DamageDate", model.DamageDate);
            parameters.Add("LatestServiceDate", model.LatestServiceDate);
            parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
            parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
            parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
            parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
            parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
            parameters.Add("AmountIncVat", model.AmountIncVat);

            try
            {
            var requestIDenum = await _sqlconnection.QueryAsync<int>($@"INSERT INTO [dbo].[Request]
                                                    (WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
                                                     LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
                                                     CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
                                                    VALUES
                                                    (@WorkshopEmail,@WorkshopContactperson,@WorkshopCellphone,@DamageDate,@LatestServiceDate,
                                                     @LatestServiceKilometer,@DamageKilometerreading,@CurrentKilometerreading,
                                                     @CarOwnerDescription,@WorkshopDiagnos,@AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
            requestID = requestIDenum.First();
            CreateRequest = false;

            }
            catch(Exception ex)
            {

                int hej = 0;
            }
        }

        if (item.fileuploadresults != null)
        {
            foreach (FileUploadResult f in item.fileuploadresults)
            {
                var parameters = new DynamicParameters();

                parameters.Add("file", f.filename);

                var filemessage = await _sqlconnection.QueryAsync<int>($@"INSERT INTO [dbo].[OptionalFile] ([FileName])
                                                  VALUES (@file); SELECT SCOPE_IDENTITY();", parameters);

                int FileMessageID = filemessage.First();

                await _sqlconnection.QueryAsync<int>($@"INSERT INTO[dbo].[ClaimCrossOptionalFile]
                                                    (ClaimID,FileID)
                                                    VALUES
                                                    ({claimID},{FileMessageID});");
            }
        }

    return true;
    //return list;
}

Controller:
 [HttpPost]
        public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
        {
            // if (!ModelState.IsValid)
            // {

            Request request = JsonConvert.DeserializeObject<Request>(jsonData);

            try
            {
                //await _request.AddRequest(request);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

            return Ok();
        }

Interface:
Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);

Sidenote: This is part of the code, as i've tried to keep it short, so perhaps some } or something is missing here, but there's no problem. If i should add the whole code i could perhaps send it in a link or something similar, as it would be a lot to upload here.
However, I do not now how to proceed with this issue at the moment. I've not worked with form-data much before, at least not with passing json as a value. Perhaps there's something I'm missing/have to do in the controller with the json data? I've tried looking for solutions but I've gotten stuck here. The only issue is that the database does not get updated.
Update, the model:
 public class Work
    {
        //base for claim
        public string title { get; set; } = "";
        public string chargePerHour { get; set; } = "";
        public string hours { get; set; } = "";
        public string price { get; set; } = "";
        public string id { get; set; } = "";
        public string pricePerUnit { get; set; } = "";
        public string quantity { get; set; } = "";

        //service
        public int rentreasonId { get; set; } = -1;
        public int rentservicecartypeId { get; set; } = -1;

        //tyres
        public int tireserviceId { get; set; } = -1;

        public IList<TireType> tireTypes { get; set; }
        public IList<Labour> labours { get; set; }

        public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
        public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");

        //Insurance
        public string totalAmount { get; set; }
        public string requestInsuranceVatID { get; set; }
        public string vat { get; set; } = "0.0";
        public string totalExclVat { get; set; }="0.0";
        public string totalIncVat { get; set; }="0.0";

    }

    public class Labour
    {
        public string title { get; set; } = "";
        public string chargePerHour { get; set; } = "";
        public string hours { get; set; } = "";

        public string price { get; set; } = "";
    }

    public class TireType
    {
        public string quantity { get; set; } = "";
        public string brand { get; set; } = "";
        public string model { get; set; } = "";

        public string pricePerUnit { get; set; } = "";
        public string price { get; set; } = "";

        public string tireTypeId { get; set; } = "";

        public string widthID { get; set; } = "";

        public string heightID { get; set; } = "";

        public string diameterID { get; set; } = "";
    }

    public class Request
    {
        public string WorkshopEmail { get; set; } = "";

        public string WorkshopContactperson { get; set; } = "";

        public string WorkshopCellphone { get; set; } = "";

        public int AmountIncVat { get; set; } = 0;

        #region Claim
        public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");

        public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");

        public int LatestServiceKilometer { get; set; } = 0;

        public int DamageKilometerreading { get; set; } = 0;

        public int CurrentKilometerreading { get; set; } = 0;

        public string CarOwnerDescription { get; set; } = "";

        public string WorkshopDiagnos { get; set; } = "";

        //public string OptionalMessage { get; set; } = "";

        #endregion
        public IList<Service> Service { get; set; }

    }

    public class TireTread
    {
        public string tireserviceId { get; set; } = "";
        public string leftfront { get; set; } = "";
        public string rightfront { get; set; } = "";
        public string leftrear { get; set; } = "";
        public string rightrear { get; set; } = "";
        public string added1 { get; set; } = "";
        public string added2 { get; set; } = "";
        public string added3 { get; set; } = "";
        public string added4 { get; set; } = "";
        public string added5 { get; set; } = "";
    }

    public class TireMessage
    {
        public int tireserviceId { get; set; }
        public string message { get; set; }
    }

    public class Service
    {
     //   [JsonProperty("ServiceId")]
        public string RequestTypeId { get; set; } = "";
        public string CategoryId { get; set; } = "-1";

        public string OptionalMessage { get; set; } = "";

        public IList<Work> works { get; set; }
        public IList<TireTread> treads { get; set; }

        public IList<TireMessage> TireMessages { get; set; }

        //filuppladdning
        public IList<FileUploadResult> fileuploadresults { get; set; }
    }

    //filuppladdning
    public class FileUploadResult
    {
        //public IFormFile files { get; set; }

        public string filename { get; set; }
    }

Comment: Maybe provide the code for your RequestModel (I would advise to think about a different name, that is pretty generic). Also what value has the Service property when you debug?
Comment: @Sascha i updated.  When i debug i can see the entire json request passed as a value
Comment: When you debug,do `Request model` and `parameters` have value?
Comment: Why do you not use the RequestModel as type in your ASP.NET Core method?
Comment: @YiyiYou no, i can only see the json string..
Comment: @Sascha when  i add Request Model in the AddRequest method in the controller, i get a 415: unsupported media type when i run it in postman...
Answer: Firstly,the json format does not match the model structure.You need to pass json like this(Pay attention to DamageKilometerreading and LatestServiceKilometer,the type of them are int,so don't use ""):
{
   "WorkshopEmail":"workshopemail",
   "WorkshopContactperson":"workshopcontactperson",
   "WorkshopCellphone":"workshopcellphone",
   "DamageDate":"2021-05-03",
   "DamageKilometerreading":213,
   "LatestServiceDate":"2021-05-03",
   "LatestServiceKilometer":1223,
   "WorkshopDiagnos":"diagnos workshop",
   "CarOwnerDescription":"carownerdescription",
   "Service":[
      {
         "service":"Claim Airbag",
         "RequestTypeId":"1",
         "CategoryId":"25",
         "works":[
            {
               "title":"arbete 1 airbag",
               "chargePerHour":"11",
               "hours":"12",
               "price":"132.00",
               "id":"13926"
            },
            {
               "title":"arbete2 airbag",
               "chargePerHour":"1",
               "hours":"2",
               "price":"2.00",
               "id":"13927"
            },
            {
               "title":"part1 airbag",
               "pricePerUnit":"100",
               "quantity":"1",
               "price":"100.00",
               "id":"13928"
            },
            {
               "title":"part2 airbag",
               "pricePerUnit":"100",
               "quantity":"2",
               "price":"200.00",
               "id":"13929"
            }
         ]
      },
      {},
      {},
      {},
      {},
      {}
   ]
}

Then try to add public string service { get; set; }="" inService model.
Answer: I found a solution, in case anyone else comes across this problem. I needed to modify the controller and add this code:
 [HttpPost]
        public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
        {
            Request request = JsonConvert.DeserializeObject<Request>(jsonData);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                await _request.AddRequest(request, file, jsonData);

            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

            return Ok();
        }

Basically adding request (that I deserialize in the begining of the method), and adding the file, and jsonData in an await request, solved the problem. As for the fileuploading, I needed to modify that method as well, to get the filename into the database:
if (file != null)
                {

                    foreach (IFormFile f in file)
                    {
                        string filename = Path.GetFileName(f.FileName);
                        var parameters = new DynamicParameters();
                        parameters.Add("file", filename);

                        var filemessage = await _sqlconnection.QueryAsync<int>($@"INSERT INTO
                        [dbo].[OptionalFile] ([FileName])
                        VALUES (@file); SELECT SCOPE_IDENTITY();", parameters);

                    }

                }

Changing these to made it possible to send a request containg both the json key value, and multiple files, in the same request.


rotate text vertically in pentaho report 5.4 version

Question: I am using pentaho report designer. I want to rotate text by 90 degree in label.How to do that if any body knows please help me out.
Answer: There is a property called rotation in style section where you can specify the rotation between -90 to 90 based on your requirement.
Comment: but this property is not available in pantaho 5.4 version .Is there any other way to achive this?