On the cradle of the Elo Rating System, and how to find it

Question: A definitive proposal can be found in:
Elo, Arpad E. (August, 1967).
The Proposed USCF Rating System,
Its Development, Theory, and Applications.
Chess Life XXII (8): 242-247.
How exactly are

THE PERCENTAGE EXPECTANCY CURVE (Fig. 1),
TABLE I - RATING DIFFERENCES,  and
TABLE II- WINNING EXPECTANCIES

(page 243-244) calculated, including rounding details. I tried the normal distribution function with mean = 0 and sigma = 2000 / 7. But I could not get the rounding correct. For example the percentage expectancy of rating difference DP = 344 is 89% instead of 88% as in table II. Other irregularities: 54, 343, 358, 392, 620.
At page 247 we find a short reference list, including:

A. E. Elo; Analytical Reports, 1961, 1963 & 1965; (Privately Printed).

Are these reports lost forever, or are copies preserved and available in the public domain?
Update
My question is not about the validity of the model, but about the calculation within the model. How exactly can I reproduce Table II? Why is the rating expectancy of DP = 344 equal to P = .88 instead of .89 as I would expect.
In The Rating of Chess players, Elo states in chapter 8.94 Development of the Percentage Expectancy Table:

For example, suppose D = 160. Then z = 160/284.84. The table gives .7143 and .2857. as the areas of the two portions under the curve. These probabilities are rounded to two figures in table 2.11.

Apparently Elo refers to a z-table, but which z-table was in use at that time (±1960)?

@whuber
I tried.

        σ=2000/7
  D   H |z-score |  Tabel (t)         |  t/2 + 50%      |  N(z)           | P
 54  58%| 0,189  |0.14990 71832 09998 |0,574953591604999|0,574953591604999| 57%

        | 1,200  |0.76986 06595 56583 |0,884930329778292|0,884930329778292|
 343 88%| 1,2005 |                    |  interpolatie   |0,885027364557095| 89%
        | 1,201  |0.77024 87986 71795 |0,885124399335897|0,885124399335898|

 344 88%| 1,204  |0.77141 04214 54696 |0,885705210727348|0,885705210727348| 89%
 358 90%| 1,253  |0.78979 42933 03286 |0,894897146651643|0,894897146651643| 89%
 392 92%| 1,372  |0.82993 65621 86873 |0,914968281093437|0,914968281093436| 91%
 620 99%| 2,170  |0.96999 31540 52536 |0,984996577026268|0,984996577026268| 98%

Source:
(Issued June 5, 1953). Tables of Normal Probability Functions U. S. Applied Mathematics (23) (Department of Commerce National Bureau of Standards).

@cdalitz, 2000/7 is folklore, used by the Dutch Chess federation. I have no reference from literature.

Constructing TABLE-1 from TABLE-2
Table I and II are effectively mirror-images. See also the FIDE Handbook B. Permanent Commissions / 02. FIDE Rating Regulations.
R-code
D <-
  c(  3,  10,  17,  25,  32,  39,  46,  53,  61,  68,  76,  83,  91,  98, 106, 113, 121,
    129, 137, 145, 153, 162, 170, 179, 188, 197, 206, 215, 225, 235, 245, 256, 267, 278,
    290, 302, 315, 328, 344, 357, 374, 391, 411, 432, 456, 484, 517, 559, 619, 735, 736
   )

## TABLE I - RATING DIFFERENCES, between 51% and 99%.
## Column DP of TABLE-1 constitutes the midpoints of TABLE II, indexed by P.
## This is a reasonable approximation with the exception of P=99%.
table_1 <-
  head(cbind(P =seq(from=0.51, to=1.0, by=0.01),
             DP=trunc((head(D, -1) + tail(D, -1) + 1)/2) ),
       -1)
table_1

Constructing TABLE II - WINNING EXPECTANCIES  with sigma = 200 * (10/7)
Note (10/7) is a rough approximation of sqrt(2).
Conversion of rating difference to z-score gives at most 4 significant digits, which is useful when using a table indexed by z-score.
## Create rating differences, winning expectancy between 1 and 736, from 50% upto 100%.
n     <- 736
Pfull <- rep(-1, n)
pct   <- 0.50
k     <- 1
for(i in seq_along(D) ){
  while(k <= D[i]){
    Pfull[k] <- pct
    k        <- k + 1
  }
  pct <- pct + 0.01
}

## calculate / add normal probabilities (pnorm).
# P2, P15 probabilities rounded by 2, 15 digits.
df <- data.frame(D=seq(n), P=Pfull)

Deviations in Elo's expectations table
sd <- 200 * (10/7)  # standard deviation, using (10/7) instead of sqrt(2).
within(df,
{ P15 =  round(pnorm(D / sd , 0, 1,1), 15)
  P2  = round(P15, 2)
  attP2  = round(P - P2,  10)
}
) -> df2
subset(df2, attP2 != 0)

      D    P attP2   P2       P15
54   54 0.58  0.01 0.57 0.5749536
343 343 0.88 -0.01 0.89 0.8850274
344 344 0.88 -0.01 0.89 0.8857052
358 358 0.90  0.01 0.89 0.8948971
392 392 0.92  0.01 0.91 0.9149683
620 620 0.99  0.01 0.98 0.9849966

Constructing TABLE II by interpolation, third try
Consider rating values in steps of 20. The corresponding Z-score step is 20 * 7 / 2000 = 0.07.
Finding the percentage scores corresponding to the rating values D = 0, 20, 40, etc. does not require any calculations. They can be extracted directly from the Z-table.
To calculate the intermediate values, linear interpolation is the most obvious.
For example calculate the P value of 54 as follows:
sd  = 2000 / 7, the standard deviation chosen to ensure discrete steps in the Z table.
D   = 40 + 14, where 14 is the index in rating range 40-60
Z_b = 40 * 7 / 2000 = 0.14,  P_b = 0.5557 (From the Z table)
Z_e = Z_b + 0.07    = 0.21   P_e = 0.5832 (From the Z table)

The step size of P becomes: (0.5832 - 0.5557) / 20 = 0.001375

This gives:
P4  =  0.5557 + 14 * 0.001375 = 0.57495
    = 0.57495 + 5E-5 + 1E-6, rounded up to two decimals gives
P42 = 58%.

R-code.
dD <- 20                                          # step in D = 0, 20, 40, etc.
sd <- 2000 / 7                                    # standard deviation.
dZ <- dD / sd                                     # Short table, Z in two decimals.
within(df,
{ Z_sc    <- D / sd                               # 4 decimals.
  P15     <- round(pnorm(Z_sc), 15)               # value from extended table (1953).
  Z_b     <- trunc(D / dD) * dD * 7 / 2000        # index in short table, begin.
  Z_e     <- Z_b + dZ                             # index in short table, end.
  P_b     <- round(pnorm(Z_b ), 4)                # P before.
  P_e     <- round(pnorm(Z_b + dZ), 4)            # P after.

  ##  Corrections to fit Elo tables.
  ## P_b[340:359] <- .8830 - .0010                  # Feller = .8836
  ## P_b[380:399] <- .9082 + .0001                  # Feller = .9083

  ix      <- D %% dD                              # index 0 - 20.
  Pstep   <- (P_e - P_b) / dD                     # interpolation step.

  ## Pstep[340:359] <- Pstep[320:339]               # Previous step size
  ## Pstep[380:399] <- Pstep[380:399] + .00001      # .00545 --> .00555

  P4e     <- P_b + ix * Pstep                     # intermediate percentage.
  P42e    <- round(P4e + 5E-5 + 1E-6, 2)          # rounded up to next percentage.
  attP42e <- round(P42e - P, 15)                  # deviation .
}
) -> inter_lin
#subset(inter_lin, D >= 340 & D <= 360)
subset(inter_lin, attP42e != 0)

Between D = 340 and D = 400 we find 4 deviations:
 D    P attP42e P42e     P4e   Pstep ix    P_e    P_b  Z_e  Z_b       P15   Z_sc
343 0.88    0.01 0.89 0.88498 0.00066  3 0.8962 0.8830 1.26 1.19 0.8850274 1.2005
344 0.88    0.01 0.89 0.88564 0.00066  4 0.8962 0.8830 1.26 1.19 0.8857052 1.2040
358 0.90   -0.01 0.89 0.89488 0.00066 18 0.8962 0.8830 1.26 1.19 0.8948971 1.2530
392 0.92   -0.01 0.91 0.91480 0.00055 12 0.9192 0.9082 1.40 1.33 0.9149683 1.3720

How did it happen?
It is easy to see that the table is not entirely consistent. Look at the number of rating differences assigned to a percentage:
  P  L  -  H   Range
.86 303 - 315   13
.87 316 - 328   13
.88 329 - 344   16 <<<
.89 345 - 357   13
.90 358 - 374   20

Since the expectation function is monotonically increasing, the difference between H and L should not decrease. The 16 is clearly an outlier.
The error in D = 392 can be explained by using .00555 instead of .00545 as the step size for the linear interpolation.  Errors in D=343, 344, 358 can be explained by taking a wrong starting percentage (related to Z = 1.19), and the step size of the previous group.
The above is obvious an educated guess. I am afraid I have to visit the Royal Library in the Hague to find out more.
I am considering moving my question to the Chess stackexchange site. But I don't know what the best approach is yet.
Comment: I would like to suggest it's time to stop editing this post: they have become trivial and are likely to annoying users by now, because each time it bumps the thread to the top of the list of active ones.
Comment: A few sources that deal with the 2000/7 deviation mention a 1966 book by Elo named "the theory of rating systems". An online source could be the appendix in [An Application of the Elo Rating System to Professional Baseball](https://cache.kzoo.edu/handle/10920/14854) which would be available to students from Michigan.
Comment: Where did you read that $\sigma=2000/7$? Towards the end of p. 243 (rightmost column), Elo writes of $\sigma=200$.
Comment: "which z-table was in use at that time (±1960)?" The article is from 1967, so the classic reference book for tables would have been Abramowitz, Stegun: "Handbook of Matehmatical Functions" from 1964.
Comment: I have read about $200 \sqrt{2}\approx 2000/7$ before here: https://stats.stackexchange.com/questions/477721/does-the-elo-system-work-with-different-expected-value-functions/601502#comment1131823_601502 (edit: ah, that was you)
Comment: It would be helpfull if you copy the table. Now people will have to navigate to another page in order to get more details about the table beyond the few quoted figures.
Comment: @sextus-empiricus Interesting. Is this not inconsistent with the Elo's claim in the same article (and on p. 130 of his 1978 book) that the standard deviation is 200?
Comment: Older tables (usually before 1970 or so) relied on single-precision (or worse) arithmetic and, often, on interpolations within tables.  You will appreciate the issue better by attempting to do some of these calculations with pencil and paper -- which is how many of them were (literally) done.
Comment: It's important to use numerical judgment.  The "P" values in the table are given to *two* significant figures. You needn't, therefore, work with 15 sf in your calculations -- and I'm sure you haven't, because I'm confident you haven't used a pencil for any part of this post!  As a practical matter, an author of the time might have carried 3 sf in their calculations, knowing this would be more than good enough, even if occasionally the least significant digit were off by 1. A really good author would have checked their results with a finite difference calculation, but that didn't always happen.
Comment: Usually you can't reconstruct the original calculations, especially when they were done by hand, or using low-precision tables or low-precision calculators, and were transcribed from handwritten results.   If you really want to try to reverse-engineer it, then the first steps are to plot the tables and to compute the finite differences to detect inconsistencies.  (I have done that with many historical papers and tables: it works.)
Comment: Re 2000/7: this number ($285.7$) approximates $202.3\sqrt{2} = 286.1,$ which is the standard deviation of the difference of two independent Normally distributed variables each with an SD of 202.3. I don't know the origin of 202.3: the nominal value stated in the article is 200 (but 202.3 fits the tables much better).
Comment: The Dutch Chess Federation uses sd = 2000/7, with a reference to "The Theory of rating systems".  This seems strange at first glance, because Elo mentions 200Sqrt(2) many times. But converting rating differences to z-scores amounts to multiplying by 7, dividing by 2000, yielding only four significant figures.  In any case, Table II fits this sigma, leaving aside the rounding errors.
Comment: Re the edits: recreating $p$ from $d$ goes in the wrong direction: the calculation was performed by computing $d$ from $p.$  That's why you should compare the tabulated valued of $d$ to those computed from the *exact* values of $p.$
Comment: The mere fact that $d$ is given to 3 sig figs and $p$ to 2 sig figs alone indicates comparing $d$ to its prediction.  Anything else loses power to detect what is going on.  Besides, regardless of what the book might say, the table clearly was *not* constructed in that fashion: it is organized around an arithmetic progression of values of $p.$
Comment: Right.  I attribute the differences to the (inevitable) failure of typical approximations to the Normal distribution function out in the tails.  There is *always* some point at which the approximation begins systematically departing from the correct value.
Answer: There is a book by Elo entirely devoted to his formulas:

Arpad. E. Elo: "The Rating of Chessplayers." Ishi Press, 1978

Although the book presents some formulas, the derivation is not argued in details, and some formulas only hold under strong (rarely holding) assumptions, and it is not even discussed what these assumptions are or whether the estimators are biased or consistent. Just as one example, consider the "performance rating formula" (1) in your cited article. It can be derived by the "method of moments", i.e. by equating an expected value with its observed value as follows:

If a player of unknown rating $r$ plays against $n$ players with ratings $q_1,\ldots,q_n$, then the expected number of wins $W$ is $$E(W) = \sum_{j=1}^n \Phi(r-q_j)$$ where $\Phi$ is the normal distribution function with mean zero and variance $\sigma^2$.
Setting the observed number of wins $\hat{W}$ equal to the expected number of wins in the above formula yields an equation for $r$, that cannot be solved in closed form.
For solving this equation, Elo makes the assumption (without even mentioning it) that $\sum_j \Phi(x_i) = \Phi\left(\sum_i x_i\right)$  and obtains $$\Phi^{-1}\left(\frac{\hat{W}}{n}\right) + \frac{1}{n} \sum_j q_j = r$$ which is the "performance rating formula" (1).
Obviously, Elo's assumption does not hold unless $\Phi$ is a linear function, and at some later point (p. 133, equation(18) in the 1978 book above) he says that $\Phi(x)$ may be taken as $x/4\sigma$ "for the most used portion of the curve". Unfortunately, he did not explain how he arrived at this approximation. A Taylor expansion of $\Phi$ around $x=0$ would yield $\Phi(x)\approx x/\sqrt{2\pi}\sigma $, and $\sqrt{2\pi}$ is considerably different from 4, so it is not clear how Elo derived his approximation. Fortunately, this (presumable) error does not matter much, because he later subsumes the factor $4\sigma$ together with other factors in a value $K$, for which he suggests two different choices, depending on the number $n$ of played games. In any case, the linear approximation only holds when the ratings of all players are quite close to each other.

For a more lucid presentation of the mathematical model and an accurate derivation of estimation formulas (which are different from Elo's formulas), see

Batchelder, William H., and Neil J. Bershad. "The statistical analysis of a Thurstonian model for rating chess players." Journal of Mathematical Psychology 19.1 (1979): 39-60.

The discussed model differs from Elo's model, though, in the additional assumption that a chess game can result in ties (Elo only uses a model with two possible outcomes: win or loss, and draws are later counted in the formulas as half wins, which means that you cannot compute the probability of a draw with Elo's model). Elo's model can be obtained, however, as a special case of Batchelder's and Bershad's model simply by assuming that a tie is impossible and thereby setting the "tie width" $t$ to zero.
To address your question what the three terms mean in the context of the model, we must frst define the model:
$$P(\mbox{i wins against j})=\Phi(r_i - r_j)$$
where $\Phi$ is the distribution function of the normal (or alternatively: logistic) distribution with zero mean and standard deviation $\sigma$. In the cited article Elo alleges that he uses $\sigma=200$, but this does not match the tables listed in his article. Table I should be $\Phi^{-1}$ and Table II $\Phi$. I obtain approximately similar numbers with the choice $\sigma=286$, e.g.
> # reproduce values from Table I
> qnorm(0.60, sd=286)
[1] 72.45727
> qnorm(0.19, sd=286)
[1] -251.0783

or
> # reproduce values from Table II
> pnorm(210, sd=286)
[1] 0.7686066
> pnorm(95, sd=286)
[1] 0.6301187

which approximately matches the numbers in the tables. The alleged choice of $\sigma=200$ is also inconsistent with the use of a logistic distribution:
> plogis(220, s=200*sqrt(3)/pi)
[1] 0.88029

which is very far from the number given by Elo.
Comment: Elo uses σ = 200 as the USCF class interval for a single player, and 200sqrt(2) for a single game. That is: 282.84. In reality, however, he used 2000 / 7 (almost 286). Why? I think because 1 / σ gives only at most 4 significant decimal places. This is useful when looking up values in tables. I assume when the table was created (before 1960) he did not yet have a pocket calculator.
Are the few differences inaccuracies or is there a reasonable explanation? To be found in the missing documents?
Comment: My question is not about the validity of the model, but about calculations within the model, regardless of interpretation. How to reproduce?
Comment: @clp You are right that the tables in Elo's article do not match his description what the numbers allegedly are. It seems that he used a different choice for $\sigma$ for computing the tables.
Answer:
The values in table I seem to be an average of the values in table II (rather than a direct computation with the quantile function).
The values in table II correspond very well with a normal distribution that has standard deviation $2000/7$. The upper boundaries will be equal to the percentile scores of the normal distribution rounded down and the lower boundaries will be equal to the percentile scores of the normal distribution rounded up. Below you see a comparison of three methods.

The logistic distribution or a normal distribution with standard deviation $200 \sqrt{2}$ have large differences.
For the normal distribution with standard deviation $2000/7$ there are some small discrepancies, but only of the order of $\pm 1$ and that can be due to round-off errors and use of tables with lower precision* or possibly a typo.
p = seq(0.505,0.995,0.01)
elo1 = qnorm(p,0,2000/7)
elo2 = qnorm(p,0,200*sqrt(2))
elo3 = -log10(1/p-1)*400

x = c(3,10,17,25,32,39,46,53,61,68,76,83,91,98,106,113,121,129,137,145,153,162,170,179,188,197,206,215,225,235,245,256,267,278,290,302,315,328,344,357,374,391,411,432,456,484,517,559,619,735)

plot(x,x-x, type = "l", xlab = "Elo's upper boundary", log = "", ylim = c(-2,15), ylab = "difference with table")
points(x,elo1-x, pch = 20)
points(x,elo2-x, pch = 2)
points(x,elo3-x, pch = 4)

legend(1,15, c("normal 2000/7", "normal 200*sqrt(2)", "logistic distribution"), cex = 1, pch = c(20,2,4))

lines(x,x*0+1)

In 'The rating of chess players, past and present' Elo writes an example

For example. let D = 160. Then z = 160/282.84 = .566. The table gives .7143 and .2857 as the areas of the two portions under the curve. These probabilities are rounded to two figures in table 2.11

This suggests that he used sufficiently accurate tables with at least 4 figures. An example could be Table X (copied from Pearson) in Garrett's 'statistics in psychology and education' which occurs as a reference.
Comment: Table I is derived from table II. So it is about table II. Most values are only one rating point off, with the exception of 343, 344. Elo is rather vague over the origin of his table. Is it possible to reconstruct his calculation from old sources?
I tried simulating tables with less precision, but nothing worked.
Answer: Elo was specific: "This basic relationship ... turns out to be the familiar cumulative proportion curve of probability theory, the 'standard sigmoid'."  That's an old-fashioned way of saying that differences on the rating scale are linearly related to Z-scores: standard Normal deviates.
Here is his plot of that relationship for differences of scores, which therefore are nominally $200\sqrt{2}\approx 283$ per standard deviation unit:

This evidently is hand drawn.  Here is my plot of the same, but using a scale of $202.3\sqrt{2}$ because that matches the tables better:

The dots plot the values from Table 1.  The entire point is that on this Normal probability plotting scale, the relationship between ratings and probability is linear.
Plotting the difference between the rating difference "$d(P)$" and the rating as computed from the Normal distribution from the probability "$P$" (the residuals in the foregoing plot) suggests Elo used an approximation that works poorly in the tails (beyond the central 95% of the distribution, more or less).  (More detailed study suggests this is a severely truncated rational approximation.)  The worst discrepancy is at the end, where the score difference of 677 really should be 666.
Those who want details might be interested in the code that generated this figure.
#
# Table 1.
#
d <- c(677, 589, 538, 501, 470, 444, 422, 401, 383, 366, 351, 336, 322, 309, 296, 284,
       273, 262, 251, 240, 230, 220, 211, 202, 193, 184, 175, 166, 158, 149, 141, 133, 125,
       117, 110, 102, 95, 87, 80, 72, 65, 57, 50, 43, 36, 29, 21, 14, 7, 0)
p <- seq(1.0, 0.50, length = length(d) + 1)[-1]
X <- data.frame(P = p, Delta = d)
#
# The transformations relating "P" to "d(P)" in the table.
#
F. <- function(x, lambda = 202.3 * sqrt(2)) pnorm(x / lambda)
Q. <- function(p, lambda = 202.3 * sqrt(2)) lambda * qnorm(p)
X$Q <- round(Q.(X$P), 0)
X$Check <- with(X, Delta - Q)
with(X, plot(Delta, round(Q.(P) / Delta - 1, 3)))
with(X, plot(Delta, Q.(P) - Delta))
X$F <- round(F.(X$Delta), 3)
with(X, plot(P, round(F.(Delta) - P, 3)))
#
# Replot Figure 1.
#
y <- c(.01, .1, .5, 1, 2, 5, 10, 20, 30, 40)
y <- c(y, 50, 100 - rev(y)) / 100                        # The y grid
x <- seq(0, 900, by = 100)                               # The x grid

library(ggplot2)
X <- subset(X, P < 1)
scale.USCF <- 202.3
rho <- 4/3 * diff(range(x)) / diff(range(qnorm(y)))      # 4/3 is aspect ratio
alpha <- atan(rho / scale.USCF * sqrt(2) / 2) * 180 / pi # Angles of the lines

ggplot(data.frame(x = x)) +
  geom_vline(aes(xintercept = x), col = gray(0.7)) +
  geom_hline(aes(yintercept = y), data = data.frame(y = y), col = gray(0.7)) +
  geom_abline(slope = c(-1, 1) * 1 / (scale.USCF * sqrt(2))) +
  geom_point(aes(Delta, P), data = X, col = hsv(0.05, 1, .8)) +
  geom_point(aes(Delta, 1 - P), data = X, col = hsv(.6, 1, .8)) +
  coord_fixed(ylim = range(y), xlim = c(0, 920), expand = FALSE, ratio = rho) +
  scale_y_continuous(trans = scales:::probability_trans("norm"), breaks = y) +
  scale_x_continuous(breaks = x) +
  annotate("text", x = rep(400, 2), y = pnorm(c(1.58, 0.36 - 1.58)),
           label = paste(c("Higher", "Lower"), "Rated Player"),
           angle = alpha * c(1, -1), size = 3.5) +
  xlab("Difference in Rating (USCF Scale)") +
  ylab("Probability of Winning a SingleGame") +
  ggtitle("The Percentage Expectancy Curve", "After ELO (1967) Figure 1") +
  theme(panel.grid = element_blank(),
        panel.background = element_blank())

Comment: Why would Elo use an approximation or graphical method when tables of that time give highly accurate results? In "The rating of chess players, past and present" he writes an example  *"For example. let D = 160. Then z = 160/282.84 = .566. The table
gives .7143 and .2857 as the areas of the two portions under the curve. These probabilities are rounded to two figures in table 2.11"* which suggests that he used tables that gave at least 4 figures. An example could be Table X (copied from Pearson) in Garrett's "statistics in psychology and education"
Comment: A very good question (not an answer). The point is that he apparently did not, at least not consistently. Try D=25. Then DP=54%. However, the table (p. 176) shows 53%. I am using the table from Feller's `An Introduction to Probability Theory and its Applications`, Z in two figures, P in four figures.
Comment: In those days many people did calculations by hand -- literally, pencil and paper.  It is not at all unusual to see inconsistencies, imprecision, the unstated use of not so good approximations, and so on.  Because the approach is clear and has been superseded by later writings, there seems little point to trying to reproduce either of these tables exactly.
Comment: These tables have never been corrected and are still in use.
Comment: Then you might try to correct them.  Speculating about why they might be imprecise doesn't really help with that.  I say "try" because sometimes, even when a procedure is not completely correct, it can become a standard or part of a law or so deeply embedded within a complex system that it *shouldn't* be corrected.  But that's a matter for chess authorities to consider.


Logging data while debugging in VS2015

Question: Been trying to find any feature like this or a way of doing this. Basically, a way to log data through the VS debugger, instead of writing the data logging through code, as it would be much faster this way for what I'm doing.
Answer: You can add a breakpoint at critical sections of your code, or on specific variables, and set the breakpoint to log data (instead of, or when stopping execution).
There is some basic explanation here: using breakpoints. Just looking through the properties of a breakpoint will help you discover what is possible.
Answer: Visual Studio has a great feature called Tracepoints - basically, a tracepoint is just like a Breakpoint, except instead of breaking into the debugger, the debugger writes a logging message to the Output window.
The great thing about Tracepoints is that you can change your logging dynamically as you debug your code - without having to your solution and re-run the program all over again each time you want to change it.
I co-created a commercial Visual Studio extension called OzCode which extends Visual Studio's Tracepoints by baking a fully featured log-viewer into Visual Studio to view the results, and allowing you to export the results to Excel. See instructional video on youtube

Logging data while debugging in VS2015


Are the epochs equivalent to the iterations?

Question: I'm testing a multilayer perceptron with both scikit-learn and keras using the tensorflow backend.
Keras: epochs=X
Scikit:  max_iter=X
The epochs of keras are the same as the iterations of scikit learn???
Thanks
Answer: I have no experience with SciKit Learn, however, in deep learning terminology an "iteration" is a gradient update step, while an epoch is a pass over the entire dataset. For example, if I have 1000 data points and am using a batch size of 100, every 10 iterations is a new epoch. See Epoch vs iteration when training neural networks.
Answer: Although the other answer is correct for the standard terminology, unfortunately scikit-learn uses non-standard terms here, as can be seen from the source: sklearn.neural_network.MLP{Classifier,Regressor} use max_iters to refer to the number of epochs. The relevant lines look essentially like:
for it in range(self.max_iter):
    X, y = shuffle(X, y)
    for batch in gen_batches(n_samples, batch_size):
        # compute gradients on batch
        # take a step along that gradient

    # check stopping criterion

where the gen_batches helper splits up the whole dataset.
I sent a pull request clarifying this as a result of this question; the docs are now clearer, so thanks for asking!


Can a form triggering an ajax call reload itself on drupal 7?

Question: I'm trying to built a page to ask questions with a stream on top, so I need ajax to avoid the reload. It is actually simple. On top is a node with the stream and I add to blocks beneath.

A table with the questions, number of votes for the questions and an "add vote" button
A form to add a new node "question with 0 votes"

I have two problems.
A)When I click on the submit button of the 2. Block I add a question, I can update the table with the new question, but the add question form is not being emptied.
B)When I add a vote on the table (currently an ajax call from a checkbox) I get the database to have an increased counter and as far as I could check the callback delivers the new table, but the old one is never replaced. I thought it was the cache, but I even managed to avoid using the cached one, still no replacement. I get a few headers allready sent notices, but I don't understand why. I just want the form to be replaced by the new one.
(don't mind me getting a view instead of just a database result, it's just to built the table)
function questions_list_voting_form($form, &$form_state){
global $user;
$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['table'] = array(
        '#tree' => TRUE,
        '#theme' => 'table',
        '#header' => array(t("Title"),t("Votes"),t("Add vote")),
        );
    $view = views_get_view('questions_view');
}
$view->is_cacheable = FALSE;
$view->execute('block');
foreach ($view->result as $row){
    //['rows']['row-'.$row->nid]
    $question = array('#markup'=>$row->node_title);
    $vote = array('#markup'=>$row->field_data_field_votes_field_votes_value);
    $addvote = array(
    '#type'=>'checkbox',
        '#return_value' => 'add_vote'.$row->nid,
    '#ajax' => array(
      'callback' => 'ajax_addvote_callback',
      'wrapper' => 'question-list-table',
        'effect' => 'slide',
    ));
    $tab_arr = array(
            'question' => &$question,
            'vote' => &$vote,
            'addvote'.$row->nid => &$addvote
    );
    $tab_rows = array(
            array('data' => &$question),
            array('data' => &$vote),
            array('data' => &$addvote),
    );
            $form['table'][] = $tab_arr;
    $form['table']['#rows'][] = $tab_rows;
    $form['redirect'] = FALSE;
    $form['#rebuild'] =TRUE;
    unset($question);
    unset($vote);
    unset($addvote);
       }
     return $form;
}
function questions_list_voting_form_submitx($form, $form_state){
   if(substr($form_state['triggering_element']['#value'],0,8) == 'add_vote'){
    $tmp_node = node_load(substr($form_state['triggering_element']['#value'],8,2)); //question node
    $tmp_node->field_votes['und'][0]['value']++;
    node_save($tmp_node);
   }
}
function ajax_addvote_callback($form, &$form_state){
questions_list_voting_form_submitx($form, $form_state);
$form_state['no_redirect'] = TRUE; // avoid redirect?? maybe not working
$form_state['input'] = array('test'=>'etch'); //something to avoid cache
$form = drupal_build_form('questions_list_voting_form', $form_state);
$form_html = drupal_render($form);
return $form_html;
}

Answer: Your form id is 'questions-list-table' but you have 'wrapper' => 'question-list-table' (letter s is missing). You might also want to be explicit with 'method' => 'replace' since the ajax is causing problems.
You should add a '#submit' => 'submit_function' and modify your $form_state in that function instead of trying to modify it in the ajax callback.
Why do you rebuild and render the form in your ajax callback? I think you just want to return the part of the form to replace - in this case, $form itself.
Comment: I'm pretty sure I checked that a few times on the actual code, but you are right the typo here is the problem. I'm going to test that again. Thanks
Answer: Have a look here Remove tabledrag statuses on Ajax submit and display status message after Ajax submit I had a similar issue
Also as Joe Beuckman said you have a typo on your #ajax['wrapper'] value.


Inequality with maximum

Question: This should be simple, but I can't figure it out.
In an ordered field, does this hold? :
$$ \max\{ a,b\} - \max\{ c,d\} \le \max \{a-c,b-d\} $$
If not, does this hold? :
$$ |\max\{ a,b\} - \max\{ c,d\}| \le |\max \{a-c,b-d\}| $$
Edit:
Haskell's quickcheck says the first property holds (and by extension the second):
<code>prop1 :: Double -> Double -> Double -> Double -> Bool
prop1 a b c d = (max a b - max c d) <= (max (a-c) (b-d))

*Main Test.QuickCheck> quickCheck prop1
+++ OK, passed 100 tests.
quickCheckWith stdArgs { maxSuccess = 100000 } prop1
+++ OK, passed 100000 tests.
</code>
I would still like to see a proof, though.
Answer: Separating it into cases will help.
Let $S=\max\{a-c,b-d\}-\max\{a,b\}+\max\{c,d\}$.

If $a\ge b,c\ge d,a-c\ge b-d$, then $S=a-c-a+c=0$.
If $a\ge b,c\ge d,a-c\lt b-d$, then $S=b-d-a+c=(b-d)-(a-c)\gt 0$.
If $a\ge b,c\lt d$, then $a-c\ge b-d$ and $S=a-c-a+d=d-c\gt 0$.
If $a\lt b,c\ge d$, then $a-c\lt b-d$ and $S=b-d-b+c=c-d\ge 0$.
If $a\lt b,c\lt d,a-c\ge b-d$, then $S=a-c-b+d=(a-c)-(b-d)\gt 0$.
If $a\lt b,c\lt d,a-c\lt b-d$, then $S=b-d-b+d=0$.

Hence, $$S\ge 0\iff \max\{a,b\}-\max\{c,d\}\le \max\{a-c,b-d\}$$ always holds.

Inequality with maximum


Is a "switch bowling" action legal in cricket?

Question: In the current era of cricket, we see batsmen using switch hits to play a ball. That is, while playing a ball they change their batting side (left to right handed and vice versa) just before the ball comes to them.
My question is, can a bowler bowl a switch ball? Meaning, can a left hand bowler bowl right handed to a batsman? If it is not permitted, then is it not unfair to the bowlers that batsmen can change their batting style but not the bowlers? Or are there are any rules against a switch hit?
Comment: Do you mean a bowler runs in with the ball in his left hand and delivers it with his right? If so, there are loads of bowlers who do that.
Comment: @Orangecrush **a left hand bowler bowling right handed to a batsmen** not a right hand bowler running before bowling with the ball in left hand and delivering the ball with right handonlt
Answer: This would be a No-Ball as dictated by Law 21, No ball, of the Laws of Cricket

21.1 Mode of delivery
21.1.1 The umpire shall ascertain whether the bowler intends to bowl right handed or left handed, over or round the wicket, and shall so inform the striker.
It is unfair if the bowler fails to notify the umpire of a change in his mode of delivery. In this case the umpire shall call and signal No ball.

So the bowler has to tell the Umpire which arm they will use and which side of the wicket they will bowl from. The umpire then informs the batter. If the bowler wants to change the arm or side of the wicket they must inform the umpire first, who then relays this again to the batter.
Answer: ICC has opined that there is nothing wrong with switch hits as these are within the the laws of the game. In fact, they claim that it has made cricket more exciting.
On the other hand, once a bowler starts his run up, he cannot legally bowl a switch ball, that is, he cannot change his bowling hand. The only way this is permitted is if the bowler informs the umpire before his run up that he is bowling with this other hand. The umpire in turn informs the batsman.
The fact that switch hits are permitted but switch balls aren't, is a hugely debated topic. Switch hits surprise the bowlers. The fact that this surprise element is not available to the bowlers is something that doesn't go down too well with people who are against switch hits.
Comment: yes you are right but it is somewhat unfair to the bowlers as they can be hit to six or four with switch hit but the can not bowl a switch bowl directly.:(
Answer: As far as I'm concerned it's not legal. Yes, switch hits are still OK.
A bowler with an unexpected sudden change of his action is likely to hurt a batsman. So the bowler must inform the umpire before doing that.
A batsman who switch sides can get hit by the ball too, but it's his choice and he has the permission to do that at his own risk.
Comment: Hi, Welcome to Sports.SE! Do you have any reference to support your answer?


How to send GET/POST requests using express and react router?

Question: I currently have express set up to serve a static html page where my react components mount to. I'm also using react router because I have nested routes. For example:

I have an App component (green outline). Within that component, I'm rendering a Header component (orange outline) and a Footer component (red outline) and passing in a Review component (blue outline) through this.props.children.
My server.js file (express):
const express = require('express');

const app = express();

app.use(express.static('dist'));

const PORT = process.env.PORT || 3000;

app.listen(PORT, function() {
  console.log(`Listening on port ${PORT}...`);
});

My routes.js file (react-router):
import React from 'react';
import ReactRouter, {
  Router,
  Route,
  browserHistory,
  IndexRoute,
} from 'react-router';

import App from '../components/App';
import Home from '../components/Home';
import Review from '../components/Review';
import Game from '../components/Game';

const routes = (
  <Router history={browserHistory}>
    <Route path="/" component={App} >
      <IndexRoute component={Home} />
      <Route path="/game/:id" component={Game} />
      <Route path="/game/:id/review" component={Review} />
      <Route path="*" component={Home} />
    </Route>
  </Router>
);

export default routes;

My question is, I want to be able to make GET/POST requests (GET from the Game component to display all reviews from a db and POST to create a new review from the Review component), but where should that happen? I can't tell if it has to happen in my express routes because it seems to me that all express is doing is rendering the static html page and then react-router is taking over after that with handling which components to display.
Any and all help is greatly appreciated.
Comment: Any luck with this? How can we access POST params in react component on the lines of location.query to access GET params?
Answer: For the GET request, you can load initial data in a separate function, than load that data in after the component has mounted using componentDidMount like so:
class Game extends React.Component {
  constructor() {
    this.state = { data: [] }
  }

  loadCommentsFromServer() {
    $.ajax({
       ....
      }
    });
  }

  componentDidMount() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  }
}

You can do simply have another function for the POST.
Answer: I just wanna share my experience, hope it helps. I'm never doing a request on React Route although it can. So, I prefer to perform this action inside component itself on componentDidMount() method, in your case it will be on Game component.
My consideration is to make component reusable, especially if the the component is depends on the request. The benefit when you're implementing request inside the component is your component will automatically call for the request when it mount, wherever you're mounting the component on the route path.
Refers to my experience, you can also make a request on express as server side request, because there are particular condition that need to perform a request handling from server side. Such as handling Cross Origin Resource Sharing (CORS) issue when request to public API from client side, authentication request handling like using OAuth, and more.
If you're request is quite simple, I think request inside the component is sufficient.
Hope it helps. Thank you


$f(x)$ is a quadratic function with vertex $(1, −2)$, opens up.

Question: I got this on a practice quiz. I couldn't figure it out without at least another point on the graph. $f(x)$ is a quadratic function with vertex $(1, −2)$, opens up.
Comment: What is the precise problem, to find a unique equation of the parabola? In that case you are correct when you say you need another point since any polynomial of the form $f(x)=a(x-1)^2-2$ with $a>0$ satisfies those properties.
Answer: Equation of the parabola in Vertex Form where the point $(h,k)$ represents the vertex of this parabola is represented as this.
$f(x)= a(x-h)^2 + k $
If we take the point you have provided as vertex we will have $h=1$ and $k=-2$
The equation becomes like this=>
$f(x)= a(x-1)^2 -2 $
Now what is the role of "opens up" in this problem.
For Parabolas of form $f(x)=ax^2$ there are two cases
If $a>0$ (it is the case where parabola opens up):

For $a<0$(this parabola opens down):

So for the case of having your parabola Open Up ! Choose some $a>0$ to get positive coefficient in your equation $f(x)= a(x-1)^2 -2 $


Solving a matrix equation.

Question: Questions in this general form have been asked a lot here, but I've searched for hours and I haven't found any that I can generalize to my problem, so I've asked it again:
I've been given three matrices,
$A = \begin{bmatrix}
     5 & 3 \\
     3 & 2 \\
     \end{bmatrix}$,
$B = \begin{bmatrix}
     6 & 2 \\
     2 & 4 \\
     \end{bmatrix}$, and have to solve the equation AX+B = X. I've no clue where to start at all, so any help would be appreciated.
Comment: What about re-arranging, $AX-X=-B$ then $(A-I)X=-B$ so $X=-(A-I)^{-1}B$.  This of course assumes that you can find the inverse of $A-I$.
Comment: @user $M = IM=MI$ for every matrix $M$ and appropriately shaped $I$., So you have $AX - X = AX - IX = (A-I)X$ since distribution holds in matrix arithmetic as well.
Comment: Copy-paste error, fixed.
Comment: what about solving $(I-A)X = B?$
Comment: Can you explain how you moved from AX−X=−B to (A−I)X=−B?
Answer: $AX+B-X=0$
$(A-I)X=-B$
$X=-(A-I)^{-1}B$
Answer:
And, here's an example to model this process:
Comment: why is the font so huge?

Solving a matrix equation.


WingIDE Debug Message:No debug process

Question: After reading all stack commentary and trial running several other Python IDEs I'd like to use WingIDE for Python but getting stuck on debug process. I want to:
1) test a script of def function module in editor that prompts user for response (ie raw_input('Enter your Name')
2) enter the corresponding input in the Python shell when prompted
3) see the results of function in Python Shell
However this is the error message I receive in WingIDE Messages box:
Debugger: Listening for back-connection
Debugger: Connected to debug process
Debugger: Debug process running: pid=27554 [0 modules loaded]
Debugger: No debug process/not listening for connections
Message in WingIDE OS Commands:
Process Failed to Start
Project PythonPath is set to:
 /Users/myname/Python-2.4.6
Thoughts?
Answer: The OS Commands tool doesn't run things in the debugger, but just in a separate process space.  Use Debug/Continue in the Debug menu and then you will see the prompt from raw_input() in the Debug I/O tool and you can enter your input there.  If you want to work in the Python Shell instead, use Evaluate File in Python Shell in the Source menu.  You may want to run through the tutorial in the Help menu.

WingIDE Debug Message:No debug process


trouble with location regex and redirection in nginx

Question: I want to setup proxy in nginx:
location ~ ^/m/([^/]*)/([^/]*)/([^/]*)$ {
  proxy_pass http://127.0.0.1:8080/redir/m/$1/$2/$3;
  proxy_redirect off;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

It works but this address
http:// myhost/m/test//ss

gets translated to
http:// 127.0.0.1:8080/redir/m/test/ss;

How can I get my second slash??
Thanx.
Answer: You can't.  A // is defined as being equivalent to /, and nginx will always reduce a URL to the canonical form before passing it on.


Create Gtk toolbar with buttons and text in PyGobject

Question: I found a couple of tutorials (PyGTK) that use this code:
    from gi.repository import Gtk

    [...]

    self.toolbar = Gtk.Toolbar()
    self.toolbar.set_style(Gtk.TOOLBAR_BOTH)

    [...]

but using Python3 and GTK3 (PyGobject) I get the message:
AttributeError: 'gi.repository.Gtk' object has no attribute 'TOOLBAR_BOTH'
Does anyone know how to handle this in PyGobject?
Answer: Most likely Gtk.ToolbarStyle.BOTH; to convert a C constant to Python like GTK_TOOLBAR_BOTH which is a member of the GtkToolbarStyle enum, it's (module name).(enum name without module name).(constant name without enum prefix).


Sound Pool Permissions

Question: I am playing audio through my app using the sound pool, do I need to ask for certain app permissions?
If I do, which ones do I need?
Thanks for your help!
Answer: You dont need any permissions for using the SoundPool or media player.
Just go through these tutorials. It will helpful for you.
Play Audio resource using sound pool
Play foreground and background music using SoundPool and MediaPlayer

Sound Pool Permissions


Display data scraped from Nokogiri in Rails?

Question: I recently started learning Rails, and am trying to build a simple application which scrapes football fixtures from a website and displays the data in my index.html. Users can then try to predict the scoreline of the fixtures.
I managed to scrape the data into a fixtures.rb file using Nokogiri:
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open("http://www.bbc.co.uk/sport/0/football/21784836"))
doc.css("tr.row2").each do |item|
  puts item.at_css("td.left.first p").text
end

What would be the easiest way to add this into a Ruby on Rails application? Can I put this into the controller? I'm having trouble pasting the text in full as a view.
Answer: Add it to an array and then use it in your controller.
@football = []
doc.css("tr.row2").each do |item|
  @football << item.at_css("td.left.first p").text
end

Then in your view you can reference the contents:
<% if @football %>

    <% @football.each do |foot| %>

<%= foot %>

    <% end %>

<% end %>

Comment: Many Thanks Richard. I just tried this but I get the error{ undefined method `each' for nil:NilClass } I think it implies that there is only 1 @football?
Comment: Did you put that code in the action associated with your view?  I edited the response to only display the code if `@football` has a value.
Comment: Thanks Richard. It works now. I originally placed the action outside the index method in the controller. It works when inside. Appreciate it.


Lots of FAILURE AUDIT: an account failed to log on entires in Security Log

Question: I have received lots of failure audits on my server. From the log, I have identified the particular machine that is the culprit. How can I identify which process is sending the login request?
Do you have any idea how to find out?
Below is the detail of the log.
Security log on \QKSRVDC212:
[2465151] Microsoft-Windows-Security-Auditing

    Type:     FAILURE AUDIT

    Computer: QKSRVDC212.Corp.abc.com

    Time:     7/26/2012 9:31:00 AM   ID:       4625

An account failed to log on.
  Subject:
    Security ID:        S-1-0-0
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0
  Logon Type:           3

  Account For Which Logon Failed:
    Security ID:        S-1-0-0
    Account Name:       Quality
    Account Domain:     QDMNT140

  Failure Information:
    Failure Reason:     Unknown user name or bad password.
    Status:         0xc000006d
    Sub Status:     0xc0000064

  Process Information:
    Caller Process ID:  0x0
    Caller Process Name:    -

  Network Information:
    Workstation Name:   QDMNT140
    Source Network Address: 10.1.1.185
    Source Port:        3973

  Detailed Authentication Information:
    Logon Process:      NtLmSsp
    Authentication Package: NTLM
    Transited Services: -
    Package Name (NTLM only):   -
    Key Length:     0

Answer: On the login source system 'QDMNT140' use netstat -ano | findstr 3973 to see which process has the matching source port '3973' open.  Replace 3973 with whatever the port changes to if it's not static.


R- do I made a mistake using boot() within the boot library

Question: I am trying to run a correlation test between different columns within a table. I also use the bootstrap method to run the same test. I want to compare the result but found out that those are exactly the same result. So I am wondering is there anything I did it wrong.
df is a 20000 row * 7 column data.table, the first column is key
Below is my bootstrap code. Please help me to check it.
Is that possible that the result after the bootstrap will be same as run the whole dataset?  Thank you!
n = nrow(df)
cor.small <- function(d,i= c(1:n)){
 d2 <- d[i,]
 cormat <- cor(d2[,-1,with=FALSE])
 upper <- get_upper_tri(cormat)
 return(upper)
}

result <- boot(data = df,statistic = cor.small, R= 999)

Comment: I suspect you don't know why we use bootstrapping. I also suspect your problem is that you don't understand what the output of `boot` means. Anyway, a quick check (after some googling and guessing how `get_upper_tri` might be defined) indicates that your code works as expected.
Comment: The boostrap estimates would be `colMeans(result$t)`. Read the help page, section `Value`: `t0 The observed value of statistic applied to data.` And `cor(df[, -1])` is the matrix you are getting (without the `NA` values). Also, get rid of `=c(1:n)` since this is the `indices` argument and should vary from call to call.
Answer: You should call the boot function  like this (I have used the Iris dataset to work with something, and modified the code a bit in places) :
cor.small <- function(d, i ){
        cormat <- cor(d[i ,-1])
        upper <- cormat[lower.tri(cormat)]
        return(upper)
}

df <- iris[ ,-5]
nsamp = ceil(nrow(df) / 2) # or use a different value
nrun = 10
set.seed(1)
cor.small(df,sample(1:nsamp,nsamp,replace=TRUE))

boot(data = df,statistic = cor.small, R= nrun)


export CVS repository

Question: how to export a CVS repository from one machine to another? Would it work if i transfer the whole CVSROOT then make it the CVSROOT of the new machine? if so, would it also include all the revision history? or there are additional directories need to be exported...
Thanks in advance
Answer: Here's a good step by step guide: http://www.solarorange.com/docs/cvs/repositorymove.html
It looks like you just zip it up.

export CVS repository


How to share a volume between VM in ESX 4?

Question: I want to access a single volume from vmware ESX4 vms, in three ESX hosts with datastores in an Equallogic PS6000 SAN. I know how to manage the datas (through a cluster filesystem), but I cannot seems to find a way to do this.

How can I share VMDK accross hosts ? (the relevant files are on the SAN)
Is this even possible ?
Is there a mean to do this with RDM ?

On all guests, the OS is GNU/Linux Debian 5 "Lenny", 64 bits version.
Answer: Yep, there's a couple of ways you can do this, though you don't mention your guest OSs or how you intend to manage this shared disk.
A common reason to do this is to support MS Clustering, for this you can easily create a couple of small ~1GB LUNs, expose them to all hosts ideally with the same LUN # then add them through a second SCSI controller to your VMs as Raw Device Mappings (the RDM you mentioned), these VMs will then see and have full control of these two new LUNs, you simply then use your MS Cluster setup to format the disks with NTFS and MSDTC will look after the disks to ensure writes are arbitrated. Use one for the Quorum and the second for the MSDTC files (you may be able to combine these, I'm not an MS expert sorry), if you're using this setup you may well need one or more additional shared LUNs setup in the same way for storing data/logs etc. depending on your app. You can do pretty much the same thing for Linux guests but ensure you're using a cluster-aware file system such as OCFS2 otherwise you'll corrupt your disk almost instantly.
Another option is to create a .vmdk and use the 'independent' option when creating, there are a number of limitations this brings with it but we'd need to know more about your use-case before going into them too deeply.
Feel free to come back to us with more detail but your answer is basically yes, it's very possible.
Comment: edited, it's Debian Lenny 64bits. The key in your answer, I think, is "expose them to all hosts". I'm trying now.
Comment: cool, what FS are you going to use?
Comment: for the moment, I think about using OCFS2. I'd like to know more about differences between this and GFS2 and have asked around, but to no avail.
Comment: Oh you'll be fine with either to be honest, they're very similar - we're just an Oracle-house so I happen to know OCFS2 better but I'd just jump in and get your hands dirty if I were you :)
Comment: Ok, we have opted for OCFS2 :)
Answer: There are thousands of different requirements and limitations if you go with virtual disks or RDM. You need to decide if you want cluster in a box (many VMs on one physical host), or cluster across boxes (each VM sits on its own physical box), and you can't really mix and match or move VMs around: once you've chosen one or the other, you're stuck, because they require completely different configurations. Read the VMware MSCS document to understand (it doesn't matter that it's written with Windows VMs in mind, the design concepts and requirements still apply).
Instead, you can do something much simpler. Configure new vNICs for your VMs, connected to your iSCSI VLAN(s). Set up iSCSI initiator in the VMs, using the new vNICs. Provision the LUNs to the VMs, not to the ESX host. Basically, pretend that those VMs are regular servers talking iSCSI to your SAN. It will just work, as long as you build the network side of it right (multipathing, jumbo frames, vmxnet3 adapters, etc.)


Normal basis of $GF(2^m)$ over $GF(2)$

Question: Can someone help me to understand how to find normal basis of $GF(2^m)$ over $GF(2)$. For example $GF(2^{60})$. I need to multiply polynomials in this field and I would like to use the normal basis to do it but I don't understand how to find the normal basis. I read this articule but I don't really understand.
I'll really appreciate an explanation through an example.
Thank you in advance.
Answer: This is an easy special case where a so called optimal normal basis is available.
Let $\alpha$ be a root of unity of order $61$. Because $2$ generates the multiplicative group $\Bbb{Z}_{61}^*$, we know that

$GF(2^{60})=GF(2)[\alpha]$,
The powers $\alpha,\alpha^2,\alpha^3,\cdots,\alpha^{60}$ are all conjugates of each other. In other words, they are the same set as $\alpha,\alpha^2,\alpha^4,\alpha^8,\cdots,\alpha^{2^{59}}$.
Because the minimal polynomial of $\alpha$, the cyclotomic polynomial $\Phi_{61}(x)$, is of degree $60$, we see that the list of the preceding bullet is a basis of this field extension. Because they are also conjugates of each other they form a normal basis.
Unless $i+j=61$ the product $\alpha^i\cdot\alpha^j=\alpha^{i+j}$ is another basis element. When $i+j=61$ we get $\alpha^i\cdot\alpha^j=1=\sum_{k=1}^{60}\alpha^k$ is a sum of $60$ basis elements. Together these imply that the multiplication table of this normal basis has the minimum possible number of non-zero coefficients.
Comment: Thank you for your answer. But I really didn't understand I'm new in this subject so I don't know what is cyclotomic polynomial. I just want to understand the steps I have to follow to find normal basis in general case. When I will understand that I'll try to do some improvements if possible. Thank you for your help

Normal basis of $GF(2^m)$ over $GF(2)$


Regex from character until end of string

Question: Hey. First question here, probably extremely lame, but I totally suck in regular expressions :(
I want to extract the text from a series of strings that always have only alphabetic characters before and after a hyphen:
string = "some-text"

I need to generate separate strings that include the text before AND after the hyphen. So for the example above I would need string1 = "some" and string2 = "text"
I found this and it works for the text before the hyphen, now I only need the regex for the one after the hyphen.
Thanks.
Answer: You don't need regex for that, you can just split it instead.
var myString = "some-text";
var splitWords =  myString.split("-");

splitWords[0] would then be "some", and splitWords[1] will be "text".
If you actually have to use regex for whatever reason though - the $ character marks the end of a string in regex, so -(.*)$ is a regex that will match everything after the first hyphen it finds till the end of the string. That could actually be simplified that to just -(.*) too, as the .* will match till the end of the string anyway.
Comment: I need to match *from* the last instance of a character - this is a solution: https://stackoverflow.com/a/8374980/845584


Assert the range of a binomial coefficient divided by power of a number

Question: I found this question in a previous year post graduate entrance exam for mathematics.The question was
What is the range of
\begin{equation*}
\frac{200 \choose 100}{4^{100}}
\end{equation*}
The choices were
\begin{align*}
[\frac{3}{4}, 1) && \text{or} &&(0, \frac{1}{2}) && \text{or} && [1, \infty) && \text{or} && [\frac{1}{2}, \frac{3}{4})
\end{align*}
Comment: Showing the result is less than $1$ is easy but to determine which interval is correct seems difficult. Perhaps you may use the expression $\binom{2n}{n} \sim 4^n/\sqrt{\pi n}$. This is asymptotic but strongly hints that $(0,1/2)$ is the correct interval... This result can also be obtained applying the better known Stirling Approximation, but again the result would be asymptotic unless you know specifics of the error terms.
Comment: Nitpick;  $\frac {200 \choose 100}{4^{100}}$ is a specific value. It doesn't have a range because it has no variance.  Do you mean "which of the following intervals contain the value"?
Answer: Hint:
Compare $\binom{200}{100}$ with $\sum_{k=0}^{200}\binom{200}k$.
This in the understanding that: $$\sum_{k=0}^{200}\binom{200}k=2^{200}=4^{100}$$
Comment: Do you mean compare like $4^{100}=\sum_{k=0}^{200} \binom{200}{k} < 201 \binom{200}{100}$?
Comment: More something like $4^{100}=\binom{200}{100}+\sum_{k=0,k\neq100}^{200}\binom{200}{k}$. The second term on RHS is much larger than the first. Divide both sides by $4^{100}$ and you get $1=a+b$ with $a$ smaller than $\frac12$ and $b$ larger than $\frac12$. You are looking for an estimation of $a$, so...
Comment: Right but that still technically falls under the category of furious handwaving right :p Intuitively it is clearly true of course
Comment: For making it rigorous it is enough already to prove that $\binom{200}{99}+\binom{200}{101}=2\binom{200}{99}>\binom{200}{100}$.
Answer: $$\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+...+\binom{n}{n}=2^n$$ so you can rewrite
$$\begin{equation*}
\frac{200 \choose 100}{4^{100}}=\frac{200 \choose 100}{2^{200}}=\frac{200 \choose 100}{\binom{200}{0}+\binom{200}{1}+\binom{200}{2}+...+\binom{200}{100}+...+\binom{200}{199}+\binom{200}{200}}<<1
\end{equation*}$$
you can make a sence by looking at pascal's triangle
$$1\\1\space 1\\1 \space 2 \space 1 \\
1 \space 3 \space 3 \space 1\\1\space 4\space 6 \space 4 \space 1\\1\space 5 \space 10 \space 10 \space 5\space 1\\1\space 6 \space 15 \space 20 \space 15\space 6 \space 1$$ for example at $n=4\to  \frac{6}{16}<\frac8{16}$
and $n=6\to  \frac{20}{64}<\frac 13$
and so on
Answer: Write the expression as $$\frac {200!}{(2^{100}\cdot 100!)(2^{100}\cdot 100!)}$$
The first term in the denominator cancels all the even factors in the numerator, leaving us with
$$\left(\frac{199}{200}\right)\left(\frac{197}{198}\right)\left(\frac{195}{196}\right)\ldots\left(\frac{1}{2}\right)$$
The last factor is $\frac 12$ and all the rest are less than $1$, so the product is less than $\frac 12$


Iptables remote port forwarding and dynamic remote ip

Question: I want to forward a port from my remote vps to my domestic server and I am quite a newbie with iptables.
The problem is that I am using a dynamic dns service to reach my home server from the internet so I don't have a fixed ip and iptables doesn't like urls.
The rules I am willing to use are these:
-t nat -A PREROUTING -p tcp -i eth0 -d xxx.xxx.xxx.xxx --dport 8888 -j DNAT --to myhome.tld:80
-A FORWARD -p tcp -i eth0 -d myhome.tld --dport 80 -j ACCEPT

Of course I recevie a Error BAD IP ADDRESS because of myhome.tld.
What can I do?
Answer: This will not work as iptables needs fixed ip addresses.
I'd suggest either running a VPN between the machines or having a watchdog that will reapply the rules when your home address changes.
Comment: +1 for VPN. This results in consistent iptables rules, as your VPN internal IP address won't change. It also means if you are offline, your VPS isn't forwarding traffic to some other person's home connection.
Answer: Try using Shorewall to build your firewall.  It will expand DNS for you with caveats.  (DNS must be reachable during startup.)  There are notes in the documentation.  You will need a trigger to reload the firewall when your IP address changes.  The DHCP clients have hooks where you can do this.


PDO will not execute, but works just fine in phpmyadmin

Question: I have the following code:
<?php
// ... other code...
$prepared_statement = <<< MYSQL
SELECT `Organization`, `City`, `Region`, `Country`, `Contact`, `Manager`, `Description`
FROM `businesses`
WHERE (
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Manager` LIKE ? OR `Description` LIKE ?)
  AND
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Source` LIKE ? OR `Description` LIKE ?)
)
ORDER BY `Timestamp`;
MYSQL;
$value_list = ["Missouri","Missouri","Missouri","Missouri","Missouri","Missouri","US","US","US","US","US","US"]; // Populated through some passed in parameters, simplified to a known result here for simplicity sake.
try {
  $query = $this_pdo -> prepare();
  $query->execute($value_list); // <-- This line is where it breaks, but doesn't trigger the catch and doesn't output any error. Doing it in phpmyadmin returns 1 result.
  $result = $query->fetchAll(PDO::FETCH_ASSOC);
  return $result;
} catch (PDOException $e) {
  return ["A database problem has occurred: " . $e->getMessage()];
}

I've tried running the query directly in the database, replacing the "?" marks with values in the array, and it works. But execute doesn't?
Answer: Found my problem. Simple mistake... forgot to put my prepared statement into the prepare call.
* pdo->prepare() does not return an error if it is empty, despite it being empty fails subsequent execute calls.*


Sql Server adding another user

Question: I have a Database say TestDatabase.I have already added an user under
NTAuthority\SYSTEM(Role) Db_owner.
Again i wish to add another user to the same Database under NTAuthority\System with
different role.
I received the following error :
The login already has an accoind under different username.

SQL Server Error :15063

How can i add different users to the same database with different role.
I would appreciate if i receive elobarate explanation.
Comment: Please unmark this question as Community Wiki. CW is usually for objective questions with no "real" answer.
Answer: You can't. You add the same user to multiple roles.
db_owner already has all rights anyway withing the database so any other permissions are superfluous.
CREATE USER [NTAuthority\SYSTEM] FROM LOGIN [NTAuthority\SYSTEM];
EXEC sp_addrolemember 'db_owner', 'NTAuthority\SYSTEM'
-- ...and fails
CREATE USER [bob] FROM LOGIN [NTAuthority\SYSTEM];

--Normally, for one user in multiple roles
EXEC sp_addrolemember 'DoStuff', 'NTAuthority\SYSTEM'
EXEC sp_addrolemember 'DoSpecialStuff', 'NTAuthority\SYSTEM'
--... and for another user
EXEC sp_addrolemember 'DoStuff', 'AnotherUser'
--... and for yet another user
EXEC sp_addrolemember 'DoLimitedStuff', 'TheThirdUser'

Edit:
Look at the MS documentation: Database-Level Roles and the parent Identity and Access Control topic
Comment: Then what is the possibility of having the role based authentication on same DB?
Comment: Good Explanation.It gives the full details of what i expected.
Answer:
if is db_owner there is no point in adding him to any other role.
to add an existing user to a new role you run sp_roleaddmember
Comment: Pls let me know how can i achieve two different roles having different rights on same DB.

Sql Server adding another user


Como definir um breakpoint no gdb para todas funções de certo arquivo?

Question: É possivel definir um breakpoint para todas funções de um determinado arquivo no gdb? Uma aplicação, por exemplo, seria verificar se o programa passa por certo arquivo durante sua execução.
Answer: Utilize o rbreak, que define breakpoints de acordo com uma expressão regular. Para setar breakpoints em todas funções do arquivo arquivo.c, utilize o seguinte comando:
(gdb) rbreak arquivo.c:.

Mais informações, na documentação.


Where should whole notes be drawn within a measure?

Question: In this Lilypond-generated score, the whole notes are in different positions. The first is slightly to the left, the middle one is approximately centered, and the right one is slightly to the right. Is there a reason for this?
Answer: Whole notes should appear near the beginning of the measure.  When other notes are present, it should be vertically aligned with the first note/rest in the bar.  This is a good example from PianoAndSynth.com:

You can see that each first note is approximately the same distance from the left barline or key signature, whether a whole or otherwise, and no matter how wide the bar is.  This is to make it easy to see exactly when the note should begin to be played — you can rely on the type/shape of the note to know how much of the bar it should occupy.
For a bar with just a whole note, you would make the bar thinner but generally not so much that the note would end up centered (and definitely not any thinner than that).
I can only guess that your example varies due to a bug.
Comment: Interestingly, note that whole *rests* are placed differently. Whole notes align to the first beat of the measure (like in m. 2 of @Matthew Read's example), and the dotted half in m. 1 is aligned with beat 1 as well. But note that the whole rest is put right in the middle of the measure.
Comment: @Sam there are two different uses of the "whole-note rest" symbol. One is to show a rest for a *whole measure*. That is drawn in the center of the bar, and the duration of the rest depends on the *time signature* - it may be longer or shorter than four quarter notes. The other use is to show a rest that is exactly four quarter-notes long and does *not* occupy a full measure, in time signatures like 3/2 or 4/2. In that case, the symbol is drawn in the same position in the measure that a whole *note* would occupy.
Comment: I went looking for said bug but found instead a mistake in my Lilypond score. The time signature was in 3/4. After changing it to 4/4 the whole notes appeared as you described.
Comment: The grouping of the rest in the first bar is incorrect. it should be a minim rest and next to it a crotchet rest.
Comment: There is a subtle engraving issue here, though it is irrelevant to the OP's problem which he solved for himself. If a measure contains *only* a single whole note or whole-bar rest in every stave of the score, the whole notes *are* sometimes engraved in the center of the measure. The reason is simply because it looks neater on the page when all the notes and rests line up vertically. But If some staves have shorter notes, this does *not* apply, and the whole-notes are positioned to align vertically with the other notes at the start of the measure.
Comment: @NeilMeyer that is true (with very few exceptions, rests should *never* be "dotted" like notes) but in the OP's score, it would be better to start with a pickup bar one quarter-note long, with just a quarter note in the top staff and a quarter rest in the bottom staff.


Desempenho "where em foreach vs if"

Question: Qual dos casos teria um melhor desempenho?
var chaves = new list<string>();
foreach(var item in lista)
{
   if(!string.IsNullOrEmpty(item.Chave))
   {
      chaves.Add(item.Chave);
   }
}

Ou
listaValida = lista.Where(x => !string.IsNullOrEmpty(x.Chave));
foreach(var item in listaValida)
{
    chaves.Add(item.Chave);
}

Existe diferença de performance entre os dois casos ?
Comment: O segundo código é mais rápido e mais legível.
Answer: O 1 código foi mais rápido (porém eu acho ele bem mais feio de ler)
Segue o que utilizei para testar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace SpeedTest
{
    public class ItemChave
    {
        public string Chave { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            List<ItemChave> lista = new List<ItemChave>();
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });
            lista.Add(new ItemChave() { Chave = "a" });
            lista.Add(new ItemChave() { Chave = "b" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "c" });
            lista.Add(new ItemChave() { Chave = "" });
            lista.Add(new ItemChave() { Chave = "d" });

            Stopwatch sw = new Stopwatch();
            sw.Start();
            var chaves = new List<string>();
            foreach (var item in lista)
            {
                if (!string.IsNullOrEmpty(item.Chave))
                {
                    chaves.Add(item.Chave);
                }
            }
            sw.Stop();
            Console.WriteLine("Tempo 1 ={0}", sw.Elapsed);

            Stopwatch sw2 = new Stopwatch();
            sw2.Start();

            var listaValida = lista.Where(x => !string.IsNullOrEmpty(x.Chave));
            foreach (var item in listaValida)
            {
                chaves.Add(item.Chave);
            }
            sw2.Stop();
            Console.WriteLine("Tempo 2 ={0}", sw2.Elapsed);
            Console.ReadKey();

        }
    }
}

Answer: A resposta certa é: depende.
O jbueno já explicou como funciona no caso em que sua lista foi criada com base em dados disponíveis apenas no espaço de memória da aplicação, i.e.: que sua aplicação montou sozinha.
Porém! O LINQ também pode ser usado para se obter dados de uma base de dados, caso você deseje abstrair-se completamente da linguagem SQL.
Se a sua lista fosse carregada em tempo real de um banco de dados, através de Entity Framework, a situação seria bem diferente.
Nesse caso:
var chaves = new list<string>();
foreach(var item in lista)
{
    if(!string.IsNullOrEmpty(item.Chave))
    {
       chaves.Add(item.Chave);
    }
}

Você pode ter feito o equivalente a um SELECT sem WHERE, que pode carregar milhões de registros para a memória. Daí você seleciona os registros que lhe interessam no C#. Pode ser um desperdício de recursos.
Nesse caso:
listaValida = lista.Where(x => !string.IsNullOrEmpty(x.Chave));
foreach(var item in listaValida)
{
    chaves.Add(item.Chave);
}

O LINQ gera um comando SQL mais ou menos assim:
SELECT * FROM tabela WHERE chave is not null AND LEN(chave) > 0

Dessa forma, você pode evitar potencialmente a carga e o trânsito de milhões de registro. Essa forma seria indiscutivelmente mais rápida para a maioria dos casos.

Em ambos os casos, se você usar o método .ToList() o seu código fica mais limpo.
Comment: Tem esse ponto tb, ainda que eu acho que ele esteja falando de uma lista em memória.
Answer: Não tem muito mistério. Sem conhecer os detalhes de como funciona a linguagem é só medindo e fazendo uma média pra ter uma base de qual é mais rápido.
Nos meus testes, com três milhões de registros, primeiro caso foi mais rápido (Caso1()), levando uma média de de 40ms a cada execução, o segundo (Caso2()) ficou com uma média de 55ms por execução.
Usando .ToList() (Caso3()) cada execução levou uma média de 90ms.
O código que eu usei pra testar foi este:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

public class Program
{
    static List<string> lista = new List<string>();
    public static void Main (string[] args)
    {
        PopularLista();

        Console.WriteLine(lista.Count);

        Caso1();
        Caso2();
        Caso3();
    }

    private static void Caso1()
    {
        var watch = Stopwatch.StartNew();

        var chaves = new List<string>();
        foreach(var item in lista)
        {
            if(!string.IsNullOrEmpty(item))
            {
                chaves.Add(item);
            }
        }

        watch.Stop();
        var ms = watch.ElapsedMilliseconds;
        Console.WriteLine("Caso 1: " + ms + " ms");
    }

    private static void Caso2()
    {
        var watch = Stopwatch.StartNew();

        var chaves = new List<string>();
        var listaValida = lista.Where(x => !string.IsNullOrEmpty(x));
        foreach(var item in listaValida)
        {
            chaves.Add(item);
        }

        watch.Stop();
        var ms = watch.ElapsedMilliseconds;
        Console.WriteLine("Caso 2: " + ms + " ms");
    }

    private static void Caso3()
    {
        var watch = Stopwatch.StartNew();

        var listaValida = lista.Where(x => !string.IsNullOrEmpty(x)).ToList();

        watch.Stop();
        var ms = watch.ElapsedMilliseconds;
        Console.WriteLine("Caso 3: " + ms + " ms");
    }

    private static void PopularLista()
    {
        for(int i = 0; i < 3000000; i++)
            lista.Add(i % 2 == 0 ? "Teste" : "");
    }
}

Você pode rodar os testes no repl.it.
Comment: Seria impossível a abstração do LINQ ser mais rápido. Só não vejo porque precisa fazer o `ToList()`.
Comment: @bigown é eu sei, mas quero achar o fonte do Linq pra ter uma base pra poder falar isso. Onde você vê os fontes do .net framework mesmo?
Comment: http://referencesource.microsoft.com/. Se bobear o `ToList()` até torna a comparação injusta pq faz o *loop* duas vezes. Só não vou afirmar porque pode ter algo que eu não saiba, mas é quase certo que será pior injustamente.
Comment: Pois é, eu pensei nisso agora pouco. Vou procurar o source e confirmar.
Comment: Agora que eu vi o código, na verdade está comparando coisas diferentes e não está usando o código dele no caso 2. Isso é injusto. Então no código está fazendo só um *loop*, mas não é bem o que ele deseja, apesar de que o resultado acabará sendo o mesmo.
Comment: Eu fiz com os dois dele e coloquei o `ToList()` como terceiro caso.
Comment: Legal pra ter um parâmetro, depois q eu vi q vc substituiu o `foreach` pelo ``Tolist()` não causando o duplo processamento. Testou na sua máquina sem mais nada rodando, especialmente VMs, Dockers e coisas do tipo? Imagino que tenha bastante memória. Hj é complicado testar sem influências externas.
Comment: Eu tava com um docker e uma VM rodando. Parei eles e testei de novo com 3M de registros. Dei uma atualizada na resposta.
Comment: Rodou algumas vezes? Foram consistentes. Tem certeza que o GC ñ entrou em ação em algum caso? :) Não estou dizendo que tem algo errado, só colocando alguns cuidados que é sempre bom ter qdo vai medir performance. Nem é tudo.
Comment: Rodei 20 vezes pra fazer a média. Só não tenho certeza se o GC "entrou em ação" ou não, como posso garantir isso?
Comment: Duvido q tenha entrado, e ñ sei se compensa, mas pode forçar uma coleta antes de cada `start` e pode usar o https://msdn.microsoft.com/en-us/library/dn906201(v=vs.110).aspx. Mas nada garante mesmo, pra saber se rodou ou não teria q fazer um *profiling*, mas acho exagero a ñ ser q precise da informação 100% correta e q isso será muito relevante, o q está longe de ser o caso. Mas aí teria q ter outras preocupações tb.

Desempenho "where em foreach vs if"


how to put inspector on both client and server WCF

Question: i heard that it is possible to to put inspector on both client and server wcf side which can intercept the message and modify it's content before it released to the client/server. i want to know is it possible if yes then how?
how could i encrypt/decrypt data with our own logic at both end when data just passed. i search Google to have some good write up on this topic but unfortunately i got none. so if anyone knows about any url which discuss how to develop this kind of inspector and deploy at both wcf client & server then please share with me. thanks
Answer: All what you need is to follow this steps
1-step
In your code you should add a MessageInspectorExtension
 class MessageInspectorExtension : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(MessageInspector); }
        }

        protected override object CreateBehavior()
        {
            return new MessageInspector();
        }
    }

MessageInspector will do all the work you need and it should be defined like this
//here the `MessageInspector` class showing what are the interfaces responsable for doing this
public class MessageInspector : IDispatchMessageInspector, IServiceBehavior, IEndpointBehavior
    {
    }

The mains methods you need are
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {}

Which is called after an inbound message has been received but before the message is dispatched to the intended operation

and
public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {//do here }
            else do your code here
       }

wich is called after the operation  has returned but before the reply message is sent

2-step
In your app config you have to add a behavior definition like the following
    <behaviors>
          <endpointBehaviors>
            <behavior name="ServiceBehaviorWithInterceptor">
              <ServiceInspector/>
            </behavior>
          </endpointBehaviors>
        <behaviors>

     <extensions>
          <behaviorExtensions>
            <add name="ServiceInspector" type="yourNameSpace.MessageInspector.MessageInspectorExtension, assemblyname, Version=126.96.36.199, Culture=neutral, PublicKeyToken=null"/>
          </behaviorExtensions>
        </extensions>

"3-step
<service name="yourServiceContractFullName" behaviorConfiguration="ServiceBehaviorWithInterceptor">
        <host>
          <baseAddresses>
            <add baseAddress="http://yourserver:port/root/yourServiceContract" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpsBindingConfig" contract="YourContract" />
      </service>

Update
how could i encrypt/decrypt data with our own logic at both end when data just passed
Normally a https connection will do the job for you see this link
but if you need a tricky way to achieve this you can use a common class that will be the main class for all you communications  and encrypt your message in one of it's property
Something like this
 [DataContract]
     public class BaseCustomEncMessage
    {
        private Object _object = null;
        [DataMemberAttribute]
        public Object CipheredMessage { get { return _object; } }
        public void Cipher(object obj )
        {
             //here you can use 3DES for example and serialize your instance as an object

        }
    }

Comment: there is no relationship between MessageInspectorExtension & MessageInspector.
Comment: is there any article available from where i can get the full source code. which keyword i should use to search google for the above scenario.
Comment: you  can  find a full  example  in  http://go.microsoft.com/fwlink/?LinkId=87352 after you  download and install  the samples  try to find \WCF\Extensibility\MessageInspectors\SchemaValidation\CS


Snip and Sketch disabling over GPO

Question: i need to block Snip and Sketch on my entire Domain, is there any chance to do that using GPO? Any suggestion would be helpful.
Thanks in advance.
Answer: You can use AppLocker and Packaged apps and packaged app installer rules. Typically, you can create a rule to allow every signed appx, and add an exception for this app.
Comment: Hello, could you be more specific please?
Answer: I am not sure what the end goal of disabling snip and sketch would be, people can still just hit print screen and paste into MSPaint, or take pictures of the screen with their phones. As a security concern it seems a little... fuzzy.
You could however just remove it from peoples computers -
Get-AppxPackage PackageFullName | Remove-AppxPackage
Comment: Hello, thanks for answering. We already disabled printscreen and snipping tool, so snip and sketch is ony left windows print screen service at users PCs.

Snip and Sketch disabling over GPO


Will the signs of coef (Estimate) of lm and glm always be the same?

Question: Will the signs of coef (Estimate) of lm and glm always be the same? ^
According to below toy example, it seems yes. Can you provide a case where they might be different? (If it matters in my real data the outcome is binary, hence used mpg > 20)
# dummy data
d <- mtcars

# fit lm, glm, glm_bi
fit_lm <- lm(mpg > 20 ~ cyl + disp, data = d)
fit_glm <- glm(mpg > 20 ~ cyl + disp, data = d)
fit_glm_bi <- glm(mpg > 20 ~ cyl + disp, family = binomial, data = d)

# Signs are always same?
# lm compared to glm
all.equal(sign(coef(fit_lm)),
          sign(coef(fit_glm)))
# output
# [1] TRUE

# lm compared to glm(family = binomial)
all.equal(sign(coef(fit_lm)),
          sign(coef(fit_glm_bi)))

# output
# [1] TRUE

^ Very much sounds like a dupe, found this similar post: Sign of coefficients in linear regression vs. the sign of correlation. Let me know if this is a dupe.
Comment: Once you realize that many GLMs effectively *weight* the data according to the inverse variance of the response, then you see that a more meaningful comparison would be between a GLM and a weighted OLS solution. That also shows how to construct counterexamples to your conjecture.
Comment: Do you ask only about GLM for Gaussian family, or *any* GLM model compared to LM?
Comment: @Tim sorry, I should have mentioned, for glm it is binomial logit link. I will update the post when I get a chance.
Comment: @whuber thank you, do you mind posting as answer with more detail in layman terms (if at all possible)? My stats knowledge is limited.
Answer: @whuber:

Once you realize that many GLMs effectively weight the data according to the inverse variance of the response, then you see that a more meaningful comparison would be between a GLM and a weighted OLS solution. That also shows how to construct counterexamples to your conjecture.


Como faço esta lista que esta na imagem

Question: Bom estou aprendendo html com css para dar entrada futuramente em php porem estou com uma dificuldade não consigo fazer Div class com listas pois ele não aplica a cor etc... a cor esta em outro arquivo de formatação.css preciso de ajuda pls
Answer: Que legal que está se aventurando nesta área do desenvolvimento web. O que você está querendo fazer é uma importação de um arquivo css para o seu arquivo html.
Suponhamos que você criou um projeto chamado loja e o representou através de uma pasta nomeada /loja. Os seus arquivos HTML e CSS devem estar dentro dessa pasta para melhor organização. Na raiz da pasta existem dois arquivos que podemos chamar de index.html representando seu arquivo de marcação HTML e style.css representando seu arquivo de estilização CSS.

Note que os dois arquivos estão na pasta raiz, ou seja, dentro da pasta loja.

Para importar uma folha de estilos (style.css) é necessário declarar um elemento link no escopo do elemento head.
<!DOCTYPE html>

        <link rel="stylesheet" href="style.css">

This is a heading

This is a paragraph.

O W3C Schools possui um ótimo conteúdo para aprendizado de HTML e também outras linguagens de interesse.
Comment: Valeu pela ajuda pessoal
Answer: De acordo com a resposta do Victor, você deve importar o seu arquivo CSS para a sua página HTML. Para mudar o fundo da lista, aqui tem um exemplo:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Comment: Valeu pela ajuda <3

Como faço esta lista que esta na imagem


Kuiper's Test P Value in R

Question: I am trying to implement a kuiper's test on a set of data and looking for an R package (or other program) that can give a p-value without monte carlo simulation or only a range of p-values. All of the packages (listed below) either give ranges of p-values or simulate (very limited because of time for simulation). I will be doing a large number of Kuiper's tests with small p-values.
The packages I've looked into:

CircStats
truncgof
circular
Answer: In order to be able to give a p-value without simulation or the use of critical values, we must be able to derive the null distribution of the test statistic.
For Kuiper's test, the null distribution of the test statistic is not known as far as I am aware. Because of this, we can not directly compute the p-value, and must either use critical values (which results in functions that return a range of p-values, as you note), or simulation (for example, bootstrapping), to obtain p-values.
Bootstrapping can be a straightforward way in this case to obtain a good approximation of the p-value.

Kuiper's Test P Value in R


Touch move gesture logic...how to determine direction of movement in 2d?

Question: How can i determine the direction of gesture ? The use case is shown in the image link. what is the right logic for detecting in which direction the person is trying to move the ball in the circular path ? I have called the direction method in move gesture...Can someone help me fine tune this ... ?
http://www.shrenikvikam.com/wp-content/uploads/2011/04/214e422a43E11S3.png-150x134.png
     private String getDirection(float firstTouchX, float finalTouchX){
        if((firstTouchX - finalTouchX)>0)
            return "Left";
        else
            return "Right";
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();

        switch (action) {
            // MotionEvent class constant signifying a finger-down event
            case MotionEvent.ACTION_DOWN: {
                Log.d("ACTION DOWN","Value ->");
                final float x = event.getX();
                final float y = event.getY();
                initialTouchX = x;
                initialTouchY = y;
                break;

            }
            // MotionEvent class constant signifying a finger-drag event
            case MotionEvent.ACTION_MOVE: {
                final float x = event.getX();
                final float y = event.getY();
                final String direction = getDirection(initialTouchX,x);
                Log.d("ACTION MOVE","diff in initial and cur value of x  ->" + direction + (initialTouchX - x) + initialTouchX + "y->" + initialTouchY);

                break;

            }
            // MotionEvent class constant signifying a finger-up event
            case MotionEvent.ACTION_UP: {
                Log.d("ACTION UP","Value ->");

                break;
            }
        }
        return true;
    }
Comment: I can't think of a proper way for tracking circular path right now but am wondering would it be more usable if you tracked up/down + left/right movement instead to adjust your spinner accordingly higher/lower values. For circular path, I'm guessing, you should calculate center point of this spinner and once user moves pointer you can calculate angle between movement points. And use this information to adjust this spinner more precisely.
Answer: It seems like the slope of the line formed by the two touch points should be equal to the tangent of the circle at that point. This link has most of the math to pursue such a solution
I have used the difference between angles to the center point of the circle with good success. That may be the way to go as well.
Answer: If you are trying to determine which way to move the ball around the ciricle, it doesn't make sense for getDirection to return "Left" and "Right", it should be working with "Clockwise" and "Counterclockwise". Consider, for example, when the ball is at the 20 marker in your image: At this point every point on the circle is "Right" of where you are now...
In order to determine if the ball is moving clockwise or counterclockwise you need to consider both the x and y co-ordinates of the touch points, the x co-ordinate alone is not sufficient. You also need to know where the centre of the circle is. I would suggest in order to determine the direction of movement, you calculate the angle between the touch points and the centre of the circle.
Comment: hmmm... let me try that out..btw..if you have some samples with similar integration as shown in the image link, do share it with me, actually struggling to get this done..
Answer:                 prevTouchX = event.getHistoricalX(event.getHistorySize()-1);
                currentTouchX = event.getX();
                if(currentTouchX<prevTouchX){
                    Log.d("LEFT",event.getX()+" and "+event.getY());
                }
                if(currentTouchX>prevTouchX){
                    Log.d("RIGHT",event.getX()+" and "+event.getY());
                }

Similarly for UP/DOWN
Answer: I use this code for rotating a view. It works very well. Have a look at this;
switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                firstX = event.getX();
                firstY = event.getY();

                break;
            case MotionEvent.ACTION_MOVE:
                int dx =(int) (event.getX() - firstX);
                int dy =(int) (event.getY() - firstY);

                Log.d("Distance Rotate Touch",Integer.toString((int) (firstX-dx)));

                if (signView.getRotation()<180){
                    if (firstX - dx > 15 && firstY - dy > 15 ){
                        View.setRotation(signView.getRotation()-5);
                    }else if(firstX - dx < -15 && firstY - dy < 15  ){
                        View.setRotation(signView.getRotation()+5);
                    }
                }else {
                    if (firstX - dx > 10 && firstY - dy < -10 ){
                        View.setRotation(signView.getRotation()+5);
                    }else if(firstX-dx < -10 && firstY - dy < -15 ){
                        View.setRotation(signView.getRotation()-5);
                    }
                }
                break;

            default: return true;
        }


Webpack 2 not loading imports for Angular2 Typescript application

Question: I'm trying to implement webpack on a medium size angular2 project that uses typescript. But when I run webpack it only bundles the 2 files I specify in the config file. It never traverses through the import tree and loads the rest of the modules.
I've got a fairly simple configuration set up. I'd like to get it just bundling the typescript to start with. Then I'll move onto bundling more files.
When I change the import {} from "x" syntax to var {} = require("x"). webpack works, however, throws hundreds of errors as it cannot resolve anything imported from the @angular2 directory.
How do I get webpack to traverse through the 'import' statements and bundle more than just one file into the result?
My configuration is as follows.
webpack.config.js
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: path.join(__dirname, 'wwwroot/app'),
    entry: {
        'vendor': './vendor',
        'app': './main'
    },
    resolve: {
        extensions: ['', '.ts', '.js']
    },
    output: {
        path: path.join(__dirname, 'wwwroot/built'),
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                loaders: ['ts', 'angular2-template-loader']
            }
        ]
    }
};

tsconfig.json
{
  "compilerOptions": {
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "system",
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib",
    "bin"
  ]
}

main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { disableDeprecatedForms, provideForms } from '@angular/forms';

import { AppComponent } from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    disableDeprecatedForms(),
    provideForms()
]).catch(err => console.error(err));

Console output on running webpack:
10% building modules 0/2 modules 2 active ...\src\wwwroot\app\main.tsts-loader: Using email@example.com and C:\BitBucket\src\tsconfig.json
8831ms building modules
1ms sealing
1ms optimizing
0ms basic module optimization
1ms module optimization
1ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
1ms advanced chunk optimization
0ms module and chunk tree optimization
1ms module reviving
0ms module order optimization
1ms module id optimization
1ms chunk reviving
0ms chunk order optimization
1ms chunk id optimization
8ms hashing
0ms module assets processing
5ms chunk assets processing
4ms additional chunk assets processing
2ms recording
0ms additional asset processing
1ms chunk asset optimization
1648ms asset optimization
10ms emitting
Hash: 8a864382625d5d236939
Version: webpack 2.1.0-beta.21
Time: 10640ms
           Asset     Size  Chunks             Chunk Names
vendor.bundle.js  3.21 kB       0  [emitted]  vendor
   app.bundle.js  3.81 kB       1  [emitted]  app
    + 2 hidden modules

Comment: I noticed that the typescript module setting in the TSCONFIG is 'system'. Thought about using 'es6' instead? And have you considered using awesome-typescript-loader instead of ts-loader?
Answer: Try change module from system to commonjs as follow:
{
  "compilerOptions": {
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs", // <--- from 'system' to 'commonjs'
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib",
    "bin"
  ]
}


Why does console.log strip characters in nodejs?

Question: My nodejs code is reading from a stream and print it on the console. I found an interested behaviour that console.log strips characters for me. For example, below is the debug window on my nodejs.

From this debug window you can see that the value of line includes some Ansi encoding characters. But when I print it to terminal by console.log, I just got this output > var prompt="dbenvy> ". It doesn't have any ansi characters. I don't understand what cause this behaviour. I am not sure whether this is something to do with console.log or terminal
Comment: After some debug I found the problem may not relate to `console.log`. Instead the problem is the terminal.
Comment: What terminal are you using?
Comment: I'm pretty sure that `console.log` *does* output all characters, renderable or not.
Comment: I am using terminal from Mac OS shell
Answer: You did not mention if it was displaying the letters in the color or format indicated by the ANSI Escape codes.  Your debugger does not support ANSI Escape, but your terminal does have at least some support -- if it is not showing the colors, at least it knows not to dump the escape codes as text.
Comment: I mean the letter format not color. The terminal doesn't support showing text in colour.