Page doesn't appear in search results

Question: I created a view (page) which shows a list of nodes of a certain content type. This page doesn't show up when searching the site.
Is this expected behavior? Is there any way to make the page show up in a search?
Answer: To answer the first question: Yes, this is the expected behavior. Views pages are not indexed by Drupal core search.
For the second question, Drupal core search is limited. More is possible by using Apache Solr search integration.
According to https://www.drupal.org/node/2570521, https://www.drupal.org/project/apachesolr_nan is an example of a module that may do what you need. But you would need access to a Solr server.
Comment: Is there a way to make a Views page indexed? Or would a workaround be to make a page and add the View as a block to it?
Comment: @rarelyred that wouldn't work, as the block would not be the 'content' of the page. So it would still not index the view part of the page.
Answer: Instead of creating a page view, I've created a block view and added it to an actual page (content). This works in my particular case and allows the site to index the page to show up in a search. It may not be fancy but I don't have to add a module to make it happen.
Thanks to user cilefen who answered my questions and got me here.

Page doesn't appear in search results


How can I add to the class name of a form element?

Question: I'm trying to add an additional class to a form element using the following code:
<code>/**
 * Implements hook_form_FORM_ID_alter().
 */
function grant_opportunity_form_grant_opportunity_node_form_alter(&$form, &$form_state, $form_id) {

    $form['grant_opportunity_end_date']['#attributes']['class'][] = 'datepicker';

}
</code>
But the additional class is not being added. Am I doing this incorrectly? This is a very simple thing I'm trying to do, so I'd prefer not to go through the trouble of overriding the theme, or anything more involved like that.
EDIT: To be clear, a class is being added to the parent div of this element, but not the element itself.
Answer: I think it needs to be an array.
Try this:
<code>$form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));
</code>
You can also call it directly from hook_form_alter().
For example in your themes template.php you could add:
<code>function YOURTHEME_form_alter(&$form, $form_state, $form_id)   {
  if($form_id == 'YOUR_FORM_ID') {
    $form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));
  }
  // this displays some general info so you can check
  drupal_set_message("Form ID is : " . $form_id);
  drupal_set_message(dprint_r($form, TRUE));
}
</code>
Comment: This seems like it would be correct, but the class isn't appearing on the form.
Comment: Did you clear the cache in Drupal? CSS and javascript are usually cached so your changes won't show up with a simple refresh.


Logistic Regression- Control Variable Not significant In Model 2

Question: I am new to this site and it's my first post, so my apologies in advance if I have made any mistakes or did not follow proper etiquette.
I am running a logistic regression analysis with six predictor variables and I have controlled for two variables (a total of 8 variables in my final model). In Model 1 with only the control variables included, both variables are significant below .05. However in Model 2 (the full model) with all of the predictor variables and both controls, one of the original control variables that was significant, dropped in its significance.
I am so confused as to how this could happen. Any ideas? Also, how would I go about reporting my results? Am I still able to report this one variable that dropped from significance as being significant in Model, even though it was not significant in the final Model 2?
Thank you in advance for anyone who can answer my question
Answer: Welcome!
With multiple logistic regression (i.e. logistic regression with more than one predictor) or linear regression for that matter, including multiple predictors slightly changes the meaning of your coefficients. If we had a model that looked like this:
$$ dv = \beta_0 + \beta_1X_1 +\epsilon$$
The slope, $\beta_1$ associated with the predictor $X_1$ would tell us about the total effect of $X_1$ on the outcome, dv. If you add a second predictor, this changes things a bit:
$$ dv = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon $$
When we include multiple predictors in logistic regression, each slope (and test of the slope) tells us about the unique effect that predictor has on the outcome. Any shared explanatory power that may exist between $X_1$ and $X_2$ is removed from the slopes for $X_1$ and $X_2$ and the slopes only represent the unique explanatory power of each predictor. So, to the extent that $X_1$ and $X_2$ are related and shared explanatory power with regard to dv, the slope for $X_1$ will become smaller in the second model. When we run regression with multiple predictors we need to mention that we controlled for other predictors and our reported effect is the effect of the predictor that is unique to that predictor and not others in the model. People use a lot of different terms to describe this but you could refer to the "unique effect of $X_1$ over and above $X_2$",the effect of $X_1$ controlling for $X_2$, the effect of $X_1$ partialling out $X_2$, etc.
If $\beta_1$ does get smaller in the second model, you can check to see which other predictors are related to this one by running a model that predicts $X_1$ using the other predictors in your model of interest ($X_2$ in our case). This issue of related predictors is often referred to as redundancy or multi-collinearity. Some people see this as a bad thing because it means one or more of your predictors is non-significant in the multiple logistic regression model, but I tend to disagree. When you find predictors that are redundant that tell you something about your model. If I found that weight was a significant predictor of whether someone got diabetes, but found that relationship was attenuated after including calories consumed consumed per day, that would tell me that weight doesn't tell me anything special about diabetes any more than how much someone tends to eat.
In terms of writing about your results, it is totally fine to report both analyses because finding that some of your predictors are no longer significant in the multiple regression framework should tell you something about your overall theoretical model. However, you will want to make it clear that you can explain what each model tells you. Hope this helps!
Comment: Thank you so much for the in-depth explanation, suggestions and advice! You were right, it turns out that I was having issues with multicolinearity among my predictors and so the additional predictors in Model 2 were taking away from some of the unique variance that was explained by the predictors included in Model 1 (with the control variables only). I also really appreciate some of the suggestions on the type of language I can use to talk about my results and overall models. Thank you again!


$14$ different balloons and $10$ (different) kids

Question: I have $14$ different balloons and $10$ different kids.
What are the odds that exactly $6$ kids get a balloon?
A 0.1512
B 0.0002
C 0.0959
D 0.6306
I know that I need to divide by $10^{14}$ (all the options).
I also know I need to multiply by $10C6$ (picking the $6$ kids).
From this point, I am having trouble thinking of a way to calculate the rest (with out counting any case more than once).
Thank you
Comment: Please read this [tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: What you have done thus far is correct.
Once the six children who will receive the balloons have been selected, we have to exclude the possibility that fewer than six children receive a balloon.  For that, we need to use the Inclusion-Exclusion Principle.
There are $6^{14}$ ways to distribute the $14$ balloons to the six selected children.  However, this counts distributions in which not all the children receive a balloon.
There are $\binom{6}{1}$ ways to select a child not to receive a balloon and $5^{14}$ ways to distribute the balloons to the other children.
There are $\binom{6}{2}$ ways to select two children to not receive a balloon and $4^{14}$ ways to distribute the balloons to the other children.
In general, there are $\binom{6}{k}$ ways to select $k$ children to not receive a balloon and $(6 - k)^{14}$ ways to distribute the balloons to the other children.
By the Inclusion-Exclusion Principle, the number of ways of distributing the balloons to exactly six children is
$$6^{14} - \binom{6}{1}5^{14} + \binom{6}{2}4^{14} - \binom{6}{3}3^{14} + \binom{6}{4}2^{14} - \binom{6}{5}1^{14}$$
Hence, the probability that exactly six of the children receive a balloon is
$$\frac{\dbinom{10}{6}\left[6^{14} - \dbinom{6}{1}5^{14} + \dbinom{6}{2}4^{14} - \dbinom{6}{3}3^{14} + \dbinom{6}{4}2^{14} - \dbinom{6}{5}1^{14}\right]}{10^{14}}$$


Bayesian equivalent of two sample t-test?

Question: I'm not looking for a plug and play method like BEST in R but rather a mathematical explanation of what are some Bayesian methods I can use to test the difference between the mean of two samples.
Comment: the original BEST paper might be what you are looking for: http://www.indiana.edu/~kruschke/BEST/BEST.pdf
Comment: Just to be clear, are we speaking of a two-sample test that is the equivalent of a frequentist test of mean differences in two groups, such as the t-test? or are you interested in tests of the strong null hypothesis for distributional differences like the Kolmogorov-Smirnoff test?
Comment: @Cam.Davidson.Pilon The link is deprecated.
Comment: Updated link: https://jkkweb.sitehost.iu.edu/articles/Kruschke2013JEPG.pdf
Answer: This is a good question, that seems to pop up a lot: link 1, link 2. The paper Bayesian Estimation Superseeds the T-Test that Cam.Davidson.Pilon pointed out is an excellent resource on this subject. It is also very recent, published in 2012, which I think in part is due to the current interest in the area.
I will try to summarize a mathematical explanation of a Bayesian alternative to the two sample t-test. This summary is similar to the BEST paper which assess the difference in two samples by comparing the difference in their posterior distributions (explained below in R).
set.seed(7)

#create samples
sample.1 <- rnorm(8, 100, 3)
sample.2 <- rnorm(10, 103, 7)

#we need a pooled data set for estimating parameters in the prior.
pooled <- c(sample.1, sample.2)
par(mfrow=c(1, 2))

hist(sample.1)
hist(sample.2)

In order to compare the sample means we need to estimate what they are. The Bayesian method to do so uses Bayes' theorem: P(A|B) = P(B|A) * P(A)/P(B) (the syntax of P(A|B) is read as the probability of A given B)
Thanks to modern numerical methods we can ignore the probability of B, P(B), and use the proportional statment: P(A|B) $\propto$ P(B|A)*P(A) In Bayesian vernacular
the posterior is proportional to the likelihood times the prior
Applying Bayes' theory to our problem where we want to know the means of samples given some data we get $P(mean.1 | sample.1)$ $\propto$ $P(sample.1 | mean.1) * P(mean.1)$. The first term on the right is the likelihood, $P(sample.1 | mean.1)$, which is the probability of observing the sample data given mean.1. The second term is the prior, $P(mean.1)$, which is simply the probability of mean.1. Figuring out appropriate priors is still a bit of an art and is one of the biggest critisims of Bayesian methods.
Let's put it in code. Code makes everything better.
likelihood <- function(parameters){
  mu1=parameters[1]; sig1=parameters[2]; mu2=parameters[3]; sig2=parameters[4]
  prod(dnorm(sample.1, mu1, sig1)) * prod(dnorm(sample.2, mu2, sig2))
}

prior <- function(parameters){
  mu1=parameters[1]; sig1=parameters[2]; mu2=parameters[3]; sig2=parameters[4]
  dnorm(mu1, mean(pooled), 1000*sd(pooled)) * dnorm(mu2, mean(pooled), 1000*sd(pooled)) * dexp(sig1, rate=0.1) * dexp(sig2, 0.1)
}

I made some assumptions in the prior that need to be justified. To keep the priors from prejudicing the estimated mean I wanted to make them broad and uniform-ish over plausible values with the aim of letting the data produce the features of the posterior. I used recommended setting from BEST and distributed the mu's normally with mean = mean(pooled) and a broad standard deviation = 1000*sd(pooled). The standard deviations I set to a broad exponential distribution, because I wanted a broad unbounded distribution.
Now we can make the posterior
posterior <- function(parameters) {likelihood(parameters) * prior(parameters)}

We will sample the posterior distribution using a markov chain monte carlo (MCMC) with Metropolis Hastings modification. Its easiest to understand with code.
#starting values
mu1 = 100; sig1 = 10; mu2 = 100; sig2 = 10
parameters <- c(mu1, sig1, mu2, sig2)

#this is the MCMC /w Metropolis method
n.iter <- 10000
results <- matrix(0, nrow=n.iter, ncol=4)
results[1, ] <- parameters
for (iteration in 2:n.iter){
  candidate <- parameters + rnorm(4, sd=0.5)
  ratio <- posterior(candidate)/posterior(parameters)
  if (runif(1) < ratio) parameters <- candidate #Metropolis modification
  results[iteration, ] <- parameters
}

The results matrix is a list of samples from the posterior distribution for each parameter which we can use to answer our original question: Is sample.1 different than sample.2? But first to avoid affects from the starting values we will "burn-in" the first 500 values of the chain.
#burn-in
results <- results[500:n.iter,]

Now, is sample.1 different than sample.2?
mu1 <- results[,1]
mu2 <- results[,3]

hist(mu1 - mu2)

mean(mu1 - mu2 < 0)
[1] 0.9953689

From this analysis I would conclude there is a 99.5% chance that the mean for sample.1 is less than the mean for sample.2.
An advantage of the Bayesian approach, as pointed out in the BEST paper, is that it can make strong theories. E.G. what is the probability that sample.2 is 5 units bigger than sample.1.
mean(mu2 - mu1 > 5)
[1] 0.9321124

We would conclude that there is a 93% chance that the mean of sample.2 is 5 unit greater than sample.1. An observant reader would find that interesting because we know the true populations have means of 100 and 103 respectively. This is most likely due to the small sample size, and choice of using a normal distribution for the likelihood.
I will end this answer with a warning: This code is for teaching purposes. For a real analysis use RJAGS and depending on your sample size fit a t-distribution for the likelihood. If there is interest I will post a t-test using RJAGS.
EDIT:
As requested here is a JAGS model.
model.str <- 'model {
    for (i in 1:Ntotal) {
        y[i] ~ dt(mu[x[i]], tau[x[i]], nu)
    }
    for (j in 1:2) {
        mu[j] ~ dnorm(mu_pooled, tau_pooled)
        tau[j] <- 1 / pow(sigma[j], 2)
        sigma[j] ~ dunif(sigma_low, sigma_high)
    }
    nu <- nu_minus_one + 1
    nu_minus_one ~ dexp(1 / 29)
}'

# Indicator variable
x <- c(rep(1, length(sample.1)), rep(2, length(sample.2)))

cpd.model <- jags.model(textConnection(model.str),
                        data=list(y=pooled,
                                  x=x,
                                  mu_pooled=mean(pooled),
                                  tau_pooled=1/(1000 * sd(pooled))^2,
                                  sigma_low=sd(pooled) / 1000,
                                  sigma_high=sd(pooled) * 1000,
                                  Ntotal=length(pooled)))
update(cpd.model, 1000)
chain <- coda.samples(model = cpd.model, n.iter = 100000,
                      variable.names = c('mu', 'sigma'))
rchain <- as.matrix(chain)
hist(rchain[, 'mu[1]'] - rchain[, 'mu[2]'])
mean(rchain[, 'mu[1]'] - rchain[, 'mu[2]'] < 0)
mean(rchain[, 'mu[2]'] - rchain[, 'mu[1]'] > 5)

Comment: @baxx burn-in is removing samples from the beginning of an MCMC chain that are influenced by the starting points and thus don't represent the parameters you want to estimate see e.g. http://users.stat.umn.edu/~geyer/mcmc/burn.html#what. Also called ["warm up"](https://statmodeling.stat.columbia.edu/2017/12/15/burn-vs-warm-iterative-simulation-algorithms/)
Comment: Just wondering if there is a reasonable solution to use the Bayesian two sample comparison with this type of data sets. https://stackoverflow.com/q/57503523/7288088
Comment: I don't think I followed the "burn-in" part, anywhere i can read an explanation about that please?
Comment: An implementation of the same test using PyMC3 with the NUTS sampler: https://docs.pymc.io/en/v3/pymc-examples/examples/case_studies/BEST.html
Answer: The excellent answer by user1068430 implemented in Python
import numpy as np
from pylab import plt

def dnorm(x, mu, sig):
    return 1/(sig * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 / (2 * sig**2))

def dexp(x, l):
    return l * np.exp(- l*x)

def like(parameters):
    [mu1, sig1, mu2, sig2] = parameters
    return dnorm(sample1, mu1, sig1).prod()*dnorm(sample2, mu2, sig2).prod()

def prior(parameters):
    [mu1, sig1, mu2, sig2] = parameters
    return dnorm(mu1, pooled.mean(), 1000*pooled.std()) * dnorm(mu2, pooled.mean(), 1000*pooled.std()) * dexp(sig1, 0.1) * dexp(sig2, 0.1)

def posterior(parameters):
    [mu1, sig1, mu2, sig2] = parameters
    return like([mu1, sig1, mu2, sig2])*prior([mu1, sig1, mu2, sig2])

#create samples
sample1 = np.random.normal(100, 3, 8)
sample2 = np.random.normal(100, 7, 10)

pooled= np.append(sample1, sample2)

plt.figure(0)
plt.hist(sample1)
plt.hold(True)
plt.hist(sample2)
plt.show(block=False)

mu1 = 100
sig1 = 10
mu2 = 100
sig2 = 10
parameters = np.array([mu1, sig1, mu2, sig2])

niter = 10000

results = np.zeros([niter, 4])
results[1,:] = parameters

for iteration in np.arange(2,niter):
    candidate = parameters + np.random.normal(0,0.5,4)
    ratio = posterior(candidate)/posterior(parameters)
    if np.random.uniform() < ratio:
        parameters = candidate
    results[iteration,:] = parameters

#burn-in
results = results[499:niter-1,:]

mu1 = results[:,1]
mu2 = results[:,3]

d = (mu1 - mu2)
p_value = np.mean(d > 0)

plt.figure(1)
plt.hist(d,normed = 1)
plt.show()
```

Answer: With a Bayesian analysis you have more things to specify (that is actually a good thing, since it gives much more flexibility and ability to model what you believe the truth to be).  Are you assuming normals for the likelihoods?  Will the 2 groups have the same variance?
One straight forward approach is to model the 2 means (and 1 or 2 variances/dispersions) then look at the posterior on the difference of the 2 means and/or the Credible Interval on the difference of the 2 means.
Comment: Could you provide some more details on this? I'm not sure how to model 2 means and look at posteriors.
Comment: I think what Greg meant is that you look at the the posterior on the difference and see how far is it from 0 probabilistically.
Answer:
a mathematical explanation of what are some Bayesian methods I can use to test the difference between the mean of two samples.

There are several approaches to "testing" this. I'll mention a couple:

If you want an explicit decision you could look at decision theory.

A pretty simple thing that's sometimes done is to find an interval for the difference in the means and consider whether it includes 0 or not. That would involve starting with a model for the observations, priors on the parameters and computation of the posterior distribution of the difference in means conditional on the data.
You'd need to say what your model is (e.g. normal, constant variance), and then (at least) some prior for the difference in means and a prior for the variance. You might have priors on the parameters of those priors in turn. Or you might not assume constant variance. Or you might assume something other than normality.
Answer: First you should consider whether you would like to do this at all.
A good start would be to read this even more recent (2022) paper by Costello and Watts to learn about the various theoretical pitfalls associated with hypothesis testing in a Bayesian framework.
One of the most serious problems they see with the usual t-test null hypothesis of $\mathcal{H}_0: \Delta\mu = 0$ is that this is a "point-form null hypothesis". As $\Delta\mu$ is a real number, and its distribution is continuous, the probability $\mathrm{Pr}(\Delta\mu = 0)$ will unfortunately be exactly 0. Now, "if the null hypothesis is always false, what's the big deal about rejecting it?" -- they ask in the paper, quoting Cohen (2016).
After showing that the currently used "Bayesian t-test" is equivalent to its "classical"/frequentist counterpart (thus offering no obvious advantages), Costello and Watts also propose a different testing procedure which is supposed to be more informative. See the paper for details.
Disclaimer: I haven't done such an analysis yet (just reading myself into the subject). I would be rather curious to know if there's someone who has some practical experience with what Costello and Watts propose.


Unable to populate the Account.Name lookup value in data table

Question: I'm unable to populate the Account.Name lookup value in a data table. Although its visible in console but not on the data table.
Answer: Fields referenced in datatable mapping have to be "simple". Directly accessible properties on the object, without "jumping into" the nested object with dot notation.

You could put a formula field on Contact, call it AccountName__c, then query that and reference that in the datatable.
You can return a wrapper object created in Apex where stuff is appropriately flattened for easier use. It's more work, yes... but as your table's complexity increases the fact you have to write unit tests for it pays off when maintenance breaks something and you wouldn't notice otherwise.
Or you can intercept the data in the @wire handler method and flatten it there. Check https://salesforce.stackexchange.com/a/379451/799 out.


The jboss server is not connecting

Question: While I use the connect statement, it shows the following error
The controller is not available at localhost:9999: java.net.ConnectException: JBAS012174:
Could not connect to remote://localhost:9999. The connection failed: JBAS012174: Could not
connect to remote://localhost:9999. The connection failed: Connection refused
[disconnected /]

Answer: I had the problem with connecting to the native management interface on port 9999 and all I ended up needing to do was enable the interface by adding the following to the standalone.XML file:
<management-interfaces>
  <native-interface security-realm="ManagementRealm">
      <socket-binding native="management-native"/>
  </native-interface>
         :
<management-interfaces>

Answer: The actual native management binding (HOST:PORT) is defined in JBoss configuration file as interface name="management" and socket-binding name="management-native". By default they use localhost and 9999.
When install system service, it is necessary to specify the correct /controller host:port values if management binding has been updated.
The error below in the log indicates the CLI command line cannot connect to the management interface when shutting down:
Could not connect to remote://localhost:9999. The connection failed
Confirm the /controller parameter used when configuring system service matches the management interface and socket binding definition in JBoss configuration file (standalone.xml / domain.xml and host.xml).
When configuring system service, if not specified, the default configuration for controller is :
/controller HOST:PORT    The host and port of the management interface. If omitted, the default is localhost:9999.

Change this parameter to match the management interface and socket binding settings in the JBoss configuration file:
<interfaces>
    <interface name="management">
        <inet-address value="192.168.0.1"/>
    </interface>
......
</interfaces>

<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
    <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/>

With such configuration above you need to specify /controller as below to install the system service
service.bat install /startup /controller=192.168.0.1:9999 /config standalone-customized-1.xml

If jboss.socket.binding.port-offset is set, confirm actual port number (after offset) is passed in /controller parameter. For example, if jboss.socket.binding.port-offset is set as 300 in standalon.xml, you need to use 10299 (default 9999 + 300) as PORT number to install system service:
service.bat install /startup /controller=192.168.0.1:10299 /config standalone-customized-2.xml

The jboss server is not connecting


Normal error regression model

Question:
The normal error regression model is assumed to be applicable.
a)When testing $H_0:B_1=5$ vs $H_1:B_1\neq 5$ by means of a general
  linear test, what is the reduced model? What are the degrees of
  freedom $df_R$?
b)When testing $H_0:B_0=2,B_1=5$ vs $H_1:$not both $B_0=2,B_1=5$ by
  means of a general linear test, what is the reduced model? What are
  the degrees of fredom $df_R$?

The normal error regression model is $$Y_i=B_0+B_1X_i+\epsilon_i$$
where $\epsilon_i\sim N(0,\sigma^2)$ and the reduced model is $$Y_i=B_0+\epsilon_i$$
I know there is a difference in the degrees of freedom between the models, since the reduced model is estimated only one parameter, but I do not know essentially what the exercise is wanting.
Answer: The reduced model is the restricted model.
In the first question, your restriction is that the slope coefficient equals $5$. You run the regression using this value and note the error sum of squares which you compare with the error sum of squares of the unrestricted model to see if the restriction is too costly, in which case $H_0:b_1=5$ is rejected. The degrees of freedom are clearly $n-1$ since only one parameter is estimated.
Following the same logic, the reduced model in your second question is
$$Y=2+5 x+\varepsilon$$
and you proceed as above to test the joint hypotheses. Now there are two restrictions instead of one since we have also forced the intercept to assume a certain value. Hence the degrees of freedom are $n$, as no parameter is estimated.
Answer: You should modify your linear model as below:

If you wish to test a nonzero value, subtract it from the coefficient
  in the regression output and divide the result by the coefficient's
  SE. (Use a calculator for this.) Similarly, if you want confidence
  intervals, use the coefficient plus or minus the product of its s.e.
  with a t-value for the desired confidence level and 12 degrees of
  freedom. (Use a calculator for this.) This also works for the
  intercept using its SE.

http://courses.statistics.com/software/R/R_Ch02.htm
In both your cases, you are performing a linear regression between your data and your hypothesis, so df remains n-2.  Same procedure, just that you are regressing to something other than zero.
Comment: $Df_R$ is the notation for degrees of freedom of the reduced model in an F-test. Besides, your answer is not correct. The degrees of freedom are not $n-2$ regardless of what you are estimating.
Comment: This is about the construction of an F-test, not a t-test.
Comment: Where does he say he is seeking an F-test?
Comment: Dfr is Degrees of freedom for regression.  See below:

http://business.fullerton.edu/isds/jlawrence/361A%20New%20PP%20and%20Excel/Finished%20PowerPoint/Module%2035M%20--%20F-test.ppt

I gave Dfe as n-2.  Just because he is setting B0 or B1 to a set value, that does not mean that the model is complete or that it is the best fit.  You must still run the model against the data to determine the goodnes-of-fit.
Comment: @JohnK is correct. Notice the nature of the second hypothesis in the question: it is a linear constraint on *two* coefficients. When dealing with one coefficient at a time you certainly can use a t-test, but in this case an F-test is needed (regardless of whether the OP explicitly asked for an F test). That test needs *two* degrees-of-freedom parameters.

Normal error regression model


Using PlaySound() in MASM, need a method to help run this in the background without the code waiting for the entire .wav sound file to finish

Question: Using this code (mostly just added the irvine32.inc to the github code here: https://gist.github.com/michaellindahl/7782978
TITLE MASM PlaySound                        (PlaySoundExample.asm)

includelib winmm.lib
INCLUDE Irvine32.inc
INCLUDE macros.inc
PlaySound PROTO,
        pszSound:PTR BYTE,
        hmod:DWORD,
        fdwSound:DWORD

.data
deviceConnect BYTE "DeviceConnect",0
SND_ALIAS    DWORD 00010000h
SND_RESOURCE DWORD 00040005h
SND_FILENAME DWORD 00020000h
file BYTE "t.wav",0

.code
main PROC
     INVOKE PlaySound, OFFSET deviceConnect, NULL, SND_ALIAS
     INVOKE PlaySound, OFFSET file, NULL, SND_FILENAME

    exit
main ENDP
END main

Comment: BTW, you don't need to store your constants in `.data`, you could define them as assemble-time constants like `SND_ALIAS  = 00010000h` or with `equ`.  Loading them from memory for every call is silly when they're the same size as an address.
Comment: that's fine and everything but i just need to know how to get this code to run in a way that the code doesn't stop until the entire .wav is played to progress
Comment: That's why I said "BTW" and posted it as a comment, not an answer.  The obvious approach would be to compile some C that calls it, and disassemble it.  Or just write a C program that prints the constant with `printf("%x", SND_ASYNC);`
Comment: I should've clarified that I already tried to get the hex value, used cout<<hex<<SND_ASYNC, which just gives 1 (yours gives 1 too), if i plug it in assembly it really doesn't change anything, the audio still runs till completion and won't let me progress the code
Comment: It looks like a flag that you might OR with other flags.  (Another reason to use `=` constants, not data in memory).  IDK, consult the docs for PlaySound, and/or look for working C examples.
Comment: MASM32 already has `SND_ASYNC` defined in include/windows.inc. And there is at least one example in the examples directory that uses it.
Comment: if i were to rewrite this code after including windows.inc, can you guide me how I'd manage that since my code is giving me a ridiculous amount of errors the minute i include windows.inc
Answer: You need to add SND_ASYNC flag additionally.

The sound is played asynchronously and PlaySound returns immediately
after beginning the sound. To terminate an asynchronously played
waveform sound, call PlaySound with pszSound set to NULL.

In MASM32, you need to OR their binary bits, so your function arg has both bits set like SND_ASYNC | SND_FILENAME in C.
#define SND_ASYNC           0x0001
#define SND_FILENAME    0x00020000L

Code Sample:
.model flat, stdcall
option casemap: none

include windows.inc
include kernel32.inc
include user32.inc

includelib kernel32.lib
includelib user32.lib
includelib Winmm.lib

PlaySoundA PROTO,
        pszSound:PTR BYTE,
        hmod:DWORD,
        fdwSound:DWORD

.data
file BYTE "t.wav",0

szCaption   db  "Hello", 0
szText      db  "Hello World!", 0

.code
main PROC
     INVOKE PlaySoundA, OFFSET file, NULL, 20001H      ; SND_ASYNC | SND_FILENAME
     INVOKE MessageBox, NULL, addr szText, addr szCaption, MB_OK
     INVOKE ExitProcess, 0
main ENDP

END main

Comment: Interesting problem,

I was having a "constant expected" issue in winextra.inc, the original code had: alrt_eventname WCHAR  [EVLEN + 1] dup(?),   alrt_servicename WCHAR [SNLEN + 1] dup(?) in the STD_ALERT struct which i fixed by removing the brackets.
 However when your code finally worked it only works for the duration of the message display box and doesn't stop until the message box has been removed.
I just wanted an implementation where I could continue to push register values and do the other masm working while the music plays in the background
Comment: In asm you should be able to define constants with `=` and then combine them with `|` in the source, just like in C.  No need to hard-code an opaque `20001H` magic constant, especially without a comment.
Comment: Thanks for this!!! I just figured out the SND_ASYNC value this morning when I printed "printf("%x", SND_FILENAME | SND_ASYNC);" which gave 20001H just like you are using (didn't know they were both being AND) , but when I ran the code INVOKE PlaySound, OFFSET file, NULL, 20001H myself it didn't play any sound, will try to run your code with the additional libraries then update.
Guess it wouldn't work properly with just the Irvine library
Comment: @SatokoEntertainMent `MessageBox` is just an example (delete it at any time), to show that you can play wav files and pop up dialog box at the same time. You can add other operations that need to be completed below the `PlaySoundA` code.
Comment: @SatokoEntertainMent You can also pause it at any time, using `INVOKE PlaySoundA, NULL, NULL, 20001H`


How do I fix "The term 'sh' is not recognized as the name of a cmdlet, function, script file, or operable program." while installing k3s?

Question: I am new to kubernetes and docker. I have been trying to install k3s on my Windows 10 system with the command mentioned on the website:
curl -sfL https://get.k3s.io | sh -

I already have minikube, kubectl and docker installed on my system, and all work as expected.
However, when I run the above command, I get the following error message:
sh : The term 'sh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:32
+ curl -sfL https://get.k3s.io | sh -
+                                ~~
    + CategoryInfo          : ObjectNotFound: (sh:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

What am I doing wrong here?
Comment: according to your tags you are running on windows. sh stands for shell. sh and bash (borne again shell) are used on linux and not available on windows by default.
Answer: For the time being k3s doesn't support Windows, but there is an open issue on Github you can track.
The installation script you are trying to run, simply won't work on Windows machine. If you take a closer look at the installation requirements section in the very same documentation, you will see the following information, regarding to the supported Operating Systems:

Operating Systems
K3s is expected to work on most modern Linux systems.
Some OSs have specific requirements:

If you are using  Raspbian Buster, follow  these steps
to switch to legacy iptables.
If you are using  Alpine Linux, follow  these steps
for additional setup.
If you are using  (Red Hat/CentOS) Enterprise Linux, follow  these
steps
for additional setup.

For more information on which OSs were tested with Rancher managed K3s
clusters, refer to the  Rancher support and maintenance
terms.

So for running k3s on Windows you would need a Linux VM which can be provisioned using a hypervisor like Hyper-V or VirtualBox that can be run on your Windows host.
Take a look at the following article that presents how it can be done by using Hyper-V:
Rancher 2.4 & Kubernetes on your Windows 10 laptop with multipass & k3s — Elasticsearch/Kibana in minutes!
Comment: Thank you so much! Helped me understand really well.


Optimize SOLR Highlighter

Question: I am attempting to optimize highlighting in my SOLR instance as this seems to slow down queries by 2 orders of magnitude. I have a tokenized field index and stored with following definition:
<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="\+" replacement="%2B"/>
    <tokenizer class="solr.UAX29URLEmailTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrements="true" />

    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="\+" replacement="%2B"/>
    <tokenizer class="solr.UAX29URLEmailTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrements="true" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

Term vectors etc are also generated:
<field name="Events" type="text_general" multiValued="true" stored="true" indexed="true" termVectors="true" termPositions="true"  termOffsets="true"/>

For the highlight component I use the default SOLR config. The query I try uses FastVectorHighlighter but still takes ~1500ms, which is awfully long for ~1000 docs with 10-20 values stored in the field per doc. Here is the query:
q=Events:http\://mydomain.com/resource/term/906&fq=(Document_Code:[*+TO+*])&hl.requireFieldMatch=true&facet=true&hl.simple.pre=&hl.fl=*&hl=true&rows=10&version=2&fl=uri,Document_Type,Document_Title,Modification_Date,Study&hl.snippets=1&hl.useFastVectorHighlighter=true

What I find curious is that in the solr admin stats a single query generates 9146 requests to HtmlFormatter and GapFragmenter. Any thoughts on why this might be happening and how the performance of the highlighter can be improved?
Comment: I am using Solr 3.6 running on Tomcat 7.0.28
Comment: Running the same query on a similar field that does not have termVectors enabled shows no significant difference in response time.
Answer: It appears that the problem is caused by "hl.fl=*", which caused the DefaultSolrHighlighter to iterate over a relatively large number of fields (in my index) for each document found (10 max  in my case). This causes the additional O(n^2) time. Here is the relevant code snippet:
for (int i = 0; i < docs.size(); i++) {
  int docId = iterator.nextDoc();
  Document doc = searcher.doc(docId, fset);
  NamedList docSummaries = new SimpleOrderedMap();
  for (String fieldName : fieldNames) {
    fieldName = fieldName.trim();
    if( useFastVectorHighlighter( params, schema, fieldName ) )
      doHighlightingByFastVectorHighlighter( fvh, fieldQuery, req, docSummaries, docId, doc, fieldName );
    else
      doHighlightingByHighlighter( query, req, docSummaries, docId, doc, fieldName );
  }
  String printId = schema.printableUniqueKey(doc);
  fragments.add(printId == null ? null : printId, docSummaries);
}

Reducing the number of fields should improve the behaviour greatly. However, in my case I cannot reduce it bellow 20 fields, so I will check whether enabling the FastVectorHighlighter for all of them will improve the overall performance.
I was also wondering whether we could reduce this list even further by using some info from the matching docs (which are already available at this point).
Update
Using FastVectorHighlighter for all fields (set termVectors, termPositions and termOffsets to true for all tokenized fields) did indeed improve the highlighting speed by an order of magnitude, so that now all queries run < 1s. The size of the index increased by 3 times its original value (from 500M to 2G). There is also a problem with how the fragments for multivalued fields are generated, but the improvement of performance is high enough.
Comment: Beware that there seems to be a range of issues with the highlighting in 3.6. In addition to the problem with multivalued fields, numeric fields seem to be automatically ignored by the highlighter (https://issues.apache.org/jira/browse/SOLR-3050) and date range queries cannot be evaluated at all (https://issues.apache.org/jira/browse/SOLR-3704).

Optimize SOLR Highlighter


Proof of irrationality of a series

Question: Given the series
$$S=\sum_{k=1}^N\frac{1}{k^q}$$
$(q\gt0),(N\in\mathbb{N},N\ge1)$
is $S$ irrational for every choice of $q$ and $N$? Thanks.
Comment: Are you missing something? If $q\in\mathbb{N}$, then $S$ is rational.
Comment: The question might be better if you asked if there are any non-integer reals $q$ making the sum rational.
Comment: @Casteels: $q\in\mathbb{R}$
Comment: Do you mean $q\in\mathbb{R}\setminus\mathbb{Z}$?
Comment: I fully support coffeemath's suggestion. May be you could rephrase and precise this interesting question.
Answer: $S$ is a continuous function of $q$, which is rational for integer values of $q$. So it can't possibly be irrational for all non-integer values of $q$.
Comment: +1 very nice, simple, straighforward yet not trivial argument :)
Answer: For fixed $N$ the value of $S$ is a continuous function of the real number $q$, so one can just choose some rational number $r$ and then let $S=r$ and there will exist a $q$, provided $r$ is in the right range.
I think you can rescue the result provided one restricts $N \ge 2$ and $q$ to be a positive non-integral rational number. If $q=r/k$ with $k>1$ then for the case $N=2$ one can use that $2^{1/k}$ is irrational, and for larger $N$ then a collection of distinct primes each raised to the power $1/k$ are rationally independent. [That last claim I've seen somewhere but don't have details handy.]
It now seems better to use that $2^{r/k}$ is irrational, and that a collection of distinct primes each raised to the power $r/k$ are rationally independent. The drawback on getting rid of the numerator of the rational $r/k$ is that then one is working with powers of supposed irrationals, which are not immediately seen to be irrational / independent (though they are in this case).
Answer: This does not fully answer the question but it could help (I hope). Since $$S=\sum_{k=1}^n\frac{1}{k^q}=H_n^{(q)}$$ let us consider the case of rational values of $q$ and set $q=\frac{a}{b}$. In such a case, we have the identity $$H_n^{\left(\frac{a}{b}\right)}=\zeta(n)-b^n \sum_{k=1}^\infty \frac {1}{(a+bk)^n}$$ Should we then address the problem of the rationality of function $\zeta(n)$ ?

Proof of irrationality of a series


VMM 2012 Self Service Users and VLAN tagging

Question: I have a Production network in VMM 2012 that has a trunk from the managed ProCurve switch (running VLANs) to the guest VM nic. The connection from switch to Hyper-V guest network is a trunk carrying VLANs 69 and 200. I initially created the Fabric Logical Network as below.

Viewing the same machine as a self service user, I am unable to select the VLAN and can only select the adapter. I understand self service users cannot set VLANs.
So I instead went back and created the VLANs under the same network site:

I then added a new VM Network. Below is a screenshot of the Data subnet being added, i repeated for Server and Voice subnets so each had their own VM network:

Then when adding a new VM as a guest, I see the site is in the drop down list (one and only one site is listed here, in this case Data_0). Selecting this automatically ticks the VLAN with the correct ID:

With the above, i would need to add a separate VM Network for each site. Whilst this extra work isn't a problem, I need to check:

Is this is the correct way of doing things (adding one VM network per network subnet)?
For the VM Guest hardware NIC properties, why is there a drop down list for the VM Subnet when I can only add one site to a VM network anyway?
For the VM Subnet properties of the VM Network, is it normal to not be able to add more than one VM subnet to a VM Network?
Answer: One thing to check is scope: the user role, logical network definitions, host groups etc all need to match up on scope so they all come together. When it comes to VLANs, my understanding of logical network definitions is that these are meant to allow users to pick something with a friendly name and not have to understand the VLANs that exist underneath--so you should strive to hide the VLANs from the user and just have them select a network that logically makes sense for the purpose.
Have you had a chance to review these two resources on TechNet? Pretty comprehensive, though tough to wrap the brain around:
http://technet.microsoft.com/en-us/library/jj721568.aspx
http://technet.microsoft.com/en-us/library/jj983727.aspx
Hope that helps.


how to receive a stored procedure's result using object context?

Question: I have a stored procedure and I am working in VS10 entity framework. I want to call that stored procedure from my DAO but don't know how to receive the results. Anybody give idea please?
ConsentReleaseResult consentReleaseResult = new ConsentReleaseResult();
        try
        {
            using (PC2Entities objectContext = new PC2Entities())
            {
                var consent = objectContext.spGetConsentRelease(id);
            }
        }
        /* Handling Error Logging */
        catch (Exception exception)
        {
        }

I want to receive my result in "consentReleaseResult object".
var consent = objectContext.spGetConsentRelease(id); throws an exception. Please guide me!
Comment: The data reader is incompatible with the specified 'PC2Entities.ConsentRelease'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.
Comment: You need to accept answers to your previous questions, that will improve it
Comment: pls answer my original question
Comment: I Hope [This helps you](http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/3ccc1f17-589d-46ef-8df8-ab48abe2dfee) and [This too](http://stackoverflow.com/questions/1227130/problem-with-entity-framework-after-adding-column-to-db-table)
Comment: Is your result an output parameter or a result set?
Comment: please see the code I posted in the answer below.
Answer: You can get the results from following syntax
 if (consent != null)
 {
     foreach(var r in consent)
     {
           r.[fieldname]
     }
 }

If your store procedure returns full table value then you can get the records as
foreeach(tablename r in consent)
{
    r.[fieldname]
}


Providing a closed formula for a linear recursive sequence

Question: I am studying for an exam in linear algebra and I have some trouble solving the following:
Let $(a_n)$ be a linear recursive sequence in $\mathbb{Z}_5$ with
\begin{align}
a_0 = 2, a_1 = 1, a_2 = 0 \text{ and } a_{n+3} = 2a_{n+2} + a_{n+1} + 3a_n \text{ for }  n \in \mathbb{N}_0
\end{align}
Provide a closed formula for $a_n$.
My findings so far:
$
\begin{pmatrix} a_{n+3}  \\ a_{n+2} \\ a_{n+1} \\ \end{pmatrix}
   = \begin{pmatrix} 2 & 1 & 3  \\1 & 0 & 0  \\ 0 & 1 & 0 \\ \end{pmatrix} \cdot \begin{pmatrix} a_{n+2}  \\ a_{n+1} \\ a_{n} \\ \end{pmatrix}
$
$
\begin{pmatrix} a_{n}  \\ a_{n+1} \\ a_{n+2} \\ \end{pmatrix}
   = A^n \cdot \begin{pmatrix} a_{0}  \\ a_{1} \\ a_{2} \\ \end{pmatrix} = A^n \cdot \begin{pmatrix} 2  \\ 1 \\ 0 \\ \end{pmatrix}
$
At some point there must hold the following:
\begin{align}
T^{-1}AT = D = \begin{pmatrix} c_1 & 0 & 0  \\0 & c_2 & 0  \\ 0 & 0 & c_3 \\ \end{pmatrix}
\end{align}
such that D is a diagonal matrix containing all Eigenwerte $c_i$, $i \in {\{1,2,3} \}$  of $A$.
How shall I continue to find the matrix $A$?
Comment: [Here](http://en.wikipedia.org/wiki/Diagonalizable_matrix) is an example for how to diagonalize a matrix. By the way, there is another technique for solving such kind of recurrence relations.
Comment: http://en.wikipedia.org/wiki/Linear_recursive_sequence#Linear_homogeneous_recurrence_relations_with_constant_coefficients
Comment: Alternatively start from the observation  that the sequence is periodic
Answer: $$\begin{pmatrix}a_{n+3}\\a_{n+2}\\a_{n+1}\end{pmatrix}=\begin{pmatrix}2&1&3\\1&0&0\\0&1&0\end{pmatrix}\begin{pmatrix}a_{n+2}\\a_{n+1}\\a_n\end{pmatrix}=\ldots=\begin{pmatrix}2&1&3\\1&0&0\\0&1&0\end{pmatrix}^n\begin{pmatrix}2\\1\\0\end{pmatrix}$$
Now:
$$\det(tI-A)=\begin{vmatrix}t-2&-1&-3\\
-1&t&0\\
0&-1&t\end{vmatrix}=t^2(x-2)-3-t=(t^2-1)(t+3)\in\left(\Bbb Z/5\Bbb Z\right)[x]$$
Thus, the eigenvalues of the matrix are $\,-1,1,-3 = 1,2,4\pmod 5\;$:
$$\begin{align*}\lambda=1:& \implies \begin{cases}4x-y-3z=0\\{}\\4x+y=0\\{}\\4y+z=0\end{cases}\implies z=y=x\implies& \begin{pmatrix}1\\1\\1\end{pmatrix}\\{}\\
\lambda=2:&\implies\begin{cases}-y-3z=0\\{}\\-x+2y=0\\{}\\-y+2z=0\end{cases}\implies z\;,\;y=2z\;,\;x=4z\implies&\begin{pmatrix}4\\2\\1\end{pmatrix}\\{}\\
\lambda=4:&\implies\begin{cases}2x-y-3z=0\\{}\\-x+4y=0\\{}\\-y+4z=0\end{cases}\implies z\;,\;y=4z\;,\;x=3z\implies&\begin{pmatrix}3\\4\\1\end{pmatrix}\end{align*}$$
The above are corresponding eigenvectors to the corresponding eigenvalues, so now form the matrix:
$$P=\begin{pmatrix}1&4&3\\1&2&4\\1&1&1\end{pmatrix}$$
Find the matrix's inverse and then you'l get
$$P^{-1}AP=\begin{pmatrix}1&0&0\\
0&2&0\\0&0&4\end{pmatrix}=:D\implies P^{-1}A^nP=D^n $$
and this way you'll be able to solve your problem since exponentiating a diagonal matrix is a piece of cake... and don't forget to carry on arithmetic modulo $\,5\,$ all along!
Answer: Hint: Use elementary row operations on your matrix $A$. You shall get identity matrix as $D$. Represent $T$ by elementary matrixes


prove that $\frac{n!}{n^n}\le(\frac{1}{2})^k$ where $k=[\frac{n}{2}]$, the greatest integer $\le\frac{n}{2}$

Question:
1) For $n\ge 2$, prove that $\frac{n!}{n^n}\le(\frac{1}{2})^k$ where $k=[\frac{n}{2}]$, the greatest integer $\le\frac{n}{2}$.
  2) Deduce the value of $\underset{n\rightarrow\infty}{\lim}\frac{n!}{n^n}$.
  3) Show that the series $\underset{n=1}{\overset{\infty}{\sum}}\frac{n!}{n^n}$ is convergent and again deduce $\underset{n\rightarrow\infty}{\lim}\frac{n!}{n^n}$.

My attempt

$\forall n\in\mathbb{N}$
$1<1+\frac{1}{n}\le 2\Rightarrow 1>\frac{1}{1+\frac{1}{n}}\ge \frac{1}{2}\Rightarrow 1>\frac{1}{(1+\frac{1}{n})^n}\ge \frac{1}{2^n}$
$\Rightarrow 1>\frac{a_{n+1}}{a_n}\ge\frac{1}{2^n}\Rightarrow a_n\ge a_{n+1}\ge\frac{a_n}{2^n}$
Using induction we eventually get, $a_1\ge a_n\ge\frac{a_1}{2^{\frac{n(n-1)}{2}}}\Rightarrow 1\ge a_n\ge\frac{1}{2^{\frac{n(n-1)}{2}}}$
Using Sandwich theorem, we get $\underset{n\rightarrow\infty}{\lim}a_n=1$.

I couldn't get the required bound for $\frac{n!}{n^n}$ although, with or without using the result from 1 I can conclude the limit to be $1$.
  I did get an answer to my doubt at https://math.stackexchange.com/a/1226238/562589 but I couldn't understand how they concluded $\frac{k}{n}\frac{k-1}{n}...\frac{1}{n}\le(\frac{1}{2})^k$.

Let $a_n=\frac{n!}{n^n}$.
Then, $\frac{a_{n+1}}{a_n}=\frac{(n+1)!}{(n+1)^{n+1}}\cdot\frac{n^n}{n!}=(\frac{n}{n+1})^n=\frac{1}{(1+\frac{1}{n})^n}$
$\Rightarrow\underset{n\rightarrow\infty}{\lim}\frac{a_{n+1}}{a_n}=\underset{n\rightarrow\infty}{\lim}\frac{1}{(1+\frac{1}{n})^n}=\frac{1}{e}<1\Rightarrow\underset{n=1}{\overset{\infty}{\sum}}\frac{n!}{n^n}$ is convergent

I am not sure how to use this to deduce $\underset{n\rightarrow\infty}{\lim}\frac{n!}{n^n}$ differently(?) than done before.
Comment: @KevinSong I did, thanks for your effort! I liked the method you used and will make use of it next time!
Answer: Q(2):
$$\dfrac{n!}{n^n}=\dfrac{1}{n^{n-1}}\times\dfrac{n-1}{n^n}\times...\times\dfrac{1}{n^n}$$
Apply L'Hopital's rule to each term, and Since every term in this expression can form a convergent sequence with limit equal to $0$. And:$$\lim_{n\to\infty}(s_nt_n)=\lim_{n\to\infty}(s_n)\lim_{n\to\infty}(t_n)$$ So:
$$\implies \lim_{n\to\infty}\dfrac{n!}{n^n}=0$$
Q(3)
You used the ratio test to conclude that $\sum(a_n)$ converges
We know that:$$\lim_{n\to\infty}\inf|\dfrac{a_{n+1}}{a_n}|\le\limsup|a_n^{1/n}|\le\limsup|\dfrac{a_{n+1}}{a_n}| (*)$$exists,because$\dfrac{a_{n+1}}{a_n}=\dfrac{1}{e}<\infty$.
So $(*)<\infty$.
$$\implies\lim(a_n)<\infty$$ Hence that limit exists, then we can evaluate that value an therefore prove that it is less than $[\frac{n}{2}]$.
Answer: If $n$ is even, the first $\frac n2$ factors of $$\frac {1\cdot 2 \cdot 3 \ldots n}{n^n}$$ are less than or equal to $\frac 12$ and the rest are less than or equal to $1$, so the fraction is less than or equal to $\left(\frac 12\right)^{n/2}$.  If $n$ is odd we just need to account for one more factor $\frac 12$.  Note that $\frac {3!}{3^3}=\frac 6{27}\lt \left(\frac 12\right)^2$ and for any $n$ higher than $3$ the first term is less than $\frac 14$ which gives one more factor $\frac 12$ and we are done.


Boundary of Closure

Question: Let $X$ be a topological space. I know it is not generally true $\partial A=\partial{\overline {A}}$ for every $A\subset X$. I found it is true if $A$ is a closed ($A=\overline A)$or regularly open set($A=A^{o}=(\overline A)^{o}$). Any other subset of $X$ with different properties satisfying $\partial A=\partial{\overline {A}}$?  Is it generally true $(\partial A)^o=\emptyset$ for all $A\subset X$? Thank you. Notation: $\partial A=$ Boundary points of $A$ $\overline A=$ Closure of $A$$A^{o}=$Interior of $A$
Comment: Since $\partial A = \overline{A} \cap \overline{A^c}$ and $\partial \overline{A} = \overline{A} \cap \overline{\overline{A}^c}$, you can see that you need to look for sets for which the containment $\overline{\overline{A}^c} \subset \overline{A^c}$ is strict.
Answer: It is not generally true that boundaries have empty interior.  In $\mathbb R$ (with the usual topology), the boundary of $\mathbb Q$ is all of $\mathbb R$.
Comment: Indeed $\partial \mathbb{Q}  = \mathbb{R}$, but $\partial \overline{\mathbb{Q}}  = \partial \mathbb{R} = \emptyset$. So this is an answer to both questions.
Answer: As for all possible equations $\xi_1(A)=\xi_2(A)$ where the $\xi_i$ are each formed by composing the boundary, closure, interior, and complement operators any number of times in any order the answer to your first question "Any other subset of $X$ with different properties satisfying $\partial A=\partial{\overline {A}}?$" turns out to be "no" up to trivial substitutions such as $A^{o}=X\setminus\overline{(X\setminus A)}.$
The proof is long. Most of it appears in a paper I will be posting within the next several weeks (my last-minute literature search is what brought me here).
Also, note that
$$\partial A=\partial{\overline {A}}\iff A^{o}={\big(\,\overline A\,\big)}^{o}\iff{\big(\,\overline A\,\big)}^{o}\subseteq A\iff\partial A\subseteq X\setminus{\big(\,\overline A\,\big)}^{o}.$$

Boundary of Closure


varnish configuration with apache domains

Question: I have istalled Varnish on Debian.
I have a website running on Apache on http://example.com
Here's my /etc/varnish/default
vcl 4.0;
backend default {
    .host = "example.com";
    .port = "8080";
 }

Varnish starts, I can see the content of the website at http://127.0.0.1:6081/
Response headers:
Pragma: no-cache
Date: Tue, 25 Aug 2015 12:29:38 GMT
Content-Encoding: gzip
Server: Apache/2.4.10 (Ubuntu)
Age: 0
X-Powered-By: PHP/5.6.4-4ubuntu6.2
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
Via: 1.1 varnish-v4
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
X-Varnish: 229436
Connection: keep-alive
Accept-Ranges: bytes
Content-Length: 23044
Expires: Thu, 19 Nov 1981 08:52:00 GMT
200 OK

How can I make this visible under http://example.com ?
How to configure Varnish and Apache vhost?
Answer: In your /etc/hosts file, add example.com and any other vhost name on the 127.0.0.1 IP. When varnish accesses "example.com" it will be resolved to 127.0.0.1, but the correct hostname header will follow with the request to apache, which in its turn will be able to map it to the correct vhost. No special configuration should be needed in apache nor varnish, just configure vhosts as normal in apache.
Comment: I have example.com already in my hosts file. example.com:8080 works fine (not cached version) but example.com (on 80 port does not).
Comment: https://www.varnish-cache.org/docs/trunk/tutorial/putting_varnish_on_port_80.html


SSH'ing into Windows VirtualBox with Vagrant

Question: I am running vagrant 1.3.5 on OSX 10.9. I have a Windows Server 2008 VM installed via VirtualBox. I am trying to set it up so I can ssh into Windows Server 2008 box using vagrant. The steps I am trying to take in order to do that are as follows.

Install Windows Server 2008 on virtual box
Install virtualbox guest additions
Install cygwin and openSSH
Create a vagrant box using vagrant package --base Server2008
Edit my VagrantFile to account for this new change

 config.vm.define "worker" do |worker|
    worker.vm.box = "windows.box"
    worker.vm.box_url = "~/boxes/windows.box"
  end

Lastly, call vagrant up, vagrant ssh.

I have completed all these steps. When I call vagrant up it says it is initializing the windows worker, I look in virtualbox and see that it is indeed running. It hangs here and I have to Ctrl+C to make it stop. When I call vagrant ssh it just hangs. What do I need to do to get ssh access to a windows virtual machine w/ vagrant?
Comment: open port 22 in the windows server firewall?
Comment: I love you @lain
Answer: Don't forget to open port 22 on you windows server instance.


Tabela em html com classes do excel

Question:

<!DOCTYPE html>

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

Gostaria de saber se existe classes pronta do bootstrap ou alguma outra biblioteca que deixasse as tabelas com a formatação igual a do excel.
Comment: https://www.sitepoint.com/7-jquery-microsoft-excel-type-plugins/
Comment: como assim igual ao excel?
Comment: font padrão do excel as linhas pretas entre as linhas e colunas
Answer: Você pode usar este framework :
https://www.sitepoint.com/7-jquery-microsoft-excel-type-plugins/
Ele não necessáriamente é somente classes css como o bootstrap, mas vai muito alem:

Colunas redimensionáveis
Cabeçalhos de estilo Excel que o usuário ou o programador podem ocultar
Pode ser exibido no modo zebra-striped para melhor apresentação
Os dados podem ser passados para inicializar a planilha
O usuário ou o programador podem adicionar e excluir linhas e colunas
Ao contrário de outras planilhas, exiba apenas quantas linhas e colunas você precisa.
Adicione ou exclua-os no seu script conforme necessário, ou permita que um usuário o faça.
Os dados podem ser excluídos, copiados e colados, de / para uma
  única célula ou uma linha inteira, dentro de uma planilha ou entre
  múltiplas planilhas Interação do teclado (teclas Ctrl + C, Ctrl + V,
  Enter e Tab / Shift + Tab) Os dados podem ser recuperados em uma
  matriz bidimensional de cordas Múltiplas planilhas podem ser exibidas
  em uma página API totalmente exposta

Um exemplo de código feito com ele:
Ao invés de uma tabela no seu html, você terá que inserir uma DIV:

O segredo de como ele irá se comportar está no código javascript:
    $(document).ready(function () {
         var aData = [ [ "Redwood City", "300", "true" ], [ "San Francisco", "100", "true" ], [ "San Jose", "500", "false" ] ];
         var oTable = $( "div#contents" ).spreadsheet(
          { rows: 0, cols: 0, data: aData, zebra_striped: true, read_only: false, rowheader: true, colheader: true } );
         oTable.setNumeric( 1, true );
         $( "div#contents2" ).spreadsheet(
          { rows: 10, cols: 10, data: null, zebra_striped: false, read_only: false, rowheader: true, colheader: true } );
    } );

Cada parâmetro desse faz algum tipo de ação ao inicializar o framework
  na div "contents"

Para mais informações de parâmetros veja na documentação:
https://github.com/TanyaWebDesign/SpreadSheet
Vale lembrar que ele depende do framework jQuery.

Tabela em html com classes do excel


Binomial to Poisson Approximation

Question:
So, a little context. The image you see is from the GCE A-LEVEL syllabus where they have defined the conditions for approximating binomial to poisson.
But why did they have mention that the approximation is only possible when n > 50 and np/mean < 5? What is special about these two conditions? Is there a graphical or a proof-based reason?
THANK YOU FOR THE ANSWER(S)
Comment: "Possible" and "appropriate" don't mean the same thing.
Answer: That should be $np\geq 5$ and $n(1-p) \geq 5$ for any approximation to be taken on Binomial Distribution. The approximation can be attributed to Central Limit Theorem.
This type of approximation is defended in another way also. Binomial distribution has PMF:
$$ f(X = x) = nCx~ p^x (1-p)^{n-x} $$ with $x = 0, 1, \ldots, n$.
Now when $n \rightarrow \infty$ and $p \rightarrow 0$ the computing the quantity $nCx$ becomes cumbersome and $p^x$ and $(1-p)^{n-x}$ also become unnecessarily cumbersome. Then assuming $np = \lambda$ it becomes the mean of Poisson Distribution and the quantity $np(1-p) \rightarrow np$ as $1-p \rightarrow 1$ i.e. variance of the Binomial Distribution becomes the Variance of Poisson Distribution.
This is how the Binomial Distribution is approximated as Poisson Distribution. Binomial Distribution can be approximated as a Normal Distribution too.
Comment: Although these points are correct, neither really explains why "50" and "5" appear in the rule of thumb quoted in the question.
Comment: @whuber surely it comes from the same line of arguments that produced the fact that the sample mean is normal whenever $n\geq30$ ;)
Answer: Going by Prof G E P Box's quote "in statistics no model is perfect but some are useful", modeling data using Probability Distributions also fits this quote very well, one can use any distribution anywhere if the constraints based on assumptions are relaxed - but the estimation error will be varying depending upon what approximation is being used. These numbers like $50$, $5$ they are decided based on simulated runs on real data. Earlier not even 10 years back, it used to be $30$ as the number of samples which was used for Normal distribution to be assumed for any distribution. Generally speaking Statistics always prefer "More the Better". But these are all sample based Statistical methodology if we enter into Big Data then almost all the concepts of Statistics starting from Hypothesis Testing, Confidence Interval Estimation etc severely fail.

Binomial to Poisson Approximation


A sort of inverse question in topology

Question: Given topological spaces $X$ and $Y$, we often consider the collection of continuous functions, $f: X \rightarrow Y$. My question is, given two sets $X$ and $Y$, and a sub-collection $\{g_{i}\}$ of the collection of all functions from $X$ to $Y$, do there exist topologies on $X$ and $Y$ so that the $g_{i}$ are precisely the continuous functions from $X$ to $Y$?
I have a few thoughts on this, if $\{g_{i}\}$ is the entire collection of functions from $X$ to $Y$, then we can give $X$ the discrete topology and give $Y$ any topology and the result follows. If $\{g_{i}\}$ is just the constant functions (which are always continuous) then we can give $Y$ the indiscrete topology and give $X$ any topology and the result follows. Aside from these two trivial cases, is there anything we can say about this question? Assume that $\{g_{i}\}$ contains the constant functions.
Comment: If you pick any topology on $Y$, then there is a smallest topology on $X$ such that the $g_i$ are all continuous (the one generated by all preimages of open sets in $Y$ under the $g_i$). As Cameron points out, there may then be extra continuous functions between $X$ and $Y$. What isn't immediately clear to me (but I'd be interested to know) is what conditions you need on the set $\{g_i\}$ such that this doesn't happen; this could easily depend on the choice of topology for $Y$. Alternatively, are there conditions on the $g_i$ giving a unique topology on $X$ *and* $Y$ so they're continuous.
Comment: A related question: http://math.stackexchange.com/q/382690/56914
Comment: Also related: http://math.stackexchange.com/questions/427634/a-topology-such-that-the-continuous-functions-are-exactly-the-polynomials#427634
Answer: There need not be any such topologies in general. You've noted, for example, that all constant functions are continuous, so if your sub-collection of functions does not have all constant functions as elements, then we're out of luck in topologizing $X$ and $Y$ in the desired fashion.
There may be other necessary conditions on your subcollection to determine such topologies on $X$ and $Y$. I'll think on it.
Added: It occurred to me (very belatedly, of course) that this answer to a prior question of my own gives a very important necessary condition for such a topology to exist, if we are considering self-maps (meaning $X$ and $Y$ are the same topological space). Namely, the sub-collection of functions in question must be closed under finite compositions, i.e.:  given elements $f,g$ of the sub-collection, $f\circ g$ is also an.element.
Comment: Of course, I meant to say that. I've edited the question appropriately.
Answer: Assume $Y$ only consists of two points $Y=\{a,b\}$. There are effectively three choices for a topology on $Y$. Let us assume we don't have the indiscrete and not the discrete topology, so wlog the open sets are precisely $Y$, $\emptyset$ and $\{a\}$. Now every $g_i$ must be continuous, in other words $g_i^{-1}(a)$ has to be open. So the collection $\{g_i\}$ is the same as a subbasis of $X$. Conversely every open set $O$ in the topology of $X$ gives you a continuous function $g:X\to Y$ with $g(O)=\{a\}$ and $g(X-O)=\{b\}$.
So in this case you are asking if any subbasis of a topology is already a topology.
I guess if $Y$ is bigger the situation will get worse.
Comment: What do you mean when you say the $\{g_{i}\}$ are a subbasis of $X$. Do you mean $\{g_{i}^{-1} (a)\}$?
Comment: Yes, there is a one to one correspondence of the family of functions $\{g_i\}$ and the collection of sets $\{g_i^{-1}(a)\}$.

A sort of inverse question in topology


Can I suppress selected input before the application's main loop?

Question: As part of my Visual Studio utilities add-in SamTools, I have a mouse input routine that catches Ctrl+MouseWheel and sends a pageup/pagedown command to the active text window. Visual Studio 2010 added a new "feature" that uses that gesture for zoom in/out (barf). Currently, my add-in does send the scrolling command, but Visual Studio still changes the font size because I'm not eating the input.
I set my hook with a call to SetWindowsHookEx. Here's the callback code. My question is: is the best way to prevent Visual Studio from handling the Ctrl+MouseWheel input as a zoom command to simply not call CallNextHookEx when I get a mouse wheel event with the Ctrl key down?
(Please bear in mind this is some old code of mine.) :)
private IntPtr MouseCallback(int code, UIntPtr wParam, ref MOUSEHOOKSTRUCTEX lParam)
{
    try
    {
        // the callback runs twice for each action - this is the latch
        if (enterHook)
        {
            enterHook = false;
            if (code >= 0)
            {
                int x = lParam.mstruct.pt.X;
                int y = lParam.mstruct.pt.Y;

                uint action = wParam.ToUInt32();
                switch (action)
                {
                case WM_MOUSEWHEEL:
                    OnMouseWheel(new MouseEventArgs(MouseButtons.None, 0, x, y, ((short)HIWORD(lParam.mouseData)) / (int)WHEEL_DELTA));
                    break;

                default:
                    // don't do anything special
                    break;
                }
            }
        }
        else
        {
            enterHook = true;
        }
    }
    catch
    {
        // can't let an exception get through or VS will crash
    }

    return CallNextHookEx(mouseHandle, code, wParam, ref lParam);
}

And here's the code that executes in response to the MouseWheel event:
void mouse_enhancer_MouseWheel( object sender, System.Windows.Forms.MouseEventArgs e )
{
    try
    {
        if ( Keyboard.GetKeyState( System.Windows.Forms.Keys.ControlKey ).IsDown && Connect.ApplicationObject.ActiveWindow.Type == vsWindowType.vsWindowTypeDocument )
        {
            int clicks = e.Delta;
            if (e.Delta < 0)
            {
                Connect.ApplicationObject.ExecuteCommand( "Edit.ScrollPageDown", "" );
            }
            else
            {
                Connect.ApplicationObject.ExecuteCommand( "Edit.ScrollPageUp", "" );
            }
        }
    }
    catch ( System.Runtime.InteropServices.COMException )
    {
        // this occurs if ctrl+wheel is activated on a drop-down list. just ignore it.
    }
}

PS: SamTools is open source (GPL) - you can download it from the link and the source is in the installer.
PSS: Ctrl+[+] and Ctrl+[-] are better for zooming. Let Ctrl+MouseWheel scroll (the vastly more commonly used command).
Answer: According to MSDN, it's possible to toss mouse messages that you process. Here's the recommendation:

If nCode is less than zero, the hook
  procedure must return the value
  returned by CallNextHookEx.
If nCode is greater than or equal to
  zero, and the hook procedure did not
  process the message, it is highly
  recommended that you call
  CallNextHookEx and return the value it
  returns; otherwise, other applications
  that have installed WH_MOUSE hooks
  will not receive hook notifications
  and may behave incorrectly as a
  result. If the hook procedure
  processed the message, it may return a
  nonzero value to prevent the system
  from passing the message to the target
  window procedure.

In other words, if your mouse callback ends up using the mouse message, you don't have to call the next CallNextHookEx -- just return a nonzero value and (in theory, at least) the mouse movement should get swallowed.  If that doesn't work the way you want, comment and we can iterate.
BTW, another possible alternative: it's possible that VS's mapping to the mouse wheel shows up in the Tools...Customize... UI, just like key mappings do.  In that case, you could simply remap your add-in's commands instead of working at the hook level. But it's also posible (likely?) that this gesture is hard-coded.
Comment: Unfortunately mouse commands don't show in the customize options.


"There exists ♦" $\quad$ vs $\quad$ "... for some ♦"

Question:
Analyse the logical form of:  $X \in \bigcup\{P(A) : A \in \mathcal{F}\}$.
Solution : This time start by writing out the definition of union. Then the statement  above means that $X$ is an element of at least one of the
  sets $P (A)$, for $A ∈ \mathcal{F}$. Ie: $∃ \, A ∈ \mathcal{F} \qquad  \; X ∈ P (A) \; . \tag{\checkmark}$
  Inserting our
  analysis of the statement $X ∈ P (A)$ from Example 2.3.3, we get $∃\, A ∈
\mathcal{F} \; \qquad ∀ \, y \,(y ∈ X → y ∈ A). \qquad \blacksquare$

The second sentence of the solution says: $X \in P(A), \color{green}{ \text{ for some $A \in \mathcal{F}$   }} \iff \color{green}{∃ \, A ∈ \mathcal{F}} \qquad  \; X ∈ P (A)$.
$1.$ Predicated on (the green part) of this question, I'm asking if in general:
$\text{ ... for some ♦ } \qquad$  is the same as $\qquad \text{ There exists ♦ } \qquad$
$2.$ What can ♦ be?
Supplementary dated Mar 9 2014:  Is there any mathematical proof that "there exists" and "for some" are synonyms? I can brook this equivalence concerning the English language, but I'm anxious about it for math, though I can't pinpoint why?
Comment: Would the downvoter please divulge his/her reasons?
Comment: "For some […]" is informal, while "$\exists" is formal. Of course it says the same thing. As for the second question, you might want to go back to basics : what is a formula in a given language ?
Comment: there is a moderator!
Answer: (1). Yes. (2) anything that fits the sentence, typically something of the form "$a \in X$" or "$a \in X$ such that $\dots$" (or just "$a$", or "$a$ such that $\dots$" if it's clear what set $a$ should be coming from anyway).
Comment: +1. Thank you very much. Would you please enlarge on $1.$ in your answer? How are these clauses equivalent? Why one instead of the other and vice versa?
Comment: You're welcome. There is not really anything to say more at (1) than "Yes". If you'd write out the statement in symbolic logic, they'd become literally the same. Which one to use is a matter of style, diversity in writing, preference.
Comment: Thank you again. Would you please explain how to express $\text{ ... for some ♦ }$ in symbolic logic, in your answer and not as a comment?
Comment: What do you mean? It is already expressed in symbolic logic in the question ($\exists A \in {\mathcal F}. X \in {\cal P}(A))$.
Comment: Thank you again. I beg leave for your patience. I'm still bewildered. Where exactly is $\text{ ... for some ♦ }$ expressed therein? I only see $\text{ There exists ♦ }$ therein, in the form $\exists \, A \in F$?
Comment: In the $\exists A \in {\cal F}$ as well. The phrases "there exists" and "for some" are synonyms.
Comment: Thank you again. Is there any mathematical proof that "there exists" and "for some" are synonyms? I'm aware of this truth in the English language, but I'm tentative about it for math, though I can't pinpoint why?


Mostrar icone do jquery-ui no botão fechar do widget dialog

Question: Eu estou personalizando a aparência do widget dialog do jquery-ui e até o momento meu css é o seguinte:
.ui-dialog {
  position: fixed;
  z-index: 1050;
  display: none;
  /*overflow: auto;*/
  /*overflow-y: scroll;*/
  /*-webkit-overflow-scrolling: touch;*/
  outline: 0;
}
.ui-dialog .ui-dialog-titlebar {
  min-height: 16.42857143px;
  padding: 15px;
  border-bottom: 1px solid #e5e5e5;
}
.ui-dialog .ui-dialog-title {
  margin: 0;
  line-height: 1.42857143;
}
.ui-dialog .ui-dialog-titlebar-close {
  margin-top: -2px;
  border: 1px solid black;
  background-color: transparent;
}
.ui-dialog .ui-dialog-content {
  position: relative;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #999;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 6px;
  overflow: auto;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  outline: none;
  -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
          box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.ui-dialog .ui-dialog-buttonpane {
    text-align: left;
    border-width: 1px 0 0 0;
    background-image: none;
    margin-top: .5em;
    padding: .3em 1em .5em .4em;
}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
    float: right;
}
.ui-dialog .ui-dialog-buttonpane button {
  position: fixed;
  z-index: 1040;
  background-color: #000;
}
.ui-dialog .ui-resizable-se {
    width: 12px;
    height: 12px;
    right: -5px;
    bottom: -5px;
    background-position: 16px 16px;
}

Isso é o que é exibido no momento:

O passo final para que eu possa conseguir a aparência desejada seria mostrar o icone .ui-icon-closethick dentro do botão fechar da janela. Alguém sabe como fazer isso?
Answer: Se voce estiver usando a mesma distribuição de ícones que a template do JQUI basta modificar a url da imagem images/ui-icons_888888_256x240.png .
.ui-icon-closethick {
    background-position: -96px -128px;
}

.ui-button-icon-only .ui-icon {
    left: 50%;
    margin-left: -8px;
}

.ui-state-default .ui-icon {
    background-image: url(images/ui-icons_888888_256x240.png);
}

.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon {
    position: absolute;
    top: 50%;
    margin-top: -8px;
}

.ui-icon {
    display: block;
    text-indent: -99999px;
    overflow: hidden;
    background-repeat: no-repeat;
}

Comment: Eu adicionei esse atributo ao meu css, mas ainda não aparece nenhuma imagem no botão (Aqui tem vários arquivos, com nomes no formato ui-icons_228ef1_256x240.png), que contem todos os icones da biblioteca. Como eu devo fazer para especificar somente o que eu quero?


Prove $f:\mathbb{R}^2\to B(0,1)$ s.t. $f(x)=x/(1+||x||)$ is continuous

Question: I am trying to prove that

$$\begin{align}f:\mathbb{R}^2&\to B(0,1)\\ f(x)&=\frac{x}{(1+||x||)}\end{align}$$
is a homeomorphism between $\mathbb{R}^2$ and $B(0,1)$.

I have proved that $f$ is bijective, but got stuck in proving that it is continuous. I am trying to use the theory that $f$ is continuous if and only if for every basis element $B$ of $B (0,1)$, $f^{-1}(B)$ is open in $\mathbb{R}^2$. Any suggestion would be helpful. Thank you.
Comment: It depends on what kinds of tools you have, but you could argue that the scalar-valued function $\alpha(x) = \frac{1}{\|x\| + 1}$ is continuous, and that $\alpha(x)x$ is continuous as a product of a continuous scalar function and a continuous vector function.
Answer: The easy way is in the comments.  Inverse image of basic set isn't too hard,  take a $B(y,\epsilon)$ where $y$ is in your open sphere,  there is a preimage $x$ of $y$,  so $y=\frac x {1 + \|x\|}$.  A point within some $\delta$ of $x$ can be written as $x+\delta v$,  where $v$ is a unit vector showing the direction from $x$.  $$f(x+\delta v)=\frac {x + \delta v}{1 +\|x+\delta v\|}$$.  We just need to bound $\delta$ so that the difference between $f(x)$ and $f(x+\delta v$) is less than $\epsilon$.
$$\|f(x+\delta v)-f(x)\|=\left\|\frac {x + \delta v}{1 +\|x+\delta v\|}-\frac x {1 + \|x\|}\right\|=\left\| \frac {(1+\|x\|)(x+\delta v)-(1+\|x+\delta v\|)x}{(1 +\|x+\delta v\|)(1+\|x\|)}\right\|=$$
$$\left\|\frac {x+\delta v+\|x\|x+\|x\|\delta v-x-\|x +\delta v\|x}{(1 +\|x+\delta v\|)(1+\|x\|)}\right\|=$$
$$\left\|\frac{\delta(1+\|x\|)v+(\|x\|-\|x+\delta v\|)x}{(1 +\|x+\delta v\|)(1+\|x\|)} \right\|$$
now remember $x+\delta v$ is just a point $\delta$ away from $x$, so their norms are at maximum $\delta$ apart  The denominator is bigger than one so we can get rid of it and still have an upper bound, this lets us simplify the entire mess to
$$\|f(x+\delta v)-f(x)\|\leq \|\delta(1+\|x\|)v+\delta x\|\leq \delta (\|(1+\|x\|))v\|+\|x\|)$$
the latter split by the triangle inqequality
Since $v$ is a unit vector, this further simplifies to
$$\|f(x+\delta v)-f(x)\|\leq \delta (1 + 2\|x\|)$$
Since $|x|$ is a constant (it was just the preimage of $y$),  you can bound this to be less than $\epsilon$ by making $$\delta < \frac \epsilon {1 + 2\|x\|}$$
Note this is a generally useful way of representing points close to a vector as being that vector plus the distance times a unit vector indicating the direction.
Answer: Based on the comment of @TheoBendit, you can prove that $x\mapsto 1 + \|x\|$ and $x\mapsto x$ are continuous, from whence it results that $f$ is continuous (why?).
Indeed, this is the case. Let us prove the first claim first. In order to do so, we shall prove the norm is continuous. We shall start with arguing that $|\|x\| - \|a\|| \leq \|x - a\|$. In fact, one has that
\begin{align*}
\begin{cases}
\|x\| = \|(x + y) - y\| \leq \|x + y\| + \|y\|\\\\
\|y\| = \|(x + y) - x\| \leq \|x + y\| + \|x\|
\end{cases}
\end{align*}
which implies that
\begin{align*}
\begin{cases}
\|x + y\| \geq \|x\| - \|y\|\\\\
\|x + y\| \geq \|y\| - \|x\|
\end{cases}
\end{align*}
whence we conclude that $\|x + y\|\geq\max\{\|x\| - \|y\|,\|y\| - \|x\|\} = |\|x\| - \|y\|| $.
Particularly, if we set that $y = -a$, the desired claim holds.
Consequently, for every $\varepsilon\in\mathbb{R}_{>0}$ there corresponds $\delta_{\varepsilon} = \varepsilon$ such that for every $x\in\mathbb{R}^{2}$ it results that
\begin{align*}
\|x - a\| < \delta_{\varepsilon} \Rightarrow |\|x\| - \|a\|| < \|x - a\| < \varepsilon
\end{align*}
and we are done. Since constant functions are continuous (why?) and the sum of continuous functions is continuous (why?), we conclude the function $x\mapsto 1 + \|x\|$ is continuous.
Based on a similar argument, it is possible to prove the identity function is continuous as follows: for every $\varepsilon\in\mathbb{R}_{>0}$ there corresponds $\delta_{\varepsilon} = \varepsilon$ such that for every $x\in\mathbb{R}^{2}$ it results that
\begin{align*}
\|x - a\| < \delta_{\varepsilon} \Rightarrow \|\text{Id}(x) - \text{Id}(a)\| = \|x - a\| < \varepsilon
\end{align*}
and we are done. Gathering all the previous results, the proposed claim is true.
Hopefully this helps!


I want to run two functions simultaneously on AVR microcontroller. Is there any method to do so?

Question: int main(void)
{

    DDRC = DDRC | (1<<2);
    DDRC = DDRC | (1<<3);

    while (1)
    {
     //openSolenoidValves(100,60);
     //startStepperMotor();

    }
void openSolenoidValves(double air, double oxygen) {

                PORTC = PORTC | (1<<2);  //open oxygen(normally closed valve)
                PORTC = PORTC & (~(1<<3)); //open air (normally open valve)
                _delay_ms(oxygen);
                PORTC = PORTC & (~(1<<2));//close oxygen
                _delay_ms(air-oxygen);
                PORTC = PORTC | (1<<3);//close air
                _delay_ms(air);
}

void startStepperMotor(){
//this function also has delays
}

I want to start both openSolenoidValve function and startStepperMotor function same time.But both functions have delays. Is there any method to do that? (MicroController-Atmega32)
Answer: A single core processor cannot execute two threads of execution simultaneously in the sense of parallel processing, but you don't actually need that to solve your problem.  It is an issue of scheduling processor time rather then simultaneous execution.  In your case since both functions spend most of their time in delays doing nothing - that "do nothing" time can be shared - doing nothing concurrently is easy.
One solution would be to use an RTOS.  Simple RTOS kernels such as FreeRTOS run on AVR, but the footprint may be prohibitive for parts with tiny memories as each thread must have its own stack.
If you already have an RTOS port for your target and are familiar with such things (which I guess your are not since you asked the question), it is probably the simplest solution; your code might look something like (pseudo-code and not any particular real RTOS API):
int main(void)
{
    DDRC = DDRC | (1<<2);
    DDRC = DDRC | (1<<3);

    osCreateThread( solenoidTask, SOLONOID_PRIORITY ) ;
    osCreateThread( stepperTask, STEPPER_PRIORITY ) ;
    osStartKernel() ;  // does not return
}

void solenoidTask()
{
    for(;;)
    {
        openSolenoidValves( 100, 60 ) ;
    }
}

void stepperTask()
{
    for(;;)
    {
        startStepperMotor( 100, 60 ) ;
    }
}

void openSolenoidValves(double air, double oxygen)
{
    PORTC = PORTC | (1<<2);  //open oxygen(normally closed valve)
    PORTC = PORTC & (~(1<<3)); //open air (normally open valve)

    osDelay( oxygen ) ;

    PORTC = PORTC & (~(1<<2));//close oxygen

    osDelay( air - oxygen ) ;

    PORTC = PORTC | (1<<3);//close air

    osDelay( air ) ;
}

void startStepperMotor()
{
    // use osDelay() - not busy wait delay.
    // this function also has delays
    ...
}

However getting an RTOS running on your target may be an unacceptable overhead for simple projects if you do not have it already set-up.  In that case you need to avoid delays by polling for time and taking actions only when it is time to do so.  For that you need a "current time" or "tick" function, which is not part of the standard AVR library (clock() for example is not implemented).  I'll get to that, but say we have a free-running 1ms counter with interface millis() (note that the Arduino library does have such a function).  Then you might create a "timer" API like:
#include <stdint.h>
#include <stdbool.h>

typedef struct
{
    unsigned start ;
    unsigned expiry ;
} sTimer ;

void startTimer( sTimer* timer, uint32_t expiry )
{
    timer.expiry = expiry ;
    timer.start = millis() ;
}

bool isTimerExpired( sTimer* timer )
{
    return millis() - start >= expiry ;
}

Then you would re-write your openSolenoidValves() function as as a state machine as follows for example:
void openSolenoidValves(double air, double oxygen)
{
    static enum
    {
        START,
        ALL_OPEN,
        OXY_CLOSE,
        AIR_CLOSE
    } state = ALL_OPEN ;

    sTimer timer ;

    switch( state )
    {
        case START :
        {
            startTImer( &timer, oxygen ) ;
            PORTC = PORTC | (1<<2);    //open oxygen(normally closed valve)
            PORTC = PORTC & (~(1<<3)); //open air (normally open valve)
            state = ALL_OPEN ;
        }
        break ;

        case ALL_OPEN :
        {
            if( isTimerExpired( &timer ) )
            {
                PORTC = PORTC & (~(1<<2)) ; // close oxygen
                startTimer( &timer, air - oxygen ) ;
                state = OXY_CLOSED ;
            }
        }
        break ;

        case OXY_CLOSED :
        {
            if( isTimerExpired( &timer ) )
            {
                PORTC = PORTC | (1<<3); // close air
                startTimer( &timer, air ) ;
                state = AIR_CLOSED ;
            }
        }
        break ;

        case AIR_CLOSED :
        {
            if( isTimerExpired( &timer ) )
            {
                state = START ;
            }
        }
        break ;
    }
}

In each state, the function is called and does nothing if the current timer has not expired and returns immediately. When the timer expire it performs the necessary solenoid operation and switches state - and returns immediately.
You implement the stepper function in a similar manner, then your executive loop can be:
for(;;)
{
    openSolenoidValves( 100, 60 ) ;
    startStepperMotor() ;
}

As you can see even for quite simple scheduling it can get rather complicated compared to RTOS threads.  However if you design it with state machine diagrams before attempting to write the code, the implementation can be quite mechanistic within a basic and re-usable state-machine framework.  Note also that you need not wait only on time, you could for example poll inputs to trigger events to advance the state-machines.
Note also if you were using the Arduino Sketch framework, you would not have the endless for(;;) or while(1) loop, the state-machine functions would simply be called in the loop() function (which is in turn called withing an endless loop provided as part of the framework).
Now if you are not using Arduino for example and have no millis() or similat system tick function, on AVR you can create one using a timer peripheral incrementing a counter in the reload interrupt.  For example:
#include <stdint.h> ;
#include <avr/io.h> ;
#include <avr/interrupt.h> ;

// Timer reload value for 1ms
#define SYSTICK_RELOAD (CORE_CLK_FREQ / 1000UL)

// Millisecond counter
volatile uint32_t tick_millisec = 0 ;

ISR (TIMER1_COMPA_vect)
{
    tick_millisec++;
}

void sysTickInit()
{
    // CTC mode, Clock/1
    TCCR1B |= (1 << WGM12) | (1 << CS10);

    // Load the output compare
    OCR1AH = (SYSTICK_RELOAD >> 8);
    OCR1AL = SYSTICK_RELOAD ;

    // Enable the compare match interrupt
    TIMSK1 |= (1 << OCIE1A);

    // Enable interrupts
    sei();
}

uint32_t millis()
{
    uint32_t now = 0 ;

    // Read tick count and re-read if it is not consistent
    // (due interrupt pre-emption and update during non-atomic access)
    do
    {
        now = tick_millisec ;
    } while( now != tick_millisec ) ;

    return now ;
}

With a main() like:
int main( void )
{
    sysTickInit() ;

    DDRC = DDRC | (1<<2) ;
    DDRC = DDRC | (1<<3) ;

    for(;;)
    {
        openSolenoidValves( 100, 60 ) ;
        startStepperMotor() ;
    }
}

See also Pressing button for 3 seconds and how to measure its time with Atmega8 1MHz? for other non-blocking scheduling using system tick polling.
Answer: The ATmega32 only has one core, unfortunately.  There is such a thing called a "real time operating system" that lets you run multiple tasks like this at once and I'm sure you could select one that works on the ATmega32 and port your code to it, but that is probably way more trouble than it is worth.  Concurrent execution of code can be achieved more easily by writing your code to behave in a non-blocking way (i.e. remove all blocking delays) and/or using interrupts if appropriate.
Answer: Yes this is totally possible. It's called cooperative multitasking. Start by studying Blink Without Delay, and my answer here: How to do high-resolution, timestamp-based, non-blocking, single-threaded cooperative multi-tasking
Example:
int main(void)
{
    doSetupStuff();
    configureHardwareTimer();

    while (1)
    {
        doTask1();
        doTask2();
        doTask3();
    }
}

See my answer above for examples of how to write the 3 tasks in non-blocking ways.
When done correctly, this technique works on literally any platform, from AVR to Arduino to STM32 to Windows, Linux, Raspberry Pi, etc., and can be done in any programming language.
And, it is designed to be single threaded, so there is no need for an OS (Operating System), nor multiple cores, nor a full scheduler. In effect, this is a type of light-weight, cooperative (as opposed to preemptive) scheduler.
It is so light-weight that I believe it could be done on even the tiniest of AVR microcontrollers which have just 64 bytes of RAM, all the way up to the biggest of PCs with hundreds of gigabytes of RAM.
Answer: This millis() function help me to solve my problem.
Just like the millis() function in Arduino, this function returns the time in milliseconds since the program started.
As Developers' details, This function has only been tested on the atmega328p but may work on many other AVRs as well.
Implementing this function is easy - take a look at the example:

First you must initiate the clock with init_millis()
After calling init_millis(), call sei() to enable global interrupts
Use millis() whenever you like to get the time in milliseconds since the
program started

Developers' repo =>
https://github.com/monoclecat/avr-millis-function#:~:text=avr%2Dmillis%2Dfunction-,Just%20like%20the%20millis()%20function%20in%20Arduino%2C%20this%20function,many%20other%20AVRs%20as%20well.
Comment: Please provide an textual description of the function that helped you.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Dask calculate groupby rolling mean over the last n days and assign to original dataframe

Question: I'm trying to replicate the below pandas group by rolling mean logic in dask. But stuck at 1) how to specify time period in days and 2) how to assign it back into the original frame?
df['avg3d']=df.groupby('g')['v'].transform(lambda x: x.rolling('3D').mean())

Get errors like:
ValueError: index must be monotonic, ValueError: Not all divisions are known, can't align partitions
or  ValueError: cannot reindex from a duplicate axis
Full example
import pandas as pd
import dask.dataframe

df1 = pd.DataFrame({'g':['a']*10,'v':range(10)},index=pd.date_range('2020-01-01',periods=10))
df2=df1.copy()
df2['g']='b'
df = pd.concat([df1,df2]).sort_index()
df['avg3d']=df.groupby('g')['v'].transform(lambda x: x.rolling('3D').mean())

ddf = dask.dataframe.from_pandas(df, npartitions=4)
# works
ddf.groupby('g')['v'].apply(lambda x: x.rolling(3).mean(), meta=('avg3d', 'f8')).compute()

# rolling time period fails
ddf.groupby('g')['v'].apply(lambda x: x.rolling('3D').mean(), meta=('avg3d', 'f8')).compute()

# how do I add it to the rest of the data??
# neither of these work
ddf['avg3d']=ddf.groupby('g')['v'].apply(lambda x: x.rolling('3D').mean(), meta=('x', 'f8'))
ddf['avg3d']=ddf.groupby('g')['v'].transform(lambda x: x.rolling(3).mean(), meta=('x', 'f8'))
ddft = ddf.merge(ddf3d)
ddf.assign(avg3d=ddf.groupby('g')['v'].transform(lambda x: x.rolling(3).mean(), meta=('x', 'f8')))

Looked at
dask groupby apply then merge back to dataframe
Dask rolling function by group syntax
Compute the rolling mean over the last n days in Dask
ValueError: Not all divisions are known, can't align partitions error on dask dataframe
Comment: Your example doesn't always work. Re-running the line after `#works` comment multiple times triggers: `ValueError: index must be monotonic`.
Comment: Thanks for flagging, updated it, thought I had it working...
Answer: This problem arises due to the current implementation of .groupby in dask. The answer below is not a complete solution, but will hopefully explain why the error is happening.
First, let's make sure we get a true_result against which we can compare the dask results:
import dask.dataframe
import pandas as pd

df1 = pd.DataFrame(
    {"g": ["a"] * 10, "v": range(10)}, index=pd.date_range("2020-01-01", periods=10)
)
df = pd.concat([df1, df1.assign(g="b")]).sort_index()

df["avg3d"] = df.groupby("g")["v"].transform(lambda x: x.rolling("3D").mean())
true_result = df["avg3d"].array

Now, running the code that is commented with #works is going to generate different values every time, even though the data or computations do not have a source of randomness:
ddf = dask.dataframe.from_pandas(df, npartitions=4)
# this doesn't work
dask_result_1 = ddf.groupby("g")["v"].apply(
    lambda x: x.rolling(3).mean(), meta=("avg3d", "f8")
).compute().array

# this will fail, every time for a different reason
assert all(dask_result_1 == true_result)

Why is this happening? Well, under the hood, dask will want to shuffle data around to make sure that all the values of the groupby variable are in a single partition. This shuffling seems to be random, so when the values are stitched back together they can be out of original order.
So a quick way to fix this is to add sorting before rolling computation:
# rolling time period works
avg3d_dask = (
    ddf.groupby("g")["v"]
    .apply(lambda x: x.sort_index().rolling("3D").mean(), meta=("avg3d", "f8"))
    .compute()
    .droplevel(0)
    .sort_index()
)

# this will always pass
assert all(avg3d_dask == true_result)

Now, how do we add this to the original datafame? I don't know a simple way of doing this, but one of the hard ways would be to calculate partitions of the original dask dataframe and then split the data into appropriate chunks and assign. This approach however is not very robust (or at least requires a lot of use-case specific fine-tuning), so hopefully someone can provide a better solution for this part.


Making a dynamic table for wp7

Question: I'm trying to make a dynamic table. I tried using row definitions. I have an xml table I want to put values from to the dynamic table.
Here's my code:
<code> Grid g = new Grid();

 XElement resultElements = XElement.Parse(e.Result);
 ListBox listBox2 = sender as ListBox;

 // g.RowDefinitions.Add(rr);
 int di = -1;
 foreach (XElement nod in resultElements.Elements(@"studentPunishmentsTable"))
 {
      di++;
      RowDefinition rr = new RowDefinition();
      TextBlock u = new TextBlock();
      penalty = nod.Element("penalty").Value;
      u.Text = penalty;
      g.RowDefinitions.Add(rr);
      Grid.SetRow(u,di);
      g.Children.Add(u);
 }
</code>
How can make a dynamic table to read data line by line from a webservice table into a table on a wp7 page?
Comment: What's the questions? Just telling us what you want to do and showing a snippet of code doesn't make it easy to help. See http://tinyurl.com/so-hints
Comment: And the error you getting is?
Comment: my Q is how can make a dynamic table to read data line by line from webservice table to a table in wp7 page ?
Comment: uhm, you want it with the WCF and windows phone code or just the WCF side? dude... come on - you need to read a tutorial.
Comment: i want it with wp7 code i've read the tutorial but didnt find thing to help with this even the samples dose'nt work with me
Answer: <code>foreach (XElement nod in resultElements.Elements(@"studentPunishmentsTable"))
 {
              listb.Items.Add(penalty+Environment.NewLine+ issueDate + semesterDesc);
                Grid.SetColumn(listb, colum);
                Grid.SetRow(listb, row); row = row + 1;
}
</code>
this code make a llist dynamicly ..

Making a dynamic table for wp7