Exponential and gamma distributions

Question: I am trying to make a simulation of bacterium splits is exponentially distributed in R.
I am assuming that initially, bacterias have an exponential distribution. Let's say:
N_{0} = 1
N_{1} = 2^r with r ~ exp(\lambda)
N_{2} = N_{1} * 2^r
...
N_{t} = N_{t-1} *...* N_{1} * 2^r

So, what I would like to do is a simulation where I am able to see this. In total I would need to do two simulations, the first part showing the exponential simulation of all the
N_{t}, and then a second simulation showing log2(N_{t}).
For the first part, I tried, first simulating the exponential distribution of all the N_{t}:
X <- data.frame(Cell=paste("C", 1:1000, sep=""), DT=1)
X$N <- 1
TOT <- sum(X$N)
cell.max <- 10e10
T <- 1000
t <- 1
while (TOT <= cell.max) {
    X[,t+3]<- X[,t+2] * (2 ^ (rexp(nrow(X), X$DT)))
    TOT <- sum(apply(X[,-c(1:2), drop = F], 1, sum))
    t <- t+1
}

plot(density((t/(log2(X$N)))))

But I have errors in the plotting density, and I am not sure If I am correctly doing this simulation.
For the second simulation, I am completely lost on how to do it.
Could I have some hints/help/suggestions to do both simulations, please? All are welcome.
Comment: @Xi'an N_{t} is the time in which the bacteria is diving, here I am just assuming that I have a division of 2^r, this is each bacteria is diving into 2, and so on. But, with an exponential distribution. that´s what I want to try to simulate.
Comment: @Henry Sorry for my inexperience on this but I do not understand how you derived that $H_n/\lambda$. And why is it not gamma, at the end of the process $log2(N_{t})$ you have the sum of two exponential distributions?
Comment: In general, I just want to simulate this process, with this exponential distribution. On how cells or bacteria might behave in a simple case where there is not death and cells/bacteria proliferate with 2^r.
Comment: @RosaMaria I still do not quite see what question you want to simulate. Is it the number of bacteria at time $t$ (or the number of splits by time $t$ - one less) or the time until you have had $n$ splits or have $n$ bacteria?
Comment: Incidentally if you want the process to expect to double the number of bacteria per unit of time, then I think $\lambda = \log_e(2)$
Comment: @Henry, yes the number of splits by time t - one less because then I would simulate the log2 of this process. Again, this could be silly but I want to start training and learning on how to so this basic simulations with $\lambda = log(2)$.
Comment: You say "bacteria have an exponential distribution".  It is not clear what this means.  One possibility is that the time until a bacterium splits is exponentially distributed with some rate $\lambda$, after which each part would split again with the same time distribution.  If so, you would need to choose whether you are tracking each individual bacterium or just the total number. To track the total number you can use the memoryless property of the exponential distribution to find each time the number of bacteria increases by $1$
Comment: Yes, I edited that part, I am thinking like a cell division. So, in a way first simulate in R the N_{t}.
Comment: In the first (pseudo-)code, a single $R\sim\mathcal{E}(\lambda)$ seems to be used, is this correct?
Comment: Another question is that I do not quite see what question you want to simulate.  Is it the number of bacteria at time $t$ (or the number of splits by time $t$ - one less) or the time until you have had $n$ splits or have $n$ bacteria?  What is your `N_{t}`?
Comment: I tried a simulation, which for the number of bacteria at time $t$ looked very like a geometric distribution, though it is not obvious to me why.
Comment: Meanwhile the time at which the $n$th split appears (i.e. there are $n+1$ bacteria) was not a gamma distribution.  It is possible to find the expected time, namely $H_n/\lambda \approx \frac1{\lambda}\left(\log_e(n) + 0.5772 +\frac{1}{2n}\right)$ and the variance about $ \frac1{\lambda^2}\left(\frac{\pi^2}{6} - \frac{1}{n+\frac12}\right)$
Answer: In what follows, the simulations find the number of bacteria at a given time, based on the starting number of bacteria and the rate at which each bacterium splits according to an exponential distribution and then the two results from the split do the same from that point forward.  Note that if the rate for each bacterium is $\lambda$ then note the following points, which are used in the simulation.

The expected number of bacteria after time $t$ is $e^{\lambda t}$ times the number at the start.  If you want this to be $2^t$ then you need $\lambda=\log_e(2)$.
With $n$ bacteria at any point in time, the time until the next split has an exponential distribution with rate $n \lambda$.
Starting with $N_0=1$ bacterium, the number of bacteria at time $t$ is geometrically distributed on $1,2,3,4,\ldots$ with parameter $p=e^{-\lambda t}$, so $\mathbb P(N_t=k)=e^{-\lambda t}\left(1-e^{-\lambda t}\right)^{k-1}$. It has mean $e^{\lambda t}$ and variance $e^{\lambda t}\left(e^{\lambda t}-1\right)$.
So starting with $N_0=n$ bacteria, the number of bacteria at time $t$ is negative binomially distributed on $n,n+1,n+2,\ldots$ with parameter $p=e^{-\lambda t}$ so $\mathbb P(N_t=k)={k-1 \choose n-1}e^{-n \lambda t}\left(1-e^{-\lambda t}\right)^{k-n}$. It has mean $n e^{\lambda t}$ and variance $ne^{\lambda t}\left(e^{\lambda t}-1\right)$.

The first simulation simply splits individual bacteria until the desired time point is reached for each of them:
numberbytimeA <- function(time, rate=1, start=1){
  nextsplit <- rexp(start, rate)
  while(min(nextsplit) <= time){
    nextsplit <- c(nextsplit, nextsplit[nextsplit <= time])
    nextsplit[nextsplit <= time] <- nextsplit[nextsplit <= time] +
                                    rexp(sum(nextsplit <= time), rate)
    }
  return(length(nextsplit))
  }

The next simulation add one bacterium at a time until the desired time point is reached:
numberbytimeB <- function(time, rate=1, start=1){
  splittime <- 0
  count <- start
  while (splittime <= time){
    splittime <- splittime + rexp(1, count*rate)
    if (splittime > time){
      return(count)
      }
    count <- count + 1
    }
  }

That can be quite slow, looping many times.  An attempt to speed it up could be to generate more than enough splits to take up the time provided and then find how many there are when the time has been reached.
numberbytimeC <- function(time, rate=1, start=1,
                         maxend=start*exp(3+time*rate)){
  splittimes <- cumsum(rexp(maxend-start+1,(start:maxend)*rate))
  return(start + sum(splittimes <= time))
  }

The fourth uses the geometric and negative binomial distributions to provide a massive speed-up when the time is long.
numberbytimeD <- function(time, rate=1, start=1){
  return(start + rnbinom(1, start, exp(-rate*time)))
  }

As far as I can tell by testing, all three produce the same results (allowing for the noise associated with simulation) but at different speeds.
So here is an actual simulation, over time $3$ with your rate $\log_e(2)$ starting with $1$ bacterium, and $10^5$ simulations.  It uses the second function as the one I initially encoded, though the others would do as well but with different speeds.
set.seed(2022) # so you can reproduce my results
simB <- replicate(10^5, numberbytimeB(time=3, rate=log(2), start=1))
mean(simB) # expected 2^3 = 8
# 7.996
sd(simB)   # expected sqrt(8*(8-1)) about 7.483
# 7.432131
plot(table(simB)/10^5) # empirical frequency of final number of bacteria

Note that when you start with $1$ bacterium, the most likely outcome is $1$ bacterium at the end, i.e. $0$ splits.  As a geometric random variable, this is what we expect to happen, no matter how long the time period is or how fast the rate is; the probability of this outcome is $e^{-\lambda t}$ and tends towards $0$ as $t$ or $\lambda$ increase but other particular outcomes are always less likely.
Comment: So although $\mathbb E[N_t]=2^t$ when starting at $N_0=1$ and $\lambda = \log_e(2)$, this does not mean that $N_t$ has an exponential distribution or that $\log_2(N_t)$ does.  Being a count or a function of a count, they each have a discrete distribution ($N_t$ has a geometric distribution) while an exponential distribution is a continuous distribution
Comment: If I want to apply the $log2()$ of all the process $N_{t}$, for example for $N_{2} = N_{1}*2^r$ with $r$ following the exponential distribution, then $log2(N_{2}) = log2(N_{1}) + r$. You can note that $ log2(N_{1}) $ follow an exponential distribution too, and $r$ by assumption too, so you have the sum of two exponential distribution. How can you simulate that process ? We would expect a distribution with two exponential identities right ? I put a Wikipedia plot of this.
Comment: I think what has an exponential distribution here is the time to the next split, not the number of bacteria (the expectation of the number of bacteria grows exponentially, but that is not an exponential *distribution*).  You could try something like `plot.ecdf(log2(simA))` and might try to read it as suggesting the centre might be somewhere near $\log_2(8)=3$; that would not be correct since the median is lower than this at $\log_2(6)$, as is the mean of the logarithms - no surprise since a geometric mean is usually less than an arithmetic mean.
Comment: So, then correct me if I am wrong, please. $N_{1} = 2^r$ with $r ~ exp(\lambda)$ is just the bacteria division with that exponential frequency, and pdf $\rho(r) = \lambda e^{-\lambda}$ ?
Comment: @RosaMaria I do not understand that comment.  $N_r=2^r$ would be an exponential function of $r$ and could also be written as $N_r=e^{r \log_e(2)}$ but it would not be a random variable or a distribution.
Comment: I still do not understand what that means.  My answer was for the exponential distribution being for the time each bacterium splits, with the expected number of bacteria growing exponentially.  If that is not what you mean by an exponential distribution, than you would need another answer from somebody who does understand.
Answer: Relationship between sum and maximum of exponential distributed variables.
If the time untill a division for a single bacteria is exponentially distributed with rate $\lambda$ then the time untill a division for $n$ bacteria has a rate $n\lambda$ and the waiting time for the next division occuring decreases when there are more bacteria. This makes that the distribution of the waiting time is much like a sum of exponential distributions with variable rate, which is equivalent to the maximum of exponential distributions
$$max(s_1, s_2, \dots , s_n) \qquad \sim \qquad \sum_{k=1}^n t_k \\ \text{where $s_i \sim Exp(\lambda)$ and $t_k \sim Exp(\lambda(n+1-k))$}$$
(see question Proof that the limit of a series of exponential distributed random variables follows a Gumbel distribution from which is the following image)

The image gives an example for 9 bins. It illustrates the bins as a 2D plane (filled with points according to a Poisson process), in which the bins are horizontal strips in this 2D plane ... The horizontal direction could be viewed as the 'time'. We marked the balls red when they are the first to fill the bin.

The markings $s_i$ and $t_i$ in the image relate to variables ... They are used to express the waiting time to fill all the bins with at least 1 ball.

Time until n divisions
The time until n divisions is similar to the maximum of $n$ exponentially distributed variables. This follows approximately a Gumbel distribution.
The simulation below demonstrates this:

set.seed(1)

# This function simulates the cell division
# by tracking for each cell the time when it is gonna split.
# The algorithm starts with a vector of times untill the next split
# and keeps adding times for new cells after splitting

sim = function(lambda = 1, N_end = 1000) {

  ### the initial vector of length one when n= 1
  t_vector = c(rexp(1,lambda))

  ### start settings
  t = 0
  n = 1

  ### loop untill growth has reached N_end
  while (n < N_end) {
     # find the next cell to divide (the cell with lowest t)
     next_d = which.min(t_vector)

     # advance the time
     t = t_vector[next_d]

     # compute new time (for next cell division) for the dividing cell
     t_vector[next_d] = t + rexp(1,lambda)

     # compute time (for next cell division) for the newly created cell
     # this time is added to the vector of times
     t_vector = c(t_vector, t + rexp(1,lambda))

     # increase the counter for the cell number
     n = n + 1
  }
  return(t)
}

### make simulations
t_vec = replicate(5*10^3,sim(N_end = 100))

### plot simulations as histogram
hist(t_vec, breaks = seq(0, ceiling(max(t_vec)), 0.2), freq = 0, main = "histogram of simulated data, with Gumbel density fit")

### compute and plot gumbel density fit
pars = evir::gumbel(t_vec)$par.ests
ts = seq(0,20,0.1)
z = (ts-pars[2])/pars[1]
lines(ts, 1/pars[1] * exp(-z-exp(-z)) )

Number of divisions in time t
There is a correspondence between waiting time $t$ until $n$ events, and number of events $n$ per time $t$. (example: https://stats.stackexchange.com/a/450135)
The number of divisions $n$ within time t is equivalent to generating the image above, and keep adding bins untill one of the bins has it's first ball for a time above t. The probability for this is $exp(-\lambda t)$ for each bin. The total number of bins/bacteria untill you get a case with $s_i > t$ is geometric distributed (the geometric distribution describes the probability distribution of the number $n$ of Bernoulli succesvol trials needed to get one failure). With $p = e^{-\lambda t}$ the probability for a failure.
$$P(N = n) = (1-p)^np = (1-e^{-\lambda t})^n e^{-\lambda t}$$
This is the same result as explained in the link from Henry's answer, but argued via a different path.
Comment: Sorry my question, when you said: time untill a division for a single bacteria is exponentially distributed with rate  this is equivalent to N_{1} = 2^ with  ~ exp(\gamma), right ?
Comment: And another stupid question, I never heard about the Gumbel distribution, is this a modified Gamma distribution ? I read that the Gumbel has more connection with a uniform distribution, but not sure
Comment: @RosaMaria I am not sure whether it is equivalent to your equations, but they do not look very sound. What is for instance N_{1}? I made this answer based on your textual description of the problem. A bacteria divides after a time $t$ where $t$ is exponentially distributed.
Comment: the Gumbel distribution has a wikipedia page that explains some things about it.

Exponential and gamma distributions


Não consigo encontrar o erro dessa Stored procedure

Question: delimiter $$
create procedure reposta(out mensagem varchar(100))
begin
  if new.codigo_veiculo != null then
  set mensagem = "Algum veículo está sendo utilizado";
end $$
delimiter ;

erro que aparece

Code: 1064. You have an error in your SQL syntax; check the manual that  corresponds to your MySQL server version for the right syntax to use near '' at line 5
Comment: faltou o `end if;` após ter setado o valor em `mensagem`
Comment: funcionou obrigado....
Answer: Correção:
Para todo IF é necessário inclusão de um END IF; conforme abaixo:
delimiter $$
create procedure reposta(out mensagem varchar(100))
begin
  if (new.codigo_veiculo != null) then
     set mensagem = "Algum veículo está sendo utilizado";
  end if;
end $$
delimiter ;


Seeking explanation of how shifting bits can verify the sign of a number

Question: I have this excerpt from geeksforgeeks, assume x and y are integers.
"If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0."
I'm curious to know why this is the case.
Answer: This is the case for signed 32-bit integers in two's complement form.
The sign-bit is the most significant bit. The shift operation >>31 will shift the sign-bit to the least significant bit position. A 1 indicates, that the difference is negative.
Answer: The quote is assuming a 32-bit two's complement representation of integers (this is the most common representation of integers, though using 64 bits is becoming more common). In particular, of the 32 bits used to represent an integer, the highest order bit is used to represent whether the integer is negative or positive. Highest bit = 1 means negative, highest bit = 0 means non-negative. Thus, if you compute (x-y) and the 32nd bit tells you whether x >= y (32nd bit = 0) or x < y (32nd bit = 1). So how do you get the 32nd bit? Shift right 31 times.


How to effectively be a 1-man developer?

Question: I'm a one man show, having developed and worked on a new custom CRM customized for our business needs over the past year and half. I've had the pleasure of consulting with a 25+ year experienced developer for help.
Due to budgetary constraints, I no longer have access to his help (for the time being) and have no experience with preparing for a live deployment. (nothing is live right now)
I am currently setting up a production server (excruciatingly) and have been able to get it up and running and am currently migrating data over, getting OPcache set up, etc..
One thing he mentioned to me was to have:

Local Host (where I do my work)
Development Server (where I deploy and test my changes)
Production server (where I push the live changes too)

Question 1) Right now, I have the Dev Server and the production server. Based on your experience, is the 'Local Host -> Dev Server' process really necessary for a 1-Man show? Why not simply do my work and test my changes within the dev server? Please provide me with some examples of common practices.
Question 2) When it comes to deploying changes to the production server, what are some common ways based on your experience to do this?
Question 3) Going off of Question 2, what happens when I have an immediate problem I need to apply a 'hot fix' too?
Question 4) Finally, what are some common ways to keep track of versions based on your experience? I was considering using GitHub.
Comment: @epascarello this question is a poor fit for Programmers - it would be quickly voted down and closed over there, see http://meta.programmers.stackexchange.com/questions/6483/why-was-my-question-closed-or-down-voted/6490#6490 Recommended reading: **[What goes on Programmers.SE? A guide for Stack Overflow](http://meta.programmers.stackexchange.com/q/7182/31260)**
Comment: @gnat, while this question may spur answers that are primarily opinion-based, a common approach or at the very least 'a way' to go was my intention. Can this question be re-worded?
Answer: I'm going to assume three environments:
<code>Development --> Test ---> Production
</code>
You write code in development, migrate that code into Test (to test your migration process and your new enhancements / bug fixes) and, once statisfied, migrate that code into production.
Question 1) It's always necessary to test your code.  The last thing you want to do is push untested code into production -- your customer's business relies on this system and pushing untested code is a great way to ruin that business.
You may be confusing application testing with integration testing.  With a "one man show" there may be no integration tests, but you still need to test your code and your deployment process.  The test environment is also useful for letting users try your enhancements / bug fixes to ensure they meet their needs.
Question 2) It apears that you're deploying a PHP application.  You can read this question to get some ideas, but it's old.  In general, this becomes a highly subjective question with many different tools and opinions; StackExchange isn't the place for such debates.
Question 3) You use source code control, allowing you to create several copies of your code tree, one for each "hot fix" or "enhancement" as necessary.  When the hot-fix is done, tested, and successfully migrated into production, you can delete the hot fix directory tree.
Question 4) Again, you use source code control.  You can run Git locally using GitHub or not, or choose Mercurial, Subversion, or others.  The choice of SCM is debatable (and not an appropriate topic for StackExchange), but use of source code control solves the versioning requirement.


How can i Make This Type SSRS

Question: I have a table in data base which has column  MonthNo ,Year ,MonthValue ,AvgYTD and it has values in
<code> 1 ROW... 1 , 2010 , 2.3 , 4.0  AND

 2 ROW...  2, 2010, 3.3 ,5.0 AND

 3 ROW.. 3, 2010, 3.3, 7.9
</code>
AND I want output in my SSRS.....
WHEN I SELECT MONTH MARCH USING PARAMETER THEN OUTPUT WILL BE....A TABLE AND IT HAS COLUMN
<code>JAN  ,  FEB , MARCH , AVGYTD   and  values in row are ..

 2.3  ,3.3, 4.3, 7.9
</code>
Updates
i am using sql server 2005 and 7.9 is th AvgYTD Value comes from table for selected month march....
i want ...if i select month march then output will be show month value of jan,feb and march and AvgYTD value for only selected month..
thanks,
Answer: Use a matrix, and if SQL 2005, use the InScope function to be able to tell if you're in the SubTotal column. In SQL 2008 you can just put a column in there for the appropriate YTD value.
Edit, to explain it more thoroughly:
Put a Matrix in the report. Use a column group on Year, MonthNo. By default that group will be called matrix1_ColumnGroup1 (or something like that - go to Edit Group to set it to something better). Put a row group on whatever causes a second row to appear.
In the Cell part of the Matrix, use an expression like:
<code>=IIF(InScope("matrix1_ColumnGroup1"), First(Fields!MonthValue.Value), Last(Fields!AvgYTD.Value))
</code>
Comment: I dont know how to use Matrix please tell me complete solution i m in trouble from two days
Comment: Start by telling me which version of ssrs you're using, and where 7.9 comes from.
Comment: hi rob,

i am using sql server 2005 and 7.9 is th AvgYTD Value comes from table for selected month march....

i want ...if i select month march then output will be show month value of jan,feb and march and AvgYTD value for only selected month..

thanks,

How can i Make This Type SSRS


Why Array is Static, whereas ArrayList is Dynamic?

Question: I understand from one of Array in Java posts that ArrayList is dynamic, whereas arrays are static in Java.
So if I want to modify the size of an array, it is not possible? Is there any workaround?
Answer: A Java Array object is of fixed size. Inside ArrayList, there is an Array, which it also of fixed size, but as you add more items to your list, the ArrayList class automatically creates a larger internal Array and then copies the elements across to it.
If you want to have both flexible sizing AND array-like behaviour, then ArrayList is a good option. If you want to get a larger array sometimes, then you'll have to essentially do what ArrayList does: create a larger array and copy the existing elements across.
On the whole Array is useful for some situations where you want very efficient access to a fixed size set of data. The moment you think it might change size, you should consider on of the other, more flexible collection classes.
Comment: Thanks for having point out the mistake
Answer: Arrays having fixed lengths is how the language is defined to work.
Ultimately, all structures such as collections have a (fixed length) arrays under the covers, even the ArrayList, but its methods throw away the internal array and replace it with a larger one if it needs to grow beyond its current capacity.
Memory needs to be allocated, and for that you need to know how much, and for that you need to fix the size.
Answer: In many modern languages, array is static and lists and/or vectors are dynamic since sometimes you need a static data structure and sometimes you need a dynamic data structure :)
There is a workaround, of course, but it is quite inefficient and meaningless since there are dynamic data structures you can always use.
You can create a new array of the next size and copy all data from the previous array to the new array. Then set the new array to the old array.
Answer: Arrays are statically sized in Java , even upon creation array size must be given (or the initial size).
Array of primitives will be initialised with the default value if this primitive across the size of the array, whileas array of Wrapper/Objects will be initialised with a null values across all of its elements.
Resizing an array in Java means manually creating a new array of the desired size and selectively adding elements to it from the old array.
(Even arraylist does resizing manually behind the scenes based on its metrics).
Answer: ArrayList is can only store object datatype and is an object type. Arrays are reference types. Array does not have the capability to adjust its size however the ArrayList type has the capacity for that.
Comment: Actually in Java arrays are reference types and _not_ primitive types. Also, to improve your answer, you might want to clarify what you mean by "calling data type" as there are no calls mentioned in the question. Cheers.
Comment: I have made note of the corrections and edited my answer as so


Common denominator bpm

Question: I have a video of nature. I noticed that there are three repeating elements, one has 80.197844 bpm, the other 64.664 bpm and the other 67.4 bpm.
I want to compose music for it. To get started, how do I find a common denominator bpm value to create music that includes all the rhythms without sounding contradictory?
Comment: I would suggest starting off by rounding, but that won't help much because 67 is prime. If I were in your shoes I would remember that the main title theme to *The Terminator* is based on a loop that is not actually a full measure long at any tempo or time signature that matches the music, and the composer just performed along with it without a click track. So I wouldn't even try to get a firm tempo or beat, I would just play along as best I can and feel my way through it.
Comment: The elements don't feel like they are working together. If I focus on one element, the other one goes out of tune naturally. Isn't there any mathematical way to bring everything under one roof even though 67 is a prime number?
Comment: Not that I know of, but I only took one semester of group theory.
Answer: You need to find the ratios between the numbers, and try to fit these to round-number approximations. The actual values are not important (let alone microsecond precision!)

64.7:80.2 is close to 4:5  ...Easy!
64.7:67.4 is close to 24:25  ... hmmm

I honestly doubt if you can make anything musical out of a 24:25 ratio (other than poco piu mosso); I would think that it could be very interesting to make something out of 4:5 relative frequencies. (I hope this helps; I don't 100% understand what you plan to do.)
Answer: Construct simple, rhythmic musical lines at those three speeds and play them together.  Maybe interesting cross-modulation patterns will emerge.  Steve Reich did a lot of this sort of thing.
But, if nothing interesting DOES emerge, try a different musical concept.  Remember, Steve Reich had to make a living doing furniture removals for a long time :-)
Answer: Having done similar projects, it's probably easier to speed up or slow down the videos so that they fit the music.
Comment: It is not, as all elements appear in the same video at the same time.

Common denominator bpm


rdate for Windows 2008

Question: I need a command line tool that adjusts the time of a Windows 2008 server, using an internet clock. The purpose is to adjust the time in a script, when other apps from that script are not running.
It is not an option to use the built-in NTP service because that makes some apps on this server fail - note, that this server is used in an industrial environment with no PCs on the network and no Windows update or similar applied.
Answer: Not sure why you would want to do this with a script.  Your best bet is to set an authoritative time service.  See this technet article.   http://technet.microsoft.com/en-us/library/cc794823(WS.10).aspx
EDIT due to more information in the question and comments.  There is no way you can prevent the server from adjusting the clock if it's getting time from another source.  It seems that your best solution is to install a time server.  I do this on my network because we don't have a connection to the internet.  We currently use Symmetricom S250 devices synced to a GPS signal.  Also note that the Windows OS does not support very accurate time but there are software bundles to fix that.
Link to set an external NTP server:  http://support.microsoft.com/kb/816042
Link explaining the limits of Windows time service:  http://support.microsoft.com/kb/939322
Comment: The Windows 2008 server is an industrial computer, that is on a firewalled network that does not have any PCs attached. It is not part of a domain or anything similar. Your link does not seem to solve the problem.
Comment: It would be helpful if you explained what you want the script to do, and more importantly, why you simply don't want to point your server at pool.ntp.org.
Comment: I want to point the server at pool.ntp.org or similar, but I want to be 100% sure that the system time does not change unless I ask it to. For our industrial purpose, this is very important.
Answer: PowerShell:  sync system time with Internet time server

rdate for Windows 2008


Upon jQuery onClick, incrementing a PHP variable?

Question: I have a link like this: Print. I'm trying to increment a PHP variable when that is clicked. I could technically do it by submitting a form, but I'm sure there is an easier way. Any ideas?
Comment: PHP Variable? As in something that only exists for the duration of PHP executing (with the exception of a session/cookie). Are you sure you don't mean a DB variable, accessible through PHP?
Comment: And that PHP variable is where (relative to the page with the ANCHOR)?
Comment: Yeah like @Brad Christie and @g.d.d.c have mentioned, use a database and AJAX. JQuery is good for that http://api.jquery.com/jQuery.post/
Comment: Remove the js from the href and add an onclick="incrementFunction();return false" to the attributes. That function then calls the JQuery AJAX that runs a PHP script, which updates the database. A new value (+1 hopefully) is returned and displayed.
Answer: JavaScript is Client Side.  PHP is Server Side.  If you want to affect a PHP Variable with a JavaScript event you must issue an AJAX call of some kind.
Answer: You'll need to persist a variable like this using some sort of database. You can then issue an AJAX call to a small server-side file that increments a value in that database.
On your HTML page:

Print

Then, server-side in /increment.php (I assumed MySQL, but you could use something else like Redis for this as well):
// database connection goes here
$result = mysql_query("UPDATE stats SET stat_value = stat_value + 1 WHERE stat_key = 'prints'", $some_database_connection);
mysql_close($some_database_connection);
die( $result ? 'true' : 'false' );


Attach Database Using SMO keep Failing

Question: i use this SMO code to attach a database.
<code>        Server mServer = new Server(".");

        mServer.AttachDatabase("DbName", new StringCollection {
            "DbName.mdf",
            "DbName_log.LDF" }, AttachOptions.None);
</code>
But i keep getting the exception

Failed to connect to server.

Any Ideas?
[EDITED]
Inner Exception:
{"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}
Answer: The error says it all - SMO cannot connect to the server.

Does that local server exist?
Do you have the right to access that server??
Are you maybe using a named instance (e.g. ".\SQLExpress") ??

More points:

you don't specify a full path for the MDF/LDF file - try specifying a full path with directory and all. Does that make any difference?

Your code - as is - works flawlessly when I execute it locally on my machine. No problems at all ...... there must be something odd about your setup.

Is your SQL Server service up and running?

Your update would indicate that SMO is trying to use "named pipes" to communicate with your server. Is that protocol enabled on the server side? Check the SQL Server Configuration Manager (in the start menu; SQL Server > Configuration Tools > SQL Server Configuration Manager):

If the client tries to connect using named pipes, you need to make sure they're enabled on the server side, too (they're not, by default, as you can see from my screenshot).
Comment: Local Server exists, i can attach the file by hand...
Rights, i am the administrator of the computer.
I just use the "." string on the Server constructor.
Comment: I used the full path with Path.GetFullPath static method, checked it too..it is full... ....\bin\Debug\data\DbName.mdf etc
Comment: Yes it is...if i attach the database by hand, my program starts correctly...when my program cant connect to the server i have a form setting conn string check connection and attach database...but keeps failing.
Comment: I have enabled all these yesterday cause i was testing clients in my network. Just checked its ok.
Comment: I hate it when people say the error says it all. It sounds so condescending.
Answer: I had a similar issue. Could not attach database files via smo. But if  I copy the mdf and ldf files from the debug or release folders of Visual studio to say the root directory (C:), they attach programatically well from there.
In addition to not accessing the server, you may try moving the db files to another location. Hope that helps

Attach Database Using SMO keep Failing


Explanation of the Bounded Convergence Theorem

Question:
Theorem (Bounded Convergence Theorem) Let $\{f_n\}$ be a sequence of measurable functions on a set of finite measure $E$.  Suppose $\{f_n\}$ is uniformly pointwise bounded on $E$, that is , there is a number $M\geq 0$ for which $|f_n| \leq M$ for all $n$.  If $\{f_n\} \to f$ pointwise on $E$, then $\lim\limits_{n \to \infty} \int_E f_n = \int_E f.$

Why is it important in this theorem for it to be uniformly pointwise bounded as opposed to just pointwise bounded?  Is this because if it is not uniformly bounded than it is certainly not uniformly convergent.
Comment: What do you mean by "just bounded"?  There are two ways to relax the condition of uniformly bounded: (1) require that each $f_n$ be a bounded function, or (2) require that $\{f_n\}$ is pointwise-bounded, meaning that $|f_n(x)| \leq \phi(x)$ for some $\phi$.
Comment: Also, uniform boundedness does not imply uniform convergence.
Comment: @Jesse I mean pointwise bounded.  Uniform convergence implies uniform boundedness.  So not uniformly bounded implies not uniformly convergence.
Comment: Uniform convergence implies uniform boundedness _assuming_ each $f_n$ is a bounded function.  For example, consider the sequence $f_n\colon (0,1) \to \mathbb{R}$ given by $f_n(x) = 1/x + 1/n$, which is uniformly convergent but not uniformly bounded.
Comment: Can we say also $\lim_{n\to \infty}\int_Ef^p_n=\int_Ef^p$ for $p>1$ as well?
Answer: If you avoid the requirement of uniform boundedness then there is a counterexample
$$
f_n=n^2 1_{[0,n^{-1}]}
$$
But there are examples when the theorem holds even if the sequence of functions is not uniformly pointwise bounded. For example
$$
f_n=n^{1/2}1_{[1,n^{-1}]}
$$
The most general requirement on boundedness of $f_n$ when theorem still holds is
$$
\forall n\in\mathbb{N}\quad\forall x\in E\quad |f_n(x)|\leq F(x)
$$
for some integrable $F:E\to\mathbb{R}_+$.
You can also weaken the condition of pointwise convergence just to convergence in measure
$$
\forall\varepsilon>0\quad\lim\limits_{n\to\infty}\mu(\{x\in E:|f_n(x)-f(x)|>\varepsilon\})=0
$$
Answer: Consider the example $$f_n(x)=\cases{ nx & if $0\leq x \leq {1\over n}$\cr -n\Bigl(x-{2\over n}\Bigr) & if ${1\over n}\leq x \leq {2\over n}$\cr 0& if ${2\over n}\leq x\leq 1$}$$
Each $f_n$ is piecewise linear and continuous on the interval $[0,1]$, and $f_n(x)\to 0$ as $n\to\infty$ for each $x\in[0,1]$. However, $\int_0^1 f_n(x){\rm d}x=1$ for each $n$, so the conclusion of the Bounded Convergence Theorem does not hold here.
I think this example shows quite clearly what the problem is. You do not want to assume that the convergence is uniform, so there might be a substantial difference between $f(x)$ and each $f_n(x)$ on some set, and you need to make sure that the integral of $|f_n-f|$ over this set will be small as $n\to\infty$.
(Usually this theorem is stated in a slightly stronger form, called the Dominated Convergence Theorem, where the uniform bound $|f_n|\leq M$ is replaced by $|f_n(x)|\leq g(x)$ for each $x$ and $n$, where $g$ is an integrable function.)
Comment: The sequence of functions you have considered is not even pointwise bounded. Is it possible to say that if the sequence of functions is pointwise bounded in stead of uniformly bounded, then also bounded convergence theorem is true? Per Manne
Comment: @Anupam I think you may have misunderstood the definition of pointwise bounded. For each $x$, the sequence $\{f_n(x)\}$ has only finitely many nonzero terms, so it is surely bounded.
Comment: Menne: What I understand by pointwise bounded is as follows: A sequence of functions $(f_n)$ is called pointwise bounded if for each $x$ there exists $M_x>0$ such that $|f_n(x)|\leq M_x$ for all $n\in \mathbb N$. Is it the same thing you are also saying?
Comment: Menne: Yes I understood where I have mistaken. Thanks!


Azure backup vs Snapshots

Question: I'm an azure newbie and just trying to understand Azure better. My questions are specific to backing up Linux VMs in Azure. Please help me in understanding it better.
I read that Azure backup takes snapshots and then uploads them to the vault. I'm trying to understand how using 'Azure backup' to backup a VM is different from taking the snapshots of OS Disk and data disk of azure VM via "az vm" cli commands?
What exactly is the vault here? Is it internally implemented as a storage account with blob container or is it something similar to the Glacier in AWS?
Which is better cost wise, azure backup or osdisk snapshots?
If both the options are similar, i.e using azure backup or taking a snapshot of OS disk/Data disks. Is there an advantage of using one over the other?
Are the Snapshots of OS disk taken in Azure, global in nature or are they in any way associated with a region? If a region is down, do they become unavailable?
In the azure portal, snapshots, what is "snapshot state"? Why is the snapshot state "Unattached" for me even after spinning off a VM from the snapshot disk?
Comment: In general, a backup is for the purposes of disaster recovery and a snapshot is used for change control. If the server suddenly disappears into the ether, you restore from a backup. If you make a change on the server and need to revert, you go to a snapshot.
Answer:
I read that Azure backup takes snapshots and then uploads them to the
  vault.

You are right, Azure backup will take snapshots first, then upload them to backup vault.

how using 'Azure backup' to backup a VM is different from taking the
  snapshots of OS Disk and data disk of azure VM via "az vm" cli
  commands?

The biggest difference is that, we can use Azure Backup to restore VM directly. If we use snapshot and want to restore VM, we have to use snapshot to create OSdisk and then use this OSdisk to create new VM.
By the way, we can set backup jobs in Azure Backup, so Azure can run backup by backup policy. If we use snapshot, we should do it manually.

What exactly is the vault here?

The vault same as storage account, but we can't find it in our portal, and can't migrate backup data, we can manage the vault via Azure Backup.

Which is better cost wise, azure backup or osdisk snapshots?

For now, we can use CLI 2.0 command az snapshot create to create snapshot, but we can't use this to snapshot some on-prem resource.
If we just want on-time backup of Azure VM, and we can use PowerShell to restore it, I guess we can use snapshot.
If we want to daily backup of VM, I think we should use Azure Backup.
About cost, Azure backup and snapshot charge for the usage of storage account.

using azure backup or taking a snapshot of OS disk/Data disks. Is
  there an advantage of using one over the other?

In my opinion, take snapshot used for restore VM to one time, for example, I want to do some configure change, before that I take a snapshot of it, then change the configure, if it false I can restore VM with the snapshot.

Are the Snapshots of OS disk taken in Azure, global in nature or are
  they in any way associated with a region? If a region is down, do they
  become unavailable?

we can choose SKU for snapshot, Premium_LRS, Standard_LRS. so you are right, if the region is down, the snapshot will unavailable.

In the azure portal, snapshots, what is "snapshot state"? Why is the
  snapshot state "Unattached" for me even after spinning off a VM from
  the snapshot disk?

We can't attach the snapshot to Azure VM, so the state is unattached.
I have create a disk from the snapshot, and the state is unattached.
Comment: Please let me know if you would like further assistance.
Comment: How do I use the snapshot to restore VM? I've scoured the Internet for a while now so my google-foo needs some help.
Answer: how using 'Azure backup' to backup a VM is different from taking the snapshots of OS Disk and data disk of azure VM via "az vm" cli commands?
The biggest difference is that, we can use Azure Backup to restore VM directly. If we use snapshot and want to restore VM, we have to use snapshot to create OSdisk and then use this OSdisk to create new VM.
///Also, those snapshot can be attach to existing VM (DataDisks), for OsDisk, disk swapon is the option thru snapshot method

Azure backup vs Snapshots


What does independence between comparisons in multiple comparisons mean?

Question: From Wikipedia's Multiple Comparison

For hypothesis testing, the problem of multiple comparisons (also known as the multiple testing problem) results from the increase in type I error that occurs when statistical tests are used repeatedly. If n independent comparisons are performed, the experiment-wide significance level $\bar{\alpha}$, also termed FWER for familywise error rate, is given by
  $$
    \bar{\alpha} = 1-\left( 1-\alpha_\mathrm{\{per\ comparison\}} \right)^n$$

I don't understand how the comparisons can be independent? Let the multiple tests be $\{H_i, K_i, T_i, c_i), i \in I\}$, where the $i$-th test is $H_i$ versus $K_i$, with testing statistic $T_i$ and critical value $c_i$. Now given a sample $X$, the test statistics $T_i(X), i\in I$ can't be independent, and therefore the testing rules $I_{T_i(X) \geq c_i}$ can't be independent either. Am I wrong? Thanks!
Answer: Here is a very simple example.  Imagine you have 4 groups, (call them groups A, B, C, and D) and you want to test whether or not the mean of each of the groups is the same.  Now, you decide to perform all pairwise comparisons between the 4 groups (thus you now have to deal with multiple comparisons).  Now, two of the multiple comparisons will be comparing the mean of group A versus B and the mean of group C versus D.  Now, wouldn't you agree that the comparison of group A and B is independent of the comparison of group C and D?  This example is somewhat trivial but still gets at the point of your question.


Checking the shell method with the disc method.

Question: The problem is: "Find the volume of rotation about the $x$-axis for $y=(x-3)^\frac{1}{3} - 2$ where $11 \leq x \leq 30$. When I used the shell method I obtained:
$$\int_{0}^1 2\pi y(16-(y+2)^2) \,dy = \frac{53 \pi}{6}$$
But when I used the disc method my integral turned out to be: $$\int_{11}^{30} \pi ((x-3)^{\frac{1}{3}}-2))^2 \,dx = \frac{38 \pi}{5}$$
Comment: How did you get $(y+2)^2$ in the first integral?  Basically it looks like you have the right idea for setting up the integrals, it seems to me as if this is just a careless error.
Answer: I did a quick shell method solution and got $\frac{38\pi}{5}$.  I think your mistake is when determining the length h in the integral for shell method $V=2\pi\int_{c}^{d}{ph~dy}$.  This plot should help.
http://17trek.com/help-files/2014-03-07/plot-labeled.png

When I teach this I have my students draw these lengths and come up with the equation $x+h=30$ and solve for h giving $h=30-x$.
So all you need to do is solve the equation $y=(x-3)^{1/3}-2$ for x, plug it in that equation for h and you are set.
Answer: The shell approach is supposed to give:
$$\displaystyle\int_{0}^1 2\pi y(30) dy-\displaystyle\int_{0}^1 2\pi y(3+(y+2)^3) dy $$


how to disable the lucene kernel extension in neo4j

Question: We're using Neo4j in our current project and want to use lucene's facetet search features so updating to lucene 4 is necessary...
When I exclude "neo4j"s dependency to "neo4j-lucene-index" in my Maven POM I get an exception when trying to start the graphdatabase:
java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase,
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:351)
at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:56)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:90)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:199)

.
.
.

Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.transaction.XaDataSourceManager@3bd93525' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:328)
... 35 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@295f7c4b' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.start(XaDataSourceManager.java:164)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
... 37 more
Caused by: java.lang.IllegalArgumentException: No schema index provider org.neo4j.kernel.api.index.SchemaIndexProvider found. Kernel extensions available on classpath:

Does neo4j work without lucene ?
looking forward to your answers..
Comment: Could you accept Stefans answer? Thx :)
Comment: I did some refactoring of the original neo4j-lucene-index module to make it work with lucene 4.10.2. Code can be found here: https://github.com/TekTimmy/neo4j-lucene4-index
Answer: Not 100% sure here. When not having neo4j-lucene-index on the classpath, the kernel extension will not be loaded. Neo4j will work in that case except that all accesses to schema or manual indexes will throw IllegalArgumentException with no index provider found.
Typically in Neo4j you use indexes to lookup start points for traversals. Without indexing, every query will be a global query unless you have already a reference point available.
I guess the better approach is to use Neo4j as a server then your application can use any Lucene version indepently. If for some reason embedded mode is mandatory, you can apply class loader separation as described on http://blog.markturansky.com/archives/21 to have multiple lucene versions in the same application. However that's not easy, therefore I recommend to use Neo4j server.
Comment: Hey Stefan, i added the exception message to the questions body that is thrown when i start an graphdatabase without the lucene-index dependecy. It seems like it really does not work without it. I will try to compile my own version of the lucene-index module with lucene 4.
Comment: You're right, if you don't have an schema index provider, Neo4j won't start up. However you can write your own schema index provider. Michael blogged about that at http://jexp.de/blog/2013/05/on-creating-a-mapdb-schema-index-provider-for-neo4j-2-0/.
Comment: Wow great news! Thanks for the link!
Comment: replacing the SchemaIndexProvider is not enough .. also there's an alternative LabelScanStoreProvider necessary to be able to run neo4j without lucene-index module =( I'll try to implement it ...


Why did I get a "bad operand types for binary operator" error?

Question: I was working on an exercise which incorporates one method with another. I know that the getMinMax() method has an empty array but that's irrelevant for the purpose of the exercise.
Code:
public class Square{
    int area;

    public Square[] getMinMax(Square[][] arr){
        Square[] list = new Square[2];
        return list;
    }

    public int getArea(){
        return area;
    }

    public boolean isDifferenceSignificant(Square[][] arr){
        boolean isit = false;
        Square [] result = getMinMax (arr);
        if((result[1] - result[0])< 0.5) //The line (16) in question
            isit = true;
        return isit;
    }
}

When I compile this I get the following error:
Square.java:16: error: bad operand types for binary operator '-'
        if((result[1] - result[0])< 0.5)
                      ^
  first type:  Square
  second type: Square
1 error

I'm just lost and want to know why this error occurred.
Edit: Rohit Jain said "You probably meant - result[1].getArea() - result[0].getArea()"
and Lochemage said "if((result[1].getArea() - result[0].getArea())< 0.5)"
Both of these will work and thank you for your time!
Comment: You probably meant - `result[1].getArea() - result[0].getArea()`
Comment: @Heuster. OP has written that's irrelevant, in the first line. So, probably he is not returning an empty array.
Comment: @Rohit oops, missed that line :) just saw it one second before your comment
Comment: @RohitJain OP actually declared the `getMinMax` definition is irrelevant, not the `getArea`
Comment: @Lochemage. Yeah, that's what I was talking about. As, that is what can throw NPE, as it currently stands.
Comment: @RohitJain I think I got confused, maybe a comment was deleted, I thought your second comment was refer'ing to the `getArea() - getArea()` comment above it but you might have been responding to another one that was deleted.
Answer: I assume you actually want to test the area variable of each Square instead?
if((result[1].getArea() - result[0].getArea())< 0.5)

By doing result[1] - result[0] you are invoking the binary subtraction operator from the Square class, which may not be defined.
Answer: Java doesn't have operator overloading like C++, and you can't subtract one object from another. Use the actual value (result[1].getArea()).


Continuity of $\mu(t)=\inf\{x \in \mathcal C : \kappa(x)=t\}$.

Question: Let $\Delta = \{ 0, 1\}^{\mathbb N}$ be a Cantor set. Define $\theta : \Delta \to [0,1]$ by the formula $$\theta(x_1,x_2,\dots) = \sum_{n=1}^\infty \frac{2x_n}{3^n}.$$ Denote $\mathcal C = \theta(\Delta)$.
Define $\kappa : \mathcal C \to [0,1]$ by $$\kappa\left(\sum_{n=1}^\infty \frac{2x_n}{3^n}\right) = \sum_{n=1}^\infty \frac{x_n}{2^n}$$ and $\mu : [0,1] \to \mathcal C$ by $\mu(t)=\inf\{x \in \mathcal C : \kappa(x)=t \}$. Let $\displaystyle \mathcal D = \left\{ \frac{k}{2^n} : n \in \mathbb N, k \in \{0,1,...,2^n\}\right\}$
How can I show that $\mu$ is continuous on $[0,1] \backslash \mathcal D$?
I have shown that $\kappa$ is well defined and that it is a non-decreasing surjection, however I have trouble with dealing with $\mu$. Any help would be appreciated.
Answer: If the binary representation of $x$ is unique, the fiber of $x$ under $\kappa$ is a singleton that you can explicit. Then you have to use the fact that $\mu$ is also non-decreasing.
If $a_n \xrightarrow[n\to\infty]{} x^+$, for $a_n$ near enough to $x$, as the binary representation of $x$ (written $(x_1,x_2,...)$) contains infinitely many 0, there is $\alpha(n)\in \mathbb{N}$ such as
$x_{\alpha(n)} = 0$,
so that $x + \frac1{2^{\alpha(n)}} \in [0,1] \setminus \mathcal{D}$,
$x \leq a_n \leq x + \frac1{2^{\alpha(n)}}$.
and $\alpha(n) \xrightarrow[n\to\infty]{} \infty$
Thus $\mu(x) \leq \mu(a_n) \leq \mu(x + \frac1{2^{\alpha(n)}}) = \mu(x) + \frac2{3^{\alpha(n)}}$
This double inegality allows to establish half of the result. The other half is pretty similar (use the infinite number of 1 in the binary representation of $x$).
Answer: Maybe you can start by showing that $\forall x \in [0,1] \setminus \mathcal{D}$, the binary representation of $x$ is unique and contains infinitely many $0$ and infinitely many $1$.
Comment: This is quite obvious. How can I proceed from there?


Bayes optimal classifier vs Likelihood Ratio

Question: I am getting slightly confused by all the probabilistic classifiers.

The bayes optimal classifier is given as $ max (p(x|C)p(C)) $ and if all classes have equal prior then it reduces to $ max (p(x|C)) $
The likelihood ratio is given as $ \frac{p(x|C1)}{p(x|C2)}$

If I only have 2 classes with equal prior then what is the difference between the bayes optimal classifier and the likelihood ratio ? Wont they both return me the same class as the output ?
Comment: They are totally different things, so could you clarify what makes you consider them "essentially the same"?
Comment: Sorry I have edited my question. I hope my question is clearer now.
Comment: What you describe seems to be a Bayes classifier, not a Bayes _optimal_ classifier.
Answer: They are not the same, but in you case they could be used for the same purpose.
Optimal Bayes classifier is
$$ \DeclareMathOperator*{\argmax}{arg\,max} \argmax_{c \in C} p(c|X) $$
i.e., among all hypotheses, take the $c$ that maximizes the posterior probability. You use Bayes theorem
$$ \underbrace{p(c|X)}_{\text{posterior}} \propto \underbrace{p(X|c)}_{\text{likelihood}} \underbrace{p(c)}_{\text{prior}} $$
but since using uniform prior (all $c$ are equally likely, so $p(c) \propto 1$) it reduces to
the likelihood function
$$ p(c|X) \propto p(X|c) $$
The difference between maximizing the likelihood function and comparing the likelihood ratios, is that with likelihood ratio you compare only two likelihoods, while in maximizing the likelihood you may consider multiple hypothesis. So if you have only two hypotheses, then they will do essentially the same thing. However imagine that you had multiple classes, in such case comparing each of them with all the others pair by pair would be a really inefficient way to go.
Notice that likelihood ratio serves also other purpose than finding which of the two models has greater likelihood. Likelihood ratio can be used for hypothesis testing and it tells you how much more (or less) likely is is one of the models comparing to the other. Moreover, you can do the same when comparing the posterior distributions by using Bayes factor in similar fashion.
Comment: Thank you ! I was planning to edit my question to ask about the maximum likelihood estimation since it looks similar to the bayes classifier ! Thanks for clearing my doubt !


Camel Java DSL: Update the next polling request param using the value from the response

Question: I am new to Apache camel, this is what I am trying to figure out. In a sample code below, I am trying to use the property - "value" in the request param in next polling request.
String valueFromTheResponse= ""
m.addRouteBuilder(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("timer://foo?period=2)
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
            .setHeader("Accept", constant("application/json"))
            .to("https4://" + <myrequestURL>?param=<valueFromTheResponse>)
            .marshal().json(JsonLibrary.Jackson)
            .setProperty("value", jsonpath("$.value"))
            .process(new Processor() {
                @Override
                public void process(final Exchange exchange) throws Exception {
                    valueFromTheResponse = (String) exchange.getProperty("value");
                }
            })
        }
    });
    m.run();

What would be the best way to achieve this? or assign the class level variable the property value?
UPDATE: SOLUTION
got it working by adding the following:
.process(new Processor() {
                @Override
                public void process(final Exchange exchange) throws Exception {
                    exchange.getIn().setHeader("CamelHttpQuery", buildParamQuery());
                }
            })

Answer: You would need to store the value in a shared field in for example the RouteBuilder class itself, or a shared class instance. And then in the to http endpoint uri, you need to set the param query as a message header instead where you can get that value via a method call.
.setHeader(Exchange.HTTP_QUERY, method(this, "buildParamQuery"))

And then have a method
public String buildParamQuery() {
  return "param=" + sharedValue;
}

And then you set this field from the inlined processor with the last value. And mind about the initial value, eg the first poll the value is null so you need to maybe to return an empty string/null from the buildParamQuery method or something else.
Comment: method(this, "buildParamQuery") gave me a NPE, BUT I was able to use your suggested way by  doing this .setHeader(Exchange.HTTP_QUERY, simple(buildParamQuery())).
Looks like the problem is still the same, buildParamQuery() is only called once and not in the next polling request. Do you have any suggestions?
Comment: I somehow need to update the CamelHttpQuery for the next poll.


flask_SQLAlchemy and Blueprints

Question: I am new to Python I have been following some tutorials and now I am trying to make a site with an API on my own.
I am using Flask, Flask_SQLAlchemy and Blueprints and I was trying to create an SQLite3 Database only to be accessible by the API. (I have other blueprints called site and admin=
This is my file structure (only for the API part, I don't think the site and admin structure is relevant let me know if I am wrong):
hspmng/
+-- run.py
+-- app/
    +-- __init__.py
    +-- api/
        +-- __init___.py
        +-- routes.py

Code:
/hspmng/run.py
from app import app
app.run (debug=True)

/hspmng/app/__init__.py
from flask import Flask
from app.api.routes import mod
from app.site.routes import mod
from app.admin.routes import mod

app = Flask(__name__)
app.register_blueprint(api.routes.mod, url_prefix='/api')
app.register_blueprint(site.routes.mod)
app.register_blueprint(admin.routes.mod, url_prefix='/admin')

/hspmng/app/api/__init__.py
file is empty
/hspmng/app/api/routes.py
My idea is to have a different file for db creation but I put it into routes just for the sake of testing it.
from flask import Blueprint
from flask_sqlalchemy import SQLAlchemy

mod = Blueprint('api', __name__)

mod.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
mod.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqllite3'

db = SQLAlchemy(mod)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    location = db.Column(db.String(50))

@mod.route('/getStuff')
def getStuff():
    return '
API
'

Database creation
To create the Database I am running python in my command  line and typing the following
from app import db

and I am getting the following error
>>> from app import db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/mnt/d/Projects/hspmng/app/__init__.py", line 2, in <module>
    from app.api.routes import mod
  File "/mnt/d/Projects/hspmng/app/api/routes.py", line 5, in <module>
    mod.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
AttributeError: 'Blueprint' object has no attribute 'config'

Can you help me?
Answer: Move the following two lines where you set your config, to "app/____init___.py" where you create the app object.
config is not part of the Blueprint class, it is part of your Flask Application Object.
mod.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
mod.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqllite3'

In "app/__init__.py" you should be doing.
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqllite3'

This is so that your database URL lives on the application context so that all of your blueprints have access to it.
You can see more details about Flask.config here:
http://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.config
Comment: What if I want only the API to access it? I want the database to be independent from the other blueprints
Comment: @miguelmamfm you can use multiple databases but I'm not really sure what you are trying to do. You can just restrict database access by settings user permissions. What is the purpose of trying to set a database connection only on a blueprint??
Comment: If you want only the API to access your database, then just don't make calls to your database from anywhere else...
Comment: I think that's how it meant to be right? The API should be the only blueprint able to "see" the database...The front-end doesn't need to know that the database even exists
Comment: Hi, I understood now what you meant regarding the access to de data base for the blueprints...thanks. I made the changes you suggested but I still can't make it to work.

flask_SQLAlchemy and Blueprints


Stick the sound of the major scale in my head

Question: I recently began learning sight singing from Robert Ottman's book.
I've gotten to the point where you should sing simple melodies, with the biggest interval between 2 notes being a major second. The book says that if you have the major scale in your head it should be easy to sight sing these melodies, but I can't.
Are there any exercises I can do to stick the major scale in my head that would make me progress in this situation?
Answer: I suggest you sit at a piano, and slowly play a major scale, but just before you play each the note you sing the pitch you think you're about to hear.
If you're feeling more ambitious you can do the scale notes out of sequence - but again try to sing the note before you play it. If you find certain intervals hard you can concentrate on those, repeating until you start to feel more confident.
Moving on from single notes, you should also try singing a run of notes from the scale, say the first or last four or five notes, and then check with the piano to see whether you sang the right notes or not.
Answer: When it comes to basic building blocks like the major scale, it's often best to learn it by playing it on a piano or other instrument until you can mimic the sound yourself.
As for repertoire, the opening of "Joy to the World" is a great descending major scale. Try singing this before the beginning of every Ottman exercise to get yourself into the key and to start conceptualizing the major-scale space.
Answer: I'd head straight for the eponymous song 'Do a Deer', from the Sound of Music. Another would be 'Scales and Arpeggios' from the Aristocats.
Comment: Do you know what 'eponymous' means? If there were an eponymous song from The Sound of Music, it would be called 'The Sound of Music'.
Comment: @No'amNewman - I do, except it wasn't used correctly here! I was thinking of the song that is entitled with the tonic sol-fa names. And if it were an eponymous song, surely it'd be named after a *person* called The Sound of Music - or in this case, more accurately, he'd have been called Do Re Mi...  Go on then, what's the word I should have used?
Comment: 'Well known' and 'canonical' spring to mind. But this isn't an English language stack overflow site.....


Simple statistics - Average and global average

Question:
There are two groups of English: intermediate and advanced.

The average girls in the intermediate group is higher than that of the boys in the same group;
The average girls in the advanced group is higher than that of the boys in the same group.

It can be concluded that the overall average for girls is higher than
  overall average for boys.

I would say we can conclude that the overall average for girls is higher. It can be verified by taking some simple numbers.
However, I feel like my teacher would not have given me this if it was that simple...
Answer: Not true! This is a case of Simpson's Paradox!
Wikipedia: Simpson's Paradox
For example, suppose we had 1 girl in the advanced group and 9 in the intermediate group. Meanwhile, we have 9 boys in the advanced group and one in the intermediate group.
Suppose the girl in the advanced group has a 100% score, while the average of the boys in the advanced group have a 90% score. And suppose the girls in the intermediate group have an average of a 10% score, while the boy in the intermediate group has a 0% score. Then the average of the girls is
$$\frac{1}{10} 100 + \frac{9}{10} 10 = 19,$$
while the average of the boys is
$$\frac{9}{10} 90 + \frac{1}{10} 0 = 81.$$
Comment: I knew there was a catch! Thank for the answer!


swagger: how to validate formData

Question: So far I'm able to do swagger validation if the parameters are from "in": "body" or if the input expected is in a json format.
However, I can't find how to validate a simple string entered as formData.
Below is my swagger script (in json format)
v1swag = {
    "cancels_post": {
        "tags": ["/api/v1"],
        "parameters": [
            {
                "name": "token",
                "in": "formData",
                "type": "string",
                "required": True,
                "description": "Cancels the provided token.",
            }
        ],
        "responses": {
            "200": {
                "description": "Success!",
            }
        }
    }
}

I removed the schema as it seems to only work for "in": "body"
I've been searching the net but can't seem to find the light.
Though I will still be searching... Any hints would be greatly appreciated.
Thank you very much in advance.
Answer: A different source media type has to be consumed here. Specify "consumes" member to include media type of application/x-www-form-urlencoded.
v1swag = {
    "cancels_post": {
        "tags": ["/api/v1"],
        "consumes": [
            "application/x-www-form-urlencoded"
         ],
        "parameters": [
            {
                "name": "token",
                "in": "formData",
                "type": "string",
                "required": True,
                "description": "Cancels the provided token.",
            }
        ],
        "responses": {
            "200": {
                "description": "Success!",
            }
        }
    }
}

swagger: how to validate formData


Como fazer uma consulta em um intervalo de data no mysql?

Question: Quero fazer uma comparação se a data esta dentro de 30 dias.
Por exemplo, tenho a data 10/01/2016 e quero que me retorne todos os resultados com datas 30 dias próximos a essa por exemplo, 09/02/2016.
Comment: Qual tipo de data você está usando?! Date, DateTime, Timestamp?! Tem que citar senão fica difícil.
Comment: esta com varchar mas da pra converter para date e so utilizar STR_TO_DATE(data, "%d/%m/%Y")
Comment: 30 dias próximos em que sentido? +30, -30, +15 e -15, +30 e -30? qual deles?
Comment: Guilherme, conseguiu resolver seu problema com a resposta? Ou precisa de mais alguma informação?
Answer: Eu costumo fazer desta forma abaixo. Uso NOW() para pegar a data atual e faço uma subtração no intervalo de 30 dias usando INTERVAL 30 DAY. Na query eu faço a comparação se a data de criação (created_at do tipo timestamp) é maior, então me retorne todos os dados:
SELECT * FROM `task` WHERE created_at > (NOW() - INTERVAL 30 DAY)

Assim todos os resultados estarão dentre os 30 dias.
Comment: @GOKUSSJ4 engraçado que as questões mais importantes da pergunta as pessoas só colocam nos comentários. Aí a gente tem que deduzir o que a pessoa quer dizer. Aposto que você passou muito por isso. Abraços
Comment: obrigado por me tirar essa duvida, eu também estava precisando disso
Comment: isso conta também no mês de 28, 29 dias ?
Comment: @GOKUSSJ4 A pergunta cita uma comparação de um intervalo de 30 dias, independente de qual mês. Desta forma eu consigo obter um resultado condizente com a pergunta, baseado nos meus testes e considerando `timestamp`.
Comment: Sim eu sei da pergunta, mas gostaria de sabe se no mês de fevereiro isso funciona também dessa forma.
Comment: @GOKUSSJ4 30 dias é 30 dias amigão. Se a gente tiver em 1 de março, contando 30 dias para trás, dependendo do ano claro, vai ultrapassar e cair no mês de Janeiro! Abs.
Comment: Legal, não sabia dessa forma no mysql. +1. mas eu acho que é 30 dias pra frente.
Comment: A dica do seamusd parece viavel, mas se o cliente editar a data no computador dele, isso não afeta os resultados ? ou o php vai pegar a data atual de algum servidor ?
Comment: @OtavioFagundes data atual do servidor. Abraços
Comment: @OtavioFagundes a a função NOW é independente do PHP. Isso é direto na query. Abraços
Comment: @OtavioFagundes só deixar o +1 e tá tudo certo. Kkkkkkk briks. Precisando só dá um grito aqui. Abraços
Answer: Você pode usar a expressão;
SELECT * FROM `table`
where STR_TO_DATE(data, "%d/%m/%Y") >= STR_TO_DATE('10/01/2016', "%d/%m/%Y")
and STR_TO_DATE(data, "%d/%m/%Y") <= STR_TO_DATE(09/02/2016', "%d/%m/%Y");

Ou ainda usar o between:
   SELECT * FROM `table`
    where STR_TO_DATE(data, "%d/%m/%Y") between STR_TO_DATE('10/01/2016', "%d/%m/%Y")
  and STR_TO_DATE(09/02/2016', "%d/%m/%Y");

Comment: isso nao funciona pq preciso de todos os resultados 30 dias entre a dataparametro2
Comment: Funciona, só depende o que você passar nos parâmetros.
Answer: Consegui resolver assim
SELECT * FROM PESSOAS WHERE DATEDIFF(STR_TO_DATE(ANIVERSARIO, "%d/%m/%Y"),STR_TO_DATE('10/01/2013', "%d/%m/%Y")) BETWEEN -30 and 30

Comment: Assim, você só retorna 10 dias...
Comment: editei, mas a sua dica me ajudou demais, muito obrigado


Adding a rule in iptables with destination ip that won't resolved to it domain

Question: I'm adding this rule in iptables with the following IP address as destination:
iptables -A FOR_FILTER -d 126.96.36.199 -j ACCEPT

it added it successfully with the following result:
ACCEPT     all  --  anywhere             *.d1.sc.omtrdc.net

The rule I wanted to apply to 220.127.116.11 won't work because of this DNS resolve.
I would like to add the IP address as is, so iptables won't add the resolved domain.
something like this(but it doesn't work):
iptables -A FOR_FILTER -d "220.127.116.11" -j ACCEPT
iptables -A FOR_FILTER -d '188.8.131.52' -j ACCEPT

Answer: Iptables use IP addresses internally, if you don't want to see any DNS names when listing the rules, use iptables -L -n - it disables reverse DNS lookup.
Comment: i understand, but if it only problem of listing then why this rule wont apply in attempt to connect to 184.108.40.206?
Comment: As Pawel says, we'll need to see all your rules to help with that.  CodeP is right about the lookup issue affecting `iptables -L`, not the internal state of netfilter.
Comment: thanks for the reply,please.. im not that a beginner hehe i do know how iptable works and tables order, so i would please like to understand, every rule added to a chain is always an ip address and -L resolve to the domain just for display?
Comment: You ask "every rule added to a chain is always an ip address and -L resolve to the domain just for display?"  Yes, that is correct; internally, netfilter deals only in ip addresses.
Comment: I always use "iptables -nvL" to list the tables, reverse DNS in this case is pretty much pointless.
Answer: Two things to your question. One, as CodePainters noted, you need to use -n switch to see IP address in the listing of iptable rules.
Second thing is, iptables process rules in an order. If some previous rule forbade the connection, then adding another rule (-A adds at the end of the chain) will not help. You need to analyse the whole configuration, not just a single rule.
Answer: from the manpage:
   -s, --source [!] address[/mask]
          Source specification.  Address can be either a network  name,  a
          hostname  **(please  note  that specifying any name to be resolved
          with a remote query such as DNS is a really bad idea)**,  network
          IP address (with /mask), or a plain IP address.

   -d, --destination [!] address[/mask]
          Destination  specification.   See  the  description  of  the  -s
          (source)  flag  for  a  detailed description of the syntax.

   -n, --numeric
          Numeric  output.   IP addresses and port numbers will be printed
          in numeric format.  By default, the program will try to  display
          them  as host names, network names, or services (whenever appli-
          cable).

When you are adding rules, use IP numbers and not names.  When you are listing rules, if you want the name, omit the -n option.  To speed things up and remove the ns lookup step, add the -n to your -L.
You say: "The rule I wanted to apply to 18.104.22.168 won't work because of this DNS resolve."
I say, DNS has got nothing to do with it.


Combinatorics: All digits to be found in arbitrary number systems

Question: How many 10-digit numbers are there in the base 7 number system, where all the digits are found? How would you solve this task?
edit:
count of all 10-digit numbers: $ 6 *7^9$. That's all the cases. I would substract the number of cases where at least one of the 0,1,2,3,4,5,6 digits is missing in the number chosen. But I can't find out how much this is.
Another theory (this might not be right but) Let's say that I have a number for the first place value, so 6 unique digits left. I put another digit to the second place, 5 left, and so on. I'm left with 7 fixed unique digits and 3 arbitrary other digits. I have each of the digits in the first 7 places, which can be shuffled $6*6!$ different ways.. There are 3 digits left in the end. The problem is that even though I have lots of combinations with different numbers, the other 3 digits are at the end of my number.
Answer: what is the largest 10 digit number in the base 7 number system? What is the smallest 10 digit number? Are all numbers in between also 10 digit numbers?
All the digits are found. therefore we know that there are 7 digits once, and three remaining digits. We divide in three cases.
The three remaining digits are the same:
If all three are 0 then we have 4 0's and 1 of each other. First we chose the positions for the 0's in $\binom{9}{4}$. Then We chose a permutation of the non-zero elements in 6! to get 90720 numbers.
If the repeated  three are non-zero we first chose the location of the zero in 9 ways. Then we chose the location for the 4 repeated elements in $\binom{8}{4}$ and finally we pick the permutation of the remaining 5 elements in 5! ways giving us 75600 ways(multiplied by 6 since there are 6 non-zero digits)=453600.
two of the remaining digits are the same and one is different:
if none of them are zero then first we chose position for 0 in 9 ways.Then we chose which ones are repeated three and two times in $6*5=30$ ways Then we chose the position of the number that is there two times in $\binom{9}{2}$ and then we chose the position of the number that is there three times in $\binom{7}{3}$ ways. finally we chose a permutation for the remaining 4 elements in 4! ways. giving us 8164800.
if the one repeated twice is zero then we fix it first in $\binom{9}{2}$ ways ,pick the number repeated three times in 6 ways, and then pick the place for the one repeated three times in $\binom{8}{3}$ ways finally pick permutation of remaining in 5! ways to get 1451520 ways.
if the one repeated three times is 0 and the other one is non-zero then fix the 0's in $\binom{9}{3}$.Select the non-zero repeated one in 6 ways,  then fix the one repeated twice in $\binom{7}{2}$ and the chose permutation of remaining 5 elements in 5! ways to get 1270080 ways.
all three are different:
All of the repeated ones are non-zero. first chose position of the zero in 9 ways.Chose the repeated digits in $\binom{3}{6}$ ways. pick positions for the three pairs of repeated numbers in $\frac{\binom{9}{2}*\binom{7}{2}*\binom{5}{2}}{6}$ ways and find the 6 possible permutations for each color in each pair. Then fix the permutation of the remaining 3 elements in 3! to get 48988800
One of the repeated digits is 0. first fix the zeroes in $\binom{2}{9}$. Then pick the other two pairs of digits in $\binom{2}{6}$. Pick the two pairs of positions in $\binom{2}{8}*\binom{2}{6}$ multiply by 2 so that each of the digits can get each of the pairs.Finally permute the remaining 4 elements in 4! ways to get 362880 ways
add them all up to get $60,782,400$ out of the $242,121,642$
Comment: I think you are missing the "where all the digits are found" clause...
Answer: Hint:  the number of 10-digit numbers missing $5$ is $5\cdot 6^9$, using the same logic as you did-you have six digits and the first can't be zero.  You can subtract these off from your figure of $6\cdot 7^9$, with some care for zero-it is different.  Unfortunately, you have subtracted off the ones missing both $4$ and $5$ twice, so need to add them back in.  This is a case of the inclusion-exclusion principle
Maybe the exponent should be $6$, not $9$, as a $10$ digit number in base $7$ looks like $1234560$?
Answer: Say this number is $S_7^{10}$, and let $D_7^{10} = 6\cdot7^9$ be the total number of $10$-digits numbers in base 7. Then you have that
$$
S_7^{10} = D_7^{10}-7\cdot S_6^{10} \\
= 7^{10}-7\cdot(D_6^{10} - 6\cdot S_6^{10}) \\
= \dots
$$
The summation is not very clean, but you get the number!
Comment: There must be an easier solution without recursive approach.
Answer: Assume for the moment that a zero ($7$ in the following) at the first place is allowed. Then we have to count the number of surjective functions $f:\>[10]\to[7]$, where $[n]$ denotes the set $\{1,2,\ldots, n\}$. Any such $f$ can be generated by first partitioning the set $[10]$ into $7$ nonempty blocks and then assigning injectively a value from $[7]$ to each of these blocks. The first part can be done in $S(10,7)=5880$ ways, where $S(n,k)$ denotes the Stirling numbers of the second kind, and the second part in $7!=5040$ ways. By symmetry, one seventh of the functions so generated has $f(1)=7$, which is forbidden. It follows that the total number $N$ of admissible functions of the considered kind is given by
$$N={6\over7}\cdot 5880\cdot 5040=25\,401\,600\ .$$


Change URL in Source with reverse proxy?

Question: sometimes we make copies of live sites on another server to test new features. A lot of CMS systems hardcode the URL in the database, so it is not possible to just use another URL.
On our local systems, we just use the hosts file to redirect the requests to another IP.
This is far to complicated for our customers, so we need a simpler way for them.
It is possible to use apache (we use apache as webserver) as reverse proxy, so it redirects dev.somedomain.com to anotherdomain.com.
The only problem left is, that there are absolute links to anotherdomain.com in the HTML source.
Is there a way to just let apache (or another software) replace all links to http(s)://anotherdomain.com to http(s)://dev.somedomain.com in all pages (+js +css)?
Performance is not an issue, since this will obviously never run at a system that is used by more than a few people.
Answer: Apache does have a module for this - it's called mod_filter.
Answer: Thanks for the hint to mod_filter.
It seems to work now!
I had a problem with the fact, that the site uses both, the url with www. and the one without.
My configuration is:
<code>    <VirtualHost *:801>
      ServerName www.dev.domain1.com

      ServerAdmin email@example.com

     SetEnvIf X-Forwarded-Proto https HTTPS=on

      FilterProvider gzinflate INFLATE resp=Content-Encoding $gzip
      FilterProvider replace SUBSTITUTE Content-Type $text/
      FilterProvider gzdeflate DEFLATE Content-Type $text/
      FilterChain +gzinflate +replace +gzdeflate
      Substitute "s|domain2.com|dev.domain1.com|n"

     ProxyPass / http://www.domain2.com/
     ProxyPassReverse / http://www.domain2.com/
    # ProxyHTMLEnable On
     ProxyHTMLURLMap http://www.domain2.com/ /

      ErrorLog /var/log/apache2/dev-proxy-error.log

      LogLevel warn

      CustomLog /var/log/apache2/dev-proxy-access.log combined

    </VirtualHost>
</code>
And for the domain without www
<code>    <VirtualHost *:801>
      ServerName dev.domain1.com

      ServerAdmin email@example.com

     SetEnvIf X-Forwarded-Proto https HTTPS=on

      FilterProvider gzinflate INFLATE resp=Content-Encoding $gzip
      FilterProvider replace SUBSTITUTE Content-Type $text/
      FilterProvider gzdeflate DEFLATE Content-Type $text/
      FilterChain +gzinflate +replace +gzdeflate
      Substitute "s|domain2.com|dev.domain1.com|n"

     ProxyPass / http://domain2.com/
     ProxyPassReverse / http://domain2.com/
    # ProxyHTMLEnable On
     ProxyHTMLURLMap http://domain2.com/ /

      ErrorLog /var/log/apache2/dev-proxy-error.log

      LogLevel warn

      CustomLog /var/log/apache2/def-proxy-access.log combined

    </VirtualHost>
</code>
The ProxyHTMLURLMap alone is not enough, because it only replaces the exact same domain. on the domain with www the domain without wouldn't be replaced and vice versa.
I hope this helps someone. With this broad filter I would strongly suggest not using it on a production site, though!
Comment: Kudos for the extensive answer! I didn't have the time to write it up this morning, so I'm very glad that my short hint was of use to you. In two days you'll be able to accept your own anser as the answer to the question, I hope you'll come back and do that as it'll probably be helpful for others in the future.
Answer: I not realy understand what do you want exectly, and my reputation is too low for add a comment.
It's right, you have this situation:

yourCMS.local
|
|
+-----------> Create Copy of the System = dev.yourCMS.local

On your "copied" Webserver server you have this situation:

User add "dev.yourCMS.local" in the browser and your dev server are redirect the connection to the url yourCMS.local but on the same server (lookup 127.0.0.1)

If my understanding correct, try this solution:

Add the entry in the host file (ubuntu /etc/hosts)
<code># <IP-Adress>  <Hostname>
127.0.0.1   yourCMS.local
</code>

change the apache site configuration file in /etc/apache2/sites-available/yoursite an add:
<code><Proxy *>
        Order deny,allow
        Allow from all
</Proxy>

ProxyPass / http://yourCMS.local
ProxyPassReverse / http://yourCMS.local
</code>

Restart apache

Try it

It's no tested solution. It could be that not solve your issue, because your added url in the browser is different as configured. I never did that in this direction.
Open for other solutions and comments.
Comment: It does not solve the issue, since every web page in the testing server will contain links to the production server.
Comment: Not only links but also all the resources like css and js can link to the production server.


How many solutions are to $x_1+x_2+x_3+x_4+x_5+x_6=30$ if $x_1=6$ then $x_2\neq 4$, $x_3=6$ then $x_4\neq 4$, $x_5=6$ then $x_6\neq 4$?

Question:
How many solutions over $\mathbb N$ (includes $0$) are to $x_1+x_2+x_3+x_4+x_5+x_6=30$ if the three conditions below must hold:
if $x_1=6$ then $x_2\neq 4$, if $x_3=6$ then $x_4\neq 4$, if $x_5=6$ then $x_6\neq 4$?

I thought to use inclusion/exclusion principle here. In general there're ${30-1+6\choose 30}$ solutions.
We can count how many solutions are if $x_i=6\land x_{i+1}=4$ for $i=1,3,5$. There're ${20-1+4\choose 20}$ solutions.
If two "anti-conditions" hold together then there're ${10-1+2\choose 10}$ and if all three "anti-conditions" hold then there's only one solution.
Therefore the final answer is:
$$
{30-1+6\choose 30}-3{20-1+4\choose 20}+3{10-1+2\choose 10}-1=319351
$$
I'm not sure this is correct application of inclusion/exclusion principle here.
Comment: the idea looks right to me
Answer: if $$x_1+x_2+x_3+x_4+x_5+x_6 = 30$$
and $$x_1 = x_3 = x_5 = 6$$
$$x_2+x_4+x_6 = 30 -6×3$$
$$x_2+x_4+x_6 = 12$$
where $$x_2 ≠ x_4 ≠ x_6 ≠ 4$$
Comment: That is the situation if all of $x_1,x_3,x_5$ equal $6$. But they may take different values.


Can we edit the classic AJAX-reload script to return the value in a textbox instead of a div?

Question: How can I set the returned value to be added as a value of a textbox instead of a div ?
for example <input type="text" id="link" name="link" value="HERE" />

Answer: $.get("yourfile.php", function(data){
    $("#link").val(data);
});

EDIT:
var SANAjax = function(){
    $.get("yourfile.php", function(data){
        $("#link").val(data);
        setTimeout(SANAjax, 1000);
    }).fail(function(){
        setTimeout(SANAjax, 1000);
    });
};

$(function(){
    SANAjax();
});

Comment: Hello, thank you for the reply. Can you please edit my code? What should I put on value="" to echo the value ?
Comment: That's what my code does - it gets the data from `yourfile.php` and puts that data into the `value` of the input...
Comment: Excuse me but can you be more specific? Do I need to combine the two parts or should i put yours into value="your code here" ?
Comment: Replace your code with the one in my answer edit. Also you need to be using the latest version of jQuery - http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
Comment: It worked just great! Thank you very much! 1000 is 1 sec right ?
Comment: Yep...1000 milliseconds are equal to a second.


Viewbag value not show in ASP.NET MVC view

Question: I am using C# and ASP.NET MVC and try to pass data from the controller to the view. When I debug data show in viewbag but not show in view. The error is undefined. I don't know why this code shows an error.
This is the screenshot:
Screenshot of Debug Result
C# code:
public JsonResult mselectCOACodes(string gl_code)
{
    ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";

    if (ViewBag.mainCode != "")
    {
        ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
    }

    return Json("", JsonRequestBehavior.AllowGet);
}

jQuery:

View

            Main Code

                <input type="text" id="txtglmainCode"
                       value="@ViewBag.mainCode" class="form-control" placeholder="" />

            Description

                <input type="text" id="txtmainDescription"
                       value="@ViewBag.mainDesc" class="form-control" placeholder="" />

Comment: The view is not used at all, since the controller returns `Json()`... have a look at the result in the browser Network dev tool tab.
Comment: You're returning JSON, not a view.  And it's in an ajax request.  Your first view is already rendered.  You're getting confused which request is doing what.
Comment: You could make a partial view that updates via Ajax when code is changed and return partial view result in your controller method.
Comment: Off topic pic: Place a `!` bevore your link. Then the linked image is displayed intext (`![Screenshot of Debug Result](https://...)`)
Comment: can you give me sample @derloopkat
Answer: Firstly, don't use @ViewBag to store the input value, because you cannot access its value inside your C# code.
Here is C# code:
public JsonResult mselectCOACodes(string gl_code)
{
    string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";

    if (mainCode != "")
    {
       string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
    }

    return Json(mainDesc, JsonRequestBehavior.AllowGet);
}

Here is JQuery:

View:

            Main Code

                <input type="text" id="txtglmainCode"
                       value="" class="form-control" placeholder="" />

            Description

                <input type="text" id="txtmainDescription"
                       value="" class="form-control" placeholder="" />


Windows 2012 R2 IIS 8.5.9600.16384 and Google Go Webservice in parallel

Question: My network adapters are using three IP4 addresses:

a
b
c

The IIS runs two sites: A, B and the binding is

A>a:80
B>b:80
B>b:443

I configured the IIS to listen to a and b as follows:

netsh http add iplisten ipaddress=a:80
netsh http add iplisten ipaddress=b:80
netsh http add iplisten ipaddress=b:443

The command netsh http show iplisten shows:

a
b

The Google Go Webservice runs on IP4 address:

c

Situation: This config runs fine on Windows 2008 R2. On Windows 2012 R2 it seems to run at first BUT after restarting the server the Google Go Webservice is running but the sites A and B are stopped. However I can start them manually and all three sites are operational again.
Approach 1: The sites A and B are running. Now I disable the Google Go Webservice and restart the service. But the sites A and B are still stopped after the restart.
Approach 2: (the Go Webservice is still disabled) I now add the global IP address 0.0.0.0 for the IIS to listen. So netssh http show iplisten shows: 0.0.0.0, a, b. After the restart the sites A und B are still running. However listening on 0.0.0.0 does prevent the Google Go Webservice from running because his IP and port is now blocked by the IIS.
Question: Why does the IIS need the 0.0.0.0 IP address to start the sites? To me this looks like a flaw in Windows Server 2012 R2. In the IIS8.5 I found other flaws as well so I would not be surprised - for example you can not use the character ? in the naming of the standard website anymore which is problematic with some of our ISAPI modules (you can write xy.dll but not xy.dll?start). What can I do now to make the three sites run simultanously? Thanks for your support.
Answer: Would it be enough to have a batch script start them all up after the system comes up? Maybe not the most elegant solution, but it should work.
Comment: Well, the problem is that after starting the IIS the sites are always in a stopped state. This is because the IIS needs to be configured to not listen on the IP address 0.0.0.0. So I can start the IIS and Google Go service automatically and then the batch would have to order the IIS to start the single sites A and B. But for a production system I would not trust this configuration. The sites must be guaranteed to start after the server has been restarted. Now I will rework the IP assigment of the network adapters to check for flaws in my configuration.


Whenever I edit/update a node all the page caches for anonymous user are lost

Question: I have the following cache settings on the performance page

I have visited a few pages as anonymous user and made sure that they are being cached. Now I log in as admin in a different browser and edit a node. The moment I do this I see that Anonymous Page Cache for all the pages are cleared.
This seems counter intuitive and render caching useless for sites with high content editions.
Comment: Note : I know the answer and the reason why this is happening. It took me a little while to figure this out. So I am posting this question. I have added an answer. If I find any better answers I will accept that as the answer :)
Answer: Whenever I edit a node all my page caches are cleared.
As per the design : This behavior is intended behavior and works as per the design. If you look at the node_form_submit() node submit handler function within the node module you will notice that there is a cache_clear_all() As the comment in the line above the function call reads it clears the page and blocks cache as expected.
Reason for clearing all the caches: When a node is created/updated there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.
Work Around :
Approach 1 : Since node_form_submit is form submit handler you could just implement a hook_form_alter() and change the submit handler to your own function which can omit cache_clear_all() function call.
Approach 2 : Set Minimum Cache Life Time to a high value. (By doing this you are asking Drupal not to clear caches if they are not older than the specified Minimum Cache Life time. So now if you edit a node, the changes will not be visible immediately. Your changes will only be visible when time elapsed is greater than Minimum Cache Life time and next general cache wipe has occured.)
Once you have set the Minimum Cache Life Time you can use Expire module to implement your custom logic for Invalidating a cache. You can have settings such that whenever a node is edited drupal can clear the cache for that particular page and all the listing pages.
EDIT(After @MPDs comment) : If you are using a reverse proxy server then you might need to consider setting the Expiration of cached pages to an appropriate value and probably consider using purge module.
Futher Reading : Difference between Minimum Cache Lifetime and Expiration of Cached Pages value.
Comment: BTW, good self-answer.
Comment: Did you test approach 2?  I don't recall ever seeing the min cache time affect the TTL in `{cache_page}`, just the TTL in the HTTP headers.
Comment: @MPD I verified that. If you look at the function clear  cache.inc file (this function is in turn used cache clear all) you will notice if condition
if (variable_get('cache_lifetime', 0)) {
so the value is being used even for the cache clearing logic.

And more-over what you are referring to is actually the outcome of "Expiration of Cache Pages" which handles the expiration of External caches including Browser :)