Is my mixed effect model formula incorrect in R?

Question: I am doing a study that I would like to analyze data with a mixed effect model. I have three fixed effects and one random effect. My code output is seems a bit off and I am unsure if it is a structural problem with the code, or multicoliniarity in my data. I have tried testing fpr coliniarity, but haven't gotten the code to work (I think because I have mostly catagorical data)
Fixed Effects:
soil_type - 2 groups ("Medium" and "Fine")
treatment - 4 groups ("L", "S", "K", "C")
days - 3 sampling points (day 4, 11, 18)

Random Effect:
replicates - 3 groups (1,2,3)

My code is as followed:
cl.mod <- lmer(weighted_cl ~ soil_type + treatment + days + (1|rep),
               data = leach.conc, REML = FALSE)

I believe I have the correct code, but when I look at the output I am unsure if I am missing values:
Fixed effects:
                Estimate Std. Error t value
(Intercept)      7.01992    1.65258   4.248
soil_typeMedium -4.81518    1.05431  -4.567
treatmentKCl    10.48391    1.49103   7.031
treatmentLiquid 25.25578    1.49103  16.939
treatmentSolid   8.31138    1.49103   5.574
days            -0.32534    0.09223  -3.527

Correlation of Fixed Effects:
            (Intr) sl_tyM trtmKC trtmnL trtmnS
soil_typMdm -0.319
treatmntKCl -0.451  0.000
treatmntLqd -0.451  0.000  0.500
treatmntSld -0.451  0.000  0.500  0.500
days        -0.614  0.000  0.000  0.000  0.000*

I am unsure if this is because I have multicoliniarity in my data or if I have my code incorrect (or both). Because this is catagorical data, I am unsure about testing for coliniarity. Also, I have no missing values in my data. Any guidance or things to look at would be greatly appreciated!
Comment: Your random effect has three levels? That's a very low number.
Comment: Consider whether you need a mixed effects model at all, when there are simpler procedures that may address your need: https://stats.stackexchange.com/a/582056/121522
Comment: @JeremyMiles yes, that is how many replicates we extracted from our plots. Unsure how to increase that number aside from increasing replication our next field season
Answer: Data
So there are a number of questions in your question, and given that your data isn't on hand, I will use my own toy dataset to answer your question. First, the dput of my data in case you want to check yourself:
work <- structure(list(Work_Environment = c("Office", "Office", "Office",
"Home", "Home", "Office", "Office", "Office", "Office", "Office",
"Home", "Home", "Office", "Office", "Office", "Home", "Office",
"Home", "Home", "Office", "Office", "Home", "Office", "Home",
"Home", "Home", "Office", "Office", "Office", "Office", "Home",
"Home", "Home", "Office", "Office", "Office", "Office", "Office",
"Home", "Home", "Office", "Office", "Home", "Home", "Office",
"Home", "Home", "Office", "Office", "Home", "Home", "Office",
"Home", "Home", "Office", "Office", "Home", "Office", "Home",
"Home", "Home", "Home", "Office", "Home", "Office", "Office",
"Home", "Home", "Office", "Office", "Home", "Home", "Office",
"Office", "Home", "Office", "Office", "Home", "Office", "Office",
"Home", "Home", "Office", "Office", "Home", "Home", "Office",
"Home", "Home", "Office", "Office", "Home", "Office", "Office",
"Home", "Home", "Office", "Home", "Home", "Home", "Home", "Home",
"Home", "Office", "Home", "Office", "Office", "Home", "Home",
"Home", "Office", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Office", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Office", "Home", "Office", "Home", "Office",
"Office", "Office", "Office", "Home", "Home", "Home", "Home",
"Office", "Home", "Office", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Office", "Office", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Office", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Office", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Office", "Office", "Office",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Office", "Office", "Home", "Home",
"Office", "Office", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home",
"Home", "Home", "Home", "Home", "Home", "Office", "Office", "Office",
"Home", "Office", "Home", "Home", "Home", "Home"), Coffee_Cups = c(3L,
0L, 2L, 6L, 4L, 5L, 3L, 3L, 2L, 2L, 3L, 1L, 1L, 3L, 2L, 2L, 0L,
1L, 1L, 4L, 4L, 3L, 0L, 1L, 3L, 0L, 0L, 0L, 0L, 2L, 0L, 1L, 2L,
3L, 2L, 2L, 4L, 3L, 6L, 6L, 3L, 4L, 6L, 8L, 3L, 5L, 0L, 2L, 2L,
8L, 6L, 4L, 6L, 4L, 4L, 2L, 6L, 6L, 5L, 1L, 3L, 1L, 5L, 4L, 6L,
5L, 0L, 6L, 6L, 4L, 4L, 2L, 2L, 6L, 6L, 7L, 3L, 3L, 0L, 5L, 7L,
6L, 3L, 5L, 3L, 3L, 1L, 9L, 9L, 3L, 3L, 6L, 6L, 6L, 3L, 0L, 7L,
6L, 6L, 3L, 9L, 3L, 8L, 8L, 3L, 3L, 7L, 6L, 3L, 3L, 3L, 6L, 6L,
6L, 1L, 9L, 3L, 3L, 2L, 6L, 3L, 6L, 9L, 6L, 8L, 9L, 6L, 6L, 6L,
0L, 3L, 0L, 3L, 3L, 6L, 3L, 0L, 9L, 3L, 0L, 2L, 0L, 6L, 6L, 6L,
3L, 6L, 3L, 9L, 3L, 0L, 0L, 6L, 3L, 3L, 3L, 3L, 6L, 0L, 6L, 3L,
3L, 5L, 5L, 3L, 0L, 6L, 4L, 2L, 0L, 2L, 4L, 0L, 6L, 4L, 4L, 2L,
2L, 0L, 9L, 6L, 3L, 6L, 6L, 9L, 0L, 6L, 6L, 6L, 6L, 6L, 6L, 3L,
3L, 0L, 9L, 6L, 3L, 6L, 3L, 6L, 1L, 6L, 6L, 6L, 6L, 6L, 1L, 3L,
9L, 6L, 3L, 6L, 9L, 3L, 5L, 6L, 3L, 0L, 6L, 3L, 3L, 5L, 0L, 6L,
3L, 5L, 3L, 0L, 6L, 7L, 3L, 6L, 6L, 6L, 6L, 3L, 5L, 6L, 7L, 6L,
6L, 4L, 6L, 4L, 5L, 5L, 6L, NA, 8L, 6L, 6L, 6L, 9L, 3L, 3L, 9L,
7L, 8L, 4L, 3L, 3L, 3L, 6L, 6L, 6L, 3L, 4L, 3L, 3L, 6L, 4L, 3L,
3L, 4L, 6L, 0L, 3L, 6L, 4L, 3L, 3L, 7L, 4L, 4L, 3L, 1L, 6L, 4L,
6L, 5L, 3L, 6L, 6L, 3L, 6L, 3L, 5L, 6L, 6L, 3L, 6L, 4L, 9L, 7L,
6L, 3L, 3L, 3L, 4L, 6L, 3L, 6L, 3L, 4L, 4L, 3L, 5L, 5L, 5L, 0L,
6L, 4L, 5L, 6L, 4L, 1L, 6L, 3L, 6L, 6L, 2L, 5L, 5L, 6L, 5L, 4L,
5L, 4L, 6L, 5L, 0L, 3L, 4L, 4L, 1L, 4L, 3L, 5L, 8L, 1L, 4L, 4L,
2L, 2L, 3L, 3L, 5L, 3L, 4L, 3L, 3L, 3L, 3L, 3L, 2L, 1L, 4L, 3L,
5L, 4L, 7L, 5L, 2L, 4L, 1L, 5L, 3L), Time_Wake = c(500L, 715L,
600L, 600L, 700L, 600L, 700L, 500L, 500L, 500L, 500L, 700L, 645L,
700L, 630L, 645L, 700L, 600L, 700L, 550L, 700L, 730L, 725L, 800L,
600L, 640L, 600L, 730L, 650L, 830L, 630L, 630L, 830L, 722L, 641L,
800L, 720L, 700L, NA, NA, NA, 700L, 700L, 622L, 710L, 632L, 400L,
640L, 700L, 730L, 830L, 659L, 800L, 701L, 700L, 900L, 930L, 650L,
930L, NA, 700L, 300L, 830L, 800L, 705L, 647L, 800L, NA, 830L,
NA, 830L, 838L, 650L, 849L, 500L, 830L, 800L, 321L, 700L, 400L,
400L, NA, 700L, 600L, 604L, 700L, 730L, 700L, 700L, 500L, 700L,
630L, 500L, 600L, 700L, 600L, 830L, 600L, 500L, 600L, 738L, 758L,
645L, 702L, NA, 500L, 849L, 656L, 831L, 700L, 700L, 805L, 834L,
849L, 407L, 739L, NA, 717L, 852L, 826L, 446L, 919L, 842L, 754L,
900L, NA, 845L, 900L, 848L, 757L, 927L, 500L, 700L, 430L, 430L,
NA, 600L, NA, 452L, 700L, NA, 300L, 600L, 600L, 400L, 945L, 500L,
700L, 700L, 700L, 504L, 700L, 700L, 400L, 747L, NA, 200L, 740L,
441L, 833L, 815L, 400L, 600L, 600L, 700L, 344L, NA, 636L, 600L,
NA, 300L, 600L, 600L, 700L, NA, 822L, 360L, 600L, 945L, NA, 656L,
400L, 700L, 744L, 710L, 600L, NA, 700L, 700L, 700L, 253L, 600L,
819L, 700L, 600L, 655L, 835L, 848L, 654L, 630L, 745L, 300L, 730L,
700L, 700L, 700L, 700L, NA, 200L, 700L, 500L, NA, 500L, 700L,
700L, 730L, 700L, 830L, 825L, 700L, 600L, 700L, 700L, NA, 700L,
700L, 700L, 700L, 700L, 700L, 300L, 500L, 700L, 705L, NA, 700L,
723L, 531L, 841L, 845L, 744L, 742L, 830L, 648L, NA, 630L, 645L,
634L, 727L, 603L, 648L, 721L, 647L, 842L, 750L, 650L, NA, 645L,
645L, 751L, 130L, 729L, NA, 830L, 730L, 727L, 709L, 641L, NA,
709L, 710L, 621L, 747L, 720L, 628L, 654L, NA, 633L, 548L, 428L,
700L, 733L, 700L, 556L, 757L, 815L, 735L, NA, 500L, 707L, 751L,
601L, 500L, NA, NA, 600L, 800L, 607L, 557L, 723L, 718L, 630L,
400L, 633L, 550L, 607L, 621L, 640L, 636L, 559L, 417L, 701L, 100L,
640L, 629L, 614L, 545L, 615L, 550L, 755L, NA, 737L, 725L, 613L,
713L, 555L, 746L, 634L, 651L, 701L, NA, NA, 810L, 646L, 442L,
NA, 641L, 642L, 700L, 525L, 332L, 743L, 703L, 718L, 625L, NA,
618L, NA, NA, 400L, 329L, 748L, 700L, 720L, 602L, 727L, 842L,
842L, 400L, NA, 704L, 808L, 632L, 746L, 405L, NA, 559L, 649L,
639L, 709L, 720L, 349L, 650L, 630L, NA, NA, 630L, NA), Mins_Work = c(435L,
350L, 145L, 135L, 15L, 60L, 60L, 390L, 395L, 395L, 315L, 80L,
580L, 175L, 545L, 230L, 435L, 370L, 255L, 515L, 330L, 65L, 115L,
550L, 420L, 45L, 266L, 196L, 198L, 220L, 17L, 382L, 0L, 180L,
343L, 207L, 263L, 332L, 0L, 0L, 259L, 417L, 282L, 685L, 517L,
111L, 64L, 466L, 499L, 460L, 269L, 300L, 427L, 301L, 436L, 342L,
229L, 379L, 102L, 146L, NA, 94L, 345L, 73L, 204L, 512L, 113L,
135L, 458L, 493L, 552L, 108L, 335L, 395L, 508L, 546L, 396L, 159L,
325L, 747L, 650L, 377L, 461L, 669L, 186L, 220L, 410L, 708L, 409L,
515L, 413L, 166L, 451L, 660L, 177L, 192L, 191L, 461L, 637L, 297L,
601L, 586L, 270L, 479L, 0L, 480L, 397L, 174L, 111L, 0L, 610L,
332L, 345L, 423L, 160L, 611L, 0L, 345L, 550L, 324L, 427L, 505L,
632L, 560L, 230L, 495L, 235L, 522L, 654L, 465L, 377L, 260L, 572L,
612L, 594L, 624L, 237L, 0L, 38L, 409L, 634L, 292L, 706L, 399L,
568L, 0L, 694L, 298L, 616L, 553L, 581L, 423L, 636L, 623L, 338L,
345L, 521L, 438L, 504L, 600L, 616L, 656L, 285L, 474L, 688L, 278L,
383L, 535L, 363L, 470L, 457L, 303L, 123L, 363L, 329L, 513L, 636L,
421L, 220L, 430L, 428L, 536L, 156L, 615L, 429L, 103L, 332L, 250L,
281L, 248L, 435L, 589L, 515L, 158L, 0L, 649L, 427L, 193L, 225L,
0L, 280L, 163L, 536L, 301L, 406L, 230L, 519L, 0L, 303L, 472L,
392L, 326L, 368L, 405L, 515L, 308L, 259L, 769L, 93L, 517L, 261L,
420L, 248L, 265L, 834L, 313L, 131L, 298L, 134L, 385L, 648L, 529L,
487L, 533L, 641L, 429L, 339L, 508L, 560L, 439L, 381L, 397L, 692L,
534L, 148L, 366L, 167L, 425L, 315L, 476L, 384L, 498L, 502L, 308L,
360L, 203L, 410L, 626L, 593L, 409L, 531L, 157L, 0L, 357L, 443L,
615L, 564L, 341L, 352L, 609L, 686L, 386L, 323L, 362L, 597L, 325L,
51L, 570L, 579L, 284L, 0L, 530L, 171L, 640L, 263L, 112L, 217L,
152L, 203L, 394L, 135L, 234L, 507L, 224L, 174L, 210L, 138L, 52L,
326L, 413L, 695L, 370L, 256L, 327L, 490L, 128L, 469L, 567L, 359L,
561L, 478L, 233L, 550L, 390L, 406L, 56L, 47L, 258L, 332L, 114L,
193L, 435L, 493L, 659L, 93L, 86L, 0L, 228L, 232L, 318L, 295L,
639L, 367L, 313L, 253L, 433L, 399L, 269L, 446L, 407L, 424L, 410L,
309L, 364L, 700L, 345L, 274L, 113L, 202L, 553L, 157L, 351L, 303L,
392L, 539L, 337L, 297L, 479L, 311L, 173L, 94L, 170L, 469L, 180L,
311L, 106L, 521L, 378L, 61L, 462L, 644L, 310L, 533L, 517L, 136L,
0L, 392L, NA)), class = "data.frame", row.names = c(NA, -378L
))

The data in my model consists of two predictors: Coffee_Cups, which are how many coffee cups were consumed that day, and Time_Wake, which is the time of waking up that day. Work_Environment here was selected as a random effect with two levels to emulate what you did, but below I express that this isn't a wise choice. The expected outcome or y in this model is Mins_Work, or how many minutes of productivity were recorded that day. You can see the structure of the data with this code:
work %>%
  select(Work_Environment,
         Coffee_Cups,
         Time_Wake,
         Mins_Work) %>%
  glimpse()

As seen here:
Rows: 378
Columns: 4
$ Work_Environment <chr> "Office", "Office", "Office", "Home", "Home", …
$ Coffee_Cups      <int> 3, 0, 2, 6, 4, 5, 3, 3, 2, 2, 3, 1, 1, 3, 2, 2…
$ Time_Wake        <int> 500, 715, 600, 600, 700, 600, 700, 500, 500, 5…
$ Mins_Work        <int> 435, 350, 145, 135, 15, 60, 60, 390, 395, 395,…

Observing Missing Values
It's not clear if you have missing values in your data, as the summary output from your lmer summary doesn't appear to have the portion that states how many observations there were. That said, you can check your missing data fairly easily in R. I have checked both of my fixed effect predictors here:
#### Check NA Values ###
work %>%
  select(Mins_Work) %>%
  is.na() %>%
  table() # 2 NA values

work %>%
  select(Time_Wake) %>%
  is.na() %>%
  table() # 43 NA values

Then I checked what the total observations are in my data.
nrow(work) # 378 observations

Since there are only 378 observations and 45 missing, we should have 333 values observed by the lmer model. Here I have built my lmer model below:
hlm.work <- lmer(Mins_Work
                 ~ Coffee_Cups
                 + Time_Wake
                 + (1|Work_Environment),
                 data = work)
summary(hlm.work)

As can be seen, the model retained only the 333 observations in the "Random effects" section in the output:
Linear mixed model fit by REML. t-tests use Satterthwaite's method [
lmerModLmerTest]
Formula: Mins_Work ~ Coffee_Cups + Time_Wake + (1 | Work_Environment)
   Data: work

REML criterion at convergence: 4338.3

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.51991 -0.70343 -0.01399  0.73630  2.93450

Random effects:
 Groups           Name        Variance Std.Dev.
 Work_Environment (Intercept)  4289     65.49
 Residual                     27230    165.01
Number of obs: 333, groups:  Work_Environment, 2

Fixed effects:
             Estimate Std. Error        df t value Pr(>|t|)
(Intercept) 400.69391   64.43207   3.34404   6.219  0.00604 **
Coffee_Cups  28.71402    4.14095 329.56783   6.934 2.16e-11 ***
Time_Wake    -0.18917    0.06431 329.14364  -2.942  0.00350 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) Cff_Cp
Coffee_Cups -0.172
Time_Wake   -0.626 -0.124

Multicollinearity
The VIF in your model can be quickly observed with the performance package. The code can be seen below:
library(performance)
check_collinearity(hlm.work)

Which shows our VIF isn't high enough to warrant concern:
# Check for Multicollinearity

Low Correlation

        Term  VIF    VIF 95% CI Increased SE Tolerance Tolerance 95% CI
 Coffee_Cups 1.02 [1.00, 17.58]         1.01      0.98     [0.06, 1.00]
   Time_Wake 1.02 [1.00, 17.58]         1.01      0.98     [0.06, 1.00]

Appropriateness of Model
As to your question about the suitability of your model, there is nothing wrong specified from what I can see, but as some others have noted, you may have too few random effects to warrant their inclusion into this model. You may want to either consider a fixed effect regression or if there are other random effects you think contribute to "noise" that have enough levels, you can include them instead.
Comment: Hello @Shawn Hemelstand. Thanks so much for answering my question! Thankfully I do not have any NA values in my data, so I do not need to filter them out. I did check the VIF with the package you recommended and see High Coliniarity between soil_type and treatment and moderate correlation between days, so that is likely an issue I am running into.
Comment: Good to hear. Also please accept my answer if it was helpful :)


Lexicalmente, o que acontece quando retornamos uma variável dentro de um método que está declarada na função desse método?

Question: Alguém me ajuda a entender o contexto de execução desse código?

myVar é declarada no Global;
myVar é declarada em a();
b() é executado e myVar é declarada em b();
myVar não é encontrada em c():

dúvida: ele não deveria descer para procurar no b() ou no global? e trazer algum dos dois?

function b () {
        function c() {
            console.log(myVar);
        }
        c();
        var myVar = 3
    }
function a() {
     b();
     var myVar = 2;
}

let myVar = 1

a();
Answer: Cada função cria o seu escopo. O var quando declarado/usado dentro de uma função declara essa variável e bloqueia acesso a variáveis com o mesmo nome fora desse escopo. Contudo, nas linhas anteriores à linha onde esse var é usado, o valor da variável ainda não está definida...
O JavaScript consegue usar funções declaradas antes de correr o código mas variáveis são usadas somente quando o código chega à linha onde estão. Isto chama-se Hoisting  e a diferença é:
function add() {} // function declaration - disponível em todo o escopo

var add = function () {} // function expression - declarada em todo o escopo,
                         // mas só disponível depois da linha ter sido corrida

Repara no exemplo:

function a() {
  b();
  console.log(1, foo, typeof foo); // 1 undefined undefined
  var foo = 'bar';
  console.log(2, foo, typeof foo); // 2 bar string
  try {
    console.log(3, inexistente, typeof inexistente); // dá erro

  } catch (err) {
    console.log(4, err.message); // 4 inexistente is not defined
  }

  function b() {
    console.log(5, foo); // 5 undefined - a função corre mas a variável não
  }
}

a();

No caso da variável com o nome inexistente o código sabe que, ainda que não tenha sido declarada nas linhas que estão a ser executadas, essa variável nunca é declarada. Daí o erro.

Nota: contexto de execução refere-se ao this, a tua pergunta refere-se a Hoisting e escopo de variáveis.


SQL Query to find name ending with \\FileName

Question: Is there a way to find all records in a table that end with double slash e.g. \\Test Sample.pdf
DocPath ->
\\Main Documents\ROR456\ABC-1C9MUWP00B0-0022\\Test Sample.pdf

I tried this but no result:
SELECT * FROM Reports WHERE DocPath LIKE '[\\*.]$'

Comment: Have you looked into using the SPLIT_STRING function: https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15&viewFallbackFrom=sql-server-2014
Comment: SQL Server doesn't support regular expressions.   Try LIKE '%\\%' .
Comment: Your first sentence doesn't make sense.  First records don't "end" they have columns.  And the double slash is at the beginning -- not end -- of the string.
Answer: String manipulation is not a strong point of T-SQL, so the code that will do what is required will work slow and look ugly. Nevertheless, something like that might do the trick:
select t.Id, t.DocPath, ss.value
from (values
    (1, '\\Main Documents\ROR456\ABC-1C9MUWP00B0-0022\\Test Sample.pdf'),
    (2, '\\Main Documents\ROR456\ABC-1C9MUWP00B0-0022\Test Sample.pdf'),
    (3, '\Main Documents\ROR456\ABC-1C9MUWP00B0-0022\Test Sample.pdf'),
    (4, '\Main Documents\\ROR456\ABC-1C9MUWP00B0-0022\Test Sample.pdf')
) t (Id, DocPath)
    cross apply string_split(replace(t.DocPath, '\\', '['), '[') ss
where ss.value not like '%\%'
    and ss.value > ''
    and ss.value like '%.%';

If I would need to process a significant amount of records, I would consider an alternative. Off the top of the head:

If it's some sort of ETL process, I would utilise .NET regexps in a SSIS dataflow component (source, or transformation), which would do the job in a much more elegant manner;
For any kind of OLTP BAU activity that has to happen inside the database, I would probably resort to a CLR function, which would give the same C# / VB.Net capability as above.

P.S. Keep in mind that the string_split() function requires at least SQL Server 2016 and database compatibility level 130.
Answer: You can use this expression:
select right(DocPath, charindex('\\', reverse(DocPath)) + 1)

The above extracts the part after the last double backslash, which appears to be what you want.
However, a more literal interpretation of your query suggests you want:
SELECT *
FROM Reports
WHERE DocPath LIKE '%\\Test Sample.pdf'

Comment: Where is the table name in the query ?? Can you write complete query ?


Terminal Server local profiles fail to delete on logoff

Question: Our company is in the middle of deploying Terminal Services 2008 R2, however i have noticed that our TS Users profiles do not get removed from local Terminal Server at user logoff.
Now im aware that this is something to-do with a process holding onto a connection to the registry at logoff (or words to that affect).
so i cleared the TS event log logged in as the user, logged out as the user and this event was left in the registry.

Windows detected your registry file is still in use by other
  applications or services. The file will be unloaded now. The
  applications or services that hold your registry file may not function
  properly afterwards.
DETAIL -   2 user registry handles leaked from
  \Registry\User\S-1-5-21-1145379511-113177986-563163613-1483: Process
  968 (\Device\HarddiskVolume2\Windows\System32\svchost.exe) has opened
  key
  \REGISTRY\USER\S-1-5-21-1145379511-113177986-563163613-1483\Printers\DevModePerUser
  Process 872 (\Device\HarddiskVolume2\Windows\System32\svchost.exe) has
  opened key
  \REGISTRY\USER\S-1-5-21-1145379511-113177986-563163613-1483\Software\Microsoft\Internet
  Explorer\LinksBar

Now im still fairly new to Terminal Services and its finer bits, however i have no real idea what i should be doing with this error message, google provides some info on the problem but no specific reason for it or cure.
i can see that something within IE's Linkbar is one of the issues and what i can guess is a printer, but neiter error is more specific about what went wrong.
thanks
Kris
Comment: Is the TS server a VMware guest by any chance?
Comment: yes, the terminal server is running within VMWare VSphere 4.
Answer: If you have the Shared Folders component of VMware tools installed then that's what's probably causing the problem. I ran into this as well. Remove the Shared Folders component and that should fix it.
Comment: Exactly the problem, whilst im aware from other posters above there are other programs and apps that can generate this issue, after uninstalling the VMware Tools component the problem resolved itself. i found that on a "Typical" install of Vmware Tools it does not add the shared folders component so its possible to have the tools without the component that generates the problems.
Comment: Glad you got it resolved. I've taken to making sure the Shared Folders component of VMware Tools is not installed on any of my VMware guest machines, regardless of their roles.
Answer: You need to research the root cause of each handle leak and fix them individually. Find out which service is holding each of the two keys open. Use the Process ID as starting point. In one case maybe a specific printer driver is causing the leak.
Try to disable the offending process/funtionality and check whether that makes the symptoms go away.
Sorry I cannot be more specific - this is detective work.
Comment: thought of this one :) i have used process monitor to look at the two pid's it mentioned and there both SVCHOST processes that are running between them a large amount of fairly important (some would say) critical windows services. @Helge Klein

to give an example pid id 872 is running the following services.

winmgmt
wuauserv
SessionEnv
ProfSvc
LanManServer
IKEEXT
GPsvc
CertProSVC
AeLookupSvc

the other process id is no longer running within the list.


Como mudo a cor do iontabs?

Question: Gastaria de mudar a cor do ion tab, eu consegui mudar a cor dos icones e do texto, mas o tab em si nao consigo modificar, eu sou bem iniciante no IONIC 3. Vou mostrar o codigo até entao.
home-entregador.html
<ion-tabs selectedIndex="2" class="teste" >
    <ion-tab [root]="entregas" tabIcon="cube" tabTitle="Entrega"></ion-tab>
    <ion-tab [root]="perfil" tabIcon="person" tabTitle="perfil" ></ion-tab>
    <ion-tab [root]="configuracao" tabIcon="settings" tabTitle="configuracao"></ion-tab>
</ion-tabs>

home-entregador.scss
page-home-entregador {
    .teste{
        background: #545454;
    }
}

tentei outros metodos mas não funcionaram então comecei a tentar qualquer coisa. Se alguem poder ajudar, obrigado.
Answer: As cores da guia podem ser alteradas usando variáveis Sass. Veja o aplicativo de conferência para um exemplo de exemplo: https://github.com/driftyco/ionic-conference-app/tree/master/src/theme404
Em variables.scss:
// Use the primary color as the background for the toolbar-md-background
$toolbar-md-background:                   color($colors, primary);

// Use the default background for the tabbar since it inherits from toolbar
$tabbar-md-background:                    #f8f8f8;

// Change the color of the tabs text
$tab-button-md-active-color:              color($colors, primary);
$tab-button-md-inactive-color:            #8c8c8c;

// Change the color of the segment button text
$toolbar-md-active-color:                 #fff;
$toolbar-md-inactive-color:               #fff;
$segment-button-md-text-color-activated:  #fff;

Answer: Eu consegui resolver fazendo alguns testes, aqui esta resolução:
<ion-tabs selectedIndex="2" color="verd" >
    <ion-tab [root]="entregas" tabIcon="cube" tabTitle="Entrega"></ion-tab>
    <ion-tab [root]="perfil" tabIcon="person" tabTitle="perfil" ></ion-tab>
    <ion-tab [root]="configuracao" tabIcon="settings" tabTitle="configuracao"></ion-tab>
</ion-tabs>

este "verd" em color="verd" é uma cor que eu adicionei em variable.scss
Comment: show de bola...
Answer: Oi! Tudo tranquilo?
Você consegue adicionando classes à aba também, como por exemplo:
No HTML:
<ion-tabs selectedIndex="2" color="verd" >
    <ion-tab [root]="entregas" tabIcon="cube" tabTitle="Entrega" class="entrega"></ion-tab>
    <ion-tab [root]="perfil" tabIcon="person" tabTitle="perfil" class="perfil"></ion-tab>
    <ion-tab [root]="configuracao" tabIcon="settings" tabTitle="configuracao" class="config"></ion-tab>
</ion-tabs>

Então é só referenciar no css normalmente pelo nome da classe que funciona. :)
Algo como:
ion-tabs ion-tab.entrega { ... }
ion-tabs ion-tab.perfil{ ... }
ion-tabs ion-tab.config{ ... }

Como mudo a cor do iontabs?


How to import an svg document to a ThreeJS scene?

Question: I can see that there is a SVGLoader in the documentation, but it does not seem to be in r71. Do I have to compile master for this ?
Is there any other better way to achieve this ? Just looking for the best way to approach this.
Answer: The SVGLoader can be found in the examples/js directory here.
You must include the loader source file explicitly in your project.

three.js r.71


Why are the contents of this JSON string changing inside of my ajax call?

Question: I'm trying to pass an array of JSON objects to my controller.  When I insert an alert right before the ajax call the JSON appears to be well formed and all of the variables are populated correctly.  However, when I inspect the payload of the ajax call I see that some of the variables contain nulls.  What could be causing this? Did I make a mistake somewhere in my jQuery?
function postToController(instructionsJSON) {
    alert(instructionsJSON);
    $.ajax({
        type: "POST",
        url: "/Traffic/create",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: instructionsJSON,
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            alert(error);
        }
    });
}

Comment: I think you are seeing 2 different results. The alert has adId, marketName, estimateId... but in the Preview it is Dma, AdID, and Estimate.
Comment: the result that you are console.logging is the result from the server not the same as the results that you are sending the server. Check what your server is doing. Is is supposed to be echoing out what you put in? Then make certain the Estimate var is what you think it is.
Comment: Yes that was the problem.  I thought I was inspecting the payload but actually it was the response.  I used different property names on the server and that was the cause of the nulls.
Answer: Seems to me that you're inspecting two different sets of data.
alert(instructionsJSON); // the client data

// ...

console.log(result); // data returned from the server

If your server should be returning the same data but there's a difference, then it has to do with whatever the server is doing to the data before it returns it.
Answer: Generally you send data as key/value pair to the server side page. In your case var 'instructionsJSON` is an array of JSON and not a JSON. So it needs to be passed as a key/value pair which will hold this array.
function postToController(instructionsJSON) {
    alert(instructionsJSON);
    $.ajax({
        type: "POST",
        url: "/Traffic/create",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { dataFeildName: instructionsJSON },
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            alert(error);
        }
    });
}

Comment: Thanks for that explanation.  That may be the solution to another problem I'm having.  What is dataFieldName? I'll +1 your answer since technically I should accept the other response as the answer to the question asked.


Sequences and Series ( Power Series ) question.

Question: $(a)$ Starting with the geometric series $\displaystyle \sum_{n=0}^{\infty} x^n$, find the sum of the series $\displaystyle \sum_{n=1}^{\infty} nx^{n-1}\;, \vert x\vert<1$.
$(b)$ Find the sum of the series $\displaystyle \sum_{n=1}^{\infty} nx^n\;, \vert x\vert<1$ and $\displaystyle\sum_{n=1}^{\infty} \frac{n}{2^n}$.

Here's the image of the question. I know that the sum from $0$ to $\infty$ of part $A$ is the same as the sum to $\infty$ from $1$ if you decrease the power by $1$. So I'm guessing the series will converge, but I don't know how to find the sum ( because $x$ can be both $+ve$ and $-ve$ ( I assumed)) .
For part $A$ I got the sum as $1+x+x^2+x^3$ and so on.
So the next bit will be $1+2x+3x^2+4x^3+\dots +(\infty+1)x^{\infty}$.
My questions is am I doing it right because it seems way too easy. And if not, then what should I do?
Comment: Related : http://math.stackexchange.com/questions/732424/is-it-possible-to-bound-this-sum
Comment: Hint: Can you rewrite $\left(\sum_{n=0}^\infty x^n\right)^2$ into a power series?
Comment: Hint 2: For the second part of (b), compare $n\frac{1}{2^n}$ first to $nx^n$ and then to $nx^{n-1}$.
Answer: There is a closed formula (not written as an infinite sum) for the sum of a geometric series. Find out what that is. Now differentiate series and its sum formula.
For part (b) you are just playing with your series from part (a).
Comment: Thank you, didn't notice the derivative


The requested page could not be found error appear in page but page is render correctly-drupal 7

Question: i had create one block in my custom module, which display in "CONTENT" region, only on "currant-trustees" page.
when i access url "localhost/drupal/currant-trustees" page is render correctly, but with error "The requested page "/drupal/currant-trustees" could not be found." and also page title is page not found.
Comment: have you created a page named as currant-trustees?
Comment: you have to create a basic page first named as current-trustees and then render the block in that page.
Comment: no i create block using template file
Comment: i mean first i register block using hook_block_info(), then register template using hook_theme() and finally assign content using hook_block_view() with template file.
Comment: page is rendered as per my requirement but problem is it display error page could not be found
Comment: yes as i told you need to create a blank page named as currant-trustees. you will not get this error and your block display in that page.
Answer: It sounds to me like you only want to show said block on that page and nothing else. You might be better off implementing hook_menu() to register a callback (a page) which displays custom content, instead of creating an empty page and showing a block on that.
It might look something like this:
<code>/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['currant-trustees'] = array(
    'page callback' => 'MYMODULE_currant_trustees',
    'title' => 'Currant trustees',
    'type' => MENU_CALLBACK,
  );
  return $items;
}
function MYMODULE_currant_trustees() {
  $content = 'This is where your content should go, just copy the code from the block content';

  return $content;
}
</code>
Comment: Yes you are right when we wants to display only that block in page content region than your solution is perfect.
Answer: The problem is i just registered block with specific page/url, but there is no any page/url on which drupal going to display block, so first i need to register page/url in drupal so create one page and than display block on that page.


pandas pivot table default behaviour

Question: I have a dataframe which looks like :
col1 col2      col3 col4
   0    fst    4    7
   0    snd    5    8
   1    fst    6    9

I apply:
 pd.pivot_table(df, index='col1', columns='col2', aggfunc='count', fill_value=0.0)

output:
       col3        col4
       fst   snd   fst  snd
index
0      1     1      1    1
1      1     0      1    0

Expected output:
       fst   snd
index
0      1     1
1      1     0

Why columns have multiindex?
Comment: Because you have another two columns `col3` and `col4`, you don't need `pivot_table` just `pd.crosstab(df.col1, df.col2)`
Answer: You need to add the values
out = pd.pivot_table(df, index='col1', columns='col2', values = 'col3',aggfunc='count', fill_value=0.0)

Also in your case ,do pd.crosstab
out = pd.crosstab(df.col1, df.col2)

pandas pivot table default behaviour


MySQL returns not logical id's

Question: Today I was working on some MySQL query exercises and I come up with one of the weirder results. The image says more than a thousand words. I have no idea why this is happening so if anyone understands what is causing this issue or what I misunderstood about MySQL behavior, I would be very grateful for an explanation. I am expecting 1, 2, 3, 4 and 5 from the first query. Thank you.
Comment: put order by and see if the same result shows
Comment: Please don't just put an image and claim that the problem is obvious. Images are not searchable. Doing this will cause your question to get down voted.
Comment: Well, I am not claiming the problem is obvious, I said what results I am expecting from this query and that I don't understand what is causing results like this.
Answer: A DB is designed to grab the data as fast as possible.
If you don't add a specific order to your query then why should the DB waste time and order the data?
There is no garanteed order without an order by clause.
Comment: "DB will return the results in the way it grabs them as fast as possible"

This makes sense, but what I am wondering is why it happens even if I select 2 columns, but when 3 are included the results are good.

Is the reason same?
Comment: For the very specifics why it grabbed the data like this you would have to analize the source code of MySQL. Sometimes it is the fastest way to grab the data according to an index and since the ID is the primary key it grabs them in that order. But not garanteed
Comment: Awesome, thank you so much for an explanation, helped me a lot to understand.

MySQL returns not logical id's


Como pegar um valor de elemento html via Javascript

Question:
Eu quero pegar o valor "13" presente neste li class.
Answer: Você pode utilizar a função querySelector do javascript, conforme abaixo

var a =  document.querySelector(".pageNav-page>a");
var textoDeA = a.innerText;
console.log(textoDeA);

  13

https://www.w3schools.com/jsref/met_document_queryselector.asp


pop middle element in C

Question:
So i was doing my assignment when i got stuck in this question. We are using stack [struct]  in C and want to pop middle element of the stack, i wrote the common push and pop function, with print and isEmpty functions. i just need some help with question.
We need to pop middle element from the list.
Example of desired input and out given below
Input:  Stack[] = [1, 2, 3, 4, 5]
Output: Stack[] = [1, 2, 4, 5]

Input: Stack[] = [[1, 2, 3, 4, 5, 6]
Output: Stack[] = [1, 2, 4, 5, 6]

and my code is here
#include <stdio.h>
#include <stdlib.h>
//self-referenced structure
struct stackNode {
    int data;
    struct startNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode StackNodePtr;

//prototypes
void push(StackNodePtr *topPtr, int info);
int pop(StackNodePtr *topPtr);
void printStack(StackNodePtr currentPtr);
void isEmpty(StackNodePtr *topPtr);
int main(void){
    StackNodePtr stackPtr = NULL;
    int count= 0;
    char value;
    char input;
    printf("%s","Stack[] = [");
    scanf("%s\n", input );

    while(input != "]"){
        scanf("%c, ",&value);
        count++;
        push(&stackPtr, value);
    }
    if(count%2==0){
        count = count / 2;
    }
    else {
        ++count;
        count = count / 2;
    }
    puts("\n");
    printf("Stack[] = ");
    printStack()
}

void push(StackNodePtr *topPtr,int info){
    StackNodePtr newPtr = malloc(sizeof(StackNode));

    if (newPtr != NULL){
        newPtr->data = info;
        newPtr->nextPtr = *topPtr;
        *topPtr = newPtr;
    }
    else {
        printf("%d not inserted, no memory\n", info);
    }
}
int pop(StackNodePtr *topPtr){
    StackNodePtr tempPtr = *topPtr;
    int popValue = (*topPtr)->data;
    *topPtr =(*topPtr)->nextPtr;
    return popValue;
}
void printStack(StackNodePtr currentPtr){
    if(currentPtr == NULL) {
        puts("The stack is empty\n");
    } else {
        printf("%s","[");
        while(currentPtr != NULL) {
            printf("%d, ",currentPtr->data );
            currentPtr = currentPtr->nextPtr;
        }
        printf("%s","]");
    }
}

void isEmpty(StackNodePtr topPtr){
    return topPtr == NULL;
}

EDIT:
//Author: Shivam taneja

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//self-referenced structure
struct stackNode {
    int data;
    struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;

//prototypes
void push(StackNodePtr *topPtr, int info);
int pop(StackNodePtr *topPtr, int iter);
void printStack(StackNodePtr currentPtr);
int main(void){
    StackNodePtr stackPtr = NULL;
    int count = 0;
    char value;
    printf("%s","Stack[] = [");
    scanf("%c, ", &value);
    while(!(value == ']')) {
        printf()
        scanf("%c",&value);
        count++;
        push(&stackPtr, value);
    }
    if(count%2==0){
        count = count / 2;
    }
    else {
        ++count;
        count = count / 2;
    }
    puts("\n");
    pop(&stackPtr, count);
    printf("Stack[] = ");
    printStack(stackPtr);
}

void push(StackNodePtr *topPtr,int info){
    StackNodePtr newPtr = malloc(sizeof(StackNode));

    if (newPtr != NULL){
        newPtr->data = info;
        newPtr->nextPtr = *topPtr;
        *topPtr = newPtr;
    }
    else {
        printf("%d not inserted, no memory\n", info);
    }
}
int pop(StackNodePtr *topPtr, int iter){
    StackNodePtr tempPtr = *topPtr;
    while(iter != 0){
        iter--;
        *topPtr =(*topPtr)->nextPtr;
    }
    int popValue = (*topPtr)->data;
    return popValue;
}
void printStack(StackNodePtr currentPtr){
    if(currentPtr == NULL) {
        puts("The stack is empty\n");
    } else {
        printf("%s","[");
        while(currentPtr != NULL) {
            printf("%d, ",currentPtr->data );
            currentPtr = currentPtr->nextPtr;
        }
        printf("%s","]");
    }
}

Answer: Since you're using a list, you'll have to do it differently than with array, but here's how you do it with an array:
[0 | 1 | 2 | 3 | ? | ...]
Let's say you want to pop element 1.
You then keep the address of current stack pointer, move to one you want to pop, pop it, then shift all elements to the front, and move pointer back to previous pointer - 1.
Result:
[0 | 2 | 3 | ? | ...]
You need to do exactly the same, but with your list.
Your stack looks like this:
0->1->2->3->?
You want to pop 1, what you do is go to node 1, pop it, then move all elements to the front:
0->2->3->?.
Let's see what happens if you simply delete 1:
0->? 2->3->?
The list gets cut off, you need to rejoin it.
To rejoin it, you need to know previous node and next node, then, it's as easy as previous.next = next.
Since we can't simply peek back, you need to keep track of previous node when iterating over the list, so, find the desired element while keeping track of previous node, then simply rewire the connection from previous.next = current, to previous.next = current.next, you can then return the value of current.
Comment: i am not using a list, the whole code aint working the way i thought it would work like. my idea was to use scanf to get the numbers and each number shall be taken from the string and push to the stack and then count will do its work and pop the middle one

pop middle element in C


Disabling adjacent meta keys in Emacs

Question: I'd like to change some of my Emacs keyboard habits, as some of the keyboard shortcut combinations (typically starting with C-x, M-x, etc) I do one-handed and they involve uncomfortable hand movements.  I'd like to change this behavior.
However, as I've been doing them for about 15 years, they're programmed into my muscle memory.  It's difficult for me to remember to change the way I type.
I was wondering if it is possible to do a fine-grained remapping in Emacs, even if it's one key at a time, so that (left-control)+x is disabled, but (right-control)+x is still fine, and the like.
Comment: *(not an answer to your question, hence the comment)*... "ctl-x" all done with the left hand is probably the most RSI inducing shortcut ever, due to how often it has to be called.  But you can remap *ctl-x-map* to something else.  Here's what I do to have a saner *ctl-x* in Emacs: http://stackoverflow.com/questions/8575726/emacs-get-rid-of-c-x/8581477
Answer: You can change "ctrl-x" "meta-x" to other ergo key combo. For example:

Caps Lock. You can remap the favorite "meta-x" to this single key. It is super fast and comfortable to type. For windows, autohotkey or keytweak can do the remap job. For Linux, you just change the key layout setting.
Ctrl+/. If you have a hhkb keyboard, or you have changed "Caps Lock" to "CTRL". Ctrl+/ is a nice way to replace "Ctrl+x" or "Meta-x". Ctrl+/ is a minor key combo in emacs, so you can change the origin one. it is far easier to type than "Ctrl+x".
"Alt"  is better than "Ctrl" because you can type it with thumbs.
ergoemacs has some nice keymap tricks. It use "Alt" as main function key. You can find it in https://code.google.com/p/ergoemacs/
I use this key binding happily and never consider other key-tweak plans again.
Buy a better keyboard. Some keyboards change the layout making it easier to type "Ctrl x" "Meta x".
Kinesis keyboard is a ultimate solution. You may find more alternative with google.
Colemak Maltron Dvorak. All of them have a different key layout. If you like to try a new layout. Do'nt forget them. It may help you to handle with "Ctrl x" problem.

Disabling adjacent meta keys in Emacs


Name for outer product of gradient approximation of Hessian

Question: Is there a name for approximating the Hessian as the outer product of the gradient with itself?
If one is approximating the Hessian of the log-loss, then the outer product of the gradient with itself is the Fisher information matrix.  What about in general?
I'm looking at this in the context of explaining what the so-called Gauss-Newton matrix assumes (Schraudolph, N. N. (2002). Fast curvature matrix-vector products for second-order gradient descent. Neural Computation, 14(7), 1723–38.).  We have an input vector, followed by a linear transformation, followed by a nonlinear loss function.  The Hessian of the linear transformation (A) is approximated as an outer-product of gradients.  The Hessian of the negative log-loss function (B) is assumed to be positive semidefinite.   My question is what is the assumption A called?
Answer: The expected value of the outer product of the gradient of the log-likelihood is the "information matrix", or "Fisher information" irrespective of whether we use it instead of the negative of the Hessian or not, see this post. It is also the "variance of the score".
The relation that permits us to use the outer product of the gradient instead of the negative of the Hessian, is called the Information Matrix Equality, and it is valid under the assumption of correct specification (this is important but usually goes unmentioned), as well as some regularity conditions that permit the interchange of integration and differentiation.
Perhaps this could be useful also.
Note: In many corners it is just said "outer product of the gradient" without adding "with itself".
Comment: The approximation is related to the asymptotic variance of the maximum likelihood estimator. Its full expression is $$Avar(MLE) = [E(H)]^{-1}E(SS')[E(H)]^{-1}$$ and due to the relation, $E(SS')=-[E(H)]$ it simplifies to $-[E(H)]^{-1}$ or $[E(SS')]^{-1}$.
Comment: Thanks, that's great for building intuition about what this approximation assumes.  Do you know if this approximation is made in general cases not involving a loss function?
Comment: Thanks, I'm not sure I understand, but I've edited my question to try to be more clear.
Answer: The outer product of gradient estimator for the covariance matrix of maximum likelihood estimates is also known as the BHHH estimator, because it was proposed by Berndt, Hall, Hall and Hausman in
this paper:
<code>Berndt, E.K., Hall, B.H., Hall, R.E. and Hausman, J.A. (1974).
"Estimation and Inference in Nonlinear Structural Models".
Annals of Economic and Social Measurement, 3, pp. 653-665.
</code>
In the discussion around equation (3.8) of the paper you may get further details justifying the use of this expression.


Wide column with Bootstrap and Isotope

Question: I have a project listing where I use Isotope and Bootstrap to show our projects. I have four columns, so each project spans three columns (.col-md-3). For the highlighted projects, I tried setting .col-md-6 for this, and it works very nicely for all items not as first child. When setting double the grid size on the first item child, the layout fails.
Has anyone had this issue before? I've found this Isotope/Bootstrap code from somewhere else, that had exactly the same issue. Try removing .col-md-6 from first child to any other, and it works perfectly, but never on the first child..
http://www.bootply.com/YaqDZBusnG
Answer: try adding
$(window).load(function() { ...js ...

on isotope function.
Comment: Thanks for your comment, although the problem remained after trying this.

Wide column with Bootstrap and Isotope


Ajax table form with tabledrag only works properly AFTER first submit

Question:
So this one has me kind of stumped.
With a simple table with 4 rows, I drag one row to another position, then hit save (submit).
When the ajax returns and replaces the form, the rows snap back to the original position. If I reload the page, I can see the order in which I dragged, did indeed get saved.
I reload the page, starting over, but this time start by pressing save, before dragging anything - and nothing appears to happen. But all form inputs id's and names now have a random-string, e.g. --XjidQzhH, appended to them. I can now drag a row and hit save again - and it actually works! It stays where I dragged it, also when reloading the page.
Once the form has been replaced the first time, everything seems to work as it should.
Hopefully someone knows what I'm doing wrong here - I've been rabbit-holing this for two days now and can't figure out what I'm missing.
Happens for me on Drupal 8.9.13, both with Bartik and Bootstrap themes.
Here's some reproducable code:
namespace Drupal\some_module_name\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

class TestForm extends FormBase {

    public function getFormId() {
        return 'testform';
    }

    public function buildForm(array $form, FormStateInterface $form_state, $args = NULL) {

        #If form is shown for the first time, get some default values or previous values from session
        $values = $form_state->getValues();
        if (!$values){

            #Load data from session if exists, otherwise we use some temp test data.
            #Using persistant data to allow for manual reload of page, in order to demonstrate that data and sorting of rows is saved correctly.
            $names = @$_SESSION['test_data_names'];
            if (!$names){
                $values =   [
                    "names"=>[
                        ["first_name"=>"ONE",   "last_name"=>"ONE",],
                        ["first_name"=>"TWO",   "last_name"=>"TWO",],
                        ["first_name"=>"THREE", "last_name"=>"THREE",],
                        ["first_name"=>"FOUR",  "last_name"=>"FOUR",],
                    ],
                ];
            }else{
                $values = ["names"=>$names,];
            }

            $form_state->setValues($values);
        }

        #Build the simple table for the form
        $form['names'] = [
            "#type"=>"table",
            "#tree"=>true,
            '#empty' => t('No names yet.'),
            '#tabledrag' => [[
                'action' => 'order',
                'relationship' => 'sibling',
                'group' => "group-order-weight",
            ]],
            '#header' =>[
                ["data"=>t("First name"),],
                ["data"=>t("Last name(s)"),],
                ["data"=>t("Weight"),],
            ],
        ];

        #Build table rows for the name inputs
        foreach ($values['names'] as $key=>$name_data){

            $row = [
                '#attributes'=>[
                    'class' => ['draggable'],
                ],

                "first_name"=>[
                    "#type"             => "textfield",
                    "#default_value"    => $name_data['first_name'],
                ],

                "last_name"=>[
                    "#type"             => "textfield",
                    "#default_value"    => $name_data['last_name'],
                ],

                "weight"=>[
                    "#type"             => "weight",
                    "#attributes"=>[
                        'class' => ["group-order-weight"],
                    ],
                ],
            ];
            $form['names'][] = $row;

        }

        $form['save'] = [
            "#type"             => "submit",
            "#value"            => t("Save"),
            '#submit'           => ['::ajax_save_submit'],
            '#ajax'             => [
                'callback'  => '::ajax_save_submit_callback',
                'wrapper'   => 'table-wrapper',
            ],
        ];

        return $form;

    }

    public function validateForm(array &$form, FormStateInterface $form_state) {

        parent::validateForm($form, $form_state);
        // return $form;

    }

    public function submitForm(array &$form, FormStateInterface $form_state) {

    }

    public function ajax_save_submit_callback(array &$form, FormStateInterface $form_state){

        $response = new AjaxResponse();
        $response->addCommand(new ReplaceCommand('#testform', $form));
        return $response;

    }

    public function ajax_save_submit(array &$form, FormStateInterface $form_state){

        #Get the names and save 'em in session so they persist if user reloads page
        $names = $form_state->getValue("names");

        $_SESSION['test_data_names'] = $names;

        $form_state->setValue("names",$names);
        $form_state->setRebuild(TRUE);

    }

}

Answer: Looks like the culprit was how I was adding the name rows to the form.
Wrong:   $form['names'][] = $row;

Correct: $form['names'][$key] = $row;

The reason it was "working" after the first submit, was that the replaced form had appended token id's to the form, so the replacement could not occur on the #testform id, as it no longer existed.
Here's the updated code that works, which also includes functionality to insert new rows:
namespace Drupal\some_module_name\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class TestForm extends FormBase {

    public function getFormId() {
        return 'testform';
    }

    public function buildForm(array $form, FormStateInterface $form_state, $args = NULL) {

        $values = $form_state->getValues();
        if (!$values){
            $values =   [
                "names"=>[
                    ["first_name"=>"ONE",   "last_name"=>"ONE",   ],
                    ["first_name"=>"TWO",   "last_name"=>"TWO",   ],
                    ["first_name"=>"THREE", "last_name"=>"THREE", ],
                    ["first_name"=>"FOUR",  "last_name"=>"FOUR",  ],
                ],
            ];

            $form_state->setValues($values);
        }

        #Build the simple table for the form
        $form['names'] = [
            "#type"=>"table",
            "#tree"=>true,
            '#empty' => t('No names yet.'),
            '#tabledrag' => [[
                'action' => 'order',
                'relationship' => 'sibling',
                'group' => "group-order-weight",
            ]],
            '#header' =>[
                ["data"=>t("First name"),],
                ["data"=>t("Last name(s)"),],
                ["data"=>t("Weight"),],
            ],
            '#prefix'      => "
",
            '#suffix'      => '
',

        ];

        #sort by weights - not necessary since we receive them in correct order in the array
        // uasort($values['names'], 'Drupal\Component\Utility\SortArray::sortByWeightElement');

        #Build table rows for the name inputs
        foreach ($values['names'] as $key=>$name_data){

            $row = [
                '#attributes'=>[
                    'class' => ['draggable'],
                ],

                "first_name"=>[
                    "#type"             => "textfield",
                    "#default_value"    => $name_data['first_name'],
                ],

                "last_name"=>[
                    "#type"             => "textfield",
                    "#default_value"    => $name_data['last_name'],
                ],

                "weight"=>[
                    "#type"             => "weight",
                    "#attributes"=>[
                        'class' => ["group-order-weight"],
                    ],
                ],
            ];
            $form['names'][$key] = $row;

        }

        $form['save'] = [
            "#type"             => "submit",
            "#value"            => t("Save"),
            '#submit'           => ['::ajax_save_submit'],
            '#ajax'             => [
                'callback'  => '::ajax_save_submit_callback',
                'wrapper'   => 'table-wrapper',
            ],
        ];

        $form['add'] = [
            "#type"             => "submit",
            "#value"            => "Insert row",
            '#submit'           => ['::ajax_insert_row_submit'],
            '#ajax'             => [
                'callback'  => '::ajax_insert_row_submit_callback',
                'wrapper'   => 'table-wrapper',
            ],
        ];

        return $form;

    }

    // public function validateForm(array &$form, FormStateInterface $form_state) {
    //     $values = $form_state->getValues();
    //  parent::validateForm($form, $form_state);
    // }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        #has to be defined, otherwise we get errors like:
        #TestForm contains 1 abstract method and must therefore be declared abstract or implement the remaining methods
    }

    public function ajax_save_submit_callback(array &$form, FormStateInterface $form_state){
        return $form['names'];
    }

    public function ajax_save_submit(array &$form, FormStateInterface $form_state){
        $names = $form_state->getValue("names");

        #save logic goes here..

        $form_state->setValue("names",$names);
        $form_state->setRebuild(true);
    }

    public function ajax_insert_row_submit(array &$form, FormStateInterface $form_state){
        $names = $form_state->getValue("names");
        $names[] = ["first_name"=>"NEW",   "last_name"=>"NEW",];

        $form_state->setValue("names",$names);
        $form_state->setRebuild(true);
    }

    public function ajax_insert_row_submit_callback(array &$form, FormStateInterface $form_state){
        return $form['names'];
    }

}


DIVI Navigation Bar details

Question: Site URL: http://www.digisalud.org/desarrollo/dona/
Hello!
Please, I am using DIVI Theme and I need to make these settings in the navigation bar:
NAVIGATION BAR:

The PLATFORM button on some laptop screens is shown on the down line of the navigation in screen with size between 1056 and 1346 px.
When you place the cursor on the DONA button or on the PLATFORM button near its corners, the text is shown in white, this should appear in yellow or blue.

I show you the images with the sample of each problem. This site is already in production and I need to close these details with the client. I appreciate the help very much.

Regards
Adriana
Answer: At 1280px, for example, there isn't space enough to put all the elements into the same row.
If you inspect all the element's width, you'll see that the menu container must have, at least, 1030px of width to keep all the elements inline.
Obviously, like your menu container width is setted to 80%, when the screens size is, for example, of 1280px, the menu container have a width of 1024px (that, like I said, is not enough).
One solution can be to force the container to cover the entire width in those resolutions.
You can approach this using media queries.
Something like this:
@media(min-width: 1024px) and (max-width: 1366px) {
  .container.et_menu_container {
    width: 100%;
  }
}

Snapshot with the Plataforma button hovered:

P.S: You can also adjust the paddings/margins of the menu elements (logo, menu items, buttons...)
Comment: Hello!
Thanks but the adjustments did not work for me. Now both buttons appear at the bottom of the menu. Also, I put a gray color to the hover of the DONA button so you can visualize the error when you leave the gray area and change the text to white.
Comment: Hi @Adri Salazar, I updated my answer. Let me know if it works to you now

DIVI Navigation Bar details


Can giving input too early cause glitches?

Question: Suppose that my Python code looks like this:
While(True):
    Var = input()
    Do something

I noticed that when I run this from a Windows prompt, I can give input while the Do something is still running. For example:

If I press enter during Do something, then the next time that input is asked the Var is automatically assigned empty input.
If I press something else (like 1) during Do something, then the next time that input is asked I see this in my prompt. So it says 1, and I can still choose to delete it, add something to it or press enter.
If can also make combinations of these. If I press 1, enter, 1, enter during Do something, then the next two loops will start automatically with Var = 1.

This seems a bit strange and potentially nonintended. Is it possible that the algorithm will behave different/strangely/undefined if I give certain inputs during Do something?
(Note that Do something uses the value of Var)
Comment: This is normal behavior. It doesn't affect code that doesn't interact with the standard input or the console application.
Answer: It is absolutely intended. It is not specific to Python, it's how terminal input works: Whatever you type in goes into a buffer, and is held there until the running program chooses to read it. Then it will be read in strict sequence -- as long as you are typing at the command line, there is no chance that some of your input could be read out of order. And the input buffer is quite large, so you have to do a lot of type-ahead before your input is lost or rejected.
Actually there are buffers in multiple places. What you type is not even delivered to your program until you hit Enter-- that's line-buffering at the terminal interface. But I trust this has answered your question.


Proving that a random vector is not bivariate normal

Question: Suppose X,Y are random variables and their joint pdf is given by:
f(x,y)=2g(x)g(y) where x*y>0, and zero otherwise.
g(x) and g(y) are pdfs of standard normal distribution.
I was first able to prove that the marginal distribution of X and Y is standard normal.
However, I am having trouble with the question: Is the random vector (X,Y) bivariate normal?
Is it correct to say that since the support of bivariate normal RV is the entire R^2 plane, but since this random vector does not have a positive density at points wheres XY<0, then it cannot be bivariate normal?
I also tried to find a linear combination of X and Y and prove that it is not normally distribution, but to no avail.
Comment: Yes, I think pointing out that the bivariate normal does not have zero density anywhere is the easiest way to do this one.
Comment: Thanks Thomas. Is there a way to contradict it explicitly?
Comment: In what sense is Thomas Lumley's point not "explicit"?
Comment: I meant to ask for a counter example. As I mentioned, I have tried to find a linear combination that is not normally distributed without success. I thought someone will be able to assist in finding a specific counter example.
Comment: A counterexample to what assertion?
Answer:
Since the density is zero for some $(x,y)$ and the bivariate normal density isn't, you have a simple proof that it's not bivariate normal

It's also easy to show the conditional distributions are not normal: the distribution of $Y$ given $X=1$ is half-normal, not normal.

Linear combinations take a little more work. It helps to characterise the distribution as $(Z_1, Z_2)|\{Z_1Z_2>0\}$, with $Z_1$ and $Z_2$ being bivariate standard normal.

Let $l=x+y$ and think about when $l$ is close to zero.  That happens if $x\approx -y$, which mostly happens when $xy<0$, which isn't allowed. We'd expect $l$ to have less probability near zero than a normal distribution.
This R code shows what's going on
<code>z1<-rnorm(10000)
z2<-rnorm(10000)
keep<-(z1*z2)>0

x<-z1[keep]
y<-z2[keep]
plot(x,y)

hist(x+y)
</code>

Ok, how do we prove this isn't normal without looking at it?  Well, by Bayes' Rule
$$f_l(l)\propto f_{z_1+z_2}(l)p(z_1z_2>0|z_1+z_2=l) $$
The first term is a normal density. The second term isn't, and in fact the second term is zero if $l=0$, so the whole thing is zero at $l=0$ and has a minimum where a normal distribution would have a maximum.  Or you could use actual calculation, but I hate doing that.
Comment: That's great explanation. Thanks Thomas!


Automate installation with Composer

Question: It was easy to get Drupal installed with a single drush command before:
            drush si $profile -y \
            --db-url=mysql://$MYSQL_USER:$PASS@localhost/$DB \
            --site-name=$DOM \
            --site-mail=$EMAIL \
            --account-mail=$EMAIL \
            --account-name=$USER \
            --account-pass=$PASS >> /dev/null 2>&1

and it would completely finish Drupal installation without expecting user to do anything on UI.
Now with Drupal switching to Composer package manager, I am using the following command
composer --quiet create-project drupal-composer/drupal-project:8.x-dev $HOME --stability dev --no-interaction

however, unfortunately this method expects user to finish Drupal 8 installation on UI entering database, username and password manually. I wonder is there any way to make Composer do installation till the very end without any human interaction?
Comment: You can still install Drupal with Drush, you just use Composer to handle getting the code base and Drush. Maybe Composer has some sort of post-hook, that you could use to automatically call the Drush code.
Comment: It does @Jaypan: https://getcomposer.org/doc/articles/scripts.md. Nick, remember Composer is just a generic dependency manager for PHP libraries, it doesn't know anything about Drupal unless you tell it about it. As Jaypan said, Composer is for getting the files, drush is for working with them in a Drupal context. You can combine the two, either with a Composer post-x script, or a simple bash script, but they're separate things by default
Answer: So since nobody provided acceptable answer, based on the above comments I tried the following bash-script and it worked flawlessly:
sudo -u $USER /usr/local/bin/composer --quiet create-project drupal-composer/drupal-project:8.x-dev $HOME/public_html --stability dev --no-interaction
cd $HOME/public_html/web
drush si -y \
  --db-url=mysql://$MYSQL_USER:$PASS@localhost/$DB \
  --site-name=$DOM \
  --site-mail=$EMAIL \
  --account-mail=$EMAIL \
  --account-name=$USER \
  --account-pass=$PASS >> /dev/null 2>&1

Automate installation with Composer


Is a random variable taking every rational number or a range of rational numbers discrete or continuous?

Question: My guess would be discrete because such a variable would only take a countable set of values and "continuous" seems to imply the continuum of the real numbers.
Comment: It won't count as continuous, since you have points with non-zero probability. Whether it counts as discrete or not depends on exactly whose definition of discrete you use (there are other possibilities than discrete/continuous). By the definition I was taught, the answer is "yes that's discrete", but by another common definition the answer is "no". This doesn't change anything material other than the label we apply of course.
Comment: A great answer specifying exactly what the pmf of such a random variable might look like is [here](http://stats.stackexchange.com/a/104018/6633)
Comment: These are both very helpful, clear responses.
Answer: A continuous variable has positive length, area or volume. These terms, respectively, correspond to particular Lebesgue measures. But the Lebesgue measure of $\mathbb{Q}$ is 0; it doesn't have positive length.
Approached from another perspective, it is sufficient to note that $\mathbb{Q}$ is countable, so it's not continuous.


CSS com list-style-type personalizado em fonts awesome

Question: Como posso alerar o bullet do list-style-type para um icone do fontawesome?

<!DOCTYPE html>

<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

This is a Heading

This is a paragraph.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas

 lobortis nisi eu risus molestie rutrum. Phasellus et facilisis tellus.

 Nullam a urna est. Suspendisse convallis, enim et viverra volutpat, mauris dui malesuada libero, et pretium sem mauris et ex. Aenean sodales nibh et quam semper, nec feugiat leo dapibus.

Curabitur sollicitudin eget odio eu accumsan.

 In quis elit auctor, aliquam nisl vel, dignissim risus.

 Duis posuere sed dui et accumsan. Etiam pharetra sapien non velit consequat, eget ultrices neque porta.

 In mattis erat diam, eu tempor velit pharetra sed.

 Pellentesque convallis libero ut sagittis bibendum.

 Ut laoreet lacus libero, eleifend accumsan ante fermentum sit amet.

 Quisque tristique hendrerit pellentesque.

 Mauris magna justo, auctor sit amet risus ac, dignissim efficitur ante. Donec nec pretium urna.

Coffee

Tea

Coca Cola

Coffee

Tea

Coca Cola

Answer: Que tal usando o pseudo elemente ::after?
Primeiro vc tira o style-list default do Browser, depois com o ::after vc faz um bullet customizado.
Repare que a no ::after eu uso o font-family:FontAwesome; e no content:"\f00c"; eu uso um referencia do código do FontAwesome. Aqui tem uma listá com todos os códigos oficiais: http://fontawesome.io/cheatsheet/ (para usar no contente substitua o &#x por \ )

.lista {
    font-size: 20px;
    font-size: 1.25rem;
    margin-left: 23px;
    list-style: none;
}
.lista li::before {
    font-family: FontAwesome;
    float: left;
    margin-left: -1.5em;
    content: "\f00c";
    color: #d91f26;
    transform: scale(1, 1);
    position: absolute;
    margin-top: 2px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Projetos de construções e reformas

Soluções profissionais em engenharia

Sondagens e fundações

Projetos e estudos estruturais

Soluções em containers

Comment: E como descubro o codigo dos icones?
Comment: @britodfbr acabei de incluir um Link com todos os ícone no site oficial olha ai
Comment: Muito obrigado!!! :D
Comment: @britodfbr valeu jovem, qualquer problema é só falar, mas já uso isso a muito tempo e sempre funciona 100%
Answer: Resultado final após a ajuda do colega @hugocsl.

<!DOCTYPE html>

<link href="https://use.fontawesome.com/releases/v5.0.4/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

The display Property

 afasdfasdf

 asdfasdfasd

 font-family

 FontAwesome;

Comment: Uai jovem, não te entendi, se a sua resposta é a cópia da minha, porque desmarca-la como a resposta correta se ela é a original?


gwidgets2: how to prevent gbutton handler to run when change gbutton value?

Question: How can I change gbutton text without run the function associated to its handler?
Consider the following code:
library(gWidgets2)
w <- gwindow("Buttons", visible=FALSE)
g <- ggroup(cont=w, horizontal=FALSE)

b2 <- gbutton("ouvrir", cont=g)

## with a handler
b4 <- gbutton("click me",
              handler=function(h,...) {
                if(svalue(b2) == "open")
                  svalue(b2) <- "ouvrir"
                else
                  svalue(b2) <- "open"
                },
              action = NULL, cont=g)

visible(w) <- TRUE

svalue(b4) <- "Please not call the handler!!"

In gWidgets2 when I change the text of a button through the svalue() command, the button handler is called! However, I would like to call the handler just when the button is clicked. Any suggestion to solve this situation.
Thanks in advance.
Answer: The code calls invoke_change_handler() when setting the label. There are a few ways to work around this:

Block handlers before setting (blockHandlers) then unblock (unblockHandlers)
Ir you could grab the underlying widget and set the text, in RGtk2 with gWidgets2 something like obj$widget$setText("new value") should work.
Comment: This solve my issue of multiple execution of functions called by clicking a button (explained on GitHub: https://github.com/jverzani/gWidgets2/issues/93 )


Binary Classification with a third 'uncertain' class label

Question: Consider the task of classifying an image into two classes:

Image shows a cat;
Image shows no cat.

A data set is provided for training/testing a binary classifier. However, three labels are provided for each image in the data set:

Image shows a cat;
Image shows no cat;
Undecided.

The third class label (undecided) implies that the image is of bad quality, i.e., it is impossible to determine with confidence that the image shows either (1) a cat or (2) no cat. An example is a very blurry image.
My initial approach to solving the task was to discard the third (undecided) class label and train/test a binary classifier with the first (cat) and second (no cat) class labels, since the original task requires classifying an image as either (1) showing a cat or (2) showing no cat . However, this will reduce the size of the data set significantly. I now have the following questions:
Question 1: Consider merging the third class label (undecided) into the second class label (no cat) such that the labels in the data set would be split as follows:

Image shows a cat;
Image shows no cat or undecided.

What are the implications of training a binary classifier with this data set?
Question 2: Consider changing the original task into multiclass classification, where an image is classified into three classes:

Image shows a cat;
Image shows no cat;
Undecided.

What are the implications of training a multiclass classifier with this data set? Can an image be classified as 'undecided'?
Comment: If I take a picture of a cat but then blur the image beyond the point of being able to recognize that there is a cat in it, I might argue that it is no longer a picture of a cat.
Answer: Question 2 is easier to answer. Your model will learn that undecided is something different than cat (or no cat). Even when a picture clearly shows a cat, if the image even more clearly is blurry (or whatever else leads to "undecided"), the model may give a higher probability to "undecided" than to "cat". I'm not sure whether that's what you want, you may e.g. be interested to have a model that can classify lower quality images into cat/no cat, even humans cannot do it (or struggle), which you would (likely) not get with this option.
Question 1 makes sense if you are pretty sure that the vast majority of undecided images is "no cat"-images. You could also take a label-smoothing approach, e.g. by instead of 1 (cat) or 0 (no cat), you could use 0.1 (~10% chance this could be a cat) or 0.2 for the undecided ones depending on what you believe of them (you could even have human assigned probabilities for each image).
You could also make this two separate binary labels: 1) cat vs. no cat and 2) decided (either classified as cat or not) vs. "not decided". If you do that, you could specify that no loss should be incurred for cat vs. no cat for images from the undecided category. However, I guess this might not gain you much for cat vs. no cat.
Or you could do self-distillation, i.e. start with one of the various possible approaches (including the one where you initially don't use the "undecided" images), then train your model, then soft-label (assign model predicted probability between 0 and 1 to the undecided images) the undecided images and train again now including the soft-labelled images. Generally, I'm not sure how much this would really help you for classifying cat vs. no cat, but I'd guess that this will only help you if you have a large number of undecided images (i.e. substantially more than "decided" images). Similarly, just a large amount of unlabeled images can be used the same way and helps a lot (see e.g. here https://arxiv.org/abs/1911.04252).
Comment: Thank you for your answers. It confirms what I was suspecting. Do you have any references for your answers, i.e., the first three paragraphs?
Comment: No, I don't have any references for that (of course, some of the stuff like label smoothing has tons of papers, loss functions not incurring loss for uncertain cases was used in Rainforest sound classification challenge on Kaggle etc.). It mostly follows from reasoning on what the loss function implies.


Folder permissions. Allowed to read but not allowed to execute

Question: Dealing with a folder in windows 10, I am changing its permissions. When I go to security tab of its properties, I can see that I can allow or disallow:

Full control
Modify
Read and Execute
List folder contents
Read
Write

(The names might be different, my system is not in english).
My question is, is there a way to set the permissions of this folder as in "alllowed to read, not allowed to execute"??
(above both are in one item together)
Answer: Read and Read and Execute are two different permission "sets". If you want the user or group to only have the Read permissions then grant them only the Read permission and not the Read and Execute permission.
http://www.ntfs.com/ntfs-permissions-file-folder.htm
Comment: Is the "list folder contents" the execute(traverse) permission?? (I am not native english speaker so don't get what traverse exactly implies)


How to allow double click selection of strings with - in them, within Atom?

Question: Say I have a string like 'cheap-module-inline-source-map' in the following:

In Atom, I want to be able to just double click that string to select the entire string. However it only let's me select the words I click on.
I did find the following in Settings > Editor:

Originally it was /\()"':,.;<>~!@#$%^&*|+=[]{}?-…
I removed the - however this did not fix the issue.
Comment: FWIW many of the grammars (including Javascript) have their own non-word chars setting, try looking in that package and see if you have a specific setting that is overriding the global one. Settings -> packages -> language-javascript -> Settings
Comment: Did you close/open the window after changing that setting? I occasionally find settings in Atom that don't refresh the behavior of already-open windows/buffers.
Comment: @DanLowe Yeah I totally restarted several times :( still won't let me select and entire string like `search-box-container`
Comment: @DanLowe good to know! I just checked javascript and babel and they both have `/\()"':,.;<>~!@#$%^&*|+=[]{}`?…` in there.. posting new screenshot.
Comment: @DanLowe That was it! Ok when I entered it in, it did not save correctly... I changed the string and now it saves correctly! Want to post your answer?
Answer: You have already looked at the global settings (under "Editor"), but many settings (including this one) appear in the various packages so that you can customize things per syntax.
This setting seems to exist in both language-javascript and language-babel, and perhaps you have other Javascript packages that have it (there are many of them out there...)
If you navigate to...

Settings
Packages
search for "javascript" or "babel"
click "Settings" on the package

Then you will find a "Grammar" settings section in most syntax packages. This is the one from language-javascript.

As you can see it has a copy of the Non-Word Characters setting. You can set this explicitly, though I would have expected it to inherit from the global value.
language-babel has this too, though you need to scroll down a bit further to find it.


Solving river crossing puzzle using Jess

Question: At first I solved a problem where I'd have an infinite loop, I fixed that by adding a rule to my CONSTRAIN module.
I've taken all constrains into consideration, but it seems like all the facts are being deleted for some reason...
This my code so far:
<code>;;MAIN Module
(deftemplate state
    (slot farmer-position)
    (slot fox-position)
    (slot goat-position)
    (slot cabbage-position)
    (slot id)
    (slot prev-state (default nil))
    (multislot move (default nil)))

(deftemplate finished
    (slot value))

(deffacts initial-facts
    (state (farmer-position s1)
            (fox-position s1)
            (goat-position s1)
            (cabbage-position s1)
            (id 0))
    (opp s1 s2)
    (opp s2 s1))

;;CONSTARIN Modle
(defmodule CONSTRAIN)

(defrule CONSTRAIN::fox-goat
    (declare (auto-focus true))
    ?p<-(MAIN::state (fox-position ?f) (goat-position ?f) (farmer-position
                                                                       ~?f))
    =>
    (retract ?p))

(defrule CONSTRAIN::goat-cabbge
    (declare (auto-focus true))
    ?p<-(MAIN::state (goat-position ?f) (cabbage-position ?f) (farmer-
                                                         position ~?f))
    =>
    (retract ?p))

(defrule CONSTRAIN::no-doubles
    (declare (auto-focus true))
    ?p1<-(MAIN::state (farmer-position ?s1) (fox-position ?s2) (goat-
                       position ?s3) (cabbage-position ?s4) (id ?id1))
    ?p2<-(MAIN::state (farmer-position ?s1) (fox-position ?s2) (goat-
          position ?s3) (cabbage-position ?s4) (id ?id2&:(> ?id2 ?id1)))
    =>
    (retract ?p2))

 (defrule CONSTRAIN::stop-exc
    (declare (auto-focus true))
    ?p1<-(MAIN::state (farmer-position s2) (fox-position s2) (goat-position
                                                  s2) (cabbage-position s2))
    =>
    (assert (MAIN::finished (value yes))))

;;MOVE Module
(defmodule MOVE)

(defrule MOVE::move-fox
    ?p<-(MAIN::state (farmer-position ?old) (fox-position ?old) (id ?id))
    (not (MAIN::finished (value yes)))
    (opp ?old ?new)
    =>
    (duplicate ?p (farmer-position ?new)
        (fox-position ?new)
        (prev-state ?p)
        (id (+ ?id 1))
        (move fox ?new)))

(defrule MOVE::move-goat
    ?p<-(MAIN::state (farmer-position ?old) (goat-position ?old) (id ?id))
    (not (MAIN::finished (value yes)))
    (opp ?old ?new)
    =>
    (duplicate ?p (farmer-position ?new)
        (goat-position ?new)
        (prev-state ?p)
        (id (+ ?id 1))
        (move goat ?new)))

(defrule MOVE::move-cabbage
    ?p<-(MAIN::state (farmer-position ?old) (cabbage-position ?old) (id ?
                                                                       id))
    (not (MAIN::finished (value yes)))
    (opp ?old ?new)
    =>
    (duplicate ?p (farmer-position ?new)
       (cabbage-position ?new)
       (prev-state ?p)
       (id (+ ?id 1))
       (move cabbage ?new)))

 ;;RUN
 (reset)
 (watch all)
 (focus MOVE)
 (run)
 (facts)
</code>
And here is my output:
<code><== Focus MAIN
 ==> Focus MOVE
 FIRE 1 MOVE::move-fox f-1,, f-2
  ==> f-4 (MAIN::state (farmer-position s2) (fox-position s2) (goat-position
 s1) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move fox s2))
 ==> Activation: CONSTRAIN::goat-cabbge :  f-4
 ==> Activation: MOVE::move-fox :  f-4,, f-3
 <== Focus MOVE
  ==> Focus CONSTRAIN
 FIRE 2 CONSTRAIN::goat-cabbge f-4
 <== f-4 (MAIN::state (farmer-position s2) (fox-position s2) (goat-position
 s1) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move fox s2))
 <== Activation: MOVE::move-fox :  f-4,, f-3
 <== Focus CONSTRAIN
 ==> Focus MOVE
 FIRE 3 MOVE::move-cabbage f-1,, f-2
  ==> f-5 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
 s1) (cabbage-position s2) (id 1) (prev-state <Fact-1>) (move cabbage s2))
 ==> Activation: CONSTRAIN::fox-goat :  f-5
 ==> Activation: MOVE::move-cabbage :  f-5,, f-3
 <== Focus MOVE
  ==> Focus CONSTRAIN
 FIRE 4 CONSTRAIN::fox-goat f-5
 <== f-5 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
 s1) (cabbage-position s2) (id 1) (prev-state <Fact-1>) (move cabbage s2))
 <== Activation: MOVE::move-cabbage :  f-5,, f-3
 <== Focus CONSTRAIN
 ==> Focus MOVE
FIRE 5 MOVE::move-goat f-1,, f-2
 ==> f-6 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
s2) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move goat s2))
==> Activation: MOVE::move-goat :  f-6,, f-3
FIRE 6 MOVE::move-goat f-6,, f-3
 ==> f-7 (MAIN::state (farmer-position s1) (fox-position s1) (goat-position
s1) (cabbage-position s1) (id 2) (prev-state <Fact-6>) (move goat s1))
==> Activation: CONSTRAIN::no-doubles :  f-1, f-7
==> Activation: MOVE::move-fox :  f-7,, f-2
==> Activation: MOVE::move-goat :  f-7,, f-2
==> Activation: MOVE::move-cabbage :  f-7,, f-2
<== Focus MOVE
==> Focus CONSTRAIN
FIRE 7 CONSTRAIN::no-doubles f-1, f-7
<== f-7 (MAIN::state (farmer-position s1) (fox-position s1) (goat-position
s1) (cabbage-position s1) (id 2) (prev-state <Fact-6>) (move goat s1))
 <== Activation: MOVE::move-fox :  f-7,, f-2
 <== Activation: MOVE::move-goat :  f-7,, f-2
 <== Activation: MOVE::move-cabbage :  f-7,, f-2
 <== Focus CONSTRAIN
 ==> Focus MOVE
 <== Focus MOVE
 ==> Focus MAIN
 <== Focus MAIN
 For a total of 0 facts in module MOVE.
</code>
Answer: Fact f-6 was not retracted. The only valid first move is for the farmer to cross the river with the goat and that's the move represented by f-6. You don't have a rule for moving the farmer across the river alone, so the only valid move for the farmer from f-6 is to move back across the river with the goat which takes you back to the initial position. Since the initial position represented by f-1 is the same as f-7, the rule no-doubles retracts f-7 and there are no remaining valid moves.
If you download Jess from http://www.jessrules.com/jess/download.shtml, code for the river crossing example is available in the examples directory in the file dilemma.clp.


Why "we would be way too confident" while the confidence interval is too small

Question: I read about quantile regression and was confused about one sentence:
"We would be way too confident" about confidence interval in this post (under the second figure): here. I think that the confidence interval here is too small, so why does the author says that we could be too confident about estimating the mean of the response variable given the independent variable?
Comment: Large confidence requires larger intervals, *caeteris paribus.*  You ask about the logical converse: if you think you have large confidence but your interval is too small, then you must be mistaken and you should have *less* confidence.
Answer: The statistical use of the word confidence is different than the colloquial use, which may be the source of some confusion.
More to do with your link, a better claim would have been "we would be too precise". Precision is the inverse of variance, so when the variance is small then the precision is high.  The width of a confidence interval relies on the standard error (which is the standard deviation of the estimate, hence the square root of the variance of the estimate).  If the confidence interval is too narrow, them the estimate is too precise.
The reason I bring up precision is because the data in figure 2 in your link is heteroskedastic, which geom_smooth(method='lm') does not account for.  To properly account for heterogeneity of variance, we need a sandwhich estimator, which has the result of increasing the estimated standard error of the coefficients for the model (hence decreasing the precision).


ubuntu 11 runlevel

Question: probably a simple question, but i think im wording things wrongly to the googles:
i have a ubuntu 11 server that 90% of the time runs headless, and is only accessed over ssh.
i use it as a workstation occasionally, and use the GUI when i do. however, i do not want GDM / graphical login stuff to run at boot and waste resources.
tl;dr -- i want to have gnome installed, but not run until i login and "startx"
easy way to ensure i boot to a CLI only in ubuntu 11?
Answer:
sudo update-rc.d -f gdm remove
Comment: hrm, the above didnt work. rebooted and it still came up with GDM / ubuntu graphical login.
Comment: i was able to configure using this (slightly dated) but still 100% functional tutorial.

http://tuxthink.blogspot.com/2010/08/modifying-run-level-in-ubuntu-1004.html

thanks for the help!

ubuntu 11 runlevel


Map subfolder to subdomain in Apache

Question: I am trying to map ugc.domain.com to domain.com/ugc on my website, basically taking the subfolder and putting it in the front (I already did the DNS mapping on Digital Ocean for ugc.domain.com).
I tried the following RewriteRule:
RewriteRule ^/ugc/?$ http://ugc.domain.com/ [R=301,L]

Reloaded Apache, but navigating to ugc.domain.com did not go to my domain.com/UGC page.
So basically what I want to do is, when I go to ugc.domain.com, in the background, I am actually going to domain.com/ugc, even though in the URL, it says ugc.domain.com. I think it looks prettier and cleaner this way.
Answer: This rule does the opposite what you want. This one sends a 301 Moved Permanently response to the client when the user visits http://domain.com/ugc/ page, sending the client to http://ugc.domain.com.
What you are actually looking is to define a new virtualhost for ugc.domain.com, and then set that virtual host's directory location to the directory where domain.com/UGC page is.
Comment: Hi Tero. Could you show me with code what you mean? I'm still not really understanding what I did wrong.
Comment: http://httpd.apache.org/docs/2.2/vhosts/examples.html -page shows examples how virtualhosts are defined in Apache. Unfortunately I cannot give any more specific examples.

Map subfolder to subdomain in Apache


Preciso comparar variáveis com a falta de informação

Question: Estou criando um formulário e preciso alertar o usuário quando um campo não está preenchido. Estou tentando usar o if para fazer essa comparação, já tentei comparar com o null e não funcionou.
meu código está assim:

function Cadastrar(){

    var titulo = document.getElementById("titulo").value;
    var editora = document.getElementById("editora").value;
    var conteudoTabela = document.getElementById("livros_cadastrados");
    var novaLinha = document.createElement("tr");

    if(titulo == null || editora == null){
        alert("Dados incompletos");
    }else{
        novaLinha.innerHTML = "" + titulo + "	" + editora + "	Excluir";
        conteudoTabela.appendChild(novaLinha);
        alert("Novo livro cadastrado:" + "\n" + titulo);
    }
}

Sou bastante iniciante, portanto, se possível, gostaria de uma explicação bem detalhada.
Muito obrigado!
Comment: Onde estás a chamar essa função `Cadastrar`?
Answer: Amigo, creio que você pode fazer da seguinte maneira:
function Cadastrar(){
var titulo = document.getElementById("titulo").value;
var editora = document.getElementById("editora").value;
var conteudoTabela = document.getElementById("livros_cadastrados");
var novaLinha = document.createElement("tr");

if(titulo == '' || editora == ''){
    alert("Dados incompletos");
}else{
    novaLinha.innerHTML = "" + titulo + "	" + editora + "	Excluir";
    conteudoTabela.appendChild(novaLinha);
    alert("Novo livro cadastrado:" + "\n" + titulo);
}

}
Se sua intenção é apenas verificar se os campos estão vazios, você utiliza a verificação por '' pois é como você coloca a condição se o campo está vazio ou não. Deixar como nulo creio que não funciona ou se funcionar, não seria da melhor maneira. Irá depender um pouco também de como e onde você chama esta função, se for algo em onsubmit ou onchange até mesmo com onblur e onfocusout. Se for o caso, coloque seu código HTML também.
Comment: Funcionou! Muito obrigado!


Split groups and quasi-split groups.

Question: By definition, a quasi-split group over a field is a reductive group with a Borel subgroup defined over the field. A split group is a quasi-split group which has split torus ($T = \mathbb{G}_m^n$, $\mathbb{G}_m$ is the multiplicative group). Are there some examples of quasi-split groups which are not split? Thank you very much.
Answer: Here are two standard examples of non-split but quasi-split groups:

Non-split tori (a dumb example), e.g. U(1) over $\mathbf{R}$. If $T$ is any torus, then $T$ is a Borel subgroup of itself, and this is clearly defined over the ground field.
A slightly less dumb example: the semisimple group $SU(2, 1)$ over $\mathbf{R}$, defined as the group of 3x3 complex matrices of determinant 1 satisfying $g J \bar{g}^t = J$ where $J$ is the matrix $\begin{pmatrix} &&1 \\&1 \\ 1 \end{pmatrix}$. The intersection of this group with the upper-triangular matrices in $\operatorname{GL}_3(\mathbf{C})$ is a Borel, but there is no split maximal torus.
Comment: thank you very much. In your second example, why there is no split maximal torus?
Comment: @LJR First, the torus defined by David is maximal split because its centralizer is itself cross $SU(q)$ with $q$ anisotropic. Then, use that all maximal split tori are conjugate (Borel, Proposition 20.9 in the reductive case and it is true more generally for affine groups.)

Split groups and quasi-split groups.


Which analysis to choose for panel data with three timepoints? (Not interested in change but influence of other variable)

Question: I have data from a 3-wave panel study which I don't know how to analyze. I am interested in how an independent variable (IV) affects a dependent variable (DV). Therefore, I am not interested in the change of the single variables but how the change in one variable affects the change in the other. If I had only two timepoints, I would simply regress the change score of the DV on the change score of the IV. However, I am not sure how to deal with the 3rd time point.
Here are some things I have been looking into:

Hierarchical Regression with time-varying covariate: Implementing a hierarchical regression of DV ~ time + IV with random intercepts and slopes for the time parameter. The IV would then be a time varying covariate and I would interpret it's relationship with the DV. At the same time, I would account for individual time trends via the random parameters. This was my favorite way to go. However, it led to a lot of convergence issues which I could not resolve
Autoregressive SEM: Simply look at the relationship between IV and DV at all time points seperately and add autoregressive paths to the model. However, this is not considering the change in the variables / I could only interpret the relationship between DV and IV as cross-sectional, therefore not benefitting from the longitudinal character of the data. I also would like to calculate only one relationship between IV and DV as this relationship should not differ between the time points.
Lagged dependent model: I'd perform a linear regression like this: DV ~ DV_lagged + IV, with DV_lagged being the DV one timepoint prior than DV. However, I am not sure how exactly one would then interpret the coefficient of the IV (in which I am interested).

As you might see, I don't have any prior experience with analyzing longitudinal data. I would really appreciate if you could explain what analysis you would recommend? (of course it does not need to be one of the above!)
Also: Is it possible to simply calculate two change scores (T3 - T2 and T2 - T1) and put them into one variable?
Thank you!
Comment: Was your IV an experimental intervention, and did it happen in between any of the time points?
Comment: No, it is a purely correlational design but we assessed both the IV and DV at all 3 timepoints.
Answer: Change scores are a bad idea. And 3 is too few groups to use a random effect; I've heard estimates ranging from a minimum of 6-30 groups, though 6 is a number you'll see more often. Basically, the problem is that the modelling approaches you are interested in require more information in the time dimension than you have available to you in your data, especially since there was no experimental intervention.
I think the most straightforward way to analyse your data would be DV ~ time + IV, with time treated as categorical in the absence of further information about the problem. You could consider an interaction term as well. If you are interested in specific comparisons, you could do post-hoc tests, though I'm generally not a fan of them.
Comment: Okay, I see. Thank you again for your help!
Comment: Thank you for your answer! I would then interpret the coefficient of the IV as the relationship with the DV that cannot be explained by the general time effect, right? This then is not too different from the lagged dependent model, but I would not only control for one prior timepoint but for the general influence of the time point?
Comment: @lt0519f (i) About coefficient interpretation, you are correct - assuming you have no interaction in the model. My standard recommendation is to plot your model output - it always helps with interpretation.
Comment: @lt0519f (ii) About the comparison with the lagged model, it's fairly different to this. I've not put in any lagged values here, just time point (with time intended to be categorical - I should have specified that). Lagging can often be a good idea but yours is a curious in-between level of temporal structure and I'm inclined to just treat the time points as categories. But a lagged approach sounds defensible to me.


Sistema de postagem - "Duplicate entry '0' for key 'PRIMARY"

Question: Estou com um problema, na verdade não sei bem se é no PHP ou no banco de dados.
Em um sistema de postagem usando PHP, assim que você posta uma noticia, o ID (a primary key, que seria usada assim: index.php?ID=0) não esta mudando, ou seja, ela sempre começa no 0 e eu queria que começa-se a partir do 1, e quando eu vou criar uma postagem acaba dando o seguinte erro:

Duplicate entry '0' for key 'PRIMARY'"

e ai eu sempre tenho que mudar no MySQL para outro ID.
Código: http://pastebin.com/raw.php?i=0dQEW0n1
Teria como colocar de forma sequencial?
Comment: Cola o banco de dados também... O problema está lá!
Comment: Isso quer dizer que estás a tentar inserir mais um registo com `ID=0`. Tens no banco o `ID` como *auto increment*?
Answer: O seu problema provavelmente é na configuração da tabela. O campo ID tem que ser chave primária e auto increment. Da forma como foi feito (sem auto increment) o php informa null para o mysql que salva a primary key como zero toda vez que você roda seu código.
Comment: @WallaceMaxters é por isso que eu crio sempre as tabelas com o workbench
Comment: É exato. Isso ocorre sempre quando esqueco do `AUTO_INCREMENT`
Answer: No banco de dados deves usar o auto_increment no ID principal. Para que ao adicionar um novo registro, já adiciona também um novo id para este registro.
ALTER TABLE `suatabela` CHANGE `id` `id` INT(10) NOT NULL AUTO_INCREMENT;


Random variable on dyadic rationals

Question: I have measurable spaces $(\Omega, \mathcal{F})$ and $(\Re, \mathcal{B})$, with X a measurable map: $\Omega \rightarrow \Re$; how do I know that $X$ is a random variable if $\{X \leq x\} \in \mathcal{F}$ for all the dyadic rational numbers $x = \frac{m}{2^{k}}$ for $m, k \in Z$?
It would seem to me that for $X$ to be a random variable, we would need to ensure that there exists a measure $P$ such that $P(\Omega)=1$...
Answer: Here the question has nothing to do with the notion of measure, but rather with that of measurability. Normally, the official definition of measurable is that for all $B\in\mathcal B$, $\left\{\omega\in\Omega\mid X\in B\right\}\in\mathcal F$.
Since the Borel sets may not have a nice form, it would be convenient to have to do the test $\left\{\omega\in\Omega\mid X\in B\right\}\in\mathcal F$ for sets $B$ in a small collection of sets than $\mathcal B$. Probably you are already aware that it suffice to do it for intervals of the form $(-\infty,x]$, $x\in\mathbb R$. Here, the point is that we can even work with a smaller class.
Here, we have to prove that for all $x$, there exists a non-increasing sequence of dyadics $(d_i)$ such that $(-\infty,x]=\bigcup_{i\geqslant 1}(-\infty,d_i]$.

Random variable on dyadic rationals