What's the difference between using $this->t('text') and t('text') in a block plugin

Question: I've noticed in many tutorials for constructing block plugins,
$this->t('text')

is used to create translatable text, especially in the block form function. However using
t('text')

doesn't produce any errors. Is there any difference between using either of these? And if there isn't, what's best practice?
Comment: see also https://drupal.stackexchange.com/questions/224665/best-practice-this-t-versus-t
Answer: To be exact on your question: there's no difference in internal implementation.
But as a best practice, you should be using $this->t instead of the global t wherever possible. If you check the function, t is returning a new TranslateableMarkup object.
If your class says $this->t is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

Using this trait will add t() and formatPlural() methods to the class.
  These must be used for every translatable string, similar to how
  procedural code must use the global functions t() and
  \Drupal::translation()->formatPlural(). This allows string extractor
  tools to find translatable strings.
If the class is capable of injecting services from the container, it
  should inject the 'string_translation' service and assign it to
  $this->stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).
Answer: The documentation for t() states:

When possible, use the \Drupal\Core\StringTranslation\StringTranslationTrait::t(). Otherwise create a new \Drupal\Core\StringTranslation\TranslatableMarkup object directly.

It doesn't explain the reason for this, but if you look at the comment on the documentation page, it will give you a reason for using that trait method, or that class.

Classes can be tested individually with PHPUnit, which runs without bootstrapping core, but the t() function is only available when core is bootstrapped.
  Using $this->t() and StringTranslationTrait allows the translation to be mocked, so the class can be tested in isolation with PHPUnit.


Android : How to set content while calling a new activity?

Question: I'm new at Android development, and I would like to know something.
I know that, if I want to go to another activity I have to do :
Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
startActivity(intent);

But if my AnotherActivity contains for example a String or any variable, that I want to set before reaching it, how to do ? I would like to do something like :
AnotherActivity activity = new AnotherActivity();
activity.setValue("myValue");
// call the activity ?

Thanks for your help.
Answer: Intent intent = new Intent(getContext(), AnotherActivity.class);
intent.putExtra("extra_name", "extra_value");
startActivity(intent);

Then in AnotherActivity:
String extra_value = getIntent().getStringExtra("extra_name", "default_extra_value");


Analysing Repeated Measures RCT study. emmeans / lsmeans estimate and back-transform problems. Approach doubts

Question: Background
I am writing a project on a big multicenter RCT study, where subjects are following different dietary patterns for 2 years. I have access to their dietary intakes and I am grouping them in quartiles of protein intake.
My aim is to test whether there are any differences in effects on outcomes (continuous variables like body weight, blood parameters, etc.) between these groups.
My Approach
My approach has been to fit the full model with lme() e.g.
modWeight <- lme(wght~protein_quan*factor(week)+w0+energy_kj+age+gen+eth+smoking_status+medication+baecke_mean+alcohol,
                    random=~1|site/subject_id,method="ML",
                    corr = corExp(form = ~ week | site/subject_id, nugget=T),
                    data_wght, na.action=na.exclude)

Where:
 - protein_quan is a factor of the protein intake quartile groups
 - factor(week) is a factor of the weeks,  w0 is a continuous covariate of baseline weight
 - energy_kj is a continuous covariate of energy intake
 - age is a continuous covariate of subject age
 - gen is a factor of the subject sex group
 - eth is a factor of the subject ethnic group
 - smoking_status is a factor of the smoking status
 - medication is a factor of medication intake
 - baecke_mean is a continuos covariate of Physical Activity
I then proceed to reduce the fitted model to the most until I reach the one that is parsimonious following these steps:

Test if the model can be reduced to the continuous variable of week (time) with anova(modContinuous,modFactor)i
Analyse distribution of model, transform response if necessary (log(),sqrt(), or boxcox)
Test to see if I can reduce for serial correlation (none vs corGaus / corExp)
Reduce the random effects
Reduce the fixed effects
Final model:

``
modfitWeight <-lme(wght_cox~protein_quan+factor(week)+w0+fd_energy_kj+smoking_status,
                    random=~1|subject_id,method="REML",
                    corr = corGaus(form = ~ week | subject_id, nugget=T),
                    data=data_wght_trans,na.action=na.exclude)

Where the response variable has been transformed with boxcox.
Find my data here.
I plot the mean fitted response variables grouped by protein group and week, with ggplot:
data_wght_cmplt_trans_kgbwxenergy %>%
  mutate(pred_wght = (lambda_wght*fitted(modfitWeight)+1)^(1/lambda_wght)) %>%
  group_by(week,protein_quan)%>%
  mutate(pred_w0=pred_wght[week==min(week)],
         pred_wght_mean=mean(pred_wght),
         pred_wght_mean_upper = mean(pred_wght) + qnorm(0.975) * (sd(pred_wght) / sqrt(sum(!is.na(pred_wght)))),
         pred_wght_mean_lower = mean(pred_wght) - qnorm(0.975) * (sd(pred_wght) / sqrt(sum(!is.na(pred_wght)))),
         pred_wght_mean_w0=mean(pred_wght-pred_w0)) %>%
  ungroup() %>%
  ggplot(aes(x = week, y=pred_wght_mean,color=protein_quan)) +
  geom_line(size = 1) +
  geom_errorbar(aes(ymin = pred_wght_mean_lower, ymax = pred_wght_mean_upper)) +
  theme_pubr()

To analyse if there are any significant differences between the protein intake groups or between different weeks, I first take a look at the summary of the model:
summary(modfitWeight)

Linear mixed-effects model fit by REML
 Data: data_wght_cmplt_trans_kgbwxenergy
       AIC      BIC   logLik
  191.4532 270.5222 -74.7266

Random effects:
 Formula: ~1 | subject_id
         (Intercept)  Residual
StdDev: 0.0002939717 0.7757884

Correlation Structure: Gaussian spatial correlation
 Formula: ~week | subject_id
 Parameter estimate(s):
      range      nugget
44.71884151  0.03657875
Fixed effects: wght_cox ~ protein_quan + factor(week) + w0 + smoking_status
                              Value Std.Error  DF   t-value p-value
(Intercept)                9.869963 0.8066643 297 12.235527  0.0000
protein_quan2             -0.508055 0.2880310  22 -1.763891  0.0916
protein_quan3             -0.707052 0.3104516  22 -2.277495  0.0328
protein_quan4             -0.690427 0.3041147  22 -2.270286  0.0333
factor(week)10            -0.044499 0.0406847 297 -1.093748  0.2750
factor(week)12            -0.122841 0.0436181 297 -2.816294  0.0052
factor(week)16            -0.214534 0.0536375 297 -3.999701  0.0001
factor(week)20            -0.259108 0.0667081 297 -3.884200  0.0001
factor(week)26            -0.431458 0.0881326 297 -4.895552  0.0000
factor(week)32            -0.322749 0.1092590 297 -2.953982  0.0034
factor(week)44            -0.260876 0.1460344 297 -1.786400  0.0751
factor(week)52            -0.341910 0.1651032 297 -2.070888  0.0392
factor(week)64            -0.149894 0.1853560 297 -0.808681  0.4193
factor(week)78            -0.064264 0.1985349 297 -0.323689  0.7464
factor(week)104            0.125741 0.2063403 297  0.609386  0.5427
w0                         0.111063 0.0082458  22 13.469155  0.0000
smoking_statusDaily       -1.434396 0.5635267  22 -2.545392  0.0184

The average subject weight for week 8 (baseline) and protein group 1 is 96.4:
data_wght %>%
    mutate(pred_wght = (lambda_wght*fitted(modfitWeight)+1)^(1/lambda_wght)) %>%
    filter(week==8,fd_protein_quan_kgbw_adj=="1") %>%
    mutate(mean_weight_group=mean(pred_wght)) %>%
    dplyr::select(week, fd_protein_quan_kgbw_adj, mean_weight_group)

# A tibble: 7 x 3
   week protein_quan      mean_weight_group
  <dbl> <fct>             <dbl>
1     8 1                 96.4

By back transforming the boxcox response I get an adjusted response for week 8 and protein group 1 of:
> (lambda_cmplt_wght_kgbwxenergy*(9.869963+96.4*0.111063)+1)^(1/lambda_cmplt_wght_kgbwxenergy)
[1] 98.44476

Now I want to compare contrasts and see if there are any significant differences in my modelled groups. I try with emmeans and get a summary of my back-transformed boxcox means:
emmeans.wght <- emmeans(modfitWeight, ~ protein_quan|week )
emmeans.wght_cox <- update(emmeans.wght,tran=make.tran("boxcox", lambda_wght))
summary(emmeans.wght_cox, type="response")

 protein_quan = 1:
 week    response       SE df lower.CL upper.CL
 8       82.83042 2.740448 22 77.23589 88.60220
 10      82.49940 2.735465 22 76.91523 88.26088
 12      81.91808 2.726686 22 76.35218 87.66141
 16      81.24007 2.716405 22 75.69556 86.96215
 20      80.91140 2.711404 22 75.37730 86.62314
 26      79.64627 2.692051 22 74.15243 85.31800
 32      80.44319 2.704261 22 74.92395 86.14016
 44      80.89838 2.711206 22 75.36469 86.60971
 52      80.30246 2.702110 22 74.78770 85.99499
 64      81.71778 2.723654 22 76.15819 87.45484
 78      82.35256 2.733251 22 76.77301 88.10947
 104     83.76905 2.754521 22 78.14524 89.56993

 protein_quan = 2:
 week    response       SE df lower.CL upper.CL
 8       79.08692 2.629174 22 73.71996 84.62475
 10      78.76279 2.624271 22 73.40603 84.29048
 12      78.19361 2.615633 22 72.85483 83.70345
 16      77.52983 2.605517 22 72.21209 83.01875
 20      77.20808 2.600597 22 71.90058 82.68683
 26      75.96972 2.581553 22 70.70184 81.40910
 32      76.74975 2.593568 22 71.45687 82.21397
 44      77.19533 2.600401 22 71.88823 82.67368
 52      76.61200 2.591451 22 71.32352 82.07184
 64      77.99751 2.612650 22 72.66493 83.50118
 78      78.61902 2.622092 22 73.26679 84.14221
 104     80.00608 2.643020 22 74.61032 85.57254

 protein_quan = 3:
 week    response       SE df lower.CL upper.CL
 8       77.64213 2.198794 22 73.14308 82.26291
 10      77.32071 2.194652 22 72.83028 81.93292
 12      76.75630 2.187355 22 72.28104 81.35342
 16      76.09810 2.178809 22 71.64062 80.67755
 20      75.77907 2.174653 22 71.33023 80.34992
 26      74.55123 2.158565 22 70.13584 79.08880
 32      75.32462 2.168715 22 70.88813 79.88319
 44      75.76643 2.174488 22 71.31793 80.33693
 52      75.18804 2.166927 22 70.75526 79.74291
 64      76.56184 2.184835 22 72.09183 81.15375
 78      77.17814 2.192811 22 72.69153 81.78654
 104     78.55365 2.210490 22 74.03028 83.19862

 protein_quan = 4:
 week    response       SE df lower.CL upper.CL
 8       77.76236 2.631738 22 72.39172 83.30713
 10      77.44072 2.626784 22 72.08038 82.97524
 12      76.87591 2.618058 22 71.53373 82.39240
 16      76.21725 2.607838 22 70.89633 81.71261
 20      75.89799 2.602867 22 70.58742 81.38307
 26      74.66927 2.583628 22 69.39873 80.11458
 32      75.44321 2.595767 22 70.14742 80.91362
 44      75.88534 2.602670 22 70.57518 81.37002
 52      75.30653 2.593628 22 70.01519 80.77252
 64      76.68132 2.615044 22 71.34541 82.19157
 78      77.29805 2.624583 22 71.94229 82.82803
 104     78.67452 2.645725 22 73.27478 84.24821

Results are averaged over the levels of: smoking_status
Degrees-of-freedom method: containment
Confidence level used: 0.95
Intervals are back-transformed from the Box-Cox (lambda = 0.545) scale

And by plotting the estimates with emmip:
emmip(emmeans.wght_cox, fd_protein_quan_kgbw_adj ~ week,CIs=TRUE)+theme_pubr()

I see that the emmeans estimates have the same trends, but are not in complete alignment in, respect to the estimate sizes, with the lme summary output, and the confidence interval bars are also different. This is when i cried my first tear
Then I tried the pairs function to see if there are any significant differences:
    protein_quan = 1:
 contrast     estimate         SE  df t.ratio p.value
 8 - 10    0.044498835 0.04068474 297   1.094  0.9948
 8 - 12    0.122841338 0.04361807 297   2.816  0.1786
 8 - 16    0.214534083 0.05363752 297   4.000  0.0045
 8 - 20    0.259107766 0.06670815 297   3.884  0.0070
 8 - 26    0.431457663 0.08813258 297   4.896  0.0001
 8 - 32    0.322749062 0.10925899 297   2.954  0.1279
 8 - 44    0.260875844 0.14603437 297   1.786  0.8243
 8 - 52    0.341910138 0.16510318 297   2.071  0.6439
 8 - 64    0.149893859 0.18535605 297   0.809  0.9997
 8 - 78    0.064263508 0.19853493 297   0.324  1.0000
 8 - 104  -0.125740959 0.20634035 297  -0.609  1.0000
 10 - 12   0.078342504 0.04068474 297   1.926  0.7423
 10 - 16   0.170035249 0.04807703 297   3.537  0.0234
 10 - 20   0.214608932 0.05993849 297   3.580  0.0202
 10 - 26   0.386958829 0.08092640 297   4.782  0.0002
 10 - 32   0.278250227 0.10235049 297   2.719  0.2224
 10 - 44   0.216377009 0.14055285 297   1.539  0.9283
 10 - 52   0.297411304 0.16076764 297   1.850  0.7887
 10 - 64   0.105395024 0.18262804 297   0.577  1.0000
 10 - 78   0.019764674 0.19719872 297   0.100  1.0000
 10 - 104 -0.170239794 0.20613091 297  -0.826  0.9996
 12 - 16   0.091692745 0.04361807 297   2.102  0.6216
 12 - 20   0.136266428 0.05363752 297   2.541  0.3192
 12 - 26   0.308616325 0.07375087 297   4.185  0.0022
 12 - 32   0.199907724 0.09529330 297   2.098  0.6248
 12 - 44   0.138034505 0.13479517 297   1.024  0.9971
 12 - 52   0.219068800 0.15614450 297   1.403  0.9623
 12 - 64   0.027052521 0.17965340 297   0.151  1.0000
 12 - 78  -0.058577830 0.19570155 297  -0.299  1.0000
 12 - 104 -0.248582297 0.20588322 297  -1.207  0.9881
 16 - 20   0.044573683 0.04361807 297   1.022  0.9971
 16 - 26   0.216923580 0.05993849 297   3.619  0.0177
 16 - 32   0.108214978 0.08092640 297   1.337  0.9735
 16 - 44   0.046341760 0.12249476 297   0.378  1.0000
 16 - 52   0.127376055 0.14603437 297   0.872  0.9993
 16 - 64  -0.064640225 0.17292481 297  -0.374  1.0000
 16 - 78  -0.150270575 0.19217335 297  -0.782  0.9998
 16 - 104 -0.340275043 0.20524946 297  -1.658  0.8855
 20 - 26   0.172349897 0.04807703 297   3.585  0.0199
 20 - 32   0.063641296 0.06670815 297   0.954  0.9984
 20 - 44   0.001768077 0.10925899 297   0.016  1.0000
 20 - 52   0.082802372 0.13479517 297   0.614  1.0000
 20 - 64  -0.109213908 0.16510318 297  -0.661  1.0000
 20 - 78  -0.194844258 0.18784840 297  -1.037  0.9967
 20 - 104 -0.384848725 0.20438557 297  -1.883  0.7690
 26 - 32  -0.108708602 0.04807703 297  -2.261  0.5068
 26 - 44  -0.170581820 0.08813258 297  -1.936  0.7359
 26 - 52  -0.089547525 0.11598318 297  -0.772  0.9998
 26 - 64  -0.281563805 0.15123292 297  -1.862  0.7817
 26 - 78  -0.367194155 0.17965340 297  -2.044  0.6629
 26 - 104 -0.557198623 0.20251567 297  -2.751  0.2069
 32 - 44  -0.061873218 0.06670815 297  -0.928  0.9988
 32 - 52   0.019161077 0.09529330 297   0.201  1.0000
 32 - 64  -0.172855203 0.13479517 297  -1.282  0.9808
 32 - 78  -0.258485554 0.16915399 297  -1.528  0.9317
 32 - 104 -0.448490021 0.19972270 297  -2.246  0.5180
 44 - 52   0.081034295 0.05363752 297   1.511  0.9367
 44 - 64  -0.110981985 0.09529330 297  -1.165  0.9911
 44 - 78  -0.196612335 0.14055285 297  -1.399  0.9631
 44 - 104 -0.386616803 0.19011677 297  -2.034  0.6701
 52 - 64  -0.192016280 0.06670815 297  -2.878  0.1542
 52 - 78  -0.277646630 0.11598318 297  -2.394  0.4135
 52 - 104 -0.467651098 0.17965340 297  -2.603  0.2828
 64 - 78  -0.085630351 0.07375087 297  -1.161  0.9914
 64 - 104 -0.275634818 0.15614450 297  -1.765  0.8354
 78 - 104 -0.190004467 0.11598318 297  -1.638  0.8935

fd_protein_quan_kgbw_adj = 2:
 contrast     estimate         SE  df t.ratio p.value
 8 - 10    0.044498835 0.04068474 297   1.094  0.9948
 8 - 12    0.122841338 0.04361807 297   2.816  0.1786
 8 - 16    0.214534083 0.05363752 297   4.000  0.0045
 8 - 20    0.259107766 0.06670815 297   3.884  0.0070
 8 - 26    0.431457663 0.08813258 297   4.896  0.0001
 8 - 32    0.322749062 0.10925899 297   2.954  0.1279
 8 - 44    0.260875844 0.14603437 297   1.786  0.8243
 8 - 52    0.341910138 0.16510318 297   2.071  0.6439
 8 - 64    0.149893859 0.18535605 297   0.809  0.9997
 8 - 78    0.064263508 0.19853493 297   0.324  1.0000
 8 - 104  -0.125740959 0.20634035 297  -0.609  1.0000
 10 - 12   0.078342504 0.04068474 297   1.926  0.7423
 10 - 16   0.170035249 0.04807703 297   3.537  0.0234
 10 - 20   0.214608932 0.05993849 297   3.580  0.0202
 10 - 26   0.386958829 0.08092640 297   4.782  0.0002
 10 - 32   0.278250227 0.10235049 297   2.719  0.2224
 10 - 44   0.216377009 0.14055285 297   1.539  0.9283
 10 - 52   0.297411304 0.16076764 297   1.850  0.7887
 10 - 64   0.105395024 0.18262804 297   0.577  1.0000
 10 - 78   0.019764674 0.19719872 297   0.100  1.0000
 10 - 104 -0.170239794 0.20613091 297  -0.826  0.9996
 12 - 16   0.091692745 0.04361807 297   2.102  0.6216
 12 - 20   0.136266428 0.05363752 297   2.541  0.3192
 12 - 26   0.308616325 0.07375087 297   4.185  0.0022
 12 - 32   0.199907724 0.09529330 297   2.098  0.6248
 12 - 44   0.138034505 0.13479517 297   1.024  0.9971
 12 - 52   0.219068800 0.15614450 297   1.403  0.9623
 12 - 64   0.027052521 0.17965340 297   0.151  1.0000
 12 - 78  -0.058577830 0.19570155 297  -0.299  1.0000
 12 - 104 -0.248582297 0.20588322 297  -1.207  0.9881
 16 - 20   0.044573683 0.04361807 297   1.022  0.9971
 16 - 26   0.216923580 0.05993849 297   3.619  0.0177
 16 - 32   0.108214978 0.08092640 297   1.337  0.9735
 16 - 44   0.046341760 0.12249476 297   0.378  1.0000
 16 - 52   0.127376055 0.14603437 297   0.872  0.9993
 16 - 64  -0.064640225 0.17292481 297  -0.374  1.0000
 16 - 78  -0.150270575 0.19217335 297  -0.782  0.9998
 16 - 104 -0.340275043 0.20524946 297  -1.658  0.8855
 20 - 26   0.172349897 0.04807703 297   3.585  0.0199
 20 - 32   0.063641296 0.06670815 297   0.954  0.9984
 20 - 44   0.001768077 0.10925899 297   0.016  1.0000
 20 - 52   0.082802372 0.13479517 297   0.614  1.0000
 20 - 64  -0.109213908 0.16510318 297  -0.661  1.0000
 20 - 78  -0.194844258 0.18784840 297  -1.037  0.9967
 20 - 104 -0.384848725 0.20438557 297  -1.883  0.7690
 26 - 32  -0.108708602 0.04807703 297  -2.261  0.5068
 26 - 44  -0.170581820 0.08813258 297  -1.936  0.7359
 26 - 52  -0.089547525 0.11598318 297  -0.772  0.9998
 26 - 64  -0.281563805 0.15123292 297  -1.862  0.7817
 26 - 78  -0.367194155 0.17965340 297  -2.044  0.6629
 26 - 104 -0.557198623 0.20251567 297  -2.751  0.2069
 32 - 44  -0.061873218 0.06670815 297  -0.928  0.9988
 32 - 52   0.019161077 0.09529330 297   0.201  1.0000
 32 - 64  -0.172855203 0.13479517 297  -1.282  0.9808
 32 - 78  -0.258485554 0.16915399 297  -1.528  0.9317
 32 - 104 -0.448490021 0.19972270 297  -2.246  0.5180
 44 - 52   0.081034295 0.05363752 297   1.511  0.9367
 44 - 64  -0.110981985 0.09529330 297  -1.165  0.9911
 44 - 78  -0.196612335 0.14055285 297  -1.399  0.9631
 44 - 104 -0.386616803 0.19011677 297  -2.034  0.6701
 52 - 64  -0.192016280 0.06670815 297  -2.878  0.1542
 52 - 78  -0.277646630 0.11598318 297  -2.394  0.4135
 52 - 104 -0.467651098 0.17965340 297  -2.603  0.2828
 64 - 78  -0.085630351 0.07375087 297  -1.161  0.9914
 64 - 104 -0.275634818 0.15614450 297  -1.765  0.8354
 78 - 104 -0.190004467 0.11598318 297  -1.638  0.8935

fd_protein_quan_kgbw_adj = 3:
 contrast     estimate         SE  df t.ratio p.value
 8 - 10    0.044498835 0.04068474 297   1.094  0.9948
 8 - 12    0.122841338 0.04361807 297   2.816  0.1786
 8 - 16    0.214534083 0.05363752 297   4.000  0.0045
 8 - 20    0.259107766 0.06670815 297   3.884  0.0070
 8 - 26    0.431457663 0.08813258 297   4.896  0.0001
 8 - 32    0.322749062 0.10925899 297   2.954  0.1279
 8 - 44    0.260875844 0.14603437 297   1.786  0.8243
 8 - 52    0.341910138 0.16510318 297   2.071  0.6439
 8 - 64    0.149893859 0.18535605 297   0.809  0.9997
 8 - 78    0.064263508 0.19853493 297   0.324  1.0000
 8 - 104  -0.125740959 0.20634035 297  -0.609  1.0000
 10 - 12   0.078342504 0.04068474 297   1.926  0.7423
 10 - 16   0.170035249 0.04807703 297   3.537  0.0234
 10 - 20   0.214608932 0.05993849 297   3.580  0.0202
 10 - 26   0.386958829 0.08092640 297   4.782  0.0002
 10 - 32   0.278250227 0.10235049 297   2.719  0.2224
 10 - 44   0.216377009 0.14055285 297   1.539  0.9283
 10 - 52   0.297411304 0.16076764 297   1.850  0.7887
 10 - 64   0.105395024 0.18262804 297   0.577  1.0000
 10 - 78   0.019764674 0.19719872 297   0.100  1.0000
 10 - 104 -0.170239794 0.20613091 297  -0.826  0.9996
 12 - 16   0.091692745 0.04361807 297   2.102  0.6216
 12 - 20   0.136266428 0.05363752 297   2.541  0.3192
 12 - 26   0.308616325 0.07375087 297   4.185  0.0022
 12 - 32   0.199907724 0.09529330 297   2.098  0.6248
 12 - 44   0.138034505 0.13479517 297   1.024  0.9971
 12 - 52   0.219068800 0.15614450 297   1.403  0.9623
 12 - 64   0.027052521 0.17965340 297   0.151  1.0000
 12 - 78  -0.058577830 0.19570155 297  -0.299  1.0000
 12 - 104 -0.248582297 0.20588322 297  -1.207  0.9881
 16 - 20   0.044573683 0.04361807 297   1.022  0.9971
 16 - 26   0.216923580 0.05993849 297   3.619  0.0177
 16 - 32   0.108214978 0.08092640 297   1.337  0.9735
 16 - 44   0.046341760 0.12249476 297   0.378  1.0000
 16 - 52   0.127376055 0.14603437 297   0.872  0.9993
 16 - 64  -0.064640225 0.17292481 297  -0.374  1.0000
 16 - 78  -0.150270575 0.19217335 297  -0.782  0.9998
 16 - 104 -0.340275043 0.20524946 297  -1.658  0.8855
 20 - 26   0.172349897 0.04807703 297   3.585  0.0199
 20 - 32   0.063641296 0.06670815 297   0.954  0.9984
 20 - 44   0.001768077 0.10925899 297   0.016  1.0000
 20 - 52   0.082802372 0.13479517 297   0.614  1.0000
 20 - 64  -0.109213908 0.16510318 297  -0.661  1.0000
 20 - 78  -0.194844258 0.18784840 297  -1.037  0.9967
 20 - 104 -0.384848725 0.20438557 297  -1.883  0.7690
 26 - 32  -0.108708602 0.04807703 297  -2.261  0.5068
 26 - 44  -0.170581820 0.08813258 297  -1.936  0.7359
 26 - 52  -0.089547525 0.11598318 297  -0.772  0.9998
 26 - 64  -0.281563805 0.15123292 297  -1.862  0.7817
 26 - 78  -0.367194155 0.17965340 297  -2.044  0.6629
 26 - 104 -0.557198623 0.20251567 297  -2.751  0.2069
 32 - 44  -0.061873218 0.06670815 297  -0.928  0.9988
 32 - 52   0.019161077 0.09529330 297   0.201  1.0000
 32 - 64  -0.172855203 0.13479517 297  -1.282  0.9808
 32 - 78  -0.258485554 0.16915399 297  -1.528  0.9317
 32 - 104 -0.448490021 0.19972270 297  -2.246  0.5180
 44 - 52   0.081034295 0.05363752 297   1.511  0.9367
 44 - 64  -0.110981985 0.09529330 297  -1.165  0.9911
 44 - 78  -0.196612335 0.14055285 297  -1.399  0.9631
 44 - 104 -0.386616803 0.19011677 297  -2.034  0.6701
 52 - 64  -0.192016280 0.06670815 297  -2.878  0.1542
 52 - 78  -0.277646630 0.11598318 297  -2.394  0.4135
 52 - 104 -0.467651098 0.17965340 297  -2.603  0.2828
 64 - 78  -0.085630351 0.07375087 297  -1.161  0.9914
 64 - 104 -0.275634818 0.15614450 297  -1.765  0.8354
 78 - 104 -0.190004467 0.11598318 297  -1.638  0.8935

fd_protein_quan_kgbw_adj = 4:
 contrast     estimate         SE  df t.ratio p.value
 8 - 10    0.044498835 0.04068474 297   1.094  0.9948
 8 - 12    0.122841338 0.04361807 297   2.816  0.1786
 8 - 16    0.214534083 0.05363752 297   4.000  0.0045
 8 - 20    0.259107766 0.06670815 297   3.884  0.0070
 8 - 26    0.431457663 0.08813258 297   4.896  0.0001
 8 - 32    0.322749062 0.10925899 297   2.954  0.1279
 8 - 44    0.260875844 0.14603437 297   1.786  0.8243
 8 - 52    0.341910138 0.16510318 297   2.071  0.6439
 8 - 64    0.149893859 0.18535605 297   0.809  0.9997
 8 - 78    0.064263508 0.19853493 297   0.324  1.0000
 8 - 104  -0.125740959 0.20634035 297  -0.609  1.0000
 10 - 12   0.078342504 0.04068474 297   1.926  0.7423
 10 - 16   0.170035249 0.04807703 297   3.537  0.0234
 10 - 20   0.214608932 0.05993849 297   3.580  0.0202
 10 - 26   0.386958829 0.08092640 297   4.782  0.0002
 10 - 32   0.278250227 0.10235049 297   2.719  0.2224
 10 - 44   0.216377009 0.14055285 297   1.539  0.9283
 10 - 52   0.297411304 0.16076764 297   1.850  0.7887
 10 - 64   0.105395024 0.18262804 297   0.577  1.0000
 10 - 78   0.019764674 0.19719872 297   0.100  1.0000
 10 - 104 -0.170239794 0.20613091 297  -0.826  0.9996
 12 - 16   0.091692745 0.04361807 297   2.102  0.6216
 12 - 20   0.136266428 0.05363752 297   2.541  0.3192
 12 - 26   0.308616325 0.07375087 297   4.185  0.0022
 12 - 32   0.199907724 0.09529330 297   2.098  0.6248
 12 - 44   0.138034505 0.13479517 297   1.024  0.9971
 12 - 52   0.219068800 0.15614450 297   1.403  0.9623
 12 - 64   0.027052521 0.17965340 297   0.151  1.0000
 12 - 78  -0.058577830 0.19570155 297  -0.299  1.0000
 12 - 104 -0.248582297 0.20588322 297  -1.207  0.9881
 16 - 20   0.044573683 0.04361807 297   1.022  0.9971
 16 - 26   0.216923580 0.05993849 297   3.619  0.0177
 16 - 32   0.108214978 0.08092640 297   1.337  0.9735
 16 - 44   0.046341760 0.12249476 297   0.378  1.0000
 16 - 52   0.127376055 0.14603437 297   0.872  0.9993
 16 - 64  -0.064640225 0.17292481 297  -0.374  1.0000
 16 - 78  -0.150270575 0.19217335 297  -0.782  0.9998
 16 - 104 -0.340275043 0.20524946 297  -1.658  0.8855
 20 - 26   0.172349897 0.04807703 297   3.585  0.0199
 20 - 32   0.063641296 0.06670815 297   0.954  0.9984
 20 - 44   0.001768077 0.10925899 297   0.016  1.0000
 20 - 52   0.082802372 0.13479517 297   0.614  1.0000
 20 - 64  -0.109213908 0.16510318 297  -0.661  1.0000
 20 - 78  -0.194844258 0.18784840 297  -1.037  0.9967
 20 - 104 -0.384848725 0.20438557 297  -1.883  0.7690
 26 - 32  -0.108708602 0.04807703 297  -2.261  0.5068
 26 - 44  -0.170581820 0.08813258 297  -1.936  0.7359
 26 - 52  -0.089547525 0.11598318 297  -0.772  0.9998
 26 - 64  -0.281563805 0.15123292 297  -1.862  0.7817
 26 - 78  -0.367194155 0.17965340 297  -2.044  0.6629
 26 - 104 -0.557198623 0.20251567 297  -2.751  0.2069
 32 - 44  -0.061873218 0.06670815 297  -0.928  0.9988
 32 - 52   0.019161077 0.09529330 297   0.201  1.0000
 32 - 64  -0.172855203 0.13479517 297  -1.282  0.9808
 32 - 78  -0.258485554 0.16915399 297  -1.528  0.9317
 32 - 104 -0.448490021 0.19972270 297  -2.246  0.5180
 44 - 52   0.081034295 0.05363752 297   1.511  0.9367
 44 - 64  -0.110981985 0.09529330 297  -1.165  0.9911
 44 - 78  -0.196612335 0.14055285 297  -1.399  0.9631
 44 - 104 -0.386616803 0.19011677 297  -2.034  0.6701
 52 - 64  -0.192016280 0.06670815 297  -2.878  0.1542
 52 - 78  -0.277646630 0.11598318 297  -2.394  0.4135
 52 - 104 -0.467651098 0.17965340 297  -2.603  0.2828
 64 - 78  -0.085630351 0.07375087 297  -1.161  0.9914
 64 - 104 -0.275634818 0.15614450 297  -1.765  0.8354
 78 - 104 -0.190004467 0.11598318 297  -1.638  0.8935

Results are averaged over the levels of: smoking_status
P value adjustment: tukey method for comparing a family of 12 estimates

And I see that the backtransformation is gone in the pairwise comparison. I cried another tear
Ideally, I would like to compare the weekly contrasts by the different protein quartile groups, say, compare if contrast week8 - week104 for  protein intake group 1 is significantly different thant contrast week8 - week104 for  protein intake group 4. This would be equivalent to testing the change score between groups.
Help
Now I'm stuck looking at all this, not being able to extract the estimates, se's, sd's, and confidence intervals that I need(?).
So I was thinking, do I really need to go through all this to answer my question? Or would a simple t-test between change scores for each group suffice?
For some of my outcomes, the protein quartile groups show no effect in the model reduction phase, and therefore gets excluded from the parsimonious statistical model. Should I not reduce the model this far, for the sole purpose of being able to extract estimates (although non-significant) from my statistical model that I can report in my paper?
Since my paper is due in the near future, I need to use the approach that makes most sense to answer my questions efficiently.
So should I stick to the emmeans approach (or something similar that works), or should I simply do a two tailed t-test of unadjusted change scores to get my estimates and test sizes?
If I should stick with emmeans, what do I need to do to get the emmeans summary output to reflect the same estimates as the lme summary output. And how do I get the back-transformations to work for the pairs() function? And is there a way to test change scores (post-pre or week104-week8) between the protein groups with the emmeans package as well?
Answer: A couple of things regarding emmeans: First, the model you fitted is additive (no interaction terms). This means that there's not much sense in breaking the per-week means down by protein -- especially in doing comparisons. Note that the t statistics and P values for each comparison of weeks are identical with each protein; and that is why. If you do think that the comparisons should be different, then the interaction should be in the model. If you found the interaction was unnecessary in the model, you can just compare weeks marginally.
Second, it helps to understand the order in which things happen. The type = "response" option is an option for the summary() method; it is applied after all the statistics are compiled, just before the summaries are displayed. So with the transformation present, the pairwise comparisons are computed first, and the transformed scale upon which the EMMs lie has no natural counterpart for comparisons among them; that is why the transformation is discarded. If you want differences of back-transformed EMMs, that is possible; the method is to create a new reference grid that is on the transformed scale. This is done using regrid():
 new.emms <- regrid(emmeans.wght_cox)   # transforms everything
 pairs(new.emms)

See the vignette on transformations for details and examples.


Adding vertical text into existing pdf

Question: I am trying to modify an existing pdf, adding datas into it using FPDI and FPDF. So far everything is fine. The only thing I am stuck at is inserting vertical text into the pdf.
Tried searching online, but non of the codes really worked.
if($x==-1)
    $x=$this->x;
if($y==-1)
    $y=$this->y;
if($this->angle!=0)
    $this->_out('Q');
$this->angle=$angle;
if($angle!=0)

{
    $angle*=M_PI/180;
    $c=cos($angle);
    $s=sin($angle);
    $cx=$x*$this->k;
    $cy=($this->h-$y)*$this->k;

I tried this, but this doesnt work together with FPDI, i.e I can generate new pdfs with verical or angled texts. But what I am trying to do is to insert vertical text into the already exisitng pdf. Unfortunately, FPDF doesnt allow to set source file. FPDI does, but this code isnt working together with FPDI somehow.
Answer: The quoted code is extracted from this extension. The extension will work with FPDI as with FPDF by changing its extending class name as described here.
So the extension class definition will become e.g.:
class PDF_Rotate extends FPDI
{
    ...
}

And you can still use the methods of FPDI:
$pdf = new PDF_Rotate();
$pdf->AddPage();
$pageCount = $pdf->setSourceFile("template.pdf");
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->Rotate(100, 60, 90);
$pdf->Text(100, 60, 'Hello!');
$pdf->Rotate(0);
$pdf->Output();

Adding vertical text into existing pdf


Alternative for conditional subquery in Oracle 11g

Question: I'm getting more and more experienced with oracle pl/sql but this problem seems to be persistent: I have a procedure that merges external data into a table in the database that looks something like this:
PROCEDURE updateTable (ts DATE, val NUMBER, id NUMBER)
BEGIN
  IF id NOT IN (15, 16, 23)
  THEN
    MERGE INTO myTable dest
    USING (SELECT ts, val, id FROM Dual) src
    ON (src.id = dest.id AND src.ts = dest.ts)
    WHEN MATCHED THEN UPDATE SET dest.val = src.val
    WHEN NOT MATCHED THEN INSERT (ts, val, id) VALUES (src.ts, src.val, src.id);
  END IF;
END;

This works just fine so far. Now the problem is that the list of id's that are excluded is hardcoded and it would be much more dynamic to have those in another table, i.e. in the code above replace the line
IF id NOT IN (15, 16, 23)

with something like
IF id NOT IN (SELECT id FROM excluTable)

which returns the notorious error: PLS_00405: subquery not allowed in this context
If it was only one id, I could simply create a variable and select the id into it. Unfortunately it's quite a long list. I've tried to bulk collect them into an array but then I don't find a way to put that into the conditional clause either. I'm sure there is an elegant solution for this.
Thanks for your help!
Answer: There may be many IDs in your exclusion table, but you are only passing one into the procedure. You can see if that single value exists in the table with a count into a local variable, and then check whether the count was zero or non-zero; something like:
PROCEDURE updateTable (ts DATE, val NUMBER, id NUMBER) IS
  l_excl_id PLS_INTEGER;
BEGIN
  SELECT count(*)
  INTO l_excl_id
  FROM excluTable
  WHERE excluTable.id = updateTable.id;

  IF l_excl_id = 0
  THEN
    MERGE INTO myTable dest
    USING (SELECT ts, val, id FROM Dual) src
    ON (src.id = dest.id AND src.ts = dest.ts)
    WHEN MATCHED THEN UPDATE SET dest.val = src.val
    WHEN NOT MATCHED THEN INSERT (ts, val, id) VALUES (src.ts, src.val, src.id);
  END IF;
END;

Incidentally, it can get confusing if your procedure argument names are the same as table column names, or other identifiers. For instance, as id is the procedure argument name and the column name in the table I've had to prefix them both:
  WHERE excluTable.id = updateTable.id;

one with the table name (or alias if you add one), the other with the procedure name. If you just did
  WHERE excluTable.id = id

then the scoping rules would mean it matched every ID in the table with itself, not the argument, so you would be counting all rows - and it might not be immediately obvious why it wasn't behaving as you expected. If the arguments were named as, say, p_ts and p_id then you wouldn't have to account for that ambiguity. That's also why I've prefixed my local flag variable with l_.
Comment: Thank you Sir! That was very quick. You're right and the arguments are actually called `p_ts` and `p_id` and so on. I've just stumbled over another approach that uses an array of id's. Then `IF p_id NOT MEMBER OF idArray THEN` does the job as well.
Comment: Yes, but you're selecting more data than you need and having all that data in memory, in your array. Looking for a specific ID should be faster (at least if it's indexed).


How can I sent an activation link to my registered user in Laravel?

Question: I'm trying to sent an activation link to my registered user.

Here is my postRegister() function
public function postRegister(){

    $validator = Validator::make( Input::all(), array(
      'name'           => 'required|min:2|max:20',
      'email'          =>'required|max:50|email|unique:users',
      'username'       =>'required|max:20|min:3|unique:users',
      ));

    if ($validator->fails()) {
      return Redirect::to('/')
      ->with('error_register','Something Wrong')
      ->withErrors($validator)
      ->withInput();
    }

    $user = new User;
    $user->name = Input::get('name');
    $user->username = Input::get('username');
    $user->email = Input::get('email');
    $user->code = str_random(60);
    $user->password = '';
    $user->active = 0;
    $user->type = 'Aveniros';

    $user->save();

    // Email
    Mail::send('emails.activation', array(

      'username'=>$user->username,
      'name'=>$user->name,
      'code'=>$user->code,
      'email'=>$user->email

      ),
    function($message){

      $message->from(env('MAIL_USERNAME'),'Aveniros Site');
      $message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');

    });

    return Redirect::to('/')
    ->with('success',' Your Account has been created !  Email has been sent to set-password, and activation.');
  }
}

Bug
$message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');

Error

Undefined variable: user

How can I use/call my $user variable ?
I thought we can access them after the $user->save(); - right ?
But clearly, I can't. Please correct me if I am wrong.
Answer: I figured out my own answer, I just realize that I need to add use ($user)
into this line function($message) use ($user){

Final Mail::Sent() should look like this
// Email
Mail::send('emails.activation', array(

  'username'=>$user->username,
  'name'=>$user->name,
  'code'=>$user->code,
  'email'=>$user->email

  ),
function($message) use ($user){

  $message->from(env('MAIL_USERNAME'),'Aveniros Site');
  $message->to( $user->email, $user->name )->subject(' Aveniros Site Activation ');

});


Smallest eigenvalue of sum of two unbounded operators

Question: Suppose $T,S:D(\mathcal H)\to \mathcal H$ are two unbounded operators with discrete spectrum consisting eigenvalues    $0<\lambda_1(T)\leq\lambda_2(T)\leq\dots$ and $0<\lambda_1(S)\leq\lambda_2(S)\leq\dots$.  Moreover assume that $T+S$ also has discrete spectrum and that
Q. How large  $\lambda_1(T+S)$ can be compared to $\lambda_1(T)$ and $\lambda_1(S)$?
Comment: You could write the Question as: "Suppose $T,S:D(\mathcal H)\to D(\mathcal H)$ are two unbounded Hermetian operators with discrete spectrum and least eigenvalues $0$. If $T+S$ also has discrete spectrum, how large can it's least eigenvalue be?" (Just adding constants to $S,T$.) Also, did you mean $D(\mathcal H)\to \mathcal H$ ?
Comment: Also, do you know the answer for $2 \times 2$ matrices?
Comment: Yes, edited it. I'm so used to copy-pasting in LaTex.
Comment: You have a better chance of getting an Answer if you write the Question in the simplest possible way. If you agree that the answer follows from that of the special case I have stated then you should ask that. Anyone who could answer knows that discrete eigenvalues can be arranged in ascending sequence, so you don't need to write that out.
Answer: I answer this question, which I think implies the answer to your question:

Suppose $T,S$ are possibly unbounded Hermitian operators in a Hilbert space with discrete spectrum and least eigenvalues $0$. If $T+S$ also has discrete spectrum, how large can it's least eigenvalue be?

In the case of $2 \times 2$ matrices you can solve the problem explicitly.
For general operators you can solve the Rayleigh-Schrodinger equation, which is non-linear and involves calculating the inverse of one of the operators (With discrete spectrum, calculating the inverse not a problem.).
If you want an upper bound you can construct approximants to the
eigenvalue by simply
choosing an arbitrary sequence of vectors which spans the Hilbert space
and minimizing $\frac{(\psi , (T+S) \psi}{(\psi,\psi)}$
 in the subspace spanned by the
first $n$ vectors.
In special cases there may be explicit solutions to the eigenvalue problem . In one case ($x^4$ anharmonic oscillator) there are approximants from below.


What is the difference between Universe and Population?

Question: On one hand, the universe contains "all the entities one wishes to consider in a given situation" on the other the population is "a set of similar items or events which is of interest for some question or experiment".
A co-worker said when she learned statistics they used the word universe; when I did we said population. Neither of us had heard of the other word. What if any is the difference?
Comment: Obligatory plug: Krieger, N. (2012). [Who and what is a "population"? Historical debates, current controversies, and implications for understanding "population health" and rectifying health inequities.](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3530737/) *The Milbank Quarterly*, 90(4):634–681.
Answer: I just took stats last year.  Population is, as you described, a complete set of elements (persons or objects) that possess some common characteristic defined by the sampling criteria established by the researcher.
In statistics, Universe is a synonym of Population.
Source:
population. (n.d.) Collins English Dictionary – Complete and Unabridged, 12th Edition 2014. (1991, 1994, 1998, 2000, 2003, 2006, 2007, 2009, 2011, 2014). Retrieved October 20 2017 from https://www.thefreedictionary.com/population
Confirming the use of Universe and Population, as synonyms in modern data science:
https://stats.oecd.org/glossary/detail.asp?ID=2087
Answer: The term 'universe', while it has a well-established meaning in set theory and other related mathematical fields, in my experience is rarely used in statistics as a synonym of the term 'population'.
Indeed, all classical statistics textbooks, exclusively use the term 'population', usually defined as

entire group of individuals (not necessarily people) about which we
want information.

On the other hand, the 'sample' can be defined to be

A sample is the part of the population from which we actually collect
information. We use a sample to draw conclusions about the entire
population.

Conceptually the two terms mean essentially the same thing, i.e. the set of all possible statistical units, but past statisticians decided to call this set 'population' so we adhere to this convention.
Answer: The collection of all elements possessing common characteristics that comprise universe is known as the population. A subgroup of the members of population chosen for participation in the study is called sample. The population consists of each and every element of the entire group.
Answer: Universe is the set all experimental units, from which a sample is to be drawn. Population is the set of all values of the variables to be studied from those experimental units. Thus, a U-sample contains experimental units, whereas a P-sample contains data.
Comment: Statistics are validly applied to study designs other than **experimental** study designs.
Answer: The collection of all elements possessing common characteristic that comprise (Univers) is known as the population.
And the subgroup of the member of population chosen for participating in the studybis called (Sample).
Comment: This answer would be improved if it cited an authoritative source, such as a book, article, or other scholarly publication.
Answer: Universe, population and sample must be understood together. Universe and population can refer to same thing and can be considered as synonym if only the population you use while choosing your samples includes all the members of universe. If you have data for all the members of universe then your population is universe and you are actually sampling from the universe. However, if you have data for only some members of universe then your population is those members of universe only and you are sampling from those members of universe whose data you have access. For instance, let's say you are doing a survey research on 10 million workers in country X. Your universe is all the workers. If you have access to social security number of all the workers where you can draw your sample of 10 thousand workers, then your universe and population are the same. If you have access to social security numbers of only 1 million workers then your universe is 10 million workers, your population is 1 million workers, and your sample is 10 thousand workers.
Comment: You can use the terms this way but I don't know that your usage is at all common. In what I read a difference you are talking about is explained using _target population_ and _sampled population_. The target population is the one you would like, the sampled population is what you sample from in practice.
Answer: The universe is broad in its nature. The universe in research is the area of your study while the population is the specific characteristics of the universe and the samples are selected units of the population.


Where does internal CSS go?

Question: I know that internal CSS should be in the  section of a (X)HTML document, but does it need to be before/after certain <meta> or <title> elements or can it be any order?
Comment: I would strongly suggest using external css-files, but you probably need this for a small test or something?
Comment: The head section contains an unordered collection of tags.
Comment: As of HTML5, I think it can go anywhere in the document, not just the head.
Answer: According to the HTML5 spec, non-scoped

Where does internal CSS go?


Many to many relationship: how to relate different entities with the same one

Question: There are services that can be subscribed by both companies or people:
<code>        <--> copany subscription rel <--> company
Service
        <--> person subscription rel <--> person
</code>
Consider I also have bunches of tables to link to the subscription tables (conditions, surveys etc). But I can't link these tables having two subscription tables.
So I thought to use this solution:
<code>                          <--> company
Service <--> suvscription
                          <--> person
</code>
The problem now is that I have two ids in subscription (id_person and id_company), linked to the two tables (one of which is null). So still it doesn't look to me a good solution.
What do you suggest me to do?
Answer: I think that two relations is the better way to do it.
Comment: yes, but in that case how do I link survey for example? That should be a survery for one subscription. Should it have id_subscription_person or id_subscription_company?
Answer: Why not separately store each entity's relationship to the service in a different table, like so:
COMPANY_SUBSCRIPTION
company_id|service_id
PERSON_SUBSCRIPTION
person_id|service_id
For these two tables above, both columns become your primary key, and several companies or people can be tied to the same service.
COMPANY
company_id|company_name..
PERSON
person_id|person_name...
SERVICE
service_id|service_name..


Should I compute my scales by averaging or total score?

Question: I am conducting a research involving a serial mediation analysis using Hayes's Process (Model 6). Should I compute my scales by average or by total score? It doesn't make a difference considering standardized coefficients, but I'm going to report unstandardized coefficients, which is affected by how you compute your scales (sum or mean).
Answer: It doesn't matter. A mean is just a sum divided by the number of items. The substantive conclusion will be the same. The choice depends on what substantively makes more sense. If it's a Likert scale, it probably make more sense to compute an average. If it's a symptom scale, it makes more sense to compute a sum. Note that the fact that this is taking place in a mediation analysis is irrelevant.
Comment: Thanks for your answer. Actually my scales are all Likert type except one (this one measures Borderline personality semptoms in which 1=Yes, 0=No). At first, i thought that it doesn't matter. But after running an analysis in both ways, I saw that unstandardized coefficients differ based on the way i compute my scales. Altough the standardized coefficients were still same, it was confusing for me because i want to report unstandardized coefficients. So is this the best way that I compute Likert ones by avarage and the other one by sum, and report the unstandardized coefficients?
Comment: There is no best way. It's totally up to you. It's whatever would make the interpretation easiest for you and your readers to understand and explain. The problem with unstandardized units is that their scale is totally arbitrary, but it doesn't matter because, as I said, the substantive conclusion will be the same regardless.
Answer: A nice way to think of a sum scale is that it is equivalent to adding all the items but constrain the effects tone equal: http://maartenbuis.nl/publications/sum_constr.html If that makes sense for your variables then a sum score is appropriate.
Answer: The big question is missing values.  If you have a lot of cases with one or a few indicators missing, either you have to use casewise deletion or allow for missing values.
Let's say that mean.2(X1,X2,X3) and sum.2(X1,X2,X3) will calculate the mean and sum respectively, if there are at least two non-missing values.
Also let's say that you have a number of cases with one of X1,X2,X3 missing, and you'd like to use them.
If you use sum.2(X1,X2,X3) to form a scale, you automatically have lower values for those cases missing an indicator.  If you use mean.2(X1,X2,X3), you don't automatically have that.
Note that you still need to analyze the cases with and without missing values, because not all bias is taken care of (e.g., missing on X1 implies different values of X2 and X3).


How to prove that the inequality holds for any nonzero x?

Question: The inequality is given by
$$x^{H}(\Phi(x))^{-1}x-x^{H}\dfrac{aa^H}{a^H\Phi(x)a}x\ge0,\text{ for any }x\ne0,$$
where $\Phi(x)$ is positive definite and is a function of $x$, $a$ can be any nonzero vector.
The equality holds only when $x=\Phi(x)a$.
I know that the condition $\Phi(x)^{-1}-\dfrac{aa^H}{a^H\Phi(x)a}\succeq0 $ is sufficient but not necessary. However,  I checked it numerically and found the condition always held.
Thank you very much!!!
Answer: $\Phi(x)$ is positive definite, so it has a unique positive definite square root $P$ and the inequality in question can be rewritten as
$$
\|P^{-1}x\|^2 \|Pa\|^2 - |\langle x,a\rangle|^2 \ge 0.\tag{1}
$$
Why is this true? As $P$ is Hermitian, $\langle x,a\rangle=\langle P^{-1}x,\,Pa\rangle$. Therefore $(1)$ is merely Cauchy-Schwarz inequality and the condition that equality holds is $P^{-1}x=Pa$, i.e. $x=\Phi(x)a$.


Find large power of a non-diagonalisable matrix

Question:
If $A = \begin{bmatrix}1 & 0 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{bmatrix}$, then find $A^{30}$.

The problem here is that it has only two eigenvectors, $\begin{bmatrix}0\\1\\1\end{bmatrix}$ corresponding to eigenvalue $1$ and $\begin{bmatrix}0\\1\\-1\end{bmatrix}$ corresponding to eigenvalue $-1$. So, it is not diagonalizable.
Is there any other way to compute the power?
Comment: You can use the Cayley-Hamilton theorem to obtain constants $a,\,b,\,c$ with $A^3=aA^2+bA+cI$, so $A^{n+3}=aA^{n+2}+bA^{n+1}+cA^n$. You can then find $A^{30}$ by recurrence. In fact, you can combine with this the technique in mathematician's answer, e.g. get $A^4$ in terms of $I,\,A,\,A^2$, square to get $A^8$ etc.
Comment: You can write the matrix in Jordan form, $A=PJP^{-1}$, and then use standard results about powers of Jordan matrices.
Answer: Notice the characteristic polynomial of $A$ is
$$\chi_A(\lambda) \stackrel{def}{=}\det(\lambda I_3 - A) = \lambda^3-\lambda^2-\lambda+1
= (\lambda^2-1)(\lambda-1)$$
By Cayley-Hamilton theorem, we have
$$\chi_A(A) = (A^2 - I)(A-I) = 0 \quad\implies (A^2-I)^2 = (A^2-I)(A-I)(A+I) = 0$$
This means $A^2-I$ is nilpotent. In following binary expansion of $A^{30}$
$$A^{30} = (I + (A^2 - I))^{15} = \sum_{k=0}^{15} \binom{15}{k}(A^2-I)^k$$
only the term $k = 0$ and $1$ contributes. i.e.
$$A^{30} = I + 15 (A^2-I) =
\begin{bmatrix}
1 & 0 & 0\\
15 & 1 & 0\\
15 & 0 & 1
\end{bmatrix}
$$
Answer: You can use repeated squaring to efficiently compute large powers.
$$ A^{30} = A^{16} \cdot A^8 \cdot A^4 \cdot A^2$$
where $A^4 = {A^2} ^2$, $A^8= {A^4}^2$, etc.
Answer: Given $\mathrm A$, we compute one Jordan decomposition, $\mathrm A = \mathrm P \mathrm J \mathrm P^{-1}$, where
$$\mathrm J = \begin{bmatrix} -1 & 0 & 0\\ 0 & 1 & 1\\ 0 & 0 & 1\end{bmatrix}$$
Note that $\mathrm A^{30} = \mathrm P \mathrm J^{30} \mathrm P^{-1}$. Since $(-1)^{30} = 1$ and $\begin{bmatrix} 1 & 1\\ 0 & 1\end{bmatrix}^{30} = \begin{bmatrix} 1 & 30\\ 0 & 1\end{bmatrix}$, we have
$$\mathrm J^{30} = \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 30\\ 0 & 0 & 1\end{bmatrix}$$
Thus,
$$\mathrm A^{30} = \mathrm P \mathrm J^{30} \mathrm P^{-1} = \cdots = \begin{bmatrix} 1 & 0 & 0\\ 15 & 1 & 0\\ 15 & 0 & 1\end{bmatrix}$$
Answer: Since the given matrix is rather simple, you could also compute a few powers:
\begin{align*}
A^1&=
\begin{pmatrix}
  1 & 0 & 0 \\
  1 & 0 & 1 \\
  0 & 1 & 0
\end{pmatrix}\\
A^2&=
\begin{pmatrix}
  1 & 0 & 0 \\
  1 & 1 & 0 \\
  1 & 0 & 1
\end{pmatrix}\\
A^3&=
\begin{pmatrix}
  1 & 0 & 0 \\
  2 & 0 & 1 \\
  1 & 1 & 0
\end{pmatrix}\\
A^4&=
\begin{pmatrix}
  1 & 0 & 0 \\
  2 & 1 & 0 \\
  2 & 0 & 1
\end{pmatrix}\\
A^5&=
\begin{pmatrix}
  1 & 0 & 0 \\
  3 & 0 & 1 \\
  2 & 1 & 0
\end{pmatrix}\\
A^6&=
\begin{pmatrix}
  1 & 0 & 0 \\
  3 & 1 & 0 \\
  3 & 0 & 1
\end{pmatrix}\\
\end{align*}
Can you notice some kind of pattern and prove it by induction? (Or, if you prefer, you can do the same thing with $B=A^2$ and try to find general form of $B^n$.)

Of course, this is "naive" approach - without using any theory you have learned about matrices. For more complicated matrices it would be rather difficult to spot some kind of pattern. That's why methods which work for arbitrary matrices are more useful.
Answer: Generalized eigenvector $\;u_1=\begin{pmatrix}a\\b\\c\end{pmatrix}\;$for $\;\lambda=1\;$ :
$$Au_1=1\cdot u_1+v_1\iff \begin{pmatrix}a\\a+c\\b\end{pmatrix}=\begin{pmatrix}a\\b\\c\end{pmatrix}+\begin{pmatrix}0\\1\\1\end{pmatrix}\implies \begin{cases}b=c+1\\{}\\a+c=b+1\end{cases}\implies \begin{cases}a=2\\{}\\b=1\\{}\\c=0\end{cases}$$
$$\implies u_1=\begin{pmatrix}2\\1\\0\end{pmatrix}\;,\;\;\text{so define}\;\;P:=\begin{pmatrix}0&2&0\\1&1&1\\1&0&\!\!-1\end{pmatrix}\implies P^{-1}=\frac14\begin{pmatrix}\!\!-1&2&2\\2&0&0\\\!\!-1&2&\!\!-2\end{pmatrix}$$
and now:
$$P^{-1}AP=\frac14\begin{pmatrix}\!\!-1&2&2\\2&0&0\\\!\!-1&2&\!\!-2\end{pmatrix}\begin{pmatrix}1 & 0 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix}\begin{pmatrix}0&2&0\\1&1&1\\1&0&\!\!-1\end{pmatrix}=\begin{pmatrix}1&1&0\\0&1&0\\0&0&\!\!-1\end{pmatrix}\implies$$
$$A^{30}=P\begin{pmatrix}1&1&0\\0&1&0\\0&0&\!\!-1\end{pmatrix}P^{-1}$$
You can now check that taking powers of the above quasi-diagonal matrix ( i.e., the Jordan Canonical Form for $\;A\;$) is very easy, though not as easy as with diagonal matrices, of course.


Proving $\displaystyle \lim_{(x,y) \to (0,0)} xy = 0$

Question: Seems simple enough, but my notes do something I don't understand.
Question is:
prove lim          xy = 0
      (x,y) -> (0,0)

The notes say that
0 <| (x,y) - (0,0) | < d
implies 0 < |(x, y)| < d
step 3: implies 0 < square root (x^2 + y^2) < d

Then does:
0 <= (x+y)^2 = x^2 + 2xy + y^2
implies 2xy <= x^2 + y^2
implies 2|xy| <= x^2 + y^2
implies |xy| <= x^2 + y^2 / 2 < d/2

and chooses epsilon = d^2 /2 which impliesd^2 = epsilon / 2 which implies to pick d = square root of (epsilon/2).
Im confused on step 3. Why did they take the square root of (x^2 + y^2)? How does step 2 imply step 3?
And why was step 3 followed with
0 <= (x+y)^2 = x^2 + 2xy + y^2

Where did that come from?
I was taught to go from |xy - 0| < epsilon and try to make |xy - 0| to something like |(x,y) - (0,0)|
Comment: I think it's easier to just go with the Heine definition of convergence
Answer: They took the square root of $x^2+y^2$ because $\bigl\lVert(x,y)\bigr\rVert=\sqrt{x^2+y^2}$.
Step 2 implies step 3 because $\bigl\lVert(x,y)-(0,0)\bigr\rVert=\bigl\lVert(x,y)\bigr\rVert$.
Finally, since$$\lvert xy\rvert\leqslant\frac{\sqrt{x^2+y^2}}2,\tag1$$then, for every $\varepsilon>0$, if you take $\delta$ such that $\delta=2\varepsilon$, it follows from $(1)$ that$\sqrt{x^2+y^2}<\delta\implies\lvert xy\rvert<\varepsilon$. Yes, I know that this is not the same $\delta$ as the one that you mentioned, but I suppose that what matters to you is that some $\delta$ will do.
Comment: What comes after step 3 is **not** a consequence of that step. What they do is to prove inequality $(1)$ and, on order to do that, they take as their starting point the trivial inequality $0\leqslant(x+y)^2$.
Comment: Okay thanks. So after step 3, how did they get `0 <= (x+y)^2`? How did they know to do `(x+y)^2`? Where did `(x+y)^2` come from?
Comment: Ah ok, and on the last step before choosing epsilon, how is it known that `(x^2 + y^2)/ 2 < d/2`?
Comment: I was unable to follow that passage. That's why I provided my own choice of $\delta$.


Formatting String method

Question: I am trying to create a method that will format a string from the user using a pattern made of 'x' and '-' characters which also comes from the user.
for example
if the user inputs abcdefg, and the pattern x-x-x-x-x-x-x,
the output should be a-b-c-d-e-f-g
My problem comes when the user gives a pattern that is longer than the string which always gives me an error.
Thanks in advance.
This is what I got.
private static void FormatString()
    {

        String str,pattern= "";
        int p=0;
        Scanner in1 = new Scanner(System.in);
        Scanner in2 = new Scanner(System.in);

        System.out.println("Enter a String to be formatted");
        str = in1.nextLine();

        System.out.println("Enter pattern");
        pattern = in2.nextLine();
        char [] array1 = pattern.toCharArray();

        int ultindx = str.lastIndexOf(str);

        int ultindx2 = pattern.lastIndexOf(pattern);
        int lenght = pattern.length();
        for(int y = 0; y < lenght; y++)
        {

            if(array1[y] == 'x' )
            {
            array1[y] = str.charAt(p);
            p++;
            }

            else
                array1[y] = '-';

        }

        System.out.println(array1);
        formattry++;
    }

Comment: What is the question? What error are you getting?
Comment: "...which always gives me an error." Which would be what, exactly? Please  always include your stack trace whenever you have a question about an error.
Comment: What is the desired behavior? Do you want to return an error when the format string is too long, adjust the format string to match the length of input, or something else entirely?
Answer: You have to check if p<str.length(). If you do not do it, you get a StringIndexOutOfBoundsException
Answer: I think the problem is in the following line:
array1[y] = str.charAt(p);

When the pattern is longer then the string, the p value is bigger then string's length.
You should add additional condition
if(array1[y] == 'x' && p < str.length())
{
   array1[y] = str.charAt(p);
   p++;
}

Formatting String method


Extended characters not displaying C#

Question: I am currently working on a web application using C#.
One of the online forms allows the user to update their address.
However, when I enter for example : ÀîâãäåæéêìñóôõăąăĂąĄ into any of the address info
and then search for the same user again their address is displayed on the screen like this.
As you can see the last characters seem to be wrong.
Wrong in the database too.
Do I need to do something to the string before I send it for update, at the moment I just convert whatever is in the text field to uppercase and send the information to my stored procedure.
,@p_AddressLine1 char(40)=NULL
,@p_AddressLine2 char(40)=NULL
,@p_AddressLine3 char(40)=NULL
,@p_AddressLine4 char(40)=NULL
,@p_AddressLine5 char(40)=NULL

Please help. Note Ive tried changing to nchar - but I think this may be a C# thing?
Thanks
user.PostCode = this.tbPostCode1.Text.ToUpper().Trim() + " " + this.tbPostCode2.Text.ToUpper().Trim();
        user.AddressLine1 = this.txtAddressLine1.Text.ToUpper().Trim();
        user.AddressLine2 = this.txtAddressLine2.Text.ToUpper().Trim();
        user.AddressLine3 = this.txtAddressLine3.Text.ToUpper().Trim();
        user.AddressLine4 = this.txtAddressLine4.Text.ToUpper().Trim();
        user.AddressLine5 = this.txtAddressLine5.Text.ToUpper().Trim();

        user.Update(user);

Comment: What is your database default collation? e.g. `select serverproperty('collation')`
Comment: SQL_Latin1_General_CP1_CI_AS
Comment: When you use the debugger before presenting the info on a web page, is the value still wrong? Also, please read [this](http://stackoverflow.com/questions/1696619/displaying-unicode-symbols-in-html)
Comment: Yes the value is still wrong just before display.
Comment: Is it corrupted before your stored procedure is called?
Comment: No I can see in the debugger the format is just changed to upper text but not corrupt
Comment: You mentioned you tried changing to `nchar`, did you change the parameter type and the field type in the table too? You would also need to re-run the update though, since `char` does not really support Unicode by design you cannot store characters like these in it.
Comment: The field type goes to the DB as "String", just changed the parameter type...not the field type in the table
Comment: And what is the field type in the table? If the string is correct before calling the sp you might be trying to squeeze Unicode characters to `char`.
Answer: You are dealing with extended character set which cannot be stored in char field type and you can only use nchar or nvarchar for that, but be aware about the space requirement for the Unicode characters which will take as twice as more space.
Here is a good answer explaining the difference and here is the documentation on the data types you should be using instead.
Comment: Thank you so much this worked a treat!!!!!
Still coming through in CSV wrong though - comes through as:
ÀÎÂÃÄÅÆÉÊÌÑÓÔÕÄ'Ä"Ä'Ä'Ä"Ä"
Comment: This time it looks more like Unicode character encoded as HTML Entity

Extended characters not displaying C#


If chords progressions belong to more than one key, would tonality come from the melody?

Question: In popular music, lets say I have a song that appears to be in C major. The progression could be something like C > Em > Am > G.
This progression could also be in G major However. So, let's say we look at the melody but only the C major pentatonic scale is used and the F# or F is absent which would have been able to tell us the tonality of the song.
As a last resort, is it possible to listen to where the notes of the melody fall to get an idea of the tonality. For example the phrase could end on the G note on both the Em chord and the G chord. This kind of gives you the feeling that the song is actually in G not in C even though the chord progression starts on C and uses chords from the diatonic C major scale. Does music work in this way? I mean, the G note does feel like home in this case even without a more unambiguous chord progression being used so my question is: Surely the melody is just as much a determining factor not only in terms of which notes are used but also on what note the melody ends. Is this correct?
Comment: In a word: yes.
Answer:
In popular music, lets say I have a song that appears to be in C major. The progression could be something like C > Em > Am > G. This progression could also be in G major However.

The key isn't just a question of what the chords are - it's about the note (and tonic chords) that the piece seems to come home to. So with one phrasing, C > Em > Am > G could be fairly clearly C major. With another phrasing, C > Em > Am > G could be clearly G major. A key isn't usually something you use to describe an abstract collection of chords - it's something that describes an actual piece. When you listen to the phrasing of the actual piece, it may make it clear where the piece comes home to.
Of course it's also true that a certain phasing and articulation of those chords might still leave the 'home note', and therefore the key, ambiguous...

is it possible to listen to where the notes of the melody fall to get an idea of the tonality

...but yes, as you say, the melody may change the feeling of the piece such that a particular home note becomes clear. In fact Every aspect of a piece may have an effect on what the key of a piece is perceived as - even things like the accenting of the notes and the volume of individual parts can have an effect.
And remember that ultimately this is subjective - two people might hear the same piece and perceive a different home note. Unless there's a statement from the composer about the key that you want to take as definitive, the key of a piece can be a matter of opinion.
Comment: As in Sweet Home Alabama?
Comment: @armani at the end of the day, key isn't a feature of the music - it's a perspective from which you can look at the music.
Comment: @Tim indeed - in fact that's one I am conflicted about as I hear it coming home to D, but the lyrics state "Lord, I'm coming home to **you**" with 'you' falling on G - so clearly they see the home chord as G major ;) A reasonable article about it here: https://www.guitarmusictheory.com/in-what-key-is-sweet-home-alabama/
Comment: You'd think so, but at some concerts they finish with D - but that's not actually saying it's in D, or they think it's in D. They could, of course, be using an imperfect cadence... but I doubt it. To me it's key G, but that's just me!
Comment: Aaaah but if you actually hold that D note Youuuuu and end on the D chord you will hear it makes more sense. To me it is in D and the C chord is a b7 chord. It probably just doesnt sound so "cadenc-y" when it ends on G. What scale they chose to play over it as a solo is irrelevant, I am sure the vocal melody is in D major, it is just unfinished
Comment: @topo I disagree there, there might be a perspective but if you play those chords I mentioned, you can't feel C major if the melody ends on G the whole time.
Comment: @armani I've just tried it on the guitar (improvising melodies that end on G) and I promise you that I can still feel C - the more I emphasize C in the chord progression, the easier it is to do, and the less I emphasize C, the harder it is...
Comment: @ topo, did the melodies end on G over the two chords I mentioned? Em and G?
Comment: @topo also, you are obviously only playing the C pentatonic scale right? THat was mentioned but just checking
Comment: @armani Yes, I can restrict myself in the two ways you just described and still phrase the melody and chord progression in a way that makes C feel like home to me. Seems pretty easy to do as I'm starting on the C chord.
Comment: @Topo Thanks for actually trying it. I am not here to tell you what you can and can not hear because that is personal but to my ears the chord progression is ambiguous and so is the melody if you are using the pentatonic C major scale so I am not sure how you can definitely say that you hear C major as the root key. the first chord in a progression does not persuade my ears into hearing C major to be honest and if anything where the melody lands is at least some kind of a clue.. perhaps not the most convincing clue but then neither is what chord the progression starts with :)


Show all records on a RIGHT JOIN query with GROUP BY

Question: I inherited the following table
DEALS
id, office_id, sale_date.

There are some 13 000 records with around 60 different office_id's. I need a query to count the number of transactions (records), grouping each office_id by YEAR-QUARTER.
When I use this
SELECT  office_id, concat(YEAR(sale_date), "-", quarter(sale_date)) as period, count(id) AS transactions
FROM `deals`
GROUP BY office_id, period

I get
office_id, sale_date, transactions
66, 2020-4, 5
45, 2020-4, 9
23, 2020-4, 7
67, 2020-3, 9
43, 2020-3, 4
66, 2020-3, 3
45, 2020-3, 8
23, 2020-3, 2
66, 2020-2, 6
45, 2020-2, 5

Want I want to get is all office_id's for all periods as below even if there are no records.
office_id, sale_date, transactions
67, 2020-4, NULl
43, 2020-4, NULL
66, 2020-4, 5
45, 2020-4, 9
23, 2020-4, 7
67, 2020-3, 9
43, 2020-3, 4
66, 2020-3, 3
45, 2020-3, 8
23, 2020-3, 2
67, 2020-2, NULL
43, 2020-2, NULL
66, 2020-2, 6
45, 2020-2, 5
23, 2020-2, NULL

I hope this makes sense. Any help will be appreciated, I am a complete noob.
Comment: what determines what are "all periods"?  some specific range of quarters?  all offices found in some other table?
Comment: @ysth The periods are determined by sale_date. It is the 4 quarters of the year. Sorry I see I left out office_id in the GROUP BY. I edited the original question
Comment: let me try asking a different way:  if there are no records at all in deals, would you want no rows?  or is there some set of periods you want reported?  and same question with office_id
Comment: See https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query
Answer: MySQL 8
WITH RECURSIVE cte (n) AS
(
  SELECT MIN(sale_date) AS n FROM deals
  UNION ALL
  SELECT n + INTERVAL 1 QUARTER
  FROM cte
  WHERE EXTRACT(YEAR_MONTH FROM n) < (SELECT EXTRACT(YEAR_MONTH FROM MAX(sale_date)) FROM deals)
)
SELECT
   o.office_id,
    concat(YEAR(n), "-", quarter(n)) as period,
   COUNT(d.id) AS transactions
FROM cte
JOIN offices o
LEFT JOIN deals d ON d.office_id = o.office_id AND EXTRACT(YEAR_MONTH FROM d.sale_date) = EXTRACT(YEAR_MONTH From n)
GROUP BY o.office_id, period
ORDER BY o.office_id, period;

First cte is used to generate quarter list based on min and max sale date from deals table.
Then cross joined with office table to make sure we do've records for each office and each quarter.
Now left joined with deals table to find how many transactions per office and quarter.

There might be some optimized way but it will give you the results.
Comment: Sorry, I see I left out the Group By office_id in my question but I did have it in my query. What I want is for the 4 quarters of every year to be show in the results for each of the office_id's that exist in the table even if there are no records for a partiular office_id  in the a particular quarter (period). For example, office_id 43 only has records that falls in the period 1July 2020 to 30 Sep 2020 (the 3rd quarter of 2020). I want the other periods to show in the results for office_id 43 with a NULL value.
43 2020-1 NULL,
43 2020-2 NULL,
43 2020-3 4,
43 2020-4 NULL
Comment: This cannot provide the presence in output for the combinations `(office_id, period)` which are absent in source data.
Comment: @Akina, question has been modified after the answer. Will update accordingly. Hope a comment before downvote is good to let answerer know, that he can improve. Bcz everybody doesn't come back and correct their voting even if answer has been updated.
Comment: @AllanBateman, there are two options two make sure you get the proper answer. First if you have a table with `offices` that would be great otherwise we can find `distinct office_id` from same table. Second if you want all quarters whether there is data present or not in that situation what about a period when there is no data from any office. Do you want to generate it or skip it. Based on your response will update the answer.
Comment: @Jitendra Thank you. Yes, I do have a table with offices. That where the table id comes from when the deals table is populated. It has the Office_id and office_name. Second question, yes I want to generate it even if there is no data for any office.
Comment: *question has been modified after the answer.* I have not seen the initial question text. I operate only with question's and answer's current states. And they do not match - this is a reason of downvote. If you want the downvote to be removed (or even to receive an upvote) you must sync current question state and your answer text.
Comment: Are you sure in `<=` used in CTE's WHERE in recursive part? It must give excess row.
Comment: thank you for pointing that out. I think it would add extra one. updated my answer
Answer: You must gather the offices list in separate subquery, do the same with periods, then outer join source table to their combination.
The subqueries provides you any possible pair (office, period), even when such pair is absent in the data. But separate values for office and period must present in a table.
SELECT offices.office_id, periods.period, COUNT(deals.id) transactions
FROM (SELECT DISTINCT office_id FROM deals) offices
CROSS JOIN (SELECT DISTINCT CONCAT(YEAR(sale_date), "-", QUARTER(sale_date)) period FROM deals) periods
LEFT JOIN deals ON deals.office_id = offices.office_id
               AND CONCAT(YEAR(deals.sale_date), "-", QUARTER(deals.sale_date)) = periods.period
GROUP BY offices.office_id, periods.period

If your MySQL version is 8+ then convert subqueries to CTEs.
Demo fiddle which demonstrates the technique.
If there is no any row for some office and/or period value which must be included then some external rowsource which provides such data presence in source data array must exist. For example, this can be a table of offices or CTE which generates full periods list based on the least and greatest sales dates over whole table.
Comment: what about a missing quarter(for which no data for any office)?
Comment: @JitendraYadav If so then you must either have a table with complete quarters list in interest or generate such list in recursive CTE (or by another way).
Comment: @JitendraYadav The remark about such situation added.
Comment: I can add a table for the period which could hold the 4 quarters for every year as the "period" In other words;

id  period

1 2020-4

2 2020-3

3 2020-2

4 2020-1

5 2019-4

6 2019-3

7 2019-2

8 2019-1

and so on. Would that work? (Sorry, I don't know how to show this in table format in this chat)
Comment: @AllanBateman Of course... but I do not see the reason, it is more simple and more dynamic to specify starting and finishing date and generate the quarters list in a query (especially if your MySQL is 8+).


Which PEM file should I provide when uploading to S3 using HTTP PUT

Question: I'm trying to put a file in S3 using a presigned signature my Java web server provides
http://docs.amazonwebservices.com/AmazonS3/latest/dev/PresignedUrlUploadObjectDotNetSDK.html
I need my uploading client (currently my windows 7 using C++) to have a handshake with amazon servers and I don't know how to do it.
When I tried to send the request with a "default context" (naively) it printed a "self signed certificate in certificate chain" error and asked me to accept or not the certificate.
Then I tried to figure out how to add a certificate and found this code:
POCO C++ - NET SSL - how to POST HTTPS request
The problem is that I'm not sure which pem file is needed here.
I tried providing the pem files I've downloaded from x.509 in Amazon Web Services Console but it raised an SSL exception: SSL3_GET_SERVER_CERTIFICATE
My Code:
URI uri("https://BUCKET.s3.amazonaws.com/nosigfile?Expires=1959682330&AWSAccessKeyId=ACCESSKEY&Signature=DgOifWPmQi%2BASAIDaIOGXla10%2Fw%3D");
const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "cert(x509).pem") );
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context );
HTTPRequest req(HTTPRequest::HTTP_PUT, uri.getPathAndQuery(), HTTPMessage::HTTP_1_1);
req.setContentLength(contentLength);
session.sendRequest(req) << streamToSend;

Thanks
Answer: Poco includes certificates in the project.
You will need any.pem, rootcert.pem, yourappname.xml which you can find in the poco test suite for the SSL side.
./poco-1.4.1p1-all/NetSSL_OpenSSL/testsuite/{any.pem,rootcert.pem,testsuite.xml}

Once you include the two pem files, your xml, which is used during the initializeSSL phase you will not get the warning for self-signed certificates.
class MySSLApp: public Poco::Util::Application
{
public:
    MySSLApp()
    {
        Poco::Net::initializeSSL();
        Poco::Net::HTTPStreamFactory::registerFactory();
        Poco::Net::HTTPSStreamFactory::registerFactory();
    }

    ~MySSLApp()
    {
        Poco::Net::uninitializeSSL();
    }
protected:
    void initialize(Poco::Util::Application& self)
    {
        loadConfiguration(); // load default configuration files, if present
        Poco::Util::Application::initialize(self);
    }

    void myUpload(...) {
        ...
        FilePartSource* pFPS = new FilePartSource(szFilename);
        std::string szHost = "BUCKET.s3.amazonaws.com";
        std::string szPath = "/";
        int nRespCode = 201;
        try{
            HTTPClientSession s(szHost);
            HTTPRequest request(HTTPRequest::HTTP_POST, szPath, HTTPMessage::HTTP_1_1);
            HTMLForm pocoForm(HTMLForm::ENCODING_MULTIPART);
            pocoForm.set("AWSAccessKeyId",        ACCESSKEY);
            pocoForm.set("acl",                   "public-read");
            pocoForm.set("success_action_status", toString(nRespCode));
            pocoForm.set("Content-Type",          m_szContentType);
            pocoForm.set("key",                   m_szPath + "/" + m_szDestFileName);
            pocoForm.set("policy",                m_szPolicy);
            pocoForm.set("signature",             m_szSignature);
            pocoForm.addPart("file",              pFPS);

            pocoForm.prepareSubmit(request);

            std::ostringstream oszMessage;
            pocoForm.write(oszMessage);
            std::string szMessage = oszMessage.str();

            //AWS requires a ContentLength set EVEN though it is chunked!
            request.setContentLength((int) szMessage.length());

            s.sendRequest(request) << szMessage;
            //or:
            //pocoForm.write(s.sendRequest(request));

            HTTPResponse response;
            std::istream& rs = s.receiveResponse(response);
            int code = response.getStatus();
            if (code != nRespCode) {
                stringstream s;
                s << "HTTP Error " << code;
                throw Poco::IOException(s.str());
            }
        } catch (Exception& exc) {
            std::cout << exc.displayText() << endl;
            return;
        }
        return;
    }
 }

The xml file will look something like this:
<AppConfig>
<openSSL>
    <server>
        <privateKeyFile>${application.configDir}any.pem</privateKeyFile>
        <caConfig>${application.configDir}rootcert.pem</caConfig>
        <verificationMode>none</verificationMode>
        <verificationDepth>9</verificationDepth>
        <loadDefaultCAFile>true</loadDefaultCAFile>
        <cypherList>ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH</cypherList>
        <privateKeyPassphraseHandler>
            <name>KeyFileHandler</name>
            <options>
                <password>secret</password>
            </options>
        </privateKeyPassphraseHandler>
        <invalidCertificateHandler>
            <name>AcceptCertificateHandler</name>
            <options>
            </options>
        </invalidCertificateHandler>
    </server>
    <client>
        <privateKeyFile>${application.configDir}any.pem</privateKeyFile>
        <caConfig>${application.configDir}rootcert.pem</caConfig>
        <verificationMode>relaxed</verificationMode>
        <verificationDepth>9</verificationDepth>
        <loadDefaultCAFile>true</loadDefaultCAFile>
        <cypherList>ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH</cypherList>
        <privateKeyPassphraseHandler>
            <name>KeyFileHandler</name>
            <options>
                <password>secret</password>
            </options>
        </privateKeyPassphraseHandler>
        <invalidCertificateHandler>
            <name>AcceptCertificateHandler</name>
            <options>
            </options>
        </invalidCertificateHandler>
    </client>
</openSSL>
</AppConfig>


Linear regression for binary classification - a new classifier

Question: I am new to classification, but not to regression. I already used regression to fit a linear combination of time varying signals to match two constant signals, -1 and 1, representing their classes.
In order to decide which class the result belongs to, a standard way is to test if the average is positive or negative.
I found a classifier that gives better results, which is computed by comparing the MSE between the prediction and the two constant signals -1 and 1. The smaller MSE decides the class. I am 100% sure other people have used this before (it seems pretty intuitive), but I can't find it anywhere (most likely, I'm not searching for the right words).
Can any of you help me with the name of this classifier and/or where it was used?
Thanks in advance.
Comment: First of all: why would you use a suboptimal method where there are *lots* of better ways of doing this? Second, how exactly MSE would work here? "The smaller MSE decides the class" does not make sense since MSE is a *single* value that describes the overall errors of the model, so it us unusable for the purpose.
Comment: I am not talking about the MSE describing the overall performance of the algorithm, but an MSE computed for every time varying prediction (so for every input-output pair), in order to decide the class it belongs to. I hope this is a bit clearer.
Comment: So you are not talking about MSE, but about smaller squared distances. Still, I don't get it, since squared difference between predicted value and -1 will be smaller if the value is < 0 and and it will be smaller to +1 when the value is > 0, so it is the same as if you just took the sign of the value...
Comment: Linear regression with dichotomous dependent variable is equivalent to Fisher's linear discriminant analysis, a classifier.
Comment: Could you walk through an example of how the MSE is computed and compared between the prediction and the two constant signals?
Comment: ttnphns: I did some research on what you said, so thanks for the statement, it was helpful.

Tim: I am actually talking about the mean squared error between the predicted time series and the time series that is constant -1. And it's not the same thing, because the predicted time series could oscillate above and below 0, in which case computing the MSE would give you a classification of the whole time series, rather than a "real-time" classification.
Answer: Thanks to ttnphns, I learnt this problem is equivalent to Fisher's linear discriminant analysis, a classifier. I realised it's just a matter of choice whether you use MSE or a simple average for class prediction, depending on the application.
Thanks to everyone for their time.
Comment: Fisher's linear discriminant analysis is not based on MSE of class membership predictions.  Its loss function is based on the distance between the two covariance matrices of predictor values for group 1 subjects and predictor values for group 2 subjects.  Your original thoughts about this problem are not based on good statistical principles.


Download contents of the PHP generated page from another PHP script

Question: I have a PHP script on a server that generates the XML data on the fly, say with Content-Disposition:attachment or with simple echo, doesn't matter. I'll name this file www.something.com/myOwnScript.php
On another server, in another PHP script I want to be able to get this file (to avoid "saving file to disk") as a string (using the path www.something.com/myOwnScript.php) and then manipulate XML data that the script generates.
Is this possible without using web services?
security implications?
Thanks
Answer: Simple answer, yes:
$output = file_get_contents('http://www.something.com/myOwnScript.php');

echo '
';
print_r($output);
echo '
';

Answer: If you want more control over how you request the data (spoof headers, send post fields etc.) you should look into cURL.
link text
Comment: curl is more flexible and performant, but file_get_contents() is simpler.

Personally, I tend to start with file_get_contents(), until curl's power/performance become necessary.
Comment: cUrl allow even the HTTP authentication, really usefull (of course, just when is needed)
Answer: If you're on a shared host, you might find that you cannot use file_get_contents. This mainly because it is part of the same permission sets that allow you to include remote files. Anyway...
If you're stuck in that circumstance, you might be able to use CURL:
<?php
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "example.com");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
?>

It is more code, but it's still simple. You have the added benefit of being able to post data, set headers, cookies... anything you could do with a highly configurable browser. This makes it useful when people attempt to block bots.


Convert String[] array to RedisKey[] array

Question: Trying to use
KeyDelete(RedisKey[] keys, CommandFlags flags = CommandFlags.None);

I have array of string[] ,
I am not seeing any examples out there when I search for converting these data types. I am not even sure how to create a new RedisKey.
Tried
RedisKey redisKey = new RedisKey("d");

above does not work, any suggestions?
Comment: There is an implicit conversion defined between `RedisKey` and `string`. If you want a key with the value of "d", just make a direct assignment, `RedisKey redisKey = "d"` https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/KeysValues.md
Answer: From the source code RedisKey has an implicit conversion from string:
///
/// Create a key from a String
///
public static implicit operator RedisKey(string key)
{
    if (key == null) return default(RedisKey);
    return new RedisKey(null, key);
}

So you can create one by
RedisKey key = "hello";

or
var key = (RedisKey)"hello";

To convert an IEnumerable<string> to RedisKey[], you can do:
var keys = strings.Select(key => (RedisKey)key).ToArray();


Spyne create answer

Question: Sorry for my English.
I can not understand how SPYNE generates response to a request to send him.
Client sends in this form:
<SOAP-ENV: Envelope xmlns: ns0 = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: ns1 = "localhost" xmlns: xsi = "http://www.w3.org/2001/ XMLSchema-instance "xmlns: SOAP-ENV =" http://schemas.xmlsoap.org/soap/envelope/ ">
    <SOAP-ENV: Header />
    <Ns0: Body>
       <Ns1: prerender>
          <Ns1: secret> secret_key </ ns1: secret>
          <Ns1: requestId> 1 </ ns1: requestId>
          <Ns1: projectId> id1 </ ns1: projectId>
       </ Ns1: prerender>
    </ Ns0: Body>
</ SOAP-ENV: Envelope>

And the server responds as follows:
<Soap11env: Envelope xmlns: soap11env = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: tns = "localhost">
   <Soap11env: Body>
     <Tns: prerenderResponse>
       <Tns: prerenderResult0> secret_key </ tns: prerenderResult0>
       <Tns: prerenderResult1> 1 </ tns: prerenderResult1>
     </ Tns: prerenderResponse>
   </ Soap11env: Body>
</ Soap11env: Envelope>

please tell me how to generate such a response:
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="localhost"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <ns0:Body>
      <ns1:secret>INT</ns1:commandType>
      <ns1:requestId>STRING</ns1:secret_key>
      <ns1:projectId>INT</ns1:requestId>
    </ns0:Body>
  </SOAP-ENV:Envelope>

If I understand from the documentation. This is done using ComplexModel. But to implement such strukutru I could not get
Comment: To my knowledge, this is not a valid spyne response. However, you can use lxml.etree and ctx.out_document to return anything you want.
Answer: You can use @rpc(..., _out_variable_names=["foo", "bar"]) to change the tag names prerenderResult0 and prerenderResult1.
To my knowledge, having multiple tags under the SOAP body is not legal. You can change ctx.out_document to anything you like though.

Spyne create answer


When I ping Internet addresses like yahoo or Google, I get 2 reply packets and 2 lost packets

Question: I have Airtel broadband and a Tata broadband connection. i have around 50 PCs connecting through an airtel broadband connection.
Both are dsl connections with my phone line going into dsl modems and an Ethernet cable going from dsl modem directly into a switch. Currently, only airtel connection is connected with static IP on my private lan and using the airtel ISP DNS servers as DNS IP address and the default gateway is 192.168.1.1 (IP add. of the dsl modem). All PCs are connected in a work group.
When in full use, my users complain of certain web pages are not opening. When I ping Internet addresses like Yahoo or Google I get 2 reply packets and 2 lost packets. I suspect that a single broadband connection is not able to sustain 50 simultaneous downloads/browsing.
Is there any device which connect to both DSL and make one line so that its give me high speed simultaneous browsing. Help needed urgently. Thank you all to those who reply.
Comment: Sounds like a routing issue, some packets are being sent to a gateway that is unreachable. Since you said one of your connections is down, that's probably the culprit.
Answer: Packet loss tells me that something is malfunctioning somewhere, likely a switch or the modem itself.  Depending on what you're doing, a DSL connection should be adequate for 50 users just surfing the Web: I have several clients on standard business class DSL connections (5Mbps down, ~800Kbps up) with ~100 users using the Internet for standard Web surfing and email and performance is fine.
I do find that I regularly swap out DSL modems, regardless of manufacturer: they just seem to be cheaply made, get pretty hot, and die eventually.  Might be worthwhile as a quick test to swap in another DSL modem.
If you're a heavy Internet user (lots of downloading/uploading of large files, etc.) and with two DSL connections, I'd recommend getting an edge router that can do load balancing/failover and possibly Quality of Service (QoS): Netgate sells ALIX kits with pfSense (Open Source) firewall, which has "enterprise" features for ~$200 USD.  Best bang for the buck for a firewall I've seen.  With that configuration, you can even setup policy-based routing to route certain traffic out one connection primarily (say, core server services like email, DNS, etc. get routed out through DSL #1, web surfing out #2), while failing over when it's down.
Answer: it seems to be issue with either your [lan switch] or [dsl modem].
packets are getting dropped. so check it out.
well for bonding two internet connection you can use linux and have a web accelerator application which will cache dns queries.
these link will clear all your doubts (i suppose)
Is it possible to merge multiple internet connections?
Answer: The two received, two dropped pattern is suspicious.  Does it continue if you ping for a longer period of time (ping -t www.google.com)?  What happens during off hours when you don't have a large user load?
Do a trace-route to a web site (i.e. tracert www.google.com), then do multiple pings to each hop along the way.  This should help you narrow down where your trouble begins.
Answer: As you have 50% packet loss, this identifies a local network issue. To confirm whether the issue is being caused at the core level by either the DSL modem or a local switch, disconnect all other systems from the network, only connecting a single device to the internet. Confirm whether the problem still exists, if it does, replace one piece of hardware at a time to identify the issue.
If the issue resolves itself with a single device connected, another device on the network may be transmitting a high volume of information in a particular sequence which may be causing the packet loss pattern that you're seeing. Inspect each additional PC to identify the cause in this case. 50% packet loss in general identifies a network issue.


drf-yasg, easier way to see only certain end points?

Question: We have many apps and endpoints and its easier to expose certain endpoints to clients through yasg when we work on certain features.
Currently I'm defining separate urlpatterns for swagger in each app and aggregate it from upper url .
Do the following in each app (to selectively include endpoints)
 router_swagger.register(r'user_coupons', UserCouponViewSet)
 router_swagger.register(r'coupons', CouponViewSet)

 urlpatterns_swagger = [
     url(r'^rest_api/', include(router_swagger.urls)),
 ]

And aggregate the urlpatterns from somewhere else
swagger_urlpatterns = [
]

from review.urls import urlpatterns_swagger as s1
swagger_urlpatterns += s1
from saleor.promotion.urls import urlpatterns_swagger as s2
swagger_urlpatterns += s2

schema_view = get_schema_view(
    openapi.Info(
        title="2019_09",
        default_version='v1',
    ),
    public=True,
    patterns=swagger_urlpatterns,
    permission_classes=[permissions.IsAdminUser],
)

urlpatterns += [
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),

]

It works but its somewhat tedious, wonder if there's a better way ?
Answer: drf-yasg follows the same pattern as DRF(https://www.django-rest-framework.org/api-guide/schemas/) in implementing get_schema_view.
You could move the swagger file generation into a separate file and import all patterns into that file similar like this:
schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version="v4",
        description="Some endpoints",
        contact=openapi.Contact(email="email@example.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    patterns=s1+s2+s3
)

urlpatterns += [
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),

]


Dúvida em função recursiva

Question: Quando coloco:
return n * fatqua(n-1)

o programa retorna o resultado esperado que é 24.
Porém quando coloco:
return n * fatqua(--1)

o resultado do programa é 0. Não estou conseguindo entender a lógica dessa operação.
Segue o código:
#include <stdio.h>
#include <stdlib.h>

int fatqua(int n){

    printf("\n numero : %d",n);
    system("Pause");
    if(n>0)
    {
        return n * fatqua(n-1) ;
    }
    return 1;
}

int main(){
    int n, resul=0;

    printf("Digite um numero: ");
    scanf("%d",&n);

    resul= fatqua(n);
    printf("\n\n Fatorial e igual a: %d",resul);

}

Comment: Se você quer dizer `--n`, isso ocorre porque o decremento de `n` vai acontecer antes da multiplicação. Portanto quando `n` for `1` você vai multiplicar o resultado final por `0`.
Comment: @bigown eu acho que ele quis dizer `--n`
Comment: `--1` não faz sentido, pra que fazer isso?
Comment: @bfavaretto tu respondeu 2s antes de mim :|
Comment: @Genos Se quiser postar uma resposta mais detalhada abaixo, fique à vontade ;). Eu parei por aqui.
Comment: @bfavaretto eu vou esperar o dono da pergunta responder se é `--n`. Se for eu posto. Valeu!
Comment: Eu não respondi porque não sei o que ele quer ainda.
Comment: --1 é igual a 1, não?
Comment: @Sorack ??????? é erro de sintaxe. E se não fosse, faria mais sentido que desse zero, não?
Comment: Não sei te dizer, --1 em javascript da erro, mas em C não tenho nem idéia
Comment: Nós entendemos perfeitamente o fatorial, mas uma dica é sempre indicar a entrada que gerou a saída informada. Neste caso, sabemos que 24 é 4!
Comment: era --n mesmo, vlw
Answer: Assumindo que você queria o parâmetro --1:
Isso gera um erro de compilação:
fat2.c:10:27: error: lvalue required as decrement operand
         return n * fatqua(--1) ;

Apenas para deixar claro, lvalue é o mesmo que locator value. Isto quer dizer que a função espera receber um valor endereçável, e não uma constante.
Assumindo que você queria o parâmetro --n:
Bom, aqui temos algo interessante e a sua pergunta já foi feita no stackoverflow. Temos neste link e neste outro algumas respostas úteis.
Ressalto aqui alguns pontos importantes:

Usar --n causará o decremento antes que a instrução seja executada. Devido ao pré-decremento, a expressão avaliada será (n-1) * fatqua(n-1);
A multiplicação é comutativa (A * B = B * A), e isto a torna perigosa na hora de avaliar esta expressão. A ordem de avaliação dos argumentos é indefinida neste caso. Por isso é uma boa prática não usar duas vezes na mesma expressão uma variável que você está incrementando ou decrementando.
Se gostaria muito de usar --n para resolver o fatorial, execute o código abaixo:
#include <stdio.h>
unsigned int fatqua(unsigned int n){
    printf("\nnumero : %d", n);
    if (n < 2)
        return 1;
    return fatqua(--n) * (n+1);
}
void main() {
    unsigned int n, resul = 0;
    printf("Digite um numero: ");
    scanf("%d", &n);
    resul = fatqua(n);
    printf("\n\n Fatorial de %d eh igual a: %d\n", n, resul);
}

Note que fica horrível e muito menos legível que a primeira forma (com (n-1) no parâmetro da chamada recursiva). Além disso, um detalhe seria utilizar unsigned int também, já que não existe fatorial de número negativo. Ressalto mais uma vez, pelas razões citadas, que você deve utilizar
return n * fatqua(n-1);

Answer: Como já comentado, provavelmente a intenção original seria chamar como parâmetro --n. De qualquer modo, isso é perigoso e estraga a operação, pois pela ordem de precedência de operadores em C, o decremento é feito antes da multiplicação propriamente dita, gerando uma recursão da forma
n-1 * n-2 * ... * 2 * 1 * 0 * 1

Onde cada termo é -1 do que deveria ser (observe que o último 1 é o caso base da recursão, explicitado em return 1).
Numa nota extra, seria ainda mais perigoso ainda fazer algo do tipo fatqua(n--), pois nesse caso a chamada recursiva ocorre antes do decremento de n. Isso geraria infinitas recursões e, consequentemente, estouro de pilha.

Dúvida em função recursiva


WPF Combo and Rx FromEvent Pattern

Question: I am in process of developing a WPF app to practice Rx with MVVM.
Scenario
I have a View (MVVM) with a combo (some company name) and a detail (company journal) section; I wanted to populate detail section when user select an item from combo box.
The detail section data is populated with the help of a WCF service method, which take company name as input and Task<> as output.
Problem
Users sometime select combo box items in quick succession, which leads my window to freeze. I presume, this might be because of event queue up  Or due to slow result from wcf service method.
Therefore, I am thinking to use Rx's FromEvent pattern (MVVM fashion), which shall be able to observe ComboBox SelectedItem Change event to load  data from wcf and skip events those are coming in quick succession using some throttle.
I appreciate any sample implementations while respecting MVVM.
Answer: I think that the operator you are looking for is Switch(). I couldn't find an msdn page for it, but this is the signature you're after:
public static IObservable<TSource> Switch<TSource>(this IObservable<Task<TSource>> sources)

That will take an IObservable<Task<T>> and turn it into an IObservable<T> which produces the results of the most recent Task<T> received.
Here is an example implementation that doesn't use any MVVM, but I'm sure you can see how it would apply:
MainWindow.xaml
<Window x:Class="LastFromCombo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <ComboBox Name="cbx" />
            <TextBlock Name="result" />
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.cbx.ItemsSource = Enumerable.Range(0, 100);

        Observable.FromEventPattern<SelectionChangedEventArgs>(this.cbx, "SelectionChanged")
            .Select(ev => ev.EventArgs.AddedItems.Cast<object>().FirstOrDefault())
            .Select(GetDetails)
            .Switch()
            .ObserveOnDispatcher()
            .Subscribe(detail => this.result.Text = detail);
    }

    private static async Task<string> GetDetails(object data)
    {
        await Task.Delay(TimeSpan.FromSeconds(3.0));
        return "Details from " + data;
    }
}

WPF Combo and Rx FromEvent Pattern