Replicating bgtest from lmtest

Question: Cross-posted from SO.
I am trying to replicate the results of bgtest from the lmtest R package.
I am using the following dataset:
           rs   month   r20
1    2.365042  1952m3  4.33
2    2.317500  1952m4  4.23
3    2.350833  1952m5  4.36
4    2.451833  1952m6  4.57
5    2.466167  1952m7  4.36
6    2.468417  1952m8  4.11
7    2.485583  1952m9  4.20
8    2.415125 1952m10  4.19
9    2.389875 1952m11  4.15
10   2.418167 1952m12  4.22
11   2.396042  1953m1  4.13
12   2.401042  1953m2  4.10
13   2.400833  1953m3  4.04
14   2.383500  1953m4  3.94
15   2.366708  1953m5  3.95
16   2.365625  1953m6  4.02
17   2.348583  1953m7  3.98
18   2.334375  1953m8  3.94
19   2.133542  1953m9  3.78
20   2.097375 1953m10  3.80
21   2.097708 1953m11  3.78
22   2.130583 1953m12  3.83
23   2.096000  1954m1  3.79
24   2.064042  1954m2  3.79
25   2.115083  1954m3  3.76
26   2.047333  1954m4  3.71
27   1.713875  1954m5  3.65
28   1.606167  1954m6  3.61
29   1.561667  1954m7  3.35
30   1.613292  1954m8  3.36
31   1.621083  1954m9  3.35
32   1.587667 1954m10  3.35
33   1.637792 1954m11  3.38
34   1.865917 1954m12  3.51
35   2.356417  1955m1  3.64
36   3.810000  1955m2  3.85
37   3.797000  1955m3  3.83
38   3.906000  1955m4  4.15
39   3.937000  1955m5  4.21
40   3.969000  1955m6  4.33
41   3.971000  1955m7  4.47
42   4.005000  1955m8  4.84
43   4.072000  1955m9  4.68
44   4.071000 1955m10  4.50
45   4.104000 1955m11  4.64
46   4.072000 1955m12  4.70
47   4.071000  1956m1  4.84
48   5.218000  1956m2  4.87
49   5.165000  1956m3  5.02
50   5.008000  1956m4  4.85
51   4.955000  1956m5  5.12
52   5.136000  1956m6  5.25
53   4.977000  1956m7  5.27
54   4.027000  1956m8  5.20
55   5.091000  1956m9  5.35
56   4.991000 1956m10  5.33
57   5.020000 1956m11  5.50
58   4.858000 1956m12  5.29
59   4.553000  1957m1  4.91
60   4.148000  1957m2  4.93
61   4.099000  1957m3  5.08
62   3.914000  1957m4  5.11
63   3.921000  1957m5  5.43
64   3.854000  1957m6  5.55
65   3.845000  1957m7  5.60
66   4.121000  1957m8  5.75
67   6.605000  1957m9  5.98
68   6.603000 1957m10  5.84
69   6.459000 1957m11  5.89
70   6.375000 1957m12  5.81
71   6.127000  1958m1  5.66
72   6.014000  1958m2  5.65
73   5.523000  1958m3  5.64
74   5.179000  1958m4  5.45
75   4.816000  1958m5  5.46
76   4.294000  1958m6  5.45
77   4.159000  1958m7  5.46
78   3.760000  1958m8  5.49
79   3.625000  1958m9  5.36
80   3.584000 1958m10  5.35
81   3.305000 1958m11  5.36
82   3.152000 1958m12  5.36
83   3.107000  1959m1  5.20
84   3.276000  1959m2  5.20
85   3.287000  1959m3  5.24
86   3.283000  1959m4  5.22
87   3.382000  1959m5  5.28
88   3.452000  1959m6  5.18
89   3.484000  1959m7  5.13
90   3.488000  1959m8  5.21
91   3.472000  1959m9  5.33
92   3.386000 1959m10  5.06
93   3.400000 1959m11  5.04
94   3.687000 1959m12  5.21
95   4.538000  1960m1  5.34
96   4.554000  1960m2  5.43
97   4.621000  1960m3  5.53
98   4.652000  1960m4  5.59
99   4.556000  1960m5  5.62
100  5.681000  1960m6  5.92
101  5.546000  1960m7  5.97
102  5.588000  1960m8  5.95
103  5.565000  1960m9  5.97
104  5.090000 1960m10  5.97
105  4.639000 1960m11  5.97
106  4.349000 1960m12  6.01
107  4.165000  1961m1  6.01
108  4.399000  1961m2  6.04
109  4.485000  1961m3  6.05
110  4.407000  1961m4  6.01
111  4.436000  1961m5  6.08
112  4.537000  1961m6  6.33
113  6.688000  1961m7  6.52
114  6.700000  1961m8  6.63
115  6.552000  1961m9  6.65
116  5.727000 1961m10  6.33
117  5.389000 1961m11  6.34
118  5.403000 1961m12  6.41
119  5.242000  1962m1  6.35
120  5.531000  1962m2  6.26
121  4.405000  1962m3  6.25
122  4.052000  1962m4  6.24
123  3.816000  1962m5  6.25
124  3.921000  1962m6  6.24
125  3.887000  1962m7  5.98
126  3.752000  1962m8  5.77
127  3.635000  1962m9  5.27
128  3.858000 1962m10  5.37
129  3.689000 1962m11  5.42
130  3.717000 1962m12  5.36
131  3.491000  1963m1  5.54
132  3.426000  1963m2  5.74
133  3.756000  1963m3  5.69
134  3.709000  1963m4  5.50
135  3.635000  1963m5  5.31
136  3.702000  1963m6  5.28
137  3.761000  1963m7  5.20
138  3.723000  1963m8  5.22
139  3.674000  1963m9  5.21
140  3.745000 1963m10  5.26
141  3.739000 1963m11  5.51
142  3.721000 1963m12  5.63
143  3.758000  1964m1  5.64
144  4.307000  1964m2  5.85
145  4.302000  1964m3  5.76
146  4.302000  1964m4  5.93
147  4.384000  1964m5  5.90
148  4.464000  1964m6  5.97
149  4.654000  1964m7  6.02
150  4.656000  1964m8  6.00
151  4.703000  1964m9  6.00
152  4.698000 1964m10  6.06
153  6.630000 1964m11  6.23
154  6.627000 1964m12  6.41
155  6.543000  1965m1  6.41
156  6.442000  1965m2  6.43
157  6.549000  1965m3  6.53
158  6.375000  1965m4  6.61
159  6.364000  1965m5  6.76
160  5.542000  1965m6  6.78
161  5.630000  1965m7  6.80
162  5.559000  1965m8  6.65
163  5.559000  1965m9  6.35
164  5.440000 1965m10  6.37
165  5.395000 1965m11  6.40
166  5.521000 1965m12  6.59
167  5.483000  1966m1  6.52
168  5.620000  1966m2  6.61
169  5.604000  1966m3  6.77
170  5.638000  1966m4  6.78
171  5.659000  1966m5  6.82
172  5.728000  1966m6  7.03
173  6.679000  1966m7  7.29
174  6.726000  1966m8  7.41
175  6.747000  1966m9  7.29
176  6.513000 1966m10  6.96
177  6.738000 1966m11  6.97
178  6.527000 1966m12  6.78
179  6.080000  1967m1  6.58
180  6.035000  1967m2  6.49
181  5.495000  1967m3  6.50
182  5.412000  1967m4  6.46
183  5.248000  1967m5  6.65
184  5.275000  1967m6  6.86
185  5.345000  1967m7  6.92
186  5.291000  1967m8  6.90
187  5.475000  1967m9  6.98
188  5.726000 1967m10  7.00
189  7.553000 1967m11  7.22
190  7.484000 1967m12  7.20
191  7.520000  1968m1  7.28
192  7.374000  1968m2  7.28
193  7.108000  1968m3  7.29
194  7.080000  1968m4  7.34
195  7.241000  1968m5  7.50
196  7.242000  1968m6  7.87
197  7.059000  1968m7  7.63
198  6.945000  1968m8  7.63
199  6.577000  1968m9  7.64
200  6.493000 1968m10  7.70
201  6.789000 1968m11  7.93
202  6.777000 1968m12  8.17
203  6.728000  1969m1  8.47
204  7.711000  1969m2  8.61
205  7.782000  1969m3  8.81
206  7.798000  1969m4  8.90
207  7.850000  1969m5  9.46
208  7.880000  1969m6  9.31
209  7.830000  1969m7  9.19
210  7.790000  1969m8  9.49
211  7.811000  1969m9  9.21
212  7.743000 1969m10  8.95
213  7.738000 1969m11  9.29
214  7.650000 1969m12  9.04
215  7.550000  1970m1  9.03
216  7.600000  1970m2  8.79
217  7.270000  1970m3  8.75
218  6.940000  1970m4  8.94
219  6.190000  1970m5  9.40
220  6.870000  1970m6  9.58
221  6.850000  1970m7  9.33
222  6.820000  1970m8  9.19
223  6.820000  1970m9  9.28
224  6.810000 1970m10  9.15
225  6.810000 1970m11  9.51
226  6.820000 1970m12  9.62
227  6.790000  1971m1  9.51
228  6.750000  1971m2  9.35
229  6.660000  1971m3  9.07
230  5.920000  1971m4  9.07
231  5.650000  1971m5  9.03
232  5.590000  1971m6  9.08
233  5.570000  1971m7  9.22
234  5.750000  1971m8  8.96
235  4.830000  1971m9  8.50
236  4.630000 1971m10  8.51
237  4.480000 1971m11  7.79
238  4.360000 1971m12  8.10
239  4.360000  1972m1  7.93
240  4.370000  1972m2  7.90
241  4.340000  1972m3  8.16
242  4.300000  1972m4  8.26
243  4.270000  1972m5  8.60
244  5.210000  1972m6  9.32
245  5.600000  1972m7  9.23
246  5.790000  1972m8  9.36
247  6.440000  1972m9  9.54
248  6.740000 1972m10  9.46
249  6.880000 1972m11  9.45
250  7.760000 1972m12  9.62
251  8.210000  1973m1  9.56
252  8.080000  1973m2  9.65
253  8.070000  1973m3 10.01
254  7.670000  1973m4  9.93
255  7.330000  1973m5 10.02
256  7.060000  1973m6 10.15
257  8.270000  1973m7 10.60
258 10.910000  1973m8 11.30
259 10.970000  1973m9 11.55
260 10.770000 1973m10 11.28
261 11.730000 1973m11 12.00
262 12.460000 1973m12 12.50
263 12.090000  1974m1 12.89
264 11.920000  1974m2 13.50
265 11.950000  1974m3 13.68
266 11.520000  1974m4 14.21
267 11.360000  1974m5 13.80
268 11.230000  1974m6 14.38
269 11.200000  1974m7 14.88
270 11.240000  1974m8 15.29
271 11.060000  1974m9 14.95
272 10.930000 1974m10 15.68
273 10.980000 1974m11 16.75
274 10.990000 1974m12 17.18
275 10.590000  1975m1 16.02
276  9.880000  1975m2 14.58
277  9.500000  1975m3 13.43
278  9.260000  1975m4 13.89
279  9.470000  1975m5 14.53
280  9.430000  1975m6 14.41
281  9.710000  1975m7 13.93
282 10.430000  1975m8 13.87
283 10.360000  1975m9 13.79
284 11.420000 1975m10 14.66
285 11.100000 1975m11 14.81
286 10.820000 1975m12 14.79
287  9.990000  1976m1 13.79
288  8.760000  1976m2 13.46
289  8.460000  1976m3 13.88
290  9.060000  1976m4 13.77
291 10.440000  1976m5 13.59
292 10.960000  1976m6 14.09
293 10.870000  1976m7 14.16
294 10.880000  1976m8 14.33
295 12.050000  1976m9 14.79
296 14.000000 1976m10 16.03
297 14.140000 1976m11 15.79
298 13.780000 1976m12 15.48
299 12.730000  1977m1 14.48
300 11.020000  1977m2 13.93
301  9.920000  1977m3 13.25
302  8.240000  1977m4 13.05
303  7.400000  1977m5 12.69
304  7.450000  1977m6 13.26
305  7.430000  1977m7 13.62
306  6.540000  1977m8 13.12
307  5.680000  1977m9 11.88
308  4.530000 1977m10 10.98
309  4.960000 1977m11 11.28
310  6.370000 1977m12 11.16
311  5.810000  1978m1 11.06
312  5.960000  1978m2 11.75
313  5.930000  1978m3 11.72
314  6.730000  1978m4 12.39
315  8.400000  1978m5 12.72
316  9.170000  1978m6 12.79
317  9.220000  1978m7 12.72
318  8.900000  1978m8 12.55
319  8.980000  1978m9 12.64
320  9.860000 1978m10 12.91
321 11.510000 1978m11 13.16
322 11.570000 1978m12 13.22
323 11.860000  1979m1 13.68
324 12.630000  1979m2 13.94
325 11.350000  1979m3 12.35
326 11.320000  1979m4 11.68
327 11.350000  1979m5 11.94
328 12.570000  1979m6 12.69
329 13.320000  1979m7 12.25
330 13.320000  1979m8 12.30
331 13.380000  1979m9 12.60
332 13.380000 1979m10 13.16
333 15.330000 1979m11 14.54
334 15.900000 1979m12 14.72
335 15.790000  1980m1 14.17
336 16.140000  1980m2 14.45
337 16.180000  1980m3 14.70
338 16.170000  1980m4 14.27
339 16.090000  1980m5 14.01
340 15.800000  1980m6 13.78
341 14.550000  1980m7 13.07
342 14.860000  1980m8 13.58
343 14.400000  1980m9 13.38
344 14.290000 1980m10 13.12
345 13.950000 1980m11 13.22
346 13.070000 1980m12 13.67
347 12.820000  1981m1 13.96
348 12.090000  1981m2 13.89
349 11.530000  1981m3 13.68
350 11.330000  1981m4 13.64
351 11.350000  1981m5 14.31
352 12.090000  1981m6 14.57
353 13.150000  1981m7 15.14
354 13.420000  1981m8 15.09
355 13.960000  1981m9 15.59
356 15.550000 1981m10 15.95
357 14.080000 1981m11 15.44
358 14.510000 1981m12 15.65
359 14.160000  1982m1 15.58
360 13.300000  1982m2 14.74
361 12.480000  1982m3 13.72
362 12.890000  1982m4 13.96
363 12.530000  1982m5 13.69
364 12.230000  1982m6 13.56
365 11.280000  1982m7 13.20
366 10.080000  1982m8 12.23
367  9.910000  1982m9 11.40
368  8.910000 1982m10 10.50
369  9.220000 1982m11 10.64
370  9.960000 1982m12 11.34
371 10.590000  1983m1 11.60
372 10.740000  1983m2 11.50
373 10.470000  1983m3 10.97
374  9.840000  1983m4 10.56
375  9.700000  1983m5 10.65
376  9.470000  1983m6 10.39
377  9.370000  1983m7 10.95
378  9.340000  1983m8 11.07
379  9.160000  1983m9 10.67
380  8.840000 1983m10 10.61
381  8.840000 1983m11 10.29
382  8.870000 1983m12 10.35
383  8.870000  1984m1 10.28
384  8.850000  1984m2 10.42
385  8.430000  1984m3 10.23
386  8.380000  1984m4 10.40
387  8.820000  1984m5 10.93
388  8.860000  1984m6 11.15
389 10.970000  1984m7 11.67
390 10.210000  1984m8 10.98
391 10.020000  1984m9 10.78
392  9.850000 1984m10 10.69
393  9.230000 1984m11 10.32
394  9.100000 1984m12 10.46
395 10.550000  1985m1 10.96
396 12.690000  1985m2 11.06
397 12.930000  1985m3 10.90
398 11.930000  1985m4 10.68
399 11.940000  1985m5 10.88
400 11.890000  1985m6 10.70
401 11.390000  1985m7 10.44
402 10.960000  1985m8 10.37
403 11.060000  1985m9 10.39
404 11.050000 1985m10 10.22
405 11.110000 1985m11 10.37
406 11.150000 1985m12 10.45
407 11.980000  1986m1 10.80
408 12.020000  1986m2 10.40
409 11.060000  1986m3  9.39
410  9.990000  1986m4  8.76
411  9.700000  1986m5  9.00
412  9.320000  1986m6  9.23
413  9.450000  1986m7  9.37
414  9.390000  1986m8  9.41
415  9.610000  1986m9  9.97
416 10.250000 1986m10 10.62
417 10.630000 1986m11 10.80
418 10.660000 1986m12 10.69
419 10.520000  1987m1 10.09
420 10.290000  1987m2  9.83
421  9.350000  1987m3  9.16
422  9.430000  1987m4  9.12
423  8.460000  1987m5  8.82
424  8.540000  1987m6  8.90
425  8.840000  1987m7  9.23
426  9.790000  1987m8  9.20
427  9.690000  1987m9  9.98
428  9.450000 1987m10  9.88
429  8.430000 1987m11  9.20
430  8.190000 1987m12  9.57
431  8.370000  1988m1  9.57
432  8.790000  1988m2  9.38
433  8.270000  1988m3  9.12
434  7.740000  1988m4  9.12
435  7.540000  1988m5  9.27
436  8.880000  1988m6  9.32
437 10.050000  1988m7  9.51
438 11.130000  1988m8  9.47
439 11.530000  1988m9  9.60
440 11.540000 1988m10  9.23
441 12.070000 1988m11  9.30
442 12.540000 1988m12  9.46
443 12.450000  1989m1  9.35
444 12.390000  1989m2  9.15
445 12.410000  1989m3  9.26
446 12.470000  1989m4  9.52
447 12.540000  1989m5  9.52
448 13.590000  1989m6  9.88
449 13.290000  1989m7  9.53
450 13.320000  1989m8  9.37
451 13.440000  1989m9  9.62
452 14.460000 1989m10  9.81
453 14.450000 1989m11  9.99
454 14.500000 1989m12  9.96
455 14.500000  1990m1 10.28
456 14.450000  1990m2 10.72
457 14.570000  1990m3 11.46
458 14.590000  1990m4 11.77
459 14.500000  1990m5 11.49
460 14.380000  1990m6 11.01
461 14.320000  1990m7 11.03
462 14.310000  1990m8 11.41
463 14.260000  1990m9 11.32
464 13.370000 1990m10 11.12
465 12.920000 1990m11 10.94
466 12.960000 1990m12 10.40
467 13.000000  1991m1 10.22
468 12.390000  1991m2  9.89
469 11.640000  1991m3 10.06
470 11.250000  1991m4  9.99
471 10.840000  1991m5 10.15
472 10.720000  1991m6 10.34
473 10.520000  1991m7 10.10
474 10.200000  1991m8  9.89
475  9.660000  1991m9  9.54
476  9.860000 1991m10  9.62
477  9.980000 1991m11  9.68
478 10.100000 1991m12  9.56
479  9.970000  1992m1  9.34
480  9.800000  1992m2  9.21
481 10.100000  1992m3  9.54
482  9.970000  1992m4  9.33
483  9.430000  1992m5  8.99
484  9.420000  1992m6  9.02
485  9.430000  1992m7  8.90
486  9.650000  1992m8  9.13
487  9.160000  1992m9  9.12
488  7.470000 1992m10  9.24
489  6.490000 1992m11  8.84
490  6.390000 1992m12  8.84
491  6.050000  1993m1  8.92
492  5.370000  1993m2  8.63
493  5.380000  1993m3  8.33
494  5.330000  1993m4  8.39
495  5.300000  1993m5  8.60
496  5.190000  1993m6  8.39
497  5.130000  1993m7  7.96
498  5.060000  1993m8  7.39
499  5.170000  1993m9  7.18
500  5.150000 1993m10  7.09
501  4.950000 1993m11  7.06
502  4.870000 1993m12  6.46
503  4.890000  1994m1  6.41
504  4.760000  1994m2  6.83
505  4.830000  1994m3  7.47
506  4.880000  1994m4  7.83
507  4.810000  1994m5  8.24
508  4.880000  1994m6  8.55
509  5.090000  1994m7  8.41
510  5.340000  1994m8  8.52
511  5.390000  1994m9  8.72
512  5.440000 1994m10  8.63
513  5.630000 1994m11  8.53
514  5.870000 1994m12  8.44
515  5.930000  1995m1  8.61
516  6.160000  1995m2  8.52
517  6.090000  1995m3  8.50
518  6.300000  1995m4  8.39
519  6.200000  1995m5  8.18
520  6.370000  1995m6  8.16
521  6.620000  1995m7  8.36
522  6.590000  1995m8  8.24
523  6.520000  1995m9  8.09
524  6.530000 1995m10  8.34
525  6.380000 1995m11  8.01
526  6.220000 1995m12  7.94

which is saved as ukrates.csv.
Here is the code to attempt to reproduce the bgtest module.
rm(list = ls())

library(zoo)
library(lmtest)
library(dynlm)

# read in the data
dfUK = read.csv('./data/ukrates.csv', header = TRUE)
summary(dfUK)

# run the time series regression
zooUK = zoo(dfUK[, c('rs', 'r20')], order.by = as.yearmon(dfUK$month,
                                                          '%Ym%m'))
zooUKAug = merge(zooUK,
                 'drs' = diff(zooUK$rs, 1),
                 'ldr20' = lag(diff(zooUK$r20, 1), -1))
lmUK2 = dynlm(drs ~ ldr20, data = zooUKAug)

# Breusch-Godfrey regression
zooUKBG = merge(zooUKAug, 'resid' = resid(lmUK2))
lmBG = dynlm(as.formula(paste('resid',
                              '~',
                              attr(lmUK2$terms, 'term.labels'),
                              ' + L(resid, 1)')),
             data = zooUKBG)

# BG test using lmtest package
bgtest(lmUK2, order = 1, type = 'Chisq') # 14.5614

# attempt to recreate BG-test
length(lmBG$residuals)*
  sum(lmBG$fitted^2)/sum(lmBG$residuals^2)

This is based on the following code for computing the chi-squared statistic directly from the bgtest function code:
> bgtest
function (formula, order = 1, order.by = NULL, type = c("Chisq",
    "F"), data = list(), fill = 0)
{
    dname <- paste(deparse(substitute(formula)))
    if (!inherits(formula, "formula")) {
        X <- if (is.matrix(formula$x))
            formula$x
        else model.matrix(terms(formula), model.frame(formula))
        y <- if (is.vector(formula$y))
            formula$y
        else model.response(model.frame(formula))
    }
    else {
        mf <- model.frame(formula, data = data)
        y <- model.response(mf)
        X <- model.matrix(formula, data = data)
    }
    if (!is.null(order.by)) {
        if (inherits(order.by, "formula")) {
            z <- model.matrix(order.by, data = data)
            z <- as.vector(z[, ncol(z)])
        }
        else {
            z <- order.by
        }
        X <- as.matrix(X[order(z), ])
        y <- y[order(z)]
    }
    n <- nrow(X)
    k <- ncol(X)
    order <- 1:order
    m <- length(order)
    resi <- lm.fit(X, y)$residuals
    Z <- sapply(order, function(x) c(rep(fill, length.out = x),
        resi[1:(n - x)]))
    if (any(na <- !complete.cases(Z))) {
        X <- X[!na, , drop = FALSE]
        Z <- Z[!na, , drop = FALSE]
        y <- y[!na]
        resi <- resi[!na]
        n <- nrow(X)
    }
    auxfit <- lm.fit(cbind(X, Z), resi)
    cf <- auxfit$coefficients
    vc <- chol2inv(auxfit$qr$qr) * sum(auxfit$residuals^2)/auxfit$df.residual
    names(cf) <- colnames(vc) <- rownames(vc) <- c(colnames(X),
        paste("lag(resid)", order, sep = "_"))
    switch(match.arg(type), Chisq = {
        bg <- n * sum(auxfit$fitted^2)/sum(resi^2)
        p.val <- pchisq(bg, m, lower.tail = FALSE)
        df <- m
        names(df) <- "df"
    }, F = {
        uresi <- auxfit$residuals
        bg <- ((sum(resi^2) - sum(uresi^2))/m)/(sum(uresi^2)/(n -
            k - m))
        df <- c(m, n - k - m)
        names(df) <- c("df1", "df2")
        p.val <- pf(bg, df1 = df[1], df2 = df[2], lower.tail = FALSE)
    })
    names(bg) <- "LM test"
    RVAL <- list(statistic = bg, parameter = df, method = paste("Breusch-Godfrey test for serial correlation of order up to",
        max(order)), p.value = p.val, data.name = dname, coefficients = cf,
        vcov = vc)
    class(RVAL) <- c("bgtest", "htest")
    return(RVAL)
}
<environment: namespace:lmtest>

I am wondering why I am getting the different results.
Comment: Always create generated random data set, instead of providing the original data set. Something along the lines `set.seed(100)`, `x<-rnorm(100)`, `dfUK<-data.frame(x=x,y=1+2*x+rnorm(100))`. Much easier to replicate than to copy the original data to some file, clean it up, and then load into R.
Comment: Please, [don't cross-post](http://meta.stackexchange.com/q/64068/150510). For those who are not necessarily so fluent with the R language, could you please add some background information (besides comments in your R code). This would help to make this post self-contained, and underline the *statistical aspect* of the question, if any. (Do not see it as petty criticism; I know you are familiar with how SE sites work.)
Answer: The formula you are using for the statistic is incorrect. The Breusch-Godfrey test involves calculating $R^2$ of the auxiliary regression and the formula for the $R^2$ is $SS_{reg}/SS_{tot}$, where $SS_{reg}=\sum (f_i-\bar y)^2$  and $SS_{tot}=\sum (y_i-\bar y)$, with $f_i$ being the fitted values, $y_i$ - the response variable and $\bar y$ its mean.
The response variable in the auxiliary regression is the residuals of the original regression, hence their mean is zero. So the BG test then is simply $n\frac{\sum f_i^2}{\sum y_i^2}$. You got the denominator right, but in the nominator you put the squares of the residuals of the auxiliary regression.
The correct code would be
length(lmBG$residuals)* sum(lmBG$fitted^2)/sum(lmUK2$residuals^2)

which gives the same result as
bgtest(lmUK2, order = 1, type = 'Chisq',fill=NA)

Note the fill=NA, the default is fill=0.
Comment: Ah, yes. Typo got me. :)

Replicating bgtest from lmtest


How to break apart $\operatorname*P(X^2 < 0.5)$?

Question: I get confused easily whenever I see expression like this:

$\operatorname*P(X^2 < 0.5)$ to  $\operatorname*P(X > -\sqrt{0.5})$ and $\operatorname*P(X < \sqrt{0.5})$.

Is there a rule or process to break it down? Currently I am using trial and error, thanks! Any tips would be greatly appreciated!
Answer: We have this:
$$x^2<0.5$$
Thus, taking the square root of both sides:
$$|x|=\sqrt{x^2}<\sqrt{0.5}$$

$$|x|<\sqrt{0.5}$$

So, either $x$ is positive or $x$ is negative:
$$\begin{cases}+x<\sqrt{0.5}\\-x<\sqrt{0.5}\end{cases}\implies\begin{cases}x<+\sqrt{0.5}\\x>-\sqrt{0.5}\end{cases}$$
Recalling that signs flip when $x$ is negative and we remove the absolute value bars.


Activity onBackPress not showing alert dialog

Question: I have an Activity in which when I press back button then its not showing alert dialog.
What could be the problem?
Here is my code
<code>@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LogFish.this);

                // set title
                alertDialogBuilder.setTitle("Exit");
                alertDialogBuilder.setIcon(R.drawable.ic_action_search);

                // set dialog message
                alertDialogBuilder
                    .setMessage("This action will cause you to abandon all changes on current new fish log. \n\nAre you sure you want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("YES",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            startActivity(new Intent(LogFish.this,MainActivity.class));
                            finish();

                        }
                      })
                    .setNegativeButton("NO",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close

                            dialog.cancel();
                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();

                    }
</code>
Comment: Actually its called but immediately your Activity get finished because you have written `super.onBackPressed();`. If you remove this then your Activity not finished on back Press and your dialog is shown.
Comment: Please check if your back key is not captured in onKeyDown()....
Comment: Check if you don't crash because you run on the main thread?
Answer: You have to Remove super.onBackPressed();
Answer: <code>@Override
public void onBackPressed() {

    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Title");
    builder.setMessage("Your Message");
    builder.setIcon(android.R.drawable.ic_dialog_alert);

    builder.setPositiveButton("YES", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            //implement your logic for YES
        }
    });

    builder.setNegativeButton("NO", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            //implement your logic for NO
        }
    });
    builder.setOnCancelListener(null);
    builder.show();
}
</code>
Answer: <code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
                YourClass.this.finish();
            }

        })
        .setNegativeButton(R.string.no, null)
        .show();

        return true;
    }
    else {
        return super.onKeyDown(keyCode, event);
    }

}
</code>


Do corner kick takers get an assist for a scored goal?

Question: Does the player who delivers a corner kick to the box get an assist if the ball is scored directly from the kick?
If not, how come they don't get an assist?
Comment: Maybe it could help to look at some examples. In the last [Liverpool-Man City mathch](http://www.premierleague.com/en-gb/matchday/matches/2013-2014/epl.match-report.html/liverpool-vs-man-city) Škrtel scored after a corner. Soccerway [shows an assist](http://int.soccerway.com/matches/2014/04/13/england/premier-league/liverpool-fc/manchester-city-football-club/1483790/?ICID=PL_MS_07) for Gerrard. But I did not find official assist statistics for this match on EPL website. Perhaps other users can find examples from other competitions, where we can see whether the kick taker was awarded an assist.
Comment: @Martin good idea, I was actually thinking this might be the best and easiest way to verify...
Answer: There are no specific rules for such statistics. In theory it may differ from league to league.
Even so, I've never seen any league do not counting pass from corner which leads to goal as a "goal assist". I can't find UEFA's official laws of statistics, but this is quote from UEFA's fantasy football rules and I'm sure this is a way which is used for official game statistics:

A player will be credited with a 'goal assist' when he delivers/plays
  the final pass, cross, header or shot, which leads to the goal being
  scored. This will also apply to set plays (i.e. corner, free kick,
  throw-in etc.)
Answer: As with all statistics, the answer to that question will vary depending on who's counting. As far as I know, there are no "official guidelines" for football statistics, but I assume most statisticians do count assists from cornerkicks. Anything else would surprise me, but I can't really back it up with any real evidence...
Answer: I know that on the Barclays premier league site there is a fantasy football game and they award points for an assist on corners and that is the official site for the Premier League. I always see this on sites like Goal.com as well where assists are awarded for corners.


Solve $2^x+7=y^2$ for integer $(x,y)$

Question: How many ordered solutions $(x,y)$ are there to the equation $2^x+7=y^2$ , where $x$ and $y$ are integers?

I tried taking cases for $x$ and $y$ like they are even or odd but I couldn't solve further.
Comment: See [Ramanujan-Nagell equation](http://en.wikipedia.org/wiki/Ramanujan-Nagell_equation).
Answer: HINT:
First of all, if $x<0,$ the Left Hand Side won't remain integer unlike the Right one.
Now, we have $\displaystyle 2^x+6=y^2-1=(y-1)(y+1)$
Observe that $\displaystyle y+1-(y-1)=2\implies y\pm1$ have same parity
If both are odd $2^x$ must be odd $\implies x=0$ (please test for $x=0$)
If both are even the Right Hand Side is divisible by $4$
For $x\ge2, 2^x\equiv0\pmod4\iff 2^x+6\equiv2\pmod4\implies x<2$
Comment: What do you mean by (mod4) ?
Comment: @Samurai, http://mathworld.wolfram.com/Congruence.html
Answer: Given: $2^x+7=y^2$
Since $L.H.S.$ is odd, $R.H.S$. must be odd.
Putting $y=2m+1$,
$2^x+6=4m^2+4m$,
or $2^{x-1}+3=2m^2+2m$
this forces $x=1$
putting it in original equation, we get $y=3$ and $y=-3$
Thus we have solutions $(1,3)$ and $(1,-3)$
Answer: For $x \geq 2$, the left side is $3 \pmod{4}$, while the right side can only be $0, 1 \pmod{4}$. Check by hand for the values of $x = 0, 1$.

Solve $2^x+7=y^2$ for integer $(x,y)$


How to output child links based on the current page

Question: When landing on a page which has a menu item that is a parent to other pages menu items, I would like to be able to show a list of those child menu items. I am using the following code.
$trail = menu_get_active_trail();
menu_build_tree('main-menu', array(
  'expanded' => array($trail[1]['mlid'])
));

However, the returned array looks like this (with a lot of unnecessary removed).
array
'49950 PKY Truck Beauty 312' =>
array
  'link' => &
    array
      'menu_name' => string 'main-menu' (length=9)
      'mlid' => string '312' (length=3)
      'plid' => string '311' (length=3)
  'below' =>
    array
      '49952 Seminars 314' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '314' (length=3)
              'plid' => string '311' (length=3)
      '50000 HDMA Breakfast 316' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '316' (length=3)
              'plid' => string '311' (length=3)
      '50000 MATS Concert 315' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '315' (length=3)
              'plid' => string '311' (length=3)

Notice how 314, 315, and 316 are 'below' 312? They are siblings in my menu structure, and that seems to be verified by each one having the same value for plid (311).  Obviously I can fix this by passing the array through another function, but I can't help but think I'm just missing something.
Comment: I [posted an answer](http://drupal.stackexchange.com/a/38921/2368) with another approach, I think that is one of the easiest solutions. And it works correctly. The suggested module is really popular amongst Drupal users.
Comment: In the interest of time, I'm fixing the issue with CSS, although I'm not happy with it. `$tree = menu_build_tree('main-menu', array(
  'expanded' => array($trail[1]['mlid'])
));`
`drupal_render(menu_tree_output($tree))`
Then using CSS I can style the links to remove the `ul` padding, making them appear they are all on the same level.  Not ideal, but effective. EDIT: sorry, I can't figure out how to get line breaks to work.
Comment: couldn't you post a sample screenshot of what you would like to achieve? To be honest, I found the question a little bit messy (I dare to say that because no answers have been written yet). Where would you like to be able to show the child items? Why aren't the menu related modules satisfying? Please clarify the question a little bit more, and maybe we could find a good solution.
Comment: @Sk8erPeter, I apologize if it's messy.  The solution I went with (referenced in my comment) is being used here: [link](http://truckingshow.com/events-home).  The main question is: why is menu_build_tree() returning a nested array that has unexpected levels (all links should be on the same)? To see where I'm showing the child items, use the link I included and click on any link in the main nav bar (css is used to give the illusion they are not clickable).
Comment: Regarding the modules, a cursory glance did not turn up anything that would suffice. That could be because I wasn't very interested in installing another module for a solution that should be accomplished in 4 or 5 lines of code.  I already have a custom 'includes' module that I use for things like this.  Now, from anywhere, I call `get_sub_menu_based_on_active_page()` and I'm all set.  I had to move on from trying to figure out the nesting issue as css makes the user none the wiser.
Comment: by the way, I realized on your current site, that the menu items' order is different in the left sidebar from the ones in the top navigation bar: http://i.stack.imgur.com/rkXhk.png
Comment: Have you already managed to try it?
Comment: @Sk8erPeter I did not try the suggested module.  I didn't want to install a new module when the API provided the functionality for me.  The code I posted along with some CSS was a suitable solution.  Thanks!
Comment: in this case, please post your own solution as a separate answer, and accept it! This way this question could be marked as solved.
Answer: Just wanted to follow-up. I came back to this question and found the following: https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal which is exactly what I needed.
The code, copied from the above-mentioned link and modified to fit my needs (mainly to use the current path to build the menu tree from, rather than using a hard-coded value:
$parent = menu_link_get_preferred($_GET['q']);
$parameters = array(
  'active_trail' => array($parent['plid']),
  'only_active_trail' => FALSE,
  'min_depth' => $parent['depth']+1,
  'max_depth' => $parent['depth']+1,
  'conditions' => array('plid' => $parent['mlid']),
);

$children = menu_build_tree($parent['menu_name'], $parameters);

return '
' . drupal_render(menu_tree_output($children)) . '
';

Comment: This works well, but you should use `current_path()` instead of `$_GET['q']`. `$_GET['q']` will return the path alias, where `current_path()` will get node/id.
Answer: It can easily be done with using Menu block module (it takes about 5 minutes to configure it).

All you have to do is

Enabling the module
Going to admin/structure/block
Clicking "Add menu block"
Set "Starting level" to "2nd level (Secondary)" and setting the region where it should be displayed under "Specify in which themes and regions this block is displayed."
Screenshots:

This is the way the configuration page looks like

admin/structure/block page with the enabled Menu block module blocks

I generated some "Basic page" contents with Devel module, and provided some menu links to them, and created a nested menu hierarchy

This is the default front page with no submenus (The "Main menu - 2nd level" block can NOT be seen in the left sidebar, as it doesn't have any second level child items)

This is the second menu, with some child elements, you can already see the "Main menu - 2nd level" in the left sidebar, but only the 2nd level child elements can be seen

Now going deeper:

I think that using Menu block module for this task is one of the easiest and fastest solutions.
Comment: I would be really curious why I got a downvote for this post. The recommended module does the job, and I wrote a step-by-step tutorial. Why doesn't the downvoter post a comment of the reasons? (Maybe it would be useful (maybe not), I could at least react.)
Answer: As noted in the comments, I ended up using the API function and then styling with CSS:
/* --------------- *\
    Sub-menus
    used on main pages
\* --------------- */
.content-sub-menu ul.menu {
  list-style: none;
  padding: 0;
  margin: 0;
}
.content-sub-menu > ul.menu {
  margin-bottom: 25px;
}
.content-sub-menu ul.menu a {
  font-size: 1.5em;
  padding: 10px;
  margin-top: 5px;
  display: inline-block;
  min-width: 33%;
}

Answer: This functions working correctly to get sub-menu of current page:
function build_left_menu()
{
    global $language_url;
    static $use_theme = NULL;
// Get the entire main menu tree
    $left_menu_tree = menu_tree_all_data('main-menu'); // Your main menu
$left_menu_tree_values = array_values($left_menu_tree); //get value only
    $html = "

In this section:
";
foreach ($left_menu_tree_values as $index => $item) {
        $link = $item["link"];
        if ($index === 0) {
            $item_class = "first-item panel side-menu ";
        } else {
            $item_class = "panel side-menu ";
        }
        $options_anchor = array();
        if ($item["below"]) {
            $options_anchor = array("attributes" => array('class' => array('dropdown-toggle'),
                'data-toggle' => 'dropdown',
                'data-delay' => 1000,
                'data-close-others' => "false",
                'data-hover' => "dropdown",
            )
            );
        }
        // Merge in defaults.
        $options_anchor += array(
            'attributes' => array(),
            'html' => FALSE,
        );

        //Default needed class
        $options['attributes']['class'][] = 'subpage-link collapsed';
        // Append active class.
        if (($link['link_path'] == $_GET['q'] || ($link['link_path'] == '<front>' && drupal_is_front_page())) &&
            (empty($options_anchor['language']) || $options_anchor['language']->language == $language_url->language)) {
            if ($item["below"]) {
                foreach ($item["below"] as $item_below) {
                    $link_below = $item_below["link"];
                    $options_anchor = array();
                    $html .= "
";
                    $html .= override_left_l($link_below['link_title'], $link_below['link_path'], $options_anchor).'
';
                }
            }
        }
    }
    $html .= "

";
    return $html;
}

Hope this help!
Comment: Your function calls an undefined function (override_left_l)!
Answer: I have just finished posting a function that gets child menu items given a node's path. You can check it here: http://softkube.com/blog/getting-child-menu-items-drupal-menu-tree
I'm including the link to future proof the answer in case the post gets updated and I'll also copy/paste the full code at the end.
In your case, you can simply run something like this in your theme to list all child menu items. Modify the echo statement and theme to your liking.
$path = current_path();
$nids = skl_get_all_menu_node_children_ids($path);
$children = node_load_multiple($nids);
foreach($children as $c) {
    echo $c->title . ': ' . url('node/' $c->nid) . '
';
}

And here's the function's full code. Check the link for possible future updates.
Good luck.
/**
 * Returns node ids of all the child items, including children of children
 * on all depth levels, of the given node path. Returns an empty array
 * if any error occurs.
 *
 * @param string $node_path
 * @return array
 */
function skl_get_all_menu_node_children_ids($node_path) {
    //Stop and return an empty array if node path is empty
    if(empty($node_path)) {
        return array();
    }

    //Init empty array to hold the results
    $nids = array();

    //Init parent keys. Check 'foreach' loop on parent keys for more info.
    $parent_keys = array('plid', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9');

    //Collect menu item corresponding to this path to begin updates.
    //Reference: http://stackoverflow.com/a/11615338/136696
    //Note: we couldn't find a way to get the sub-tree starting from this item
    //only and hence we had to get the whole menu tree built and then loop on
    //the current item part only. Not so bad considering that Drupal will
    //most probably have the whole menu cached anyway.
    $parent_menu_item = menu_link_get_preferred($node_path);

    //Stop and return empty array if a proper current menu item couldn't be found
    if(empty($parent_menu_item['menu_name']) || empty($parent_menu_item['mlid'])) {
        return array();
    }

    //Init parent item mlid for easier usage since now we know it's not empty
    $parent_menu_item_mlid = $parent_menu_item['mlid'];

    //Build whole menu based on the preferred menu_name gotten from this item
    $menu = menu_build_tree($parent_menu_item['menu_name']);

    //Reset menu cache since 'menu_build_tree' will cause trouble later on after
    //you call pathauto to update paths as it can only be called once.
    //Check: https://www.drupal.org/node/1697570
    menu_reset_static_cache();

    //Init processing array. This will hold menu items as we process them.
    $menu_items_to_process = array();

    //First run to fill up the processing array with the top level items
    foreach($menu as $top_level_menu_item) {
        $menu_items_to_process[] = $top_level_menu_item;
    }

    //While the processing array is not empty, keep looping into lower
    //menu items levels until all are processed.
    while(count($menu_items_to_process) > 0) {
        //Pop the top item from the processing array
        $mi = array_pop($menu_items_to_process);

        //Get its node id and add it to $nids if it's a current item child
        //Note that $parent_keys contains all keys that drupal uses to
        //set a menu item inside a tree up to 9 levels.
        foreach($parent_keys as $parent_key) {
            //First, ensure the current parent key is set and also mlid is set
            if(!empty($mi['link']['mlid']) && !empty($mi['link'][$parent_key])) {
                //If the link we're at is the parent one, don't add it to $nids
                //We need this check cause Drupal sets p1 to p9 in a way you
                //can easily use to generate breadcrumbs which means we will
                //also match the current parent, but here we only want children
                if($mi['link']['mlid'] != $parent_menu_item_mlid) {
                    //Try to match the link to the parent menu item
                    if($mi['link'][$parent_key] == $parent_menu_item_mlid) {
                        //It's a child, add it to $nids and stop foreach loop.
                        //Link_path has the path to the node. Example: node/63.
                        if(!empty($mi['link']['link_path'])) {
                            $nids[] = str_replace('node/', '',
                                      $mi['link']['link_path']);
                            break;
                        }
                    }
                }
            }
        }

        //Add its child items, if any, to the processing array
        if(!empty($mi['below']) && is_array($mi['below'])) {
            foreach($mi['below'] as $child_menu_item) {
                //Add child item at the beginning of the array so that when
                //we get the list of node ids it's sorted by level with
                //the top level elements first; which is easy to attain
                //and also useful for some applications; why not do it.
                array_unshift($menu_items_to_process, $child_menu_item);
            }
        }
    }

    //Return
    return $nids;
}

Comment: Thanks Mario. Can you comment on why you chose this over using `$parameters` in `menu_build_tree`?
Comment: Thanks for the feedback. I couldn't get the needed info no matter what `$parameters` I used, and believe me I looked a lot. All I wanted is, given a path, get all child menu items on all levels, and I simply couldn't find a way. If there's one please inform me I'll be glad to learn and update my answer and blog post. Cheers.
Answer: @Chris Rockwell and @ Mario Awad
I am newbie in Drupal so its hard to understand for me where to add this function.. I apologize for that. But, can you guys please mentioned it that In which file, should we add this function?
I am trying to create side bar navigation that will display only child elements on each page.
How to create navigation menu on sidebar with different navigation links displayed on different pages?
I Appreciate!
Thanks!


How to skip the first row of data in SQL Query?

Question: I have this code:
select DOLFUT from [DATABASE $]
How do I get it to get data from the 2nd line? (skip only the first line of data and collect all the rest)
Comment: It looks like this question has been asked already: https://stackoverflow.com/questions/15032803/select-all-rows-except-top-row/15032884
Comment: how are you defining "first one"? you arent even ordering by anything
Comment: Does this answer your question? [MySQL skip first 10 results](https://stackoverflow.com/questions/2827029/mysql-skip-first-10-results)
Answer: You can use LIMIT to skip any number of row you want. Something like
SELECT * FROM table
LIMIT 1 OFFSET 10

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

MySql docs
Comment: `LIMIT` isn't available in MS Access - since the OP has marked this answer as the solution, perhaps this question is tagged incorrectly.
Answer: Data in tables have no inherent order.

To get  data from the 2nd line

, you have to set up some sort sequence and then bypass the first record of the set - as Gustav has shown.
Answer: In Access, which you seem to use, you can use:
Select DOLFUT
From [DATABASE $]
Where DOLFUT Not In
    (Select Top 1 T.DOLFUT
    From [DATABASE $] As T
    Order By 1)


copyright information for image repositories (schema.org, json-ld)

Question: This is not exactly a technical question, it's about understanding the elements of CreativeWork and ImageObject in schema.org.
When creating structured data for an image, there are some attributes I can use to convey the copyright information, notably:

creator
copyrightHolder
license

This looks quite straightforward for me (even considering the legal differences of "copyright" in the Anglo-American and European worlds).
What I'm looking for is how to include the copyright information from pictures bought on image repositories like iStock. The information provided looks like: istock.com ©acreator ID-000000000.
How is this information meant to be used with schema.org?
As copyrightHolder is meant to be a Person or Organization, using the string 'istock.com ©someone' as the person's or organisation's name doesn't seem to be the right thing to do.
So I came up with this JSON-LD code:
[
  {
    "@context": "https://schema.org",
    "@type": "ImageObject",
    "contentUrl": "https://path/to/my/image",
    "copyrightHolder": {
      "name": "istock.com"
    },
    "creator": {
      "name": "someone"
    },
    "copyrightNotice": "istock.com ©acreator ID-000000000",
    "license": "https://www.istockphoto.com/en/legal/license-agreement"
  }
]

I'm still not sure where to put the ID of the image, and also I'm not happy using the id on istock.com as "name" attribute for "creator".
I could also only use the copyrightNotice and not use "creator" and "copyrightHolder" but I'm not sure if I'd meet the legal requirement then.
Answer: The schema.org information not really related to any legal requirement issues (It is vocabulary for search engines).
The credit should be visible to the user (With -or- Without schema) if the license requires adding a credit (Who is the copyrightHolder VS creator also not related to schema.org).
More important:

Don't mark up content that is not visible to readers of the page. Google Guidelines

So only add structured data that visible to the users. I guess you don't have in your web design clickable text to istock license (So you don't need to add this).
Even creditText could be enough.
Example (The markup visible to readers):

Basic example - Withtout

By Jane Doe
copyrights istock.com. Author Leonardo

Basic example - With

  By Jane Doe
  copyrights istock.com Author: Leonardo

image id
You can use https://schema.org/identifier.


How to call a function when a node is being viewed?

Question: Whenever I view a node page, I want to call a function but I'm not sure how to do that.
I was thinking I should use hook_menu() and declare the path as node/%, and attach a callback function to that path. Is that the right way, or is there a correct/better way?
Comment: Yes the answer's very simple, but I'm not sure why that makes this a bad question. The downvote seems unnecessary IMO. I edited to clarify and make it obvious that you've though about this yourself, hopefully that'll be enough to appease the nay-sayers :)
Comment: is this very simple to answer?
Comment: I must admit Clive's edit significantly improved readability of this question :) +1 from me. Questions simple to answer when you know the answer are not always bad, it's sometimes hard to search them on the net or drupal.og docs.
Answer: You can implement hook_node_view()

Act on a node that is being assembled before rendering.

e.g.
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'the_type' && $view_mode == 'full') {
    // Call your function here.
    my_function($node);
  }
}

Answer: Rules module can also react to URL access. You can specify an action supposed to happen on event if condition is true.

Event: Content is viewed
Condition: Probably  'Textual Comparison' on [site:current-page:path]
Action: If none of already provided meets your needs, you can provide your own function as Rules Action.


How to correct a view query?

Question: I would like to know how to correct a view query, when Drupal goes nuts ?
I'm using a view that should list media by categories (taxonomy term).
This view is called by a node, that held a reference to the same categories (same taxonomy term) that the medias I wish to display.
I need to order thos categories according to the delta field on my node object.
So in my views I did a join from the media taxonomy field to the taxonomy terms.
Then, I have a join on my any node that hold the taxonomy field.
I filter on the nid through contextual filters.
Until then all is good.
However, if I add the sort Critera on the delta value of categorie, the views module add another (unnecessaray) join on the table holding data for my taxonomy field on my node. This confuses my database and then I get a scalar product as results (every media is sent back, for each existing delta line).
Exemple of the query (I get two joins on node__field_categorie) :
<code>    SELECT DISTINCT field_categorie_taxonomy_term_field_data__node__field_categorie.delta AS field_categorie_taxonomy_term_field_data__node__field_catego, media_field_data.mid AS mid, taxonomy_term_field_data_media__field_standard_termref_1.tid AS taxonomy_term_field_data_media__field_standard_termref_1_tid, field_categorie_taxonomy_term_field_data.nid AS field_categorie_taxonomy_term_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {media__field_standard_termref_1} media__field_standard_termref_1 ON media_field_data.mid = media__field_standard_termref_1.entity_id AND media__field_standard_termref_1.deleted = '0'
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_media__field_standard_termref_1 ON media__field_standard_termref_1.field_standard_termref_1_target_id = taxonomy_term_field_data_media__field_standard_termref_1.tid
INNER JOIN {**node__field_categorie**} taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie ON taxonomy_term_field_data_media__field_standard_termref_1.tid = taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.field_categorie_target_id AND taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.deleted = '0'
INNER JOIN {node_field_data} field_categorie_taxonomy_term_field_data ON taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.entity_id = field_categorie_taxonomy_term_field_data.nid
LEFT JOIN {media__field_domain} media__field_domain ON media_field_data.mid = media__field_domain.entity_id AND media__field_domain.deleted = '0' AND (media__field_domain.langcode = media_field_data.langcode OR media__field_domain.bundle = 'useful_document')
LEFT JOIN {**node__field_categorie**} field_categorie_taxonomy_term_field_data__node__field_categorie ON field_categorie_taxonomy_term_field_data.nid = field_categorie_taxonomy_term_field_data__node__field_categorie.entity_id AND field_categorie_taxonomy_term_field_data__node__field_categorie.deleted = '0'
WHERE ((media_field_data.status = '1') AND (media_field_data.bundle IN ('useful_document'))) AND (media__field_domain.field_domain_target_id LIKE 'intranet_adapei69' ESCAPE '\\')
ORDER BY field_categorie_taxonomy_term_field_data__node__field_catego ASC
</code>
Exemple of my view, so you can better understand.

How can I correct such a query ?
I'm using Drupal 8.7.12 and can't upgrade for the moment.
I guess the easier way around this would be to be able to add an order by clause using the column made available by my first join on : node__field_categorie
I looked into query_alter and views_query_alter hooks, but it seems it is no longer possible to add an order by clause there (or I tried the wrong way). Any ideas ?
Answer: Finally, I found how to do it. I don't understand why I got lots of errors previously.
<code> function sully_ad_import_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'document_list' && in_array($view->current_display,array('block_1','block_3'))) {

  $query->addField(
    'taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie',
    'delta',
    'delta'
  );
  $query->addOrderBy(
    NULL,
    NULL,
    'asc',
    'delta'
  );

}
</code>
}

How to correct a view query?


CORS error in reading file

Question: I'm working on a headless website based on Drupal 8; I installed the CORS module and in CORS domain set *|*. Client side can read my view rest endpoint, but when client side try to load a file url returned by views rest result, I am faced with CORS error:

XMLHttpRequest cannot load http://domain.com/sites/default/files/home-slider-slide3-audio/2016-11/tr_SaidNursi.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.domain.com' is therefore not allowed access.

How can I resolve this problem?
The webserver is Nginx.
Answer: As this file is public the HTTP request is not served by Drupal. You need to
configure your web server to send correct CORS headers. If you are using Apache and have mod_headers installed you can set these HTTP headers in .htaccess file.
http://enable-cors.org/server_apache.html
Answer: As @ya.teck mentioned first it need handled by webserver so puting following lines in your site Nginx Configuration could help
add_header Access-Control-Allow-Origin '$http_origin' always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Headers 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
add_header Access-Control-Expose-Headers 'Authorization';

CORS error in reading file


Advantage of the modified destroy method? (Agile RoR)

Question: I'm working through Agile Web Development with Rails
In part E3, it says to replace the following method:
def destroy
  @cart = Cart.find(params[:id])
  @cart.destroy

with
def destroy
  @cart = current_cart
  @cart.destroy

where
def current_cart
  Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end

My question is, what is the advantage of using the second method over the first? I can't see any circumstance where the second would fail? This is calling the method from:
<%= button_to 'Delete Cart', method: :destroy %>

From within the cart view. Doesn't it implicitly always pass in the correct cart_id?? Or is this modification for destroy for future uses, for example when we are trying to delete the cart from another view? If this latter explanation is correct, do we need to always store id's in the :session hash?
Thanks for your help.
Answer: For starters, it offers a some protection against someone maliciously modifying the url and passing &cart_id=ID_TO_CART_I_DONT_OWN. See https://www.owasp.org/index.php/Top_10_2010-A4.
You're also saving yourself a database lookup by getting the cart from the session [although rails is pretty good with db caching by default]. About it possibly failing, what happens if the record no longer exists by the time you hit the "Delete Cart" button ? Cart.find(params[:id]) will raise an exception that you're not handling, the second method will handle the exception and fail quietly; this is not necessarily always a good thing.
Comment: Would that be considered failing quietly though?  It's returning a new cart object in the case one doesn't exist.
Comment: "fail" might not be the best word to use, the new cart object it returns gets destroyed immediately; like I said, it's not necessarily a good thing. I'd personally just get rid of the cart creation part and just raise the exception, let the caller decide how to handle it.
Answer: Since you are dealing with real time application like Shopping Cart, there is a great chance that two or more users access the application at the same time and buy the same product. Although the params[:id] is unique for each user but any user can maliciously enter into other with a hack and this will cause a serious drawback.
Having so, Your application has a session for each user in which you can store small amounts of data that will be persisted between requests for that user. Managing sessions for each user maintains the consistency and there is a nice resource management. This will not create any havoc.


AsynchTask crashes on return from doInBackground

Question: I have the following code:
public class TestSynch extends Activity {

public static ArrayList<HashMap<String,String>> list;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);
    Context ctx = this.getApplicationContext();

    new ProcessFileTask().execute(ctx);

    Intent i = new Intent(TestSynch.this, ListSchools.class);
    i.setAction(Intent.ACTION_VIEW);
    i.putExtra("arraylist", list);
    startActivity(i);

}

private class ProcessFileTask extends AsyncTask<Context, Void, ArrayList<HashMap<String,String>>> {
    @Override
    protected ArrayList<HashMap<String,String>> doInBackground(Context... ctx) {

        ArrayList<HashMap<String,String>> threadList = FileOperations.getListAsMaps(ctx[0]);
        return threadList;
    }
    @Override
    protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
         list = result;
        return;
    }
}

I can debug to the return threadList; line in doInBackground, and the ArrayList variable threadList is perfectly correct.
However, onPostExecute doesn't seem to get called and the Activity crashes on return from doInBackground, with LogCat suggesting a nullPointerException attempting to fire the Intent (which I have previously tested and worked ok before I started messing with AsynchTask)
Any idea why this is happening? The code seems simple enough...
Thanks
Answer: You need to move startActivity part inside Async's onPostExecute method.
for example:
public class TestSynch extends Activity {

//public static ArrayList<HashMap<String,String>> list;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);
    Context ctx = this.getApplicationContext();

    new ProcessFileTask().execute(ctx);
}

private class ProcessFileTask extends AsyncTask<Context, Void,
        ArrayList<HashMap<String,String>>> {
    @Override
    protected ArrayList<HashMap<String,String>> doInBackground(Context... ctx) {

        ArrayList<HashMap<String,String>> threadList =
             FileOperations.getListAsMaps(ctx[0]);

        return threadList;
    }
    @Override
    protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
         Intent i = new Intent(TestSynch.this, ListSchools.class);
         i.setAction(Intent.ACTION_VIEW);
         i.putExtra("arraylist", result);
         startActivity(i);
    }
}

Answer: I think Waqas is correct.  You are performing an AsyncTask that after it has executed sets a  public static variable list.  This list is used to pass into the Intent that you create in onCreate.  However there is no guarantee that the AsyncTask has actually completed at the point when you create the Intent.  As such the value of list at this point is null.
So, as Waqas suggests, you need to create the Intent after you have set a value for list, i.e. within onPostExecute.
Comment: Thanks - I was thinking that nothing happened 'downstream' of the execute until it completed, but then it wouldn't be a thread, LOL
Comment: i think its better to keep it in a thread because you may not know how much time it may require to complete `FileOperations.getListAsMaps(ctx[0])`. And if it takes more than 5 seconds then your app qualifies for ANR and may be killed forcefully by Android
Answer: Just to clarify, AsyncTask executes asynchronously, as its name implies.  When you call
     new ProcessFileTask().execute(ctx)
That piece of code goes off and does what it does but then the rest of your code continues to execute, which means that the list may not be populated by the time you try to start the new Intent because the AsyncTask might not have completed executing by the time you try to start the new Activity and pass in the List object to it.
Comment: Yes, I understand that now - also I was confused by the debug process. By putting a breakpoint in the doInBackground method, my mind is concentrating on the AsynchTask whereas the main thread had already crashed by that point, but debugging wont show that up until it completes. Thanks for your comment


Difficulty understanding contingency table and logistic regression coefficient

Question: I have the following contingency table
<code>      D    not-D
E     980    122
not-E 2420  6439
</code>
where D may stand for disease, and E for exposure.
This leads to the odds ratio (OR)
$$
\frac{odds(D|E)}{odds(D|\bar{E})} = 21.4
$$
[1] I hope that is correct?
[2] This ratio says the odds of having D given E is about 21 times the odds of having D given you do not have E i.e. having E greatly increases the chance of D?
[3] Therefore, in a logistic regression where D is the response and where E is included (amongst several other predictors) as a binary predictor variable, with $\bar{E}$ as the reference level, I would expect its model coefficient to be positive, so that if E is present the odds of D is greater than if E is not present?
[4] The problem I have is that the model coefficient for E is negative which I interpret to mean having E reduces the odds of having D, which contradicts what I understand the OR is telling me?
EDIT:
Using R, with some variable name changes,
<code>
    fit <- glm(D ~ x1 + x2 + x3 + x4 + xE, family = binomial, data = df)
</code>
Comment: Welcome to CV, PM.! Can you edit your question to indicate your software and command for your logistic regression?
Answer:
Yes
Yes
No, after adjustment for other variables, it's possible for the association to change direction. The above table is a crude odds ratio, so may be subject to bias of confounding.
To verify you haven't made a coding issue, fit the logistic model without adjustments and verify that the log odds ratio is log(21.4).
Comment: @AdamO If I understood your suggestion correctly, I ran the fitting with xE as the only predictor variable, and obtained the coefficient 3.06214. Now, log(21.4)=3.063391 so they are equal ( subject to a bit of rounding i.e. 21.4 is the OR rounded to 1 d.p. )
Comment: @PM. great, it sounds like your other adjustments have a VERY strong correlation with both E and D if the crude OR is 21 and the adjusted OR is less than 1. I would just be sure to describe very carefully what you did, and how you selected those adjustments, when you report the findings.
Comment: @AdamO Many thanks, very helpful. I clearly have a few things to ponder and some further reading to do.


LINQ to Entities, several one-to-one references to the same tables and naming

Question: I've started porting a .NET SQL Server application to LINQ to Entities. I have (among others...) one table called Users, and one called Time. Time is reported on a specific user (UserId), but it is also recorded which user made the report (InsertedByUserId) and possibly who has updated the Time since insert (UpdatedByUserId). This gives me three references to the table Users.
When I generate a .EDMX from this I get three references to the table Users: User, User1 and User2. Without manual edit I have no way of knowing which one refers to the UserId, InsertedByUserId or UpdatedByUserId field.
How do others solve this? Maybe it's not necessary to register ALL references, and stick with InsertedByUserId and UpdatedByUserId as ints?
(The manual edit wouldn't be a problem if the database were never updated, but as we make changes to the database every now and then we occasionally have to regenerate the .EMDX, thus removing all manual changes.)
Thanks in advance!
Comment: Maybe should add that I am using ASP.NET and Visual Studio 2010.
Answer: Jos,
Generally when I make my foreign keys,  I name them accordingly.  From the Entity designer you can differentiate between the different Navigation Properties (ie User, User1, User2) by looking at the FK association (as long as you named your foreign keys distinctly).   For Instance I have a ModifiedById and CreatedById field in each table.  Both fields reference my SystemUser table,   My foreign keys are named like this: FK_[TableName]_SystemUser_CreatedBy and FK_[TableName]_SystemUser_ModifiedBy.

You should notice that in the Navigation properties you can see the Foreign key.   You can also modify the name of the Navigation Property (which is in the Conceptual Side "CSDL portion" of the EDMX), and this change will stay when you update your EDMX from the database.
Comment: Thank you for your answer! Exactly what I wanted to know, I name my FKs and then manually edit the Navigation Properties, and instead of deleting the EDMX I use the refresh/update function. That's how you do it? I imagined the EDMX generator would be smarter, and that I did something wrong..


What data analyses should I use for my research study?

Question: I am currently doing a research study about social media use and youth's well-being. My research questions are:

How does the amount of time spent on social media affect the youth's well-being,
How does the amount of social media following affect the youth's well-being,
How does gender identity play a role in youth's well-being as a whole considering the
(a) amount of social media following and
(b) amount of time spent on social media, and
How does grade level play a role in youth's well-being as a whole considering the
(a) amount of social media following and
(b) amount of time spent on social media.

I have already started my survey, and I can't do another survey again due to the limited resources and time that I have. I just want to know what statistical analysis / analyses should I use, using the data that I have?
Comment: Can you clarify the data that you have, & the structure of your study? You seem to have laid out your goals here, but we'll need more information to answer your questions.
Comment: The analysis is very straightforward, if you took a definitely representative sample of youths, randomly assigned them to the conditions you want to compare and objectively (at least with a very well validated instrument) directly assessed their well-being etc. before & after intervention. If you did not do any of these three things, this is an incredibly difficult question. Depending on which of these is not done that way starting over with a properly planned experiment might be best.
Comment: In my survey, I asked them what their gender and grade level are, how much time they spend on social media, how many social media following they have, and there was a rating scale that would measure their well-being (self-esteem, self-worth, and mental health (anxiety, depression, and hostility). I hope it's enough data to provide answers to the research questions.
Comment: @Björn i'm sorry my research questions were wrongly crafted. I'm not intending to do an experiment for my study, I just to know the effect or correlation of the dependent variables to the independent variables.
Answer: That's an obvious case for a regression with some continuous and some categorical predictors and some interaction terms.
It looks like you might have all the information you need, but it's obviously a very bad idea to start a survey without knowing how to analyze the data.
Comment: Yeah, I just have come to realize that. We immediately started with the survey because there was a deadline we had to meet. But can you please enlighten me more on how to do regression, because I am relatively new to using programs like stata and spss.
Comment: @user75283 Using which program to analyze is not important at this step. You should first come up with your hypotheses and operationalize them. Then you should consider which programs to use.
Comment: How do i "operationalize" them? This is the first time that I'm doing a research like this. We weren't also taught about statistical analyses in our school, so I don't really know anything about stats (except for slovin's formula maybe).


Goroutine invoked in a method defined in a package does not run

Question: I am just wondering that if a goroutine invoked in a method which is defined in a package may not run.
Here is the structure my sample program:
sample
├── abc
│   └── abc.go
└── main.go

And the following is the source code of abc.go and main.go
abc.go
1 package abc
2
3 import (
4   "fmt"
5 )
6
7 func PrintCde() {
8   fmt.Println("Cde")
9 }
10
11
12 type Abc struct {}
13
14 func (a Abc)PrintAbc() {
15   fmt.Println("Abc")
16   go PrintCde()
17   for {}
18 }

main.go
1 package main
2
3 import (
4   "sample/abc"
5 )
6
7 func main() {
8   var a abc.Abc
9   a.PrintAbc()
10
11 }

Then if I run the program, I never get the string "Cde" printed on the screen.
What I can guess is the for loop in the method PrintAbc occupies the computing resources and function PrintCde never got scheduled to run.
If this is the reason, is there any other ways to prevent
the method PrintAbc from retruning but not occupy the resources to let function printCde run?
Answer: Yes, an empty/infinite for will generally cause this problem. For this purpose, use the empty select{} which is a blocking operation instead, and will encourage/force the runtime to swap Goroutines. Other options include increasing GOMAXPROCS or (in a real program) using something like a sync.WaitGroup to wait until the other Goroutine has finished processing before naturally terminating the program.
Comment: I am using sync.WaitGroup to hang the server now ! Many thanks.


Are they different Sigma algebras generated by a semialgebra and an algegra?

Question: Are they different Sigma algebras generated by a semialgebra $A$ and an algegra $A'$ of subsets of a set $X$?
where the Algebra $A'$ is obtained by all the disjoint collection of all finite unions of sets from $A$.
If yes, any proof? (I have proved only that the sigma algebra generated by the semialgebra is a subset of the other but I cannot prove the other direction)
Thanks!!
Comment: It is not clear what you are asking.
Answer: If I understand you, your question is:

If $\mathcal{A}$ is a semialgebra and $\mathcal{A}'$ is the algebra of finite, disjoint unions of members of $\mathcal{A}$, then is $\sigma(\mathcal{A}) = \sigma(\mathcal{A}')$?

The answer to this question is yes. Clearly, $\sigma(\mathcal{A}) \subseteq \sigma(\mathcal{A}')$, as you have already observed.
For the other inclusion, observe that $\sigma(\mathcal{A})$ contains every finite, disjoint union of members of $\mathcal{A}$ because it is a sigma-algebra and therefore closed under finite unions. Thus, $\mathcal{A}' \subseteq \sigma(\mathcal{A})$. Since, $\sigma(\mathcal{A}')$ is the smallest sigma-algebra containing $\mathcal{A}'$, we conclude that $\sigma(\mathcal{A}') \subseteq \sigma(\mathcal{A})$.
Comment: Thanks you, it was so easy....(xaxaxa)


What is a paired observation or paired variable?

Question: The question kind of asks itself, can anyone explain what a paired observation or paired variable is in basic terms?
My data consist of the number of words learnt in a week for 19 different participants, the data show each subjects age and the number of words learn individually, would this therefore be considered a paired observation?
Thanks for any help!
Comment: While $(\text{age}_i,\text{words}_i)$ would constitute a pair of values associated with participant $i$, those wouldn't normally be regarded as *paired data*. The term would normally be reserved for cases where you'd be interested in changes from the first member of the pair to the second (so they'd be measured in the same units, for starters). [Often you'd be interested specifically interested in within-pair *differences*.]
Answer: A typical example of paired observation is when you take a measurement before and after a certain event. More in general, there should be some natural association between the two.
In the example you mentioned, you don't have paired observations. Two paired observations would be, for instance, words learned, and words remembered after a week.


Z-test and sampling distribution

Question: The basic trick behind the z-test is the "sampling distribution". The "sampling distribution" is the distribution of all means of all samples.
So what we are interested is: if the population means of the two groups really differs.
H0 - the two groups (control and treated) have the same mean

So we first calculate the std of the treated group (std of the control group over n of the treated squared).
Then we use:

this std of the treated (for normalization)
actual mean of the treated (because of the assumption that H0 is true) which equals the actual mean of the control group
the treated group mean also called the sample mean (available because we usually have the data of the treated group)

to calculate a Z score.

We produce Z in such a way that it can be compared with the sampling distribution which is represented by a Z distribution z(0,1).
As a final step we just calculate how likely/unlikely is that Z value. This is equivalent to how likely/unlikely is the suggested mean (in H0) given the sampling distribution.

Is all of the above correct, generally speaking?
Answer: Once again, I find myself in a position where I would like to leave a comment but do not have the reputation, and so must leave an incomplete answer.
I am assuming you are a newcomer to statistics, and have created my comment with this in mind, forgoing completeness for simplicity.
Anyways, as Lauren said, your description of a sampling distribution indicates some lack of understanding, which I will seek to rectify.
The understanding of sampling distributions is very important, an understanding which my fellow stats undergrads are still struggling with 4 years into study!
Something which helped further my understanding of sampling distributions is the fact that any function of a random variable is itself a random variable.
(Disclaimer: this is all going to be from a classical approach.)
I'm going to start from the basics: a statistic is a function of the data. A statistic which we are very familiar with is the mean, which is the sum of all the data divided by the number of data we have. Let's not start there. Let's instead create a new statistic, which I will call 'John Madden's statistic'. Let's also say we have some sample (x1, x2,...xn) from a normal distribution with mean 2 and variance 1 (and that they are independent and identically distributed). See this distribution on wolfram|alpha: http://www.wolframalpha.com/input/?i=normal%282%2C1%29
John Madden's Statistic = f(x1,x2,...xn) = 2*x2, that is, that my statistic is just two times the second data point that we have. The fact that I selected the second data point is arbitrary; the point of this statistic is that it doesn't have much meaning. Well, this statistic is a function of a random variable, and so must be a random variable itself! You don't have to understand why, but the distribution will be normal with mean 4 and variance 4. That is, this statistic has a distribution, just like our original data did! Except that its a little different, see it here: http://www.wolframalpha.com/input/?i=normal%284%2C2%29
Now that we've seen the concept of a sampling distribution with a meaningless statistic, we will instead look at a more important one, one which you asked about: the mean. The mean is again, a function of a random variable, and so a random variable itself. Up above, I hid how I calculated the distribution of my statistic, but for the mean, I will spell it out a little more. The statistic that is the mean of a normal distribution has as its mean (confused yet? the statistic we are looking at right now which happens to be the mean also has a mean, because it is a random variable. That is, the mean has a mean; there is a certain value the mean is most likely to take.) the same mean as the original population (I will not prove this here unless you really want me to), but a different variance. This variance happens to be the standard deviation of the original population divided by the number of observations we have (I can also prove this if you need me to). So, like above, the mean is normally distributed with a certain mean and variance.
How do we know that the mean is normally distributed? Because of the Central Limit Theorem, which I'm sure is something you have learned/are learning/will soon learn.
Answer: Close but there are some issues:
The basic trick behind the z-test is the "sampling distribution". The "sampling distribution" is the distribution of all means of all samples.(There is a very general definition of a sampling distribution-- I would expand this)
H0 - the two groups have the same mean
So we first calculate the std of the sample (std of the population over n of the sample squared).
Then we use:

this std of the sample (for normalization)
actual mean of the sample
(because of the assumption that H0 is true) which equals the first
group mean (for example the mean of the control group).(This is not phrased quite right-- Should be the population mean under the null hypothesis which is 0.)
-the sample mean (available because we usually have the data of the treated
group) to calculate the Z score.

We produce Z in such a way that it can be compared with the Null Distribution which is represented by a Z distribution z(0,1) i.e. assume the sampling distribution is normal and then we need to standardize our observed result to compare Z to a N(0,1).
As a final step we just calculate how likely/unlikely is that Z value.
This is equivalent to how likely/unlikely is the suggested mean (in H0) given the sampling distribution. I don't think this is right

Z-test and sampling distribution


$(1-a)(1-b)(1-c)(1-d)\geq abcd$ for $a^2+b^2+c^2+d^2=1$

Question: Let $a,b,c,d$ be real numbers such that $a^2+b^2+c^2+d^2=1$. Prove that $$(1-a)(1-b)(1-c)(1-d)\geq abcd.$$
I thought about substituting $a=\sqrt{w},b=\sqrt{x}$, etc. (assuming first that $a,b,c,d$ are positive), and then looking at the convexity of the function $f(r)=(1-\sqrt{r})/\sqrt{r}$ and applying some Jensen-type inequality. But such an inequality applies to the sum of functions, not the product.
Answer: Observe that  as long as $a,b,c,d \ge 0$: $$\begin{align}(1-a)(1-b) - cd &\ge 1 - a - b + ab - \left(\frac{c^2+d^2}{2}\right) \\ &= 1 - a - b + ab - \left(\frac{1-a^2-b^2}{2}\right) \\ &= \frac{1}{2}(1-a-b)^2 \ge 0\end{align}$$
Similarly, $$(1-c)(1-d) -ab \ge \frac{1}{2}(1-c-d)^2\ge 0$$
Hence, $$(1-a)(1-b)(1-c)(1-d) \ge abcd$$
Comment: what if $cd < 0$, and $ab < 0$ ? example: $4 > -2, 5 > -11$, but $20 < (-2)(-11) = 22$.
Comment: @ah-huh-moment. oh noes ! I was hurrying ! Didn't notice the OP is missing a positivity constraint ! (I edit accordingly)
Comment: If some of $a,b,c,d$ is negative, then $abcd$ never goes up, while $(1-a)(1-b)(1-c)(1-d)$ always goes up or stays the same from the corresponding positive values of $a,b,c,d$. So your proof still works :)


Pairwise comparison with Bradley-Terry

Question: I am performing a pairwise comparison test for the perceived weight of objects. I want to estimate the difference between each pair, say, A - B. I suspect that the underlying distributions of A, and B, are Normal. However I am not sure, and I have no idea what their mean values or variances are. They could be described by any other symmetrical distribution (i.e. the weights of individual objects are perceived symmetrically around the mean perceived weight).
Using a Binomial model for the difference between each pair, it is easy to assume a Normal distribution for each team A, B, etc, and achieve satisfactory results.
If I instead want to use the Bradley-Terry model, this complicates things. The B-T model basically performs logistic regression, implying that the distribution for the difference between each pair A,B is a logistic distribution. If A-B follows a logistic distribution, A and B both follow Gumbel distributions (proved through convolution of Gumbel distributions). This is a problem, because I know that A and B follow symmetric distributions, whereas Gumbel is a skewed distribution. Would it be okay for me propose a normal approximation to the logistic distribution after use of the B-T model, in which case the distributions of A, B, etc. would all be normal? Or would this be counter-intuitive?
Answer: As you correctly point out, the Bradley-Terry model and the Thurstonian model can both be formulated as binary/binomial generalized linear models (GLMs) with either a logit or a probit link. As in other GLMs logit and probit typically yield almost identical results (see e.g., Difference between logit and probit models). So while you might prefer one or the other model from theoretical considerations, this often does not matter much for the interpretation ... at least as long as very extreme probabilities (close to zero or one) are avoided.
But you can also simply try this out. For example, the BradleyTerry2 package (Turner and Firth 2012, doi:10.18637/jss.v048.i09) supports setting both family = binomial(link = "logit") (default) or family = binomial(link = "probit").

Pairwise comparison with Bradley-Terry


scaled Schoenfeld residuals slope of regression line

Question: If a regression line of scaled Schoenfeld residuals versus time (or log time) has a non-zero slope, proportionality is violated. However, what can we tell from the slope of the regression line? If it is positive, does this mean that the effect of a covariate becomes more important over time? If it is negative, does the effect get less important over time? What if it crosses 0?
Answer: If it is positive, does this mean that the effect of a covariate becomes more important over time?
It means the value of the regression coefficient increases over time. The effect doesn't necessarily become "more important", because if it is negative in the beginning, then increasing the coefficient will bring the effect closer to 0.
If it is negative, does the effect get less important over time?
Same answer as above.
What if it crosses 0?
Then the coefficient changes sign, indicating the effect changes from positive to negative (or vice versa) over time.


c# string initiates to "00-00-00-00-00-00-00-00-00-00-00-00"

Question: So I am trying to experiment with hashtables saved on disk. When I try to debug and debugger gets to POINT 1, I open variables and see that Data and Key value gets an exception 'this.Key' threw an exception of type 'System.NullReferenceException'. I step over to POINT 2, and now Data gets value of "00-00-00-00-00-00-00-00-00-00-00-00". So from where that weird value is comming from? I have also put breakpoints on Data get and set, but by the time these points were not hit.
class HashtableFile
    {
        class Hashentry
        {
            const int KEY_BYTES = 4;
            const int DATA_BYTES = 12;
            public int? Key
            {
                get
                {
                    byte[] bytes = new byte[KEY_BYTES];
                    fs.Seek((KEY_BYTES + DATA_BYTES) * Index, SeekOrigin.Begin);
                    fs.Read(bytes, 0, KEY_BYTES);
                    int data = BitConverter.ToInt32(bytes, 0);
                    return data;
                }
                set
                {
                    byte[] bytes = new byte[KEY_BYTES];
                    int key = value.GetValueOrDefault(0);
                    bytes = BitConverter.GetBytes(key);
                    fs.Seek(KEY_BYTES * Index, SeekOrigin.Begin);
                    fs.Write(bytes, 0, KEY_BYTES);
                }
            }
            public string Data
            {
                get
                {
                    byte[] bytes = new byte[DATA_BYTES];
                    //seek key too
                    fs.Seek(((KEY_BYTES + DATA_BYTES) * Index) + KEY_BYTES, SeekOrigin.Begin);
                    fs.Read(bytes, 0, DATA_BYTES);
                    string data = BitConverter.ToString(bytes, 0);
                    return data;
                }
                set
                {
                    byte[] bytes = new byte[DATA_BYTES];
                    string data = value ?? string.Empty;
                    data = data.Insert(data.Length, new string(' ', DATA_BYTES - data.Length));
                    bytes = Encoding.ASCII.GetBytes(data);
                    fs.Seek(((KEY_BYTES + DATA_BYTES) * Index) + KEY_BYTES, SeekOrigin.Begin);
                    fs.Write(bytes, 0, DATA_BYTES);
                }
            }
            private int Index;
            private FileStream fs;
            public Hashentry(int? key, string data, int index, FileStream fs)//POINT 1
            {
                this.fs = fs;
                Index = index; // POINT 2
                Key = key;
                Data = data;
            }
            public int GetIndex()
            {
                return Index;
            }
            public int? GetKey()
            {
                return Key;
            }
            public string GetData()
            {
                return Data;
            }
        }

        private int maxSize;
        private Hashentry[] table;
        private string file;
        private FileStream fs;
        public HashtableFile(int size, string filename)
        {
            file = filename;
            if (File.Exists(file))
                File.Delete(file);
            fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            maxSize = size;
            table = new Hashentry[maxSize];
            for (int i = 0; i < maxSize; i++)
            {
                table[i] = new Hashentry(null, null, i, fs);
            }
        }
}

Answer: Look at
public int? Key
{
    get
    {
        byte[] bytes = new byte[KEY_BYTES];
        fs.Seek((KEY_BYTES + DATA_BYTES) * Index, SeekOrigin.Begin);

You see? The second line of the Key getter is using fs. If fs == null (default uninitialized value for a field of a class) then NullReferenceException if you try to use Key
BUT
public Hashentry(int? key, string data, int index, FileStream fs)//POINT 1
{
    this.fs = fs;
    Index = index; // POINT 2

the first line of the constructor sets the fs! So no more NullReferenceException. So at POINT 1, this.fs == null, while at POINT 2, this.fs = something
Comment: @Mazas because *BitConverter.ToString(bytes, 0);* formats the array in that way, and *bytes = new byte[DATA_BYTES];*
Comment: So getters are called before class constructor?
Comment: @Mazas You wrote: *I open variables and see that Data and Key value gets an exception 'this.Key'*... It isn't that "getters are called by a divine being before class constructor", it is "I'm calling getters before class construtor by looking at them with debug"
Comment: Okay, but still, how does that value of "00-00-00-00-00-00-00-00-00-00-00-00" shows up?
Comment: @Mazas *fs* is a *FileStream*, so an object used to read/write files... You should look the caller what *FileStream* is passing and see what data is present in the file.
Comment: this occurs even on first loop call. So by the time file is empty. Also the amount of "00" is equal to `DATA_BYTES`.
Answer: Problem was that
string data = BitConverter.ToString(bytes, 0);

converts bytes directly to to string, not to corresponding characters. Solution was to change this line to:
string data = Encoding.ASCII.GetString(bytes);


How do I add a confirmation form after the user clicks on "Save" in an edit form?

Question: On a site I'm building, a user can edit certain fields on a node that cause a chain reaction to happen (which I've implemented using hook_nodeapi() and its "update" operation).
Since this chain reaction potentially affects a lot of other content, I'd like to inform the user of exactly what other content will be changed, which depends on the changed field values, unknow until the user submits the node.  After the user has read the list of affected content, I'd like to give them the option to click on Yes, which will save the node and start the chain reaction, or click No, which will take them back to the node edit form (with edits intact).
How can I make a confirmation form appear after the user clicks on Save?
Answer: In brief, this is what I think you need to do in a custom module:

After validation, override the submit function on the node form to submit to a new interstitial page (you'll need to implement hook_menu to create the new page)
Pass the node object to the new interstitial page and define whatever logic you need in the interstitial page's callback function.
Create a new form on the interstitial page that runs node_save on submit with node object that was passed to it.
Answer: Add javascript function as shown below and then call that function on submit using hook_form_alter. This is working for me.
/* Javascript Function */
function confirm_reg(val){
var elem = $(this).closest('#'+val);
$.confirm({
    'title'     : 'Confirmation',
    'message'   : 'Are you sure to submit the details ?',
    'buttons'   : {
        'Yes'   : {
            'class' : 'blue',
            'action': function(){
                $("#your_form_id").submit();
                return true;
            }
        },
        'No'    : {
            'class' : 'gray',
            'action': function(){
                return false;
            }   // Nothing to do in this case. You can as well omit the action property.
        }
    }
});
}
 /* hook_form_alter */
 function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
 global $user;
 if ($form_id == "your_form_id") {
    $form['submit']['#attributes'] = array('onclick' => 'if(!confirm_reg(this.id)){return false;}');
 }


Are there mutes for flute?

Question: Is there some kind of practice mute for flute? I have been lent a flute and would like to try it out without disturbing neighbours too much. Only found for trombones and such when googling.
Comment: There is a confusion as to what gets named 'flute'. Whilst a lot of us consider it to be the transverse instrument that is played by blowing over a hole near the end, the rest regard a  flute as something otherwise known as a recorder, blown straight into the mouthpiece at one end. Recorders *can* be muted, transverse flutes not.
Comment: In warm weather, when windows are open, I can hear the flute teacher who lives about 8 houses up the block... but I don't mind, it sounds nice.
Answer: Assuming you are talking about the standard orchestra flute, or another kind of traverse flute: no, it's impossible to mute a flute.
Brass instruments such as trumpet or trombone can be muted because all of the sound comes out of the bell. The sound of a flute is far more diffuse.
For other members of the flute family, fipple flutes, there are mutes available. Here's one for recorder (note the site says "flute" but they mean "recorder").
Comment: @emil The reason you can't mute a flute the same way as a trombome is that on a trombone/trumpet all the sound comes out the hole at the end, while on a flute the sound comes out of every hole. Including the one you blow in, and including the tone holes, and if you cover them partially for muting you also change the pitch. So you need soundproofing that covers the whole instrument while still letting you operate it.
Comment: @Emil - there will always be somewhere: local schools are well underused - there could be plenty of times when there are no pupils - evenings, weekends, holidays, etc. Churches often have rooms that could be used. There have been several questions revolving round 'where to practise'. If/when you find a teacher, they may have ideas.
Comment: @lvr123 The difference is that a large part of the sound of a flute comes directly from the embouchure hole, and you can't put that in a box without putting your head in there as well.
Comment: Interesting. Usually impossible things become possible with progress, but I guess there is no solution for now.
Comment: @Emil you can practice inside a soundproof booth; this is not particularly new technology, but it's prohibitively cumbersome in most contexts.
Comment: @phoog A soundproofed booth was the first thing I though of, but since the poster is just trying a flute out, it's not a useful suggestion
Comment: As I've suggetsted a few times previously, playing in a car parked somewhere would work. You'll have to sit on the left, though !
Comment: @PiedPiper it might be a useful suggestion if Emil is near a facility that rents practice rooms.
Comment: @Tim in a majority of the world's cars, there is a steering wheel on the left that might get in the way.
Comment: @phoog - the majority of cars also have the facility to move the seat backwards. We extend our arms to hold the steering wheel, which means playing flute with bent arms doesn't allow the wheel to impede our playing. Or, maybe, in a safe place, open the window on the right..? Or even sit in the back? Come on!
Comment: I don't have a car or driver's license either so won't work in my current situation. I know they rented out practice rooms in my hometown but funnily enough now that I live in one of the largest cities in my country I have not found any practice rooms, I guess you need to know where to look to find them..
Comment: Is the flute muting problem because the air column, not the instrument, is what vibrates the most? If you can nearly plug up the bell of a trumpet, why doesn't the same work at the open end of the flute?
Comment: I don't agree with. It is not impossible. Saxophones and flutes share the same issue about muting. And there exist solutions for the saxophone, such as the SAXMUTE ONE, the E-SAX WHISPER MUTE, ...
Answer: My way of playing "muted" is to barely blow in the hole. For sure you can't practice your sound quality, but you can practice everything else. I'm doing this quite regularly without anyone noticing it !
Answer: You can construct some sort of vocal booth (that's what my friend did), with some sound isolation and couple of vents for the air.

Are there mutes for flute?


In Next.js, How to Redirect page in axios interceptor?

Question: I want to redirect page in axios interceptor.
However, when  server-side rendering, I can't access to server side context in axios interceptor. So I try to use next/router. but it only works in client side.
How can I this?
Below is the function executed in the axios interceptor.
<code>// customAxios.ts
const customAxios = axios.create();

customAxios.interceptors.response.use((response) => response, responseErrorHandler);
</code>
<code>// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         // Redirect to /503 page in server side rendering
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}
</code>
Answer: It is hard to give an answer without seeing your actual implementation of getServerSideProps or getStaticProps, but this might help.
Your interceptor should probably throw a custom error you can identify  in those methods and then use Next.js redirects
<code>// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         throw new CustomError(); //Throw custom error here
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}
</code>
And then, in the data fetching methods (needs to be adapted to Typesctipt):
<code>export async function getServerSideProps(context) {

  try {
    await customAxios.get(...)
  } catch(e) {
    if (e instanceof CustomError){
      return {
        redirect: {
          destination: '/503'
        }
      };
    } else {
        //...
    }
  }

  //...
}
</code>
Comment: Thank you. I will take a look. thanks :)


DataGridView - When any cells in a row are changed, I want to prompt the user and save the changes if leaving that row

Question: If a user leaves a row where they made changes to any cells in the datagridview control, I want to ask them to save the changes and then save the changes.
The problem is that I can not find the elusive and magical combination of properties and events to get this to work. When I try to call the save routine from events like RowValidating, RowValidated, RowLeave, or RowStateChanged, the value of the changed cells, or at least the value of the last cell in the row, is not the new value.
It comes up as the old value before it was changed. It seems to be canceling the edit.
I did look at similar questions here but they did not address my issue. Can someone please help and advise on the best way, or a good way to accomplish this???
Thank you!
Valhalla
Comment: Don't annoy the end user that way.
Comment: are you familiar with javascript..? check out things like `OnBlur` I believe that this can be a good place to start..
Comment: Is it Winforms? Also: Is the DGV dataBound?
Comment: Try `DataGirdView_CellEndEdit` and `DataGirdView_CellBeginEdit` events, there you can check if value changed and raise your dialog
Comment: Thanks... No I'm using Visual Studio C# and it's DataGridView control for a desktop type application. Wouldn't CellEndEdit, CellBeginEdit and CellValueChanged all trigger around leaving the cell as opposed to leaving the row? I actually did try it unsuccessfully with CellValueChanged. I'm just starting to get familiar with this grid control so I'm green. Do you have to put it in and out of edit mode???
Comment: This problem occurs because the user enters data to an invisible text box placed over the cell. It transfers only after the focus moves. We need someone to show how to address the invisible text box directly.
Answer: Add an event handler for RowLeave as such:
private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
  if (this.dataGridView1.IsCurrentRowDirty)
  {
    this.dataGridView1.EndEdit();
    // Your prompt to save code.
  }
}