how to resolve a $q for promise?

Question: I'm using AngularJS and $q for promises, I'm confuse with the usage, How can I fix this promise?
I want to return the user when isLoggedInPromise() is called or a "AUTH_REQUIRED".
Thanks!
    function isLoggedInPromise() {
        $q.when(userWithAllData()).then(function(user) {
            return user;
        });
        $q.when(userWithAllData()).reject(function() {
            return "AUTH_REQUIRED";
        });
    }

    function userWithAllData(){
        var deferral = $q.defer();

        var query = new Parse.Query(Parse.User);
        query.include(["info", "info.rank", "privateInfo"]);
        query.get(Parse.User.current().id).then(function (loadedUser){
            deferral.resolve( loadedUser );
        });

        return deferral.promise;
    }

Comment: You seem to be wrapping a promise when you don't need to
Answer: What you want to do is call the resolve function on the promise when the function has all the data it needs to actually return
in a function that returns a promise, think of "resolve" as the actual return statement.
so your isLoggedInPromise function needs to return a promise as well which will kind of make it redundant. Anything that needs a user will have to wait for it via then.
isLoggedInPromise().then(function(result){...etc...}, function(reason){//auth needed})
If you still need the isLoggedin Function then it should look like
 function isLoggedInPromise() {
    var isLoggedIn = userWithAllData().then(
        function(user) {
            return user;
        },
        function(reason){
            return $q.reject("AUTH_REQUIRED")
        });
 }

of course you'll have to include some rejection logic in the userWithAllData function as well.

how to resolve a $q for promise?


Howto Access WiFi Settings programmatically in iOS 5.1

Question: I'm looking for a smart way letting the user of my app connect to a WiFi Network. I know how to detect if the device is connected or not. I tried to use URL's to direct the User to the correct prefs Page. Unfortunately this doesn't work anymore. Any suggestions on howto require users to connect to WiFi???
thanks for helping!!!
Answer: Try using it to access the WiFi settings in iOS 5.1
<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
</code>

Try using it to access the WiFi settings in iOS 9
<code>if (&UIApplicationOpenSettingsURLString != NULL) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
}
</code>
Try to add prefs tu URL schemes like stackoverflow.com/a/31253743/3668465 did.

You can use this option for identify a SSID:
iOS >= 4.1 it's possible to obtain SSID of wireless network that device is currenctly connected to.
For this you'd use function CNCopyCurrentNetworkInfo
Details on implemenation: iPhone get SSID without private library

question example -> how to programmatically open the WIFI settings in objective c in iOS9
Comment: Have you tested it with iOS 5.1? I mean in the Link you provided it states that the URL Scheme works again in iOS 9 BUT my Question concerns iOS 5.1. As I said this is an old Question and I won't be able to test it.
Comment: I have. This stopped working in iOS 5.1 and was working in iOS 5. Please read the other answers of the sackoverflow Reference you provided in the Comments. There people explain that this stopped working in iOS 5.1 and started working again in iOS 8.
Comment: Unfortunately the solution you suggested for iOS 5.1 stopped working in iOS 5.1. Since this Question is already pretty old, I unfortunately can not use your Solution for iOS 9 anymore.
Comment: You tried to use it **"Try to add prefs you URL schemes like http://stackoverflow.com/a/31253743/3668465 did."**. In this way the command **"prefs: root = WIFI"** will return to work perfectly on any iOS version, I even use it that way. You should do exactly what the link proposes, certainly will work.
Comment: Ok I understand. Have you ever even tried the "[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];" ? Because it is an old command might work.
Comment: =/ I understand. I'm sorry for the inconvenience. I work only with 7.0+, did not know that was discontinued in 5.1. In this case I will not know how to help you.


How to test whether a series data follow Ornstein-Uhlenbeck process (OU process)?

Question: I have some measures which seems to have some mean-reverting properties and I'm wondering whether they can be modeled as Ornstein-Uhlenbeck process (OU process). And actually I quite expect it because if so, the following work will be much easier because it seems that there has been many useful results of OU process.
But I don't know how to validate it. I used to think that I could calculate the KL distance but the probability density function seems to not have a closed form, so it can't be derived.
So I'm wondering how to test whether a series data follow an OU process?
Answer: You can fit the time series to an AR(1) process. The regression coefficients and autocorrelation function will give you an indication of its mean reversion properties.
The regression parameters of the AR(1) model can be mapped into an Ornstein Uhlenbeck process: the appendix of the Avellaneda and Lee paper has an example of the AR(1) $\rightarrow$ OU mapping
Comment: Velcome to the site!


Minimum sample size to achieve a specific confidence level and interval

Question: I am building software components that are going to be used by multiple users
simultaneously. At the current point in time, these components are known
bad. That is, if I simulate multiple users simultaneously interacting with
each component long enough I know the component will fail. I cannot
determine that a failure happened until the end of the simulation.
The result of the simulation gives me two things:

A success or failure indicator, and
The actual number of times an error occurred (although I don't know when in
the simulation the error actually happened)

I also have no idea what kind of distribution the errors have because changing
the application to record the failures at the time that they happened would
likely change the distribution itself.
My goal is to determine the smallest sample size I can use to achieve a
target confidence level CL at a target confidence interval CI so that I can
automatically have these components tested the necessary number of
iterations. I'll then fix the components but leave the automated component
tests to give me some confidence that the components aren't broken in the
future.
How can I determine the smallest number of iterations (samples) the simulator
needs to run for in order to reproduce a failure at confidence level CL% given
a confidence interval of CI%? Or, if I can't equate the number of iterations to
samples, what approach might I take to achieve the above goal?
If it helps, I can run the simulator any number of times at any number of
iterations in order to have a sufficient sample size.
As I do not know enough statistics to know exactly what questions to ask or
what research to do, let me explain my current plan:

Run the simulator for X iterations
If the simulator does not fail, repeat step 1 with a larger X until the
 simulation fails.
(As the simulation failed at X iterations) Run the simulator 1000
 times with X iterations to determine what I suspect would be something
 akin to the confidence level. (i.e., if it failed 950 of the 1000 times
 I would assume a confidence level of 95%.)
If the confidence level is not sufficiently high, repeat starting at step
 1 one with a larger X (assuming I'll get a better confidence level).

I doubt the above is mathematically sound and would like to fix that.
It feels
like the unknown distribution makes it impossible to determine the likelihood
of a failure per some number of iterations. It also feels like I could use the
actual number of times an error occurred within a simulation to my advantage -
perhaps by calculating variance over repeated simulations.
Data:
<code># iterations      # failed simulations / 1000 simulations
2^n (0 <= n <= 6) 0
128               662
256               837
512               916
1024              974
2048              734
4096              779
8192              891
16384             953
32768             968
65536             991
131072            999
2^n (n >= 18)     1000
</code>
As you can see, at 2048 iterations the simulation failed significantly fewer
times than at 1024 iterations, which to me suggests some large variance.
I'm fairly capable with general mathematics, but quite uninformed on the
statistics front, so gearing answers in that direction would help.
Answer: this may or may not be helpful for you, but Diaz-Emperanza (1996, 2000) has published on how many replications a Monte Carlo study has so that a certain width of a confidence interval for a parameter is achieved.
Here are the two papers, which can both be accessed at
http://ideas.repec.org/e/pda47.html
Ignacio Díaz-Emparanza, 2000. "Is a small Monte Carlo analysis a good analysis? Checking the size, power and consistency of a simulation-based test," Econometrics 0004005, EconWPA.
Ignacio Dmaz-Emparanza, 1996. "Selecting the Number of Replications in a Simulation Study," Econometrics 9612006, EconWPA.


How to correctly transform estimated marginal means and SEs from binomial (logit) model?

Question: Let's say I have this simple GLMM model in R: model = glmer(correct ~ treatment + (1|id), data = DATA, family = binomial(link=logit)), where correct is my dependent variable (0s or 1s) and treatment is my experimental variable including 3 distinct levels of my intervention.
I would like to get estimated marginal means using lsmeans(model, pairwise ~ treatment), all working well. However the means and SEs seem to be in logits. These are the marginal means:
             lsmean   SE
Placebo      2.51     0.151
Treatment1   2.50     0.151
Treatment2   2.67     0.152

When I transform the lsmeans using  inv.logit(), I can easily get the mean probabilities on the original response scale 0 to 1 (I need this scale for my report). However, when I do the same thing for SEs, I get very weird values ~0.54, which makes no sense and thus suggesting I am doing something incorrectly.
Interestingly, when I compute the same model and marginal means in JASP, which automatically transposes the marginal means and SEs to the original response scale, the means JASP shows are the same as in R after using the inv.logit() transformation. But! And this is may main problem: JASP shows SEs = ~0.01, which seems to be correct.
Obviously, the 0.01 from JASP <<<< inv.logit(0.151) from R. Thus, my question would be, how should I transform the SEs from R (values: 0.151, 0.152) to have the SEs on the original response scale (from 0 to 1)?
Thank you,
best,
M.
EDIT: would it be correct to estimate SE on the original response scale this way: SE = inv.logit(2.51) - inv.logit(2.51-0.151)? This would be ~0.01, as estimated in JASP.
Comment: All you need to do is summarize with `type = "response"`. See the documentation for. `summary.emmGrid` and the vignettes that come with the **emmeans** package.
Comment: (+1) Nice comment, Russ - I used it as the basis for my response.  Is it possible to compute pairs of treatments in terms of differences of probabilities (rather than ratios of odds) when using lsmeans? It would be great if it were possible!
Answer: To elaborate on the comment provided by Russ, here are some toy data:
correct <- c(0,1,1,
         1,0,1,
         1,1,0,
         0,1,1,
         1,1,0,
         0,0,0)
treatment <- rep(c("A","B","A","B","A","B"), each = 3)
id <- rep(1:6, each = 3)

DATA <- data.frame(correct, treatment, id)
DATA

DATA$id <- factor(DATA$id)
DATA$treatment <- factor(DATA$treatment)

To keep things simple, assume the treatment variable has only 2 levels: A and B.
Using these data, you can fit your model:
library(lme4)

model = glmer(correct ~ treatment + (1|id),
           data = DATA, family = binomial(link=logit))

For the purpose of this answer, ignore R's singular fit warning (but for your own data, you should not ignore that warning).
Now you can use the lsmeans() function:
library(emmeans)

emm.1 <- lsmeans(model, "treatment")

If you apply the summary() function as is to emm.1:
summary(emm.1)

you will get, for each treatment level, the log odds of your response variable taking the value 1. (The response variable is the one called correct.) R will warn you that the results provided by summary() are given on the logit (not the response) scale and will label the logits as lsmean. (Logit is the same thing as log odds.)  Here is the R output for summary(emm.1):
 treatment lsmean    SE  df asymp.LCL asymp.UCL
 A          0.693 0.707 Inf    -0.693      2.08
 B         -0.223 0.671 Inf    -1.538      1.09

Results are given on the logit (not the response) scale.
Confidence level used: 0.95

If, however, you apply the summary() function to emm.1 with the option type = "response":
summary(emm.1, type = "response")

that will prompt R to report, for each treatment level, the probability that your response variable takes the value 1. This probability will be clearly labeled as prob in the R output:
 treatment  prob    SE  df asymp.LCL asymp.UCL
 A         0.667 0.157 Inf     0.333     0.889
 B         0.444 0.166 Inf     0.177     0.749

Confidence level used: 0.95
Intervals are back-transformed from the logit scale

If you are interested in pairwise treatment comparisons, then use the command:
emm.2 <- lsmeans(model, pairwise ~ treatment)

Applying the summary() command as is to emm.2 will allow you to compare pairs of treatment levels in terms of the log odds of your response variable taking the value 1:
summary(emm.2)

The corresponding R output will look like this:
$lsmeans
 treatment lsmean    SE  df asymp.LCL asymp.UCL
 A          0.693 0.707 Inf    -0.693      2.08
 B         -0.223 0.671 Inf    -1.538      1.09

Results are given on the logit (not the response) scale.
Confidence level used: 0.95

$contrasts
 contrast estimate    SE  df z.ratio p.value
 A - B       0.916 0.975 Inf 0.940   0.3472

Results are given on the log odds ratio (not the response) scale.

Using the option type="response" with the summary() command for emm.2 will allow you to compare pairs of treatment levels by computing the corresponding odds ratios and the associated confidence intervals:
summary(emm.2, type = "response")

The R output for this last command will look like this:
$lsmeans
 treatment  prob    SE  df asymp.LCL asymp.UCL
 A         0.667 0.157 Inf     0.333     0.889
 B         0.444 0.166 Inf     0.177     0.749

Confidence level used: 0.95
Intervals are back-transformed from the logit scale

$contrasts
 contrast odds.ratio   SE  df z.ratio p.value
 A / B           2.5 2.44 Inf 0.940   0.3472

Tests are performed on the log odds ratio scale

I do not know if it is possible with lsmeans() to compare pairs of treatment levels directly on the probability scale by computing differences in probabilities rather than ratios of odds.
Addendum 1
Russ kindly clarified that it is possible to use lsmeans() to compare treatments via differences of probabilities.  Here is the R code that would facilitate that comparison for the toy data example above:
emm.3 <- lsmeans(model,  ~ treatment)

pairs(regrid(emm.3))

Here is the R output for the pairs() command:
>     pairs(regrid(emm.3))
 contrast estimate    SE  df z.ratio p.value
 A - B       0.222 0.228 Inf 0.973   0.3304

Note that all lsmeans() commands in this answer can be replaced by emmeans() commands.
Addendum 2
Note that the computed log odds, odds ratios and probabilities are conditional quantities which refer to the "typical" subject in your study (where each subject is identified by their id), that is, the subject for whom the random intercept is equal to 0.
Comment: Use the regrid() function before doing the comparisons. There are lots of examples in the vignettes
Comment: Cool! Regrid worked like a charm - I added an addendum to my response to illustrate how it works. Thank you so much for your help, Russ! I learned a lot from your comments on this thread!


Swift - Xcode doesn't recognize existing member variables

Question: I have just started making a new game in Swift with SpriteKit, but it is coming up with an error telling me that the none of my member variables exist. I can't understand why it is doing this, because I clearly created the member variables.
Am I missing something?
Here is my current GameScene.swift:
Comment: See also http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other.
Answer: You're getting an error because, even though you specified a default value for bluePortal, at the time you specify a default value for portal no variable named bluePortal actually exists. Default values are values that will be assigned only when an actual instance of the class is created.
I suggest you create an init() method where you initialise bluePortal.
P.S. Next time, please paste your code instead of using a screenshot. It'll help other users troubleshoot your problem faster.
Answer: Please add var portal : SKSpriteNode! = SKSpriteNode(texture:bluePortal) inside some method or just declare it above and use it inside some method.


Can a set be open with respect to a subset?

Question: I'm reading Bloch's First Course in Geometric Topology and I came across this practice problem:
"$1.2.1$ Show that the following sets are open in $\mathbb{R}^2$:
(1) the complement of a single point in $\mathbb{R}^n$..."
However, I thought that sets can be open relative only to supersets - that is, that the question itself has a typo, and should read
"$1.2.1$ Show that the following sets are open in $\mathbb{R}^2$:
(1) the complement of a single point in $\mathbb{R}^2$ or $\mathbb{R}$..."
Is this right? Is openness only with respect to supersets? Or, does this question make sense, and I misinterpreted it?
Answer: See the errata.  It's the first item listed.
In case that link ever dies: It's a typo.  It should read "a single point in $\mathbb{R}^2$"
My advice going forward: download that pdf and either print it out or have it in a privileged place on your computer so you can refer back to it.
Comment: @trytryagain It's pretty common for textbook authors to publish errata online for their texts.  I just copied "Bloch's First Course in Geometric Topology" from your question, and pasted it into an internet search with the word "errata".  That link was the first result that appeared.  And you're welcome.  Hopefully that knowledge helps in the future too.
Comment: Wow, where and how did you find this? I had no idea this existed. Thanks for the quick response!
Comment: I had no idea errata were that common. I'll definitely keep that in mind next time I find myself doubting a textbook! Thank you again for your help!
Answer: It does seem like there's a typo and the question should read:

Show that the following sets are open in $\mathbb R^2$: (1) the complement of a single point in $\mathbb R^2$ [or $\mathbb R \hookrightarrow \mathbb R^2$]...

Openness is "with respect to superset" as you say, or more precisely, it's with respect to some topology defined on the superset, i.e. a special kind of collection of subsets of that superset; namely, a set $A\subseteq X$ is open with respect to the topology $\tau$ on $X$ if it is an element of $\tau$. So it makes no sense to be asked whether a set that is not a subset of $X$ is open w.r.t. $\tau$.


How to tell what version of puppet you are running on centos?

Question: I'm getting started with puppet on centos and was confused about a few things.  First off a man page exists for puppet-master but not for puppetmaster even though the daemon in /etc/init.d is puppetmaster
Running the command $ puppet-master --version returns bash: puppet-master: command not found.
How do I tell what version I am running for both the master and the client?
Answer: Newer versions of puppet use a slightly different command line.  The command you are looking for would be puppet --version, puppet master --version, and puppet agent --version
For versions before 4.0, if puppet was installed as an RPM package you can query the RPM database like rpm -qa | grep puppet.  For Debian/Ubuntu/Mint fans, the package query is dpkg -l | grep puppet.
Puppetlabs has changed their packaging and the packaged puppet version is no indicated by the version number of the puppet-agent package.
Comment: I've done a little more testing and have found that I can use a 2.7 puppet agent with a 3.2.x puppet server.
Comment: Is the hyphen for pre 2.6 version? Also do the master and agent need to be running the same major version?
Comment: I'm not sure when they made the change.  With version 3 Puppet Labs commited to using semantic versioning.  This means that major version number changes indicate a change that breaks backwards compatibility.  You should be OK if you have a mix of 3.x.y.  I wouldn't try a mix of 2.x and 3.x without testing that the results match my expectations.
Answer: root@puppet01 ~:
# puppet --version
3.2.2
root@puppet01 ~:
# puppet master --version
3.2.2

Answer: # rpm -qa | grep puppet
puppet-server-2.6.18-3.el6.noarch
puppet-2.6.18-3.el6.noarch

first line is version of the server side, the second - client side
# puppet agent --version
2.6.18

# puppet master --version
2.6.18

works too
Answer: For the fun, you can also use Puppet!
puppet apply -e 'notice("$clientversion")'

Also, in a manifest on the Puppet master, you can add such line:
fail("Server version: $serverversion, Client version: $clientversion")'
fail(inline_template("<%=clientversion.split('.')[0]%>"))

(Note that $serverversion is empty when using puppet apply)
Answer: Installed the puppet on ubuntu 18.04 , got the same error , the puppet command doesn't get added to the path  hence this error
navigated to this path /opt/puppetlabs/bin and run the command puppet master --version
you get the desired result


R C5.0 tree model to list conversion

Question: I am using the C5.0 decision tree in R from the C50 package.
The training function C5.0 returns a list which also contains a "tree" element which is basically a text representation of the tree. I am wondering if there are existing ways to convert that (text tree) into a R data structure, e.g. a list or a graph. The purpose is to use it for further analysis e.g. identifying assignment nodes and not only the class.
If there are no existing packages/functions that can do this then I will consider writing my own.
I found the following blog entry that converts the text tree into graphviz but not really the same thing.
http://r-project-thanos.blogspot.de/2014/09/plot-c50-decision-trees-in-r.html
Thanks
Comment: Max (Kuhn, the `C50` maintainer) and I once talked about that it would be nice if there was an `as.party()` method for `C5.0` objects. This should be possible and the `partykit` provides similar code for `rpart` and `J48` (from `RWeka`). This enables unified printing, plotting, predictions, etc. However, so far we haven't tried to write a suitable parser for `C5.0`. If you do, please let us (`partykit` maintainers) know.
Comment: @AchimZeileis thanks for quick reply and introducing me to partykit. I will be happy to use RWeka and partykit, though I am not sure how to use it. I tried but couldn't get it working, here is CV question for it: http://stats.stackexchange.com/questions/192433/j48-partykit-access-flat-list
Comment: There is nothing wrong with wanting to use C5.0 rather then C4.5 (via J4.8) as it contains some improvements and avoids some of the shortcomings of the old algorithm. (Personally, I use neither but typically unbiased recursive partitioning algorithms like `ctree`...but I'm partial to that, of course).
Comment: Follow-up: Digging a bit deeper into `C50` it turns out that Max Kuhn has actually done this work and there is an `as.party()` method for `C5.0` objects...it is just not (yet?) exported. But you can still call it if you reach into the NAMESPACE. For an example, run `example(plot.C5.0)` and then `p1 <- C50:::as.party.C5.0(mod1)`. The result is a `party` object for which you can do `plot(p1)` or `print(p1)` or all the other things that `partykit` supports.
Answer: We haven't updated the package yet but there is an updated version of as.party for C5 trees that has been checked in. You can install it with the devtoolspackage via
devtools::install_github("topepo/C5.0/pkg/C50")

You can use the function shown here to get the rules:
> model <- C5.0(Species ~ ., data = iris)
> modParty <- C50:::as.party.C5.0(model)
> pathpred(modParty)[c(1, 51, 101), ]
      response prob.setosa prob.versicolor prob.virginica
1       setosa  1.00000000      0.00000000     0.00000000
51  versicolor  0.00000000      0.97916667     0.02083333
101  virginica  0.00000000      0.02173913     0.97826087
                                                             rule
1                                             Petal.Length <= 1.9
51  Petal.Length > 1.9 & Petal.Width <= 1.7 & Petal.Length <= 4.9
101                        Petal.Length > 1.9 & Petal.Width > 1.7

R C5.0 tree model to list conversion


set $S$ in bijection with the set $G/G_s$

Question:
Let $G$ act transitively on a (non-empty) set $S$, and fix $s ∈ S$. Then $S$ is in bijection with the set $G/G_s$ of cosets $gG_s$ of the isotropy group $G_s$ of $s$ in $G$, by
  $gs \longleftrightarrow gG_s$
  Thus, $\text{card} S = [G : G_s]$
  Proof: If $hG_s = gG_s$, then there is $x ∈ G_s$ such that $h = gx$, and $hs = gxs = gs$. On the other hand, if $hs = gs$, then $g^{−1}hs = s$, so $g^{−1}h ∈ Gs$, and then $h ∈ gG_s$.

I am not sure how this leads to the conclusion that $S$ is in bijection with the set $G/G_s$. How does $h$ being in $gG_s$ and possibility that there is $x$ in $G_s$ that $hs=gs$ lead to bijection conclusion?
Is the proof saying that all of $gG_s$ is in bijection with $h$?
Comment: The bijection is between $S$ and the set of cosets. So $g G_s$ is being regarded as an _element_ of a set here, not as a set in its own right.
Answer: Actually the proof is incomplete.
Here's a complete proof:
If $hG_s = gG_s$, then $hs = gs$.
Hence there exists a map $\psi\colon G/G_s \rightarrow S$ such that $\psi(gG_s) = gs$.
Suppose $\psi(gG_s) = \psi(hG_s)$.
Then $gs = hs$.
Hence $gG_s = hG_s$
Hence $\psi$ is injective.
Let $t \in S$.
Since $G$ acts transitively on $S$, there exists $g \in G$ such that $gs = t$.
Hence $\psi(gG_s) = t$.
Hence $\psi$ is surjective.
Therefore $\psi$ is bijective.


Am I notating this 2 layered staccato right?

Question: How should I notate syncopations happening at the level of the sixteenth note? I'm composing a piece and in the piano accompaniment, there are 2 layers of staccato, one being on beat eighth notes so 1 + 2 + 3 + 4 + etc. and the other being a sixteenth note off that beat. So far I have been notating it this way: sixteenth rest, eighth notes for as long as possible in the bar, sixteenth tied over to the next bar. But is there a better way to notate it? Here is how it is being notated right now. You can see it starts with the staccato accompaniment alone in the bass and then the main melody and the second layer of accompaniment joins in at bar 5. I only have 1 bar's worth of the upper layer of the accompaniment because I want to make sure that it is being notated in a good way before I continue writing the accompaniment to the melody.

Piece so far, with sixteenth note level syncopations at bar 5
I have been given 2 suggestions so far. Those are cross staff beaming of sixteenth notes and breaking the beam in between the third and fourth eighth note of the right hand and not having tied sixteenth notes. I was told that at 90 beats per minute, it will barely make any difference to the rhythm whether I have the sixteenths rearticulated or tied and that a pianist would get confused by both the tied note and the note that starts the tie having a staccato articulation. Here is what the piano accompaniment looks like with cross staff beaming:

So what is the best way to notate this 2 layered staccato? Is it cross staff beaming or is it the way I have notated it with 2 layers of eighth notes? I will probably put sempre staccato in the piano staff and if I want to change it to legato, I will mark it as such.
Comment: As you've written it, the tied staccato notes seems like it'd be difficult to read; the last 16th note could just be left regular, no tie, no stacc. required, and it should be equivalent.
Answer: Here are three possibilities.   I think I'd rather read B.  The LH should really keep the same notation it's had from the beginning.
Comment: So, you would rather see beaming over rests than cross staff beaming or off beat eighths(which is the way I am notating it right now). And since the sixteenth notes are so quick, even at 90 BPM, the difference between non-legato sixteenths and staccato eighths will be almost undetectable. And keeping the staccato eighths in the left hand like in example B makes the similarity to the beginning phrase and the fact that I am adding to it much more obvious than with example C, even if what results is almost exactly the same from the players.
Comment: I'd neglected the need for continuity in the LH part.  So B.  I've amended my answer.
Comment: I've seen A written more than the others. And slightly better than Caters' example, beam-wise. Tidier. The staccato problem can be alleviated by a direction written at the beginning. It also somehow portrays better what is happening - alternating notes with alternating hands.
Comment: I agree with Laurence: B is the most easy and usual for reading and interpreting. It reminds me on the setting of a March (when there are staccato quarter and eighth notes.
Answer: To take Laurence's examples, I would definitely prefer to read B. A is terrible for me, C is tolerable, B give me the easiest understanding of what's going on.
Incidentally, Beethoven used this device a great deal, and A is how he usually did it. Here's an example (bars 15-20):

The wedges are one of Schnabel (the editor)'s many eccentricities. They mean the same thing as a staccato, but Schnabel differentiated between a harder and softer staccato (sometimes called "portamento") for which he used the dot. Beethoven didn't make any such distinction in his manuscripts. (I couldn't find another performance with music that doesn't use Schnabel's score, but none of the several other scores with which I am familiar use this wedge.)


Simple Logarithmic Question

Question: I have the following equation:
$\log(S_n) = \log(u)[2T-n]\,\,$
I was just wondering how $S_n = u^{2T-n}$ is then obtained?
Thank You
Answer: By taking the exponential of both sides. Recall that $e^{a\ln b}=b^a$.
Answer: You can also use the fact that $a \times \log{x} = \log{(x^a)}$ which means that $$\log{(u)} [2T-n] = [2T-n] \times \log{(u)} \\ = \log{(u^{[2T-n]})} = \log {S_n} \Rightarrow S_n = u^{[2T-n]}$$

Simple Logarithmic Question


Interpreting the f ratio in linear regression in r

Question: The last string of my output in r is:
F-statistic: 181.4 on 15 and 2380 DF,  p-value: < 2.2e-16
How do I interpret this result?
While I understand that the f value is a ratio that compares the systematic variance to the amount of unsystematic variance i.e. "the ratio of the model to its error" (Fields et al., 2012 p.400), I do not understand how to interpret the string.
Answer: Mathematically, $F=\frac{\frac{\text{Sum Squares Model}}{\text{df Model}}}{\frac{\text{Sum Squares Error}}{\text{df Error}}}$.
If you think of your data have a certain amount of variation in it, the F-statistic essentially gives you a measure of how much of the variation is explained by the model (per parameter) versus how much of the variation is unexplained (per remaining degrees of freedom). This unexplained variation is your error sums of squares. Through this lens, a higher F-statistic means that your model explains that much more of the variation per parameter than there is error per remaining degree of freedom.
The p-value just gives you an idea of how likely it is that your model would give you these results under the null hypothesis that the model explains none of the variability in your data. The low p-value tells you that the likelihood of getting this fit if the model actually didn't fit your data at all is ridiculously low, leading to the interpretation that at least some part of your model does fit the data.
Hope that helps!
Comment: just so I understand, I will write some of this back to you. Please confirm the validity of the following statements. Since the f-value is high and the p-value is very small, the likelihood of the model not fitting the data is incredibly low. Therefore, at least some part of the model fits the data.
Comment: pretty much. i might say the probability of the model not explaining any of the data is low, but same general idea.


How can I write a paragraph wrapping up a table in bootstrap?

Question: I am unable to write a paragraph wrapping the table on the right. The table just expands as the paragraph expands.

I am copying the Wikipedia page format of Apj Abdul Kalam. Also, can we reduce the width of the column in the table?
Here is my codepen link: https://codepen.io/TariqueBaig/pen/zRrKpx

A.P.J. Abdul Kalam

Missile man of India

Avul Pakir Jainulabdeen Abdul Kalam better known as A.P.J.Abdul Kalam was born in 15th October 1931.He was the 11th President of India from 2002-2007.He was born and raise
          in Rameshwaram, TamilNadu, and studied physics and aerospace engineering.He spent the next four decades as a scientist and science administrator, mainly at the Defence Research and Development Organisation (DRDO) and Indian Space Research Organisation
          (ISRO) and was intimately involved in India's civilian space programme and military missile development efforts.He thus came to be known as the Missile Man of India for his work on the development of ballistic
          missile and launch vehicle technology.He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974.

Kalam was elected as the 11th President of India in 2002 with the support of both the ruling Bharatiya Janata Party and the then-opposition Indian National Congress. Widely referred to as the "People's President," he returned to his civilian life
          of education, writing and public service after a single term. He was a recipient of several prestigious awards, including the Bharat Ratna, India's highest civilian honour.

While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on 27 July 2015, aged 83. Thousands including national-level dignitaries attended the funeral ceremony held in
          his hometown of Rameshwaram, where he was buried with full state honours.

Kalam in 2008

11th President of India

In office
25 July 2002 - 25 July

              Prime Minister
              Atal bihari Vajpayee
Manmohan Singh

              Vice President
              Krishan Kant
Bhairon Singh Shekhawat

              Preceded By
              K.R.Narayanan

              Succeeded By
              Pratibha Patil

          Avul Pakir Jainulabdeen Abdul Kalam was born on 15 October 1931 to a Tamil Muslim family in the pilgrimage centre of Rameswaram on Pamban Island, then in the Madras Presidency and now in the State of Tamil Nadu. His father Jainulabdeen was a boat owner
          and imam of a local mosque

Comment: Then you should do away with the rows and columns. The left column cannot wrap around the right column if the left column is higher; that is not how rows and columns work. You could float the table to the right instead.
Comment: It's not clear what you want to achieve. You mean you want to have the text that is now at the bottom, "Avul Pakir Jainulabdeen Abdul Kalam was born on 15 October 1931 to a Tamil Muslim family ..." to be in the left column?
Comment: Yes,  and when it exceeds it should wrap around that info table
Comment: Have not i done like that ? put both of them in a common div ?
Comment: No. What you have is one row with two columns, containing the text and the table respectively; and then another row with only one paragraph of text. If you don't want the page to behave like that, remove all of the row/column structure, keeping only the table and text, and then start giving it the styles you do want.
Comment: i did not get it :/
Answer: Bootstrap .col-{…} are structures that do not wrap, or float around each other. As their name is, they are columns.
On the other hand, floating elements can be wrapped around by text and inline elements. A floating element is one where the value of the float css property is not none. Bootstrap 4 also has a set of shorthand classes for Float.
The example below uses the .float-right class to push the table to the right. Also, it is important to move the markup of the table right after the headings. To change the width of the table section, you can still use the .col-{} classes. (They set just the width and flex properties of the element, and without a flex container the flex does not have effect.) To set the width, another option would be to use one of the Sizing classes, but unfortunately, those not use media breakpoints.

A.P.J. Abdul Kalam

Missile man of India

Kalam in 2008

11th President of India

In office
25 July 2002 - 25 July

                    Prime Minister
                    Atal bihari Vajpayee
Manmohan Singh

                    Vice President
                    Krishan Kant
Bhairon Singh Shekhawat

                    Preceded By
                    K.R.Narayanan

                    Succeeded By
                    Pratibha Patil

Avul Pakir Jainulabdeen Abdul Kalam better known as A.P.J.Abdul Kalam was born in 15th October 1931.He was the 11th President of India from 2002-2007.He was born and raise in Rameshwaram, TamilNadu, and studied physics and aerospace engineering.He spent the next four decades as a scientist and science administrator, mainly at the Defence Research and Development Organisation (DRDO) and Indian Space Research Organisation (ISRO) and was intimately involved in India's civilian space programme and military missile development efforts.He thus came to be known as the Missile Man of India for his work on the development of ballistic missile and launch vehicle technology.He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974.

Kalam was elected as the 11th President of India in 2002 with the support of both the ruling Bharatiya Janata Party and the then-opposition Indian National Congress. Widely referred to as the "People's President," he returned to his civilian life of education, writing and public service after a single term. He was a recipient of several prestigious awards, including the Bharat Ratna, India's highest civilian honour.

While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on 27 July 2015, aged 83. Thousands including national-level dignitaries attended the funeral ceremony held in his hometown of Rameshwaram, where he was buried with full state honours.

            Avul Pakir Jainulabdeen Abdul Kalam was born on 15 October 1931 to a Tamil Muslim family in the pilgrimage centre of Rameswaram on Pamban Island, then in the Madras Presidency and now in the State of Tamil Nadu. His father Jainulabdeen was a boat owner and imam of a local mosque

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>


How to grant "edit any file" permission only to files attached to a certain node type?

Question: The same question in other words:
How a file can inherit edit permission from node permission which is attached to?
Hi all,
I have 2 node types: articles and cars.
A file entity field is attached to both so users, through media module, can attach images to articles and cars.
Now I want a moderator role that can edit files attached to cars ONLY.
How to accomplish this?
Granting "Edit any files" to Moderator allow him to edit every files, articles attached files also, but I don't want this.
Thank you for any help
Answer: Maybe I've found a workaround.
Files editing is accessible in a general direct way (bypassing their nodes) by the following url:
<code>www.mysite.com/file/[fid]/edit
</code>
So only through this link a Moderator can have access and edit ANY file (please tell me if this is correct).
So, doing:
<code>/**
 * Implementation of hook_menu_alter()
 */
function helper_menu_alter(&$items) {
  // Provide custom access callback for direct files edit url
  $items['file/%file/edit']['access callback'] = 'helper_direct_file_edit_url_access_callback';
}

/**
 * Custom access callback
 */
function helper_direct_file_edit_url_access_callback() {
  // Disallow direct files edit url to everyone but superadmin
  if (!_helper_is_user_superadmin()) {
    return FALSE;
  }
  return TRUE;
}
</code>
Moderators with "Edit any file" permission (and everyone in anycase) cannot directly access to edit files, but they can edit files with media module through nodes they have edit access to (e.g. cars)
Do you think guys this could be a good workaround?
There is a better way to accomplish this?
Thank you very much


Remove content translation links from contact form

Question: I'm having a difficult time diagnosing a problem on a site I'm working on. By default on a multilingual site Drupal puts "content translation links" at the bottom of nodes. I've disabled the content translation links in favor of the language switcher block. However, on the contact form from the contact module I still have what look like content translation links at the bottom of the form (see screenshot below).

In the screenshot the translation links that I don't want are labeled #1 and the language switcher block is labeled #2.
I've selected "hide content translation links" under /admin/settings/language/i18n , but I guess this doesn't apply to the contact form for some reason.
So far I've been able to deduce that these links are getting passed through the $content variable because when I remove print $content from page.tpl.php, the links (as well as the contact form itself, of course) disappear. It also seems that the links are being treated as part of the contact form itself; when I tried using the panels site contact page override, whenever I added the contact form widget the links were included.
I apologize if this is perhaps too "localized" (pardon the unintentional pun) a question, but any help with figuring out how to get rid of these content translation links from the contact form page would be greatly appreciated. On the one hand I highly doubt this is the expected default behavior, so I feel like I must have tripped a setting or missed a setting somewhere. But at the same time I've looked through pretty much everything I can think of, so I'm at a loss.
Comment: It can be helpful when you tag your post with the Drupal version you're using ('drupal-6', 'drupal-7' etc.)
Comment: Ah, I know... "Send e-mail", that's the Drupal 6 contact form.
Comment: I tried tagging it as drupal-6 but I got an error saying that drupal-6 was a new tag and it didn't show up on autocomplete. I meant to edit my post to say it was for D6, but I forgot. Sorry.
Answer: If you want to hide that button, you can use the CSS Injector module, create a CSS class to apply to that data, and set display:none !important. It's not necessary to use a Drupal hook.
Answer: If you use Drupal 7, you can put hide($content['language']); in node.tpl.php.
Answer: If this is a contact form problem only, you might be able to remove the links with hook_form_alter or alternatively css.
Comment: Hmm, ok. I'm new to using hooks and custom modules, so I'll try to do some research and see if I can figure it out.
Answer: This is not only a Drupal 6 issue, I had the same problem on Drupal 7 until I solved it and found this discussion. My solution was to implement template_preprocess_node() in template.php and simply unset $variables['content']['links']['translation'].
Unlike Laxman i couldn't find any data in $content['language'] in node.tpl.php and I don't think such variable exist. You can try this with var_dump($content['language']); and you'll get an empty result. However, var_dump($content['links']['translation']); will result in an array containing information on what languages current node has translations for.
A lot of help came from reading about translation_node_view in the Drupal API.


Monitor SSH-traffic per user

Question: We have a backup application that runs once every 12 hours.
Multiple servers, desktops, and laptops connect to an EC2-instance and push a backup via SFTP using their own log-in credentials.
If they need to recover a file, they can browse files via a simple SFTP-Client and restore their files. This has been running very well for the last 8 months.
I would like to know how many data is transferred on a monthly basis, per user via SSH. I don't need the logs for the past 8 months, but something that would record it starting now would be great.
Is there anything that allows me to do this?
OS: Ubuntu 10.10
Answer: It took some awk-magic, this is what my colleague and I where able to put together.
<code>#!/bin/bash

main() {
  if [ -e $1 ] ; then
    MONTH=$(date | awk '{ print $2 }')
  elif [ $1 -ge 1 -a $1 -le 12 ] ; then
    month $1
  else
    exit 1
  fi

  echo
  echo "Usage statistics for month $MONTH"
  echo

  USERS=(`awk '/^'$MONTH'.*session opened for local user.*$/ { print $(NF-2) } ' /var/log/auth.log* | sort | uniq`)
  for i in "${USERS[@]}"
  do :
    echo "################################"
    echo "Usage for user: $i"
    READ=0
    WRITTEN=0
    #processes for this user
    PROCS=(`awk '/^'$MONTH'.*session opened for local user '$i'.*$/ { gsub("\\[|]|sftp-server|:","", $(NF-8)); print $(NF-8) } ' /var/log/auth.log* | sort | uniq`)
    for j in "${PROCS[@]}"
    do :

      TEMP_READ=$(awk '/^'$MONTH'.*\['$j'\].*\ read\ [0-9]+\ written\ [0-9]+$/ { sum+=$(NF-2)}END{ print sum}' /var/log/auth.log*)
      READ=$(($TEMP_READ+$READ))
      TEMP_WRITTEN=$(awk '/^'$MONTH'.*\['$j'\].*\ read\ [0-9]+\ written\ [0-9]+$/ { sum+=$(NF)}END{ print sum}' /var/log/auth.log*)
      WRITTEN=$(($TEMP_WRITTEN+$WRITTEN))
    done
    echo "Read     $(($READ/(1024*1024))) MiB"
    echo "Written  $(($WRITTEN/(1024*1024))) MiB"
    echo "################################"
    echo
  done
}

month() {
case "$1" in
  1)  MONTH='Jan'
    ;;
  2)  MONTH='Feb'
    ;;
  3)  MONTH='Mar'
    ;;
  4)  MONTH='Apr'
    ;;
  5)  MONTH='May'
    ;;
  6)  MONTH='Jun'
    ;;
  7)  MONTH='Jul'
    ;;
  8)  MONTH='Aug'
    ;;
  9)  MONTH='Sep'
    ;;
  10)  MONTH='Oct'
    ;;
  11)  MONTH='Nov'
    ;;
  12)  MONTH='Dec'
    ;;
  *) echo 'Crash and Burn!'
     exit 1
   ;;
esac
}

main $1
exit 0
</code>
In sshd_config I put this:
<code> Subsystem sftp /usr/lib/openssh/sftp-server -l VERBOSE
</code>
Warning: This script hogs memory! If you have large logfiles, it could take up to 10 min for the script to finish (tested on EC2 Micro).
Comment: I'm glad I got something that works :-). It even allowed me to get the statistics for the past moths. I'm a happy man ;-).
Comment: shame you can't receive your own bounty...
Answer: You could track user logons by IP (available in the log files), and then use nearly any traffic monitoring solution (Netflow and IPtraf come to mind) to keep track of the port 22 traffic by that IP.
Unfortunately, historical usage for the previous few months is not available unless you already had something to this effect set up.
Answer: You might want to check out this post on sftp logging.  I think it will get you what you want, with a bit of additional work to parse the logs.
Answer: auditd is a good utility to know what have been done to every file. It might not be what you need tough.

Monitor SSH-traffic per user


Ativar Modo Manutenção Laravel 5.1 Sem Artisan

Question: Sei que existe o comando php artisan down para ativar o modo de manutenção, mas estou com minha aplicação hospedada e não sei como dar esse comando. Teria alguma outra forma de fazer isso? Editando algum arquivo?
Answer: Sim é possível sem terminal, mas antes vou falar do php artisan down, não é porque você moveu um projeto para o servidor que o comando artisan irá funcionar. Geralmente só movemos o projeto ou fazemos toda instalação dentro do servidor e até mesmo o projeto de um cliente ficará em um repositório então trabalhamos na base do composer update.
Basicamente você terá que instalar o composer e o laravel (e artisian) no servidor de produção e baixar o projeto do seu cliente por git (ou outro método semelhante) e o acesso será provavelmente todo por SSH.
Mas isto é amplo para explicar. Sem delongas irei explicar como fazer isto sem usar o terminal, você pode criar duas rotas (de preferencia com autenticação) e usar o método Artisan::call:
Route::get('/admin/down', function()
{
    return Artisan::call('down');
});

Route::get('/admin/up', function()
{
    return Artisan::call('up');
});

Ao chamar algo como http://site/admin/down ele irá entrar em modo de manutenção e se usar http://site/admin/up ele voltará ao normal.

Documentação: https://laravel.com/docs/5.2/artisan#calling-commands-via-code
Referencia: Maintenance Mode without using Artisan?
Comment: Show, vou fazer aqui daqui a pouco então. E quanto a instalação do composer e do laravel no servidor eu vou dar uma lida sobre isso tbm.
Comment: @RaylanSoares na maioria dos servidores é inviável, geralmente fazemos isto quando usamos "servidores" como o AWS.
Comment: Ah então essas hospedagens padrão q temos por aí em servidor compartilhado nem rola né
Comment: fncionou aqui, vlw!
Comment: @RaylanSoares não realmente servidor compartilhado havará muitas limitações e mesmo que seja possivel talvez seja muito trabalhoso, o melhor é trabalhar local e enviar via `ftp`, para outros comandos use o `Artisan::call` combinado com rotas.


how can I verify whether multiple ip addresses are hosting on same server?

Question: Many hosting providers put multiple ip addresses on same physical machine. If I have two ip address, for example: 192.168.1.100 and 192.168.1.101. If I can only send probing packets from afar, how can I tell if these ip addresses are hosted on same physical machine? Is there any tool I can use, such as nmap?
Thanks!
Comment: Does it respond to SSH or SSL?  Does both IPs return the same certificate/public key when you attempt to connect?  This would strongly indicate you are looking at a single host.  Since it is a very bad idea to have the same private key on many systems.
Comment: Talk to the system administrator of that server.
Answer: No - you're not terribly likely to be able to find this information unless you're on the same subnet as the IP addresses in question (in which case, ARP provides a fast and easy answer).
From outside the subnet, there are some tools you can use to potentially obtain more information.  For instance, say SSH is listening on both addresses - do the services have different or the same public keys?  Or, if you run an nmap OS detection scan, maybe the two addresses are detected as different operating systems?  Maybe they're running BIND and you can query hostname.bind in the CHAOS class?
From a different network, you're depending on information gathering techniques that may or may not bear fruit.  Don't count on it working.
(By the way, this assumes that we're talking about "same server" meaning the same logical node/OS stack.  If we're talking about trying to find if two VMs are on the same physical server, forget about it - even on the subnet, you'd need access to the switches.)
Comment: Fwiw if they are separate NICs as well as IP addresses ARP won't help you either.
Comment: @MarkHenderson Ahh yeah, good point.


Camera Projection, solving for scale

Question: I'm having trouble solving the following problem.  Hopefully someone can help!
The following is in homogeneous coordinates.  I am projecting a point into a pinhole camera. $\lambda$ is an unknown scaling factor, all other variables are known.
$\mathbf{x} = \mathtt{P}(\lambda \mathbf{X} + \mathbf{Q})$
P is a 3x4 projection matrix.  I'd like to solve for $\lambda$.  Here's some example data:
<code>x = [-0.4052 -0.0502 1.0000]'
P = [1     0     0     0
     0     1     0     0
     0     0     1     0]
X = [0.3925 0.0465 -0.9313 1.0000]'
Q = [-18.4299, 0, -7.7678, 1.0000]'
</code>
And for this data, I know $\lambda$ is about 1430 if I just brute force search. Plugging the numbers and this result into the equation gives a correct solution.  However, surely there must be a direct solution for $\lambda$?  I can't seem to work it out!
Thanks,
John
Comment: You can't solve directly for $\lambda$ without additional assumptions. Given $Q$ and $X$, $\lambda$ parameterizes a 1-d space (call it $\Lambda$) and $x$ parameterizes a 3-d space. There will only be a $\lambda$ that solves this equation if $x$ is in the image of $\Lambda$ under the mapping $P$.
Comment: Thanks for your help Chris. $x$ is actually a 2D space because I'm using homogeneous coordinates (http://www.riemers.net/eng/ExtraReading/homogenous_matrices.php). I will draw graphically what I am trying to solve and it might help... my maths is pretty poor, hence my bad explanation (and trouble solving the problem!).

Also, here's a plot of $|\mathbf{x} - \mathtt{P}(\lambda \mathbf{X} + \mathbf{Q})|$: http://imgur.com/xDHJv.  I would like to minimize this error.
Comment: Ah, if you're just interested in minimizing the error, you can solve it. See my answer below.
Answer: Notice that $|x-P(\lambda X + Q)|$ is minimized exactly when $|x-P(\lambda X + Q)|^2$ is minimized. We can rewrite this as
$$|x-PQ-\lambda PX|^2 = |x-PQ|^2 - 2\lambda(x-PQ)^TPX + \lambda^2 X^TP^TPX$$
which is simply a quadratic in $\lambda$. To minimize it we set its derivative to zero, giving
$$\lambda X^TP^TPX = (x-PQ)^TPX$$
which we solve for $\lambda$ to give
$$\lambda = \frac{(x-PQ)^TPX}{X^TP^TPX}$$
Edit: for the example you gave, this gives an optimal $\lambda$ of -1.068, in contrast to your value of ~1400. I'm not sure why the discrepancy arises.
Comment: Thanks, the discrepancy is probably to do with the use of homogeneous coordinates. When you calculate $\mathtt{P}(\lambda \mathbf{X} + \mathbf{Q})$, $x$ will be 3x1. $x$ needs to be normalised so that x(3) = 1.  Anyway, thanks very much for your help, I've got something working now.
Answer: I think what you actually want is the following:
calling $y = P ( \lambda X + Q)$, you want $\left( \frac{y_1}{y_3}, \frac{y_2}{y_3} \right)$ to be as close to $\left( \frac{x_1}{x_3}, \frac{x_2}{x_3} \right)$ as possible.
If so, then the target function to minimize is $\left| \left( \frac{x_1}{x_3} - \frac{y_1}{y_3} \right)^2 + \left( \frac{x_2}{x_3} - \frac{y_2}{y_3} \right) \right|^2$, which is a function of the form
$$
\frac{\alpha \lambda^2 + 2 \beta \lambda + \gamma}{\left( \lambda X_3 + Q_3 \right)^2}
$$
with $\alpha = (x_3 X_1 - x_1 X_3)^2 + (x_3 X_2 - x_2 X_3)^2$, $\beta = (x_3 X_1 - x_1 X_3) (x_3 Q_1 - x_1 Q_3) + (x_3 X_2 - x_2 X_3) (x_3 Q_2 - x_2 Q_3)$, and $\gamma = (x_3 Q_1 - x_1 Q_3)^2 + (x_3 Q_2 - x_2 Q_3)^2$.
This system has a simple minimum at
$$
\lambda = \frac{\beta Q_3 - \gamma X_3}{\beta X_3 - \alpha Q_3},
$$
which in your case turns out to be close to 1426.3
Comment: This looks even better, but I'm concerned that $P$ is not in the solution... have you made an error writing up your answer?
Comment: I think that Michael has used the specific P that you gave in your question.
Comment: Ah, of course. Thanks again!

Camera Projection, solving for scale


Addmefast.com checks the Like button clicked in new window? How

Question: I know how to check if Facebook like button is clicked by edge.create , but the website addmefast.com , opens the Facebook page in new window, and when you close the window, the parent window gets something return that whether i clicked like or not.
i can check this in the same window, but how do they do it on a new window, which is on separate domain i.e Facebook.
They are not using any signed application or user permissions to check his likes etc..
UPDATE:
I read the java-script of the website, and what it does is checks the number of like before, and after opening the window, and then if the likes have increased they award you points, no matter whoever like the page in that time, i tested it, i opened the window for like, and did not like, and asked my friend to like it from his computer, and i was awarded points, so they cannot really check whether i liked it or no. Obviously they need to use signed Facebook app to do this.
Comment: As far as i know, what they do is, check the likes of a page via facebook og, and opens a window, and then after closing the window they check the likes again, and decides whether likes are increased or not. But i believe its not a good idea, during that time thousands of others can like too, and that will not be certain.

I am now using facebook api signed app to do this.
Comment: you can use postMessage() to send info from another domain's window. or you can have the same server talk to both the popup and opener page using invisible ajax.
Comment: I have the same question. Anybody have the answer?
Answer: Yes, I can confirm, that's exactly the method they use.
When you click on the like button from their page, they open a child window and ask their server to make a direct call to graph.facebook.com/pageID. After that, they save a before record with the number of page likes.
When you close the child window (this means you just liked the page), they make another call to the facebook graph, retrieve the before record and check if the number of likes have increased.
<code>var win = window.open(url, name);
win.onunload = afterChildClose; // afterChildClose() is the function.
win.close(); // afterChildClose() should fire now.
</code>


How to create a swanky SurfaceSlider

Question: I am new to surface programming and stumbled upon this Image which I understand is a slider control on a tag visualization (in this case a card). This slider is

curved as opposed to conventional straight track
has a bigger thumb which displays the current position (thus eliminating the need of a separate label)
has a glowing feel (I understand this is due to overlapping controls with different blur radius)

Can anyone help with how to make such control.
-V
Answer: This is a custom-built control rather than a standard SurfaceSlider.  It's not build using TagVisualizer either but that's only because the app that this picture shows was built ~2 years prior to TagVisualizer existing.
Now you should certainly use TagVisualizer to streamline an implementation of this but you'll still have to create a custom slider control - SurfaceSlider will not be a good fit because it assumes that the user is moving their finger linearly.
Within your custom arching slider control, you can use SurfaceThumb (which SurfaceSlider itself uses) to get the big glowing thumb... then just needs to listen to the Delta events on the thumb and move it along the constrained path as appropriate.

How to create a swanky SurfaceSlider


Proof that it always exists a prime between $\sqrt n$ and $n$

Question: I'm looking for a proof that ensures that for every natural number $n > 1$ there is always a prime $p$ such that $\sqrt{n} \leq p \leq n$ holds.
I know you can deduce my previous claim as a corollary of some famous results like "Bertrand's postulate", but I was wondering if it does exist any easy self-contained proof.
Comment: @robjohn the inequalities aren't strict
Comment: It might be true for $n\gt2$, but it is not true for $n=2$. There isn't even an integer between $\sqrt2$ and $2$.
Comment: No @Winther. The answer there uses exactly what the OP says he wants to avoid using.
Comment: Erdos proof which is used here https://proofwiki.org/wiki/Bertrand-Chebyshev_Theorem is considered quite simple. I don't know if it fits your "self-contained" standards though. As others already said once you have Bertrand's Theorem the deduction follows arithmetically.
Comment: Okay, I see that in the question the inequalities are not strict, but "between" usually means strict, and that was what I reacted to.
Comment: Related: [Is there a prime number between every prime and its square?](http://math.stackexchange.com/questions/38137/is-there-a-prime-number-between-every-prime-and-its-square)
Answer: This doesn't prove the claim for all $n>2$, but it does show that there are at most finitely many counterexamples. I assume the Prime Number Theorem is allowed here (I know you want a self-contained proof, but this is the best I could do), I'm not sure how we could really do much without it.
Assume there are infinitely many $n \in \mathbb{N}$ such that $\pi(n)= \pi(\sqrt{n})$ and let $(n_i)_{i \in \mathbb{N}}$ be the ordered sequence of these natural numbers together with their square roots, so that $\pi(n_i)=\pi(\sqrt{n_i})$ for each $i$. We have, from the prime number theorem: $\displaystyle \lim_{x \to \infty} \frac{\pi(x) \log(x)}{x}=1$
In particular, this implies the following sequence converges: $( \frac{\pi(n_i) \log(n_i)}{n_i})_{i \in \mathbb{N}}$ and thus it must be Cauchy. So for every $\epsilon>0$ there is an $N \in \mathbb{N}$ such that $\sqrt{n_i}=n_{k(i)}>N$ implies:
$| \frac{\pi(n_i) \log(n_i)}{n_i}- \frac{\pi(\sqrt{n_i}) \log(\sqrt{n_i})}{\sqrt{n_i}}|< \frac{\epsilon}{4}$
But $\pi(n_i)= \pi(\sqrt{n_i})$ for each $i$, so we can simplify this to:
$\pi(n_i)| \frac{(\sqrt{n_i}/\log(\sqrt{n_i}))-1}{n_i^{3/2}/ \frac{1}{2} \log(n_i)^2}|< \frac{\epsilon}{4}$
Further simplification yields the following:
$\frac{1}{2}(\frac{\log(n_i)}{\sqrt{n_i}})(\frac{\log(n_i) \pi(n_i)}{n_i}) |\frac{\sqrt{n_i}}{\log(\sqrt{n_i})}-1|< \frac{\epsilon}{4}$
Now, $\lim \frac{\log(n_i) \pi(n_i)}{n_i}=1$ again by the prime number theorem, so we can choose $N' \geq N$ sufficiently large such that $\frac{\log(n_i) \pi(n_i)}{n_i} \geq \frac{1}{2}$ for $n_i >N'$. This gives us, for $n_i> N'$:
$\frac{1}{4}(\frac{\log(n_i)}{\sqrt{n_i}})|\frac{\sqrt{n_i}}{\log(\sqrt{n_i})}-1|< \frac{\epsilon}{4}$
So there is an $N' \in \mathbb{N}$ such that $n_i>N'$ implies:
$|2-\frac{\log(n_i)}{\sqrt{n_i}}|< \epsilon$
Since $\epsilon>0$ was arbitrary, this by definition implies:
$\lim \frac{\log(n_i)}{\sqrt{n_i}}=2$
But in general: $\displaystyle \lim_{x \to \infty} \frac{\log(x)}{\sqrt{x}}=0$, so every sequence with $x_n \rightarrow \infty$ will satsify: $(\frac{\log(x_n)}{\sqrt{x_n}}) \rightarrow 0$, so our contradiction is obvious.
So then by contradiction, there are at most finitely many $n \in \mathbb{N}$ such that $\pi(n)= \pi(\sqrt{n})$. $\Box$
Answer: No, there is no such a proof. Some years ago, I thought that there "must" be a proof of this fact, or to restate your proposition,
"There is always a prime between $n$ and $n^2$, when $n\geq 2$ "
should be proved using only combinatoric arguments and basic number theory. But I couldn't find such a proof and by the way, if you ever find such a proof, let me know, I will be very pleased too see it.


C# - Write DateTime field (with NaNo Second) to text file (using Streamwriter)

Question: See below, where dataset is returning the results from tables.
Dataset returns column which are DATETIME, but with below code - NANO seconds are removed when written to file.
For e.g
Source Data: 2014-01-01 01:23:55.596
Whats getting written in file is
Output Data: 2014-01-01 01:23:55
So I want to tweak the below code, so that NANO seconds also get printed to file.
try
{
    using (OleDbConnection connection1 = new OleDbConnection(str_ConnectionString1))
    {
        OleDbCommand command = new OleDbCommand(queryString1, connection1);
        command.CommandTimeout = 0;
        connection1.Open();
        OleDbDataReader reader1 = command.ExecuteReader();

        // This size is just for example purpose. Should be fine tuned
        StreamWriter writer1 = new StreamWriter(@str_FeedFilePath1 + @str_FileName1);
        var result = string.Empty;
        StringBuilder buffer1 = new StringBuilder(1048576);
        while (reader1.Read())
        {
            for (int j = 0; j < reader1.FieldCount; j++)
            {
                buffer1.Append(reader1[j] + "|");
            }
            buffer1.AppendLine();
            if (buffer1.Length > 1048576 - 1024)
            {
                writer1.Write(buffer1.ToString());
                buffer1.Length = 0;
            }
        }
        writer1.Write(buffer1.ToString());
        writer1.WriteLine(result);
        reader1.Close();
        writer1.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
}

Comment: Your title says VB.NET, your tags say C# and VB.NET, your code is C#.  Make your mind up.
Comment: First identify your datetime column index at `buffer1.Append(reader1[j] + "|");` then you can use `.ToString(...)` to format it as you would like.
Comment: I think you mean milliseconds... A Nanosecond is equal to one-billionth of a second!
Comment: Do you mean milliseconds or nanoseconds or NaN - not a number?
Answer: You will need to check the object returned from the reader. It will look something like this:
if (reader1[j] is DateTime)
   buffer1.Append(((DateTime)reader1[j]).ToString("o"));
else
   buffer1.Append(reader1[j]);
buffer1.Append("|");
...

PS: DateTime is only accurate to 100ns, and unless you are using MS's DateTime2 field, you may be even less accurate than that in the DB. Did you mean milliseconds?
Comment: The Sql query will return multiple columns,  which will have text and date field. So how to handle this or you think above will work if Sql query returns multiple columns


Why do we use the terminology of Type I/Type II when describing errors in hypothesis testing?

Question: I was teaching someone else about type I and type II errors, and they asked the question of why errors are called type I and type II errors. It seems to me that we could call type I errors a "False Rejection" and type II errors a "False Failure to Reject" and thus eliminate the need for students to learn mnemonics to remember which errors are of which type.
Is there any utility to using the Type I/Type II error terminology?
It appears that there wasn't any clear reason for adopting the terms originally
Answer: It's really terrible nomenclature that has led to a century of misunderstandings.  The main problem is attachment of the word "error" to the probabilities being calculated, which give a false impression that it's a worthwhile exercise.  Many people act as if type I probability (which I call type I assertion probability $\alpha$) tells you something about the probability you'll make a mistake, e.g., be wrong in concluding an effect exists.  It does nothing like that.  Instead it tells you the chance of asserting an effect when any assertion of an effect is by definition wrong.  It's not an error probability.  More is here which discusses the difference between $\alpha$ and decision errors.
To your original question, type I and type II are convenient shorthand (as long as we drop 'error') but I personally would call them assertion probabilities when, respectively, there isn't or there is a real effect.
Comment: Based on a close reading of the question, and especially of its title, I believe it is asking about the "Type I/II" nomenclature and not about the use of the term "error."
Comment: Although "false rejection" creates the same problem.  Most would interpret a false rejection to mean that you asserted an effect that turns out to not exist.  That's not what $\alpha$ is.  $\alpha$=P(asserting an effect **if** there is no effect) which is almost unrelated to the real goal.
Comment: I was hoping to understand the "Type I/II" part of the terminology, but it's helpful to understand that "error" is incorrect as well. It seems that the "Type I/II" terminology stands because there isn't really a good way to describe the different cases in just a few words.


Differential form residue

Question: It is possible to write
$$ \sqrt{ 2 + \cos(x) + \cos(y) } -2 = \frac{-a(x,y)\sin(x)}{\sqrt{ 2 + \cos(x) + \cos(y) }} + \frac {b(x,y)sin(y)}{\sqrt{ 2 + \cos(x) + \cos(y) }}$
$$
for some functions $a,b \in C^1(-\epsilon,\epsilon)$?
To give some context. Let $f = \sqrt{ 2 + \cos(x) + \cos(y) } -2$ and $\omega = dx \wedge dy$. Is there some 1-form $\alpha$ such that $ df \wedge \alpha = f \omega $ locally?
Answer: I infer from your conditions on $a,b$ that by "locally" you mean only in a neighborhood of $(0,0)$. This point is a local maximum of $f$ so, in fact, both $f$ and the $1$-form $df$ vanish at $(0,0)$. And $f$ is real analytic in a neighborhood of $(0,0)$, so you can write a power series expansion for $f(x,y)$ in a neighborhood of $(0,0)$. Indeed, using well-known expansions for $\cos(u)$ and $\sqrt{1+u}$, we see that $f(x,y) = \phi(x)+\psi(y)$, with $\phi(0)=\phi'(0)=\psi(0)=\psi'(0)=0$. Writing $\alpha = b(x,y)dx+a(x,y)dy$, as you did above, just set $b(x,y) = -\psi(y)/\psi'(y)$ [and this has a well-defined power series expansion at $0$] and $a(x,y) = \phi(x)/\phi'(x)$.

Differential form residue


A way to run more than one webserver on one virtual server

Question: I know the following is impossible, but there should be a workaround.
As I'm now having problems with my very-clickable application,
(visits) (page views) (hits)    (data)

(~100 000 php page views every day) I decided to try HipHop-PHP, an opensource application from Facebook.
It should be able to transfer my application to c++ code and compile it. It should act as a webserver, like apache. The biggest problem is that I do not need/want a compiled application on the other websites. Why is it a problem? It runs on port 80, as my apache2 does and it is just not possible.
Is there a way to run 2 webservers on one virtual server?
Answer: Another option would be to have HPHP listen on a high port and have Apache reverse-proxy requests for the domain using HPHP to that high port.
Comment: So I'd have to use apache2 as the gate between apache and HPHP?
Comment: Indeed - you'd set up a `` for the site that needs to be fed to HPHP, set `ProxyPass / http://127.0.0.1:8000/` (set to whichever non-80 port you use), and set the appropriate `ServerName`.
Comment: You can have virtual directories defined in your apache configuration which would be simply internally reverse-proxied to a server of your choice. See [the docs](http://httpd.apache.org/docs/current/mod/mod_proxy.html) for more information.
Comment: @ShaneMadden: Okay, so if I understand correctly, user would see no difference but user which access http://mydomain.com on port 80 uses `ProxyPass http://127.0.0.1/8080/` so all requests from port 80 are directed to 8080?
Comment: @genesis-φ Not all requests to port 80, just those matching the `ServerName` in the `` that's configured to do the proxying.
Answer: You can create multiple virtual domains, but if you're thinking of having more than one web server on one IP running on port 80, no. You'd have to have multiple IP's on the virtual server.
If you can get multiple IP's, then yes, you'd bind your web servers to the IP address assigned on port 80 and you can do that on one virtual machine.
Comment: You can do reverse proxying or putting them on other ports, but if you're primarily trying to fit multiple sites on the one server, personally I'd try to use either virtual domains or, if you have multiple IP's available, it's easier to manage if you use multiple IP's. Otherwise like Squillman said, yes, you can put them on other ports, but you must direct them as http://www.mydomain.com:8080/index.html or something like that.
Comment: And is it possible to run first one on 8080 and the others on 80 ? Will user's browser know where to "ask" ?
Comment: @genesis-φ Port numbers != 80 will need to be included in the URL, unless you're employing some kind of URL rewriting, with .htaccess for example.  Or see Shane's answer on reverse proxying.


Regex - any one or more character followed by one new line and equal sign

Question: I'm making an open-source Markdown parser.
I have a bit of problem on my regex as I'm not very expert on regex.
r = r.replace(/(.*)(\n=$)/g, '
$1
');

What I want here is to get any one or more character follow by \n new line and the next line would be one or more of = only.
Input is:
Hello World\n===
Expected output:
Hello World
The one I have worked but when I have two new lines it will strip off the equal signs too.
So if I have something like this
Hello World\n\n===
I should see this
Hello World

===

Comment: Sorry my title was wrong :/
Answer: You've got an end anchor ($) which means it will only match of there are no other characters following the first equals. Furthermore, it looks like you want to be able to match one or more equals signs.
I think this is what you want:
"Hello World\n===".replace(/(.+)\n=+/g, '
$1
'); //
Hello World

Comment: Should I use \r\n? or just \n would be enough?
Comment: @Ali That depends on your particular use cases. If you *know* the input will only have `\n`, I'd use that for simplicity. If you want to support any line common ending, I'd use `(\r?\n|\r)`, which will work with `\n`, `\r`, or `\r\n`.
Comment: so it will be like `(/(.+)(\r?\n|\r)=+/g, '$1');` ??
Comment: @Ali Yes, that's right. If this is coming from a database or something like that, I'd recommend normalizing the line endings before you save them in the database, though. That way you won't have to clean them up via JavaScript.
Answer: Try
(.+)\r\n=+

r = r.replace(/(.+)\r\n=+/g, '
$1
');

Answer: To match headers properly, I would suggest to use a start-of-string anchor as well, i.e.:
s.replace(/^(.+)$\r?\n={3,}/gm, '
$1
')

I'm using ^ to match the start and $ to match the line ending, in conjunction with the /m modifier they will operate on lines rather than the whole subject.
Then, \r?\n will munge exactly one line ending (CRLF or LF). Finally the ={3,} will match three or more equal signs.
Comment: I like that :D really great for matching three or more equal signs :)
Comment: But actually one problem here. it is stripping off the equal signs if there was two extra lines :/


FirebaseRecyclerAdapter 28.0

Question: I have a problem that has been going on for several days and I have not been able to solve it.
I need my application to connect to a database in Firebase and show it in a RecycleView.
I have the following:
Database in firebase:
Imagen base de datos
I have the following dependencies:
Imagen dependecias
I created my model in the following way:
Imagen modelo
Create a Holder in the following way:
Imagen Holder
After that, I have the following code so that according to what I find in the database I can publish the images of the links that are in this one.
OnCreate
Create a sub that contains the entire connection
enter image description here
but in the part where FirebaseRecyclerAdapter is declared does not enter, this option is skipped and does not enter
private void loadMenu2() {

    FirebaseRecyclerOptions <wallpaperClass> options =
            new FirebaseRecyclerOptions.Builder<wallpaperClass>()
                    .setQuery(category,wallpaperClass.class)
                    .setLifecycleOwner(this)
                    .build();

    adapter = new FirebaseRecyclerAdapter<wallpaperClass, MenuViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull MenuViewHolder holder, int position, @NonNull wallpaperClass model) {
            Toast.makeText(getApplicationContext(), "Ingreso 3!", Toast.LENGTH_SHORT).show();
            holder.txtNombre.setText(model.getName());
            Picasso.get().load(model.getLinkwall()).into(holder.imgWallpaper);
        }

        @NonNull
        @Override
        public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Toast.makeText(getApplicationContext(), "Ingreso 4!", Toast.LENGTH_SHORT).show();
            return null;
        }
    };
}

I've been with this for days, but I can not solve it, I thank everyone for their help.
Comment: please post your code add in side of question. please check this link https://stackoverflow.com/help/how-to-ask
Answer: It is not that the sentence is skipped, in fact it looks good the way you declared things, the problem is that the object "adapter" that you are creating does not assign it to any side ... you must pass it to your Recyclerview:
myRecycler.setAdapter(myAdapter);

In this way your recyclerview, you know how it will have to be filled.
Regards!

FirebaseRecyclerAdapter 28.0


How to add tags using Geolocation with Tags Input?

Question: I want to add tags input of google geolocation address.
I am using this geolocation
Autofill Address + Google Maps API
This is bootstrap tags input.
http://timschlechter.github.io/bootstrap-tagsinput/examples/
If I type address and select autocomplete address it should convert in a tag like bootstrap tags.
Answer: My solution using Twitter Typeahead with bootstrap tags-input:
<code>        var locations = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('formatted_address'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            identify: function (obj) {
                return obj.place_id;
            },
            remote: {
                url: 'https://maps.googleapis.com/maps/api/geocode/json?address=%QUERY&language={YOUR_LANGUAGE}&key={YOUR_MAPS_API_KEY}',
                wildcard: '%QUERY',
                rateLimitWait: 100,
                transform: function (response) {
                    if (response.status === 'OK') {
                        return response.results;
                    } else {
                        return [];
                    }
                }
            }
        });
        $('input').tagsinput({
            itemValue: 'place_id',
            itemText: 'formatted_address',
            typeaheadjs: [{
                highlight: true
            }, {
                displayKey: 'formatted_address',
                source: locations
            }],
            trimValue: true
        });
</code>


PHP referrer: How to make sure a request is actually coming from where it's supposed to come from

Question: I would like to put a link back to my site on other "approved" domains. When they click on the link it goes to a page that checks the referrer ($_SERVER['HTTP_REFERRER']) to make sure they came from a domain that is approved to have my link. This can be spoofed so how can I make sure the clicks are actually coming from the approved domains?
Answer: You can't do it. You can't prevent the referrer from being tempered with.
An alternative would be possible if there's collaboration between the several sites. For instance, the links in the other sites to yours could pass a token as a parameter in the URL that would be usable only once and which you could then validate.
Several validation strategies would be possible. Your site could contact the other site and ask it if the passed token is valid or you could employ a signature with the token acting as a nonce so you didn't have to contact the other site.
Comment: Indeed, was writing about the same. Affiliates and the like usually solve this by bouncing back & forth setting some cookie & get parameters in the url they can validate, and which meaning cannot easily be cracked (hashes over url & salt and the like).
Comment: The signature generation and validation would be similar to what OAuth does - you could even look at using the code from an OAuth library to do this. Make sure there is a timestamp parameter in the URL which you can check to prevent re-use of stale links. Either give enough leeway in the time check for people to click links a while after they are loaded, or make the links on the page actually redirect to a freshly generated & signed URL, allowing you to have a much shorter expiry time.
Comment: Using a timestamp based nonce is a good strategy because you don't need to store all the nonces you have ever seen to deny them in the future. You could only store those seen in e.g. the last say 3 hours and reject all that are older. If can live with some reused tokens in a small timespan you could even store nothing at all.
Comment: What's this nonce stuff all about?
Comment: @arfecto, i can't trust the other domains, so i can't rely on them to pass back the correct data to ensure the click is valid & thanks for clarifying what a nonce is. I have to make sure the link being clicked on is actually coming from an approved domain, similar to how affiliate marketers do it.
Comment: @John It's the client that claims he comes from a certain website, the website only certifies that what the client says is true. Sure, the other websites could make public the secret they use to generate the links, but you have no way to control that.
Comment: @artefacto, thanks again for clarifying. so is there any way to make this work?
Comment: @John Since the only way is to add some parameters to the link and the link is shown by the other sites, there's no way to protect yourself against rough sites that leak the link generating secret.
Comment: well how does google adsense or the google maps http api work, more specifically how does the maps api enforce a limit on requests if the IP can be spoofed?
Comment: @John An IP cannot be spoofed (over the Internet).
Comment: Ok, well if the only variable I have to check for is $_SERVER['REMOTE_ADDR'], what can I do to check for the real IP?


Limit of the finite series $\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ k^2+kn+2n^2 }{k^3+k^2n+kn^2+n^3}$

Question: The problem is to find the limit of:
$$\ \lim_{n\to\infty}\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ k^2+kn+2n^2 }{k^3+k^2n+kn^2+n^3}$$
A the series is finite, it looks as if it would be required to find the sum of the series - however, I have to find the limit. It resembles for me:
$$\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ (k+n)^2+n^2-kn }{(k+n)^3-2kn^2-2k^2n}=\\
\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ (k+n)^2+n(n-k) }{(k+n)^3-2kn(n+k)}=\\
\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ (k+n)^2+n(n-k) }{(k+n)((k+n)^2-2kn)}$$
but I don't know what to do next and how to solve it. I would appreciate your help.
Edit: Does it has something in common with Riemann sum?
Comment: @user2661923. First time I hear about *a red herring* ! Amazing.
Comment: I don't know if it could help (I am stuck) but $ \frac{ k^2+kn+2n^2 }{k^3+k^2n+kn^2+n^3}=\frac{n}{k^2+n^2}+\frac{1}{k+n}$
Comment: Is it possible that the upper end of $\lfloor n + \sqrt{n}\rfloor$ is a red herring, and you are supposed to prove that the series is divergent through a bizarre comparison to the harmonic series?
Comment: @ClaudeLeibovici Your comment is *ironic* since one of the clues was **your rating**.  If 168k+ rep is having trouble, something may be up.
Comment: user2661923, I am not sure whether it is going to end up this way. It would be more cautious to consider other options first. What about Claude Leibovici modification and the sum of Rieman integrals from 1 to $n+\sqrt(n)$? However, we have the floor here...
Comment: I don't understand "...more cautious...".  If you can prove that the summation is divergent when the upper bound on the summation is **lowered** to $n$, then **you are done**.  It seems to me that this idea is worth at least 30 minutes.
Comment: was thinking also about setting two cases: given sum if $k=j^2$ for a certain $j$ (we get $k^2+k$ in sum) and 0 otherwise. In your solution, my first thought is to substract nominator and denominator by $n^3$
Comment: @user2661923 for $n=10^9$ the value of the sum is $1.47858$. I don't think it diverges. Setting $n$ instead of $\lfloor n+\sqrt n\rfloor$ leads  to the same result, obviously.
Comment: @Raffaele Interesting, the plot thickens
Answer: First, we can omit the $\sqrt{n}$ part and only sum up to $n$. To see this,
$$
\sum_{k=n}^{n+\sqrt{n}} x_n \leq
\sum_{k=n}^{n+\sqrt{n}} \frac{4(n+\sqrt{n})^2}{4n^3} \leq \sum_{k=n}^{n+\sqrt{n}} \frac{(n+n)^2}{n^3} \leq
\sum_{k=n}^{n+\sqrt{n}} \frac{4}{n} \leq 4\frac{\sqrt{n}}{n} \mapsto 0
$$
The rest is the Riemannian sum of the integral
$$
\int_0^1 \frac{x^2 + x + 2}{x^3 + x^2 + x + 1} \mathrm{d}x = \int_0^1 \frac{1}{1+x} \mathrm{d}x + \int_0^1 \frac{1}{1+x^2}\mathrm{d}x.
$$
This can be easily computed using calculus.
Comment: I found the same result adding $10^9$ terms of the original series. By the way, the integrand can be written as $1/(1 + x) + 1/(1 + x^2)$ which lead immediately to the result.
Comment: Looking at the growth of the nominator: from 0 to 1. Thank you!
Comment: Thanks for the decomposition, I added it into the answer, hope it's ok.
Comment: Thank you very much, it looks very nice for me. However, why the interval of integration is (0,1)? It is a very important question to me, as I have not found the answer to this yet in other examples. Additionally, could you explain more clearly, how do you omit $\sqrt{n}$
Comment: @Funny I could explain all in great detail, but would it not be better if you take this as some kind of hints, and complete it? Why from 0 to 1... Well, the expression can be rewritten to $\sum_1^n \frac{1}{n} \frac{(k/n)^2 + (k/n) + 2}{(k/n)^3 + (k/n)^2 + (k/n) + 1}$. If $x=k/n$, what is the range for $x$?
Answer: Attempts
Using the integral test, we can show the  convergence since
$$I=\int  \frac{ k^2+kn+2n^2 }{k^3+k^2n+kn^2+n^3}\,dk=\int \left(\frac{n}{k^2+n^2}+\frac{1}{k+n}\right)\,dk=$$
$$I=\log (k+n)-\tan ^{-1}\left(\frac{n}{k}\right)$$
Integrating between $k=1$ and $k=\lfloor n + \sqrt{n}\rfloor$ and simplifying, we have
$$\tan ^{-1}\left(\frac{n \left(\left\lfloor n+\sqrt{n}\right\rfloor
   -1\right)}{\left\lfloor n+\sqrt{n}\right\rfloor +n^2}\right)+\log \left(\frac{\left\lfloor n+\sqrt{n}\right\rfloor +n}{n+1}\right)$$ which is asymptotic to $\frac \pi 4+\log(2)\approx 1.47855$.
Integrating between $k=0$ and $k=\lfloor n + \sqrt{n}\rfloor$ and simplifying, we have
$$\log \left(\frac{\left\lfloor n+\sqrt{n}\right\rfloor +n}{n}\right)-\tan
   ^{-1}\left(\frac{n}{\left\lfloor n+\sqrt{n}\right\rfloor }\right)+\frac{\pi }{2}$$ which shows the same asymptotic value.
On the other hand, we can write the summation as
$$-\frac{1}{2} i H_{\left\lfloor n+\sqrt{n}\right\rfloor -i n}+\frac{1}{2} i H_{i
   n+\left\lfloor n+\sqrt{n}\right\rfloor }+H_{n+\left\lfloor n+\sqrt{n}\right\rfloor
   }-H_n-\frac{1}{2 n}+\frac{1}{2} \pi  \coth (\pi  n)$$ and using the asymptotics of harmonic numbers, the same result.
Answer: Thanks to Peter Franek I would try to calculate the limit.
The sum can be rewritten as:
$$\ \sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} \frac{ k^2+kn+2n^2 }{k^3+k^2n+kn^2+n^3} = \sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} (\frac{n}{k^2+n^2}+\frac{1}{k+n}) $$
$$\ a_n=\frac{n}{k^2+n^2} = \frac{n}{n^2}\cdot\frac{1}{\frac{k^2}{n^2}+1}$$
$$\ b_n=\frac{1}{k+n} = \frac{1}{n}\cdot\frac{1}{\frac{k}{n}+1} $$
Let us consider $f(x) = \frac{1}{x^2+1} $ and $g(x)=\frac{1}{x+1}$
$$\lim_{n\to\infty}a_n=\int_0^1f(x)dx=\int_0^1\frac{1}{x^2+1}dx=\arctan(x)|_0^1=\frac{\pi}{4} \\\lim_{n\to\infty}b_n=\int_0^1g(x)dx=\int_0^1\frac{1}{x+1}dx = \int_0^1\frac{c'(x)}{c(x)}=\ln(x+1)|_0^1=\ln(2)$$
As the element $\sqrt(n)$ becomes unsignificant for $n\to\infty$ as $\frac{\sqrt(n)}{n}\to0$, the limit is:
$$ \lim_{n\to\infty}\sum_{k=1}^{\lfloor n+\sqrt{n}\, \rfloor} (\frac{n}{k^2+n^2}+\frac{1}{k+n}) = \frac{\pi}{4}+\ln(2)$$
Comment: Yes, just remove the $-1$. Also, instead of $\lim a_n$, you probably want to write $\lim \sum_1^n a_n$. And what "becomes insignificant", is the sum $\sum_n^{n+\sqrt{n}}$. And missing $\lim$ in the last equation.
Comment: Thank you @PeterFranek your corrections. However, I have some questions about your notes. Firstly, I am quite confuesd as you insist on \sum_1^na_n, because as far as I'm corncerned, the Rieman sum approximate the limit of the sequence and I haven't encountered the sum notation. Is there a difference. Secondly, the insignificance is the result of the value of the sum \sum-n^{n+\sqrt{n}}, that doesn't change the result, isn't it?
Comment: Ok, I edited my answer to add details about the $\sqrt{n}$. The rest about Riemannian sum, please read about it here, for instance https://en.wikipedia.org/wiki/Riemann_sum The sum is a way how to approximate (or define) definite integrals.


How to add a catch-all wildcard to hook_menu?

Question: I want a url structure like so:
https://example.com/bob

which loads a custom page for the user bob. This is what I'm trying:
function mymodule_storefront_menu() {

    $items = array();

    // Wildcard catch for user's storefront
    $items['%'] = array(
      'title'           => 'User custom page',
      'type'            => MENU_CALLBACK,
      'page callback'   => 'mymodule_load_user_page',
      'page arguments'  => array(0),
      'access callback' => TRUE,
    );

    return $items;
}

function mymodule_load_user_page($user) {
    echo $user;
}

However, I'm getting a server 404 and drupal is logging a 'page not found' message the the dblog. Any ideas?
Edit:
I am able to get this to work:
$items['u/%'] = array(...);

but would prefer the plain wildcard to work, if possible.
Comment: "Note that wildcards may not be used as the first component." -- https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
Answer: The documentation for hook_menu() says it in the first wildcard example it provides. (Emphasis is mine.)

Wildcards in Paths
Simple Wildcards
Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':
  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.

The reason of this is pretty easy to understand: A wildcard as first component would be a catch-up for every Drupal route.
It would also conflict with the routes every Drupal module defines. This is also the reason why Drupal core uses node/%node for nodes, and user/%user for user accounts: Despite the wildcards being qualified, Drupal would not understand if a URI like 1 is referring to a node or a user account.
Comment: thanks for pointing that out. Despite being told in another comment this was the case, I was still having trouble finding it on the page. My hope was that drupal would know to execute the wildcard last, if all other rules fail, but you make a good point about conflict. Seems allowing that would interfere with other modules that wanted to do a catch-all.
Answer: Wildcards may not be used as the first component of a route path.
Comment: You are better to add the source as you did in comment.


Which Eclipse for Android only?

Question: I am starting Android development. Which of the many Eclipse downloads do I need from http://www.eclipse.org/downloads/ ?
I am only ever going to do Android dev with Eclipse ever.
Platform: MAC 64 bit Snowleopard
Comment: ahmm.. if you just want the eclipse instance for android development, then, why exactly eclipse at all ?
I mean, what do you usually use for development ?
Answer: Check out the SDK requirements page:
http://developer.android.com/sdk/requirements.html
On my Mac I am using the "Eclipse IDE for Java Developers".
Answer: You either use Java developer or Jave EE, I am using the Java EE version
and then follwing the guide on developer.android.com to how setting up eclipse and adt
Answer: Eclipse IDE for Java Developers  should be sufficient

Which Eclipse for Android only?


Heterogeneity in residuals

Question: I am very new in here, but I will try my best to create a good question.
First of all I am doing some regression on Fama and French 3 factor model and an asset.
Thus I am doing a OLS regression, using R code with the LM function, and wanting to rolling 1 step forcasts.
However by doing a Breusch Pagan test I can see my residuals contains heteroskedasticity, furthermore they are not normally distributed.
Since those a true violation of the OLS assumption, I tried different ways of correction the residuals, but without any luck.
Data contains returns for an Asset, (MK-RF), SMB and HML, which all contains both negative, zero and positive values.
LM Regression

data <- na.omit(read.csv("Market_Data_industries.csv",sep = ";", header = TRUE))
data$Date_format <- as.Date(data$Date, format = "%m-%d-%y")
data.xts <- xts(x = data[2:14], order.by = data$Date_format)
Model <-lm(XLF ~ Mkt.RF + SMB + HML, data=data)
plot(Model,1)

Theese are the residuals, which a pagan tests tells me are heteroskedasticity.
I tried to correct for this by using GLS, however not with much succes.

glsModelx <- gls(XLF ~ Mkt.RF + SMB + HML, data=data, weights = varPower(), method="ML", control = control)
plot(glsModelx)
plot(glsModelx$fitted, glsModelx$residuals)

Furthermore I could not do a Breusch Pagan test on the GLS model
<code>> bptest(glsModelx)
</code>
Error in as.data.frame.default(data) :
cannot coerce class 'c("glsStruct", "modelStruct")' to a data.frame
Any help or suggesting is aprreciated greatly, this problem have taken me hours....
Thank you very much.
Please say if you need any other information.
Comment: Although a formal test might reject a null hypothesis of homoscedasticity, it does so only by virtue of the large amount of data.  The plot shows little indication of heteroscedasticity and no indication of an amount of heteroscedasticity that might affect the model.  The apparently non-Normal distribution is unlikely to be a problem, either.
Comment: Hi Whuber, thanks for the fast reply!
Do any case you have any sources on the fact it rejects by cirtue of the large amount of data? In this dataset there are around 5541 data points.
Answer: The graph is unclear, because the centre is solid black. One way of dealing with this is to use solid marks (not hollow circles) but with a low alpha.
Having said that, what I think I am seeing is that for larger predictions the residual is larger. Is that the issue?
If so, then you are right that an assumption of linearity is not the best way to go. Can you devise a linearization? e.g predict $log (x+0.15)$ ?
But there is another thing to look at here: while it is true the errors are biased, they are fairly rare. For the actual business purpose, how much do they matter?
Comment: If you are concerned about hetero you might just use White standard errors. Normality is not a major issue if you have a hundred or more cases.it is better to interpret the graph rather than use formal test in any case. With a lot of data, and thus high power, you may reject the null and it may not mean anything substantively.
Comment: Hey @Chrishmorris, thanks for taking your time.

The plots, are just the regression residuals against the fitted values of the regression. My formal Breusch Pagan tests, indicates heteroskedasticity, I tried to get rid of this by implementing a GLS model, however not with much succeed.

The businees purpose is to make a rolling regression of all the data, and use it to make 1 step forecasts. The above graphs are just a way of checking how all the data is related, and if the OLS assumptions hold.
Comment: Hey @user54285, I am concerned. However do you know how to just implement White standard errors? I had a hard time finding any litterature on it or how to implement it into r. Thank you for your suggestion.
Comment: I know how to do it in SAS, but not R. What software are you using. Here is one discussion of it. https://en.wikipedia.org/wiki/Heteroscedasticity-consistent_standard_errors
Comment: Another concern you should have if you are making predictions in the future, outside the range of your data that has its own issue. This is essentially time series and that is pretty complex. You should look at the types of issues that time series raises.

Heterogeneity in residuals