Find the limit of a $f(x)=\frac{\lfloor x^2\rfloor}{x^2}$ at an arbitrary point

Question: The function f is defined $f(x)=\frac{\lfloor x^2\rfloor}{x^2}$
I need to find the limit of the function at an arbitrary point.
For the continuous parts it was fine, and also for right sided limit at positive points of discontinuity (and left sided for negatives, for all of which the lim is 1), and now I'm left with left sided limit of the function at positive points of discontinuity (and vice versa for the negative part).
I know the answer from intuition: $\frac{(x^2-1)}{x^2}$, but I can't find the key to the proof.
My attempt is as follows (letting the point of discontinuity be $x_0>0$)
First, I restrict delta such that $f(x)=\frac{(x_0^2-1)}{x^2}$
Then, if $x_0=1$ then $f(x)-L=0< \varepsilon$ (restricting $x>0$)
Otherwise, I restrict my neighborhood again to $1< x< x_0$, such that
$x<x_0 \rightarrow ... \rightarrow 1/x^2 - 1/x_0^2$
and therefore $f(x)-L=...=(x_0^2-1)(1/x^2 - 1/x_0^2)< \varepsilon$
And now I'm stuck... I can't seem to find the right combo to make the delta-epsilon magic to work.
Thanks for any help!
Comment: Hi! We appreciate that you have shown effort to your question and it's a good thing! But it would be more easier for us to read your question if you learn to type set in latex and attract more good answers!

http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Oh, great! I'll edit it right away
Comment: No, worries I have done it for you :), just see that there's no mistake.
Comment: @Mann: And you check mine ... I added `\lfloor` and `\rfloor` and changed `\epsilon` to `\varepsilon` which is typographically neater, I think.
Comment: Uh, thanks I had forgot the mathjax for for floor, I right clicked to see but there was only the character for some reason so i copied it right away! :)
Comment: Ok I tried to fix it myself but it said String edited it so I cant change it. The only thing missing is 1/x2−1/x20>0
Answer: Note: We know the floor function  $\lfloor x\rfloor$ fulfills
$$\lfloor x\rfloor \leq x < \lfloor x\rfloor+1$$
with points of discontinuity at the integers.
So, its convenient to partition the set $\mathbb{R}$ of real numbers according to the points of discontinuity of the function
\begin{align*}
&f:\mathbb{R}\backslash\{0\}\rightarrow\mathbb{R}\\
&f(x)=\frac{\lfloor x^2\rfloor}{x^2}
\end{align*}
which is defined for all real numbers except $0$.
We set $$\mathbb{R}\backslash\{0\}=(-\infty,0)\cup[0,\infty)\backslash\{0\}$$ and
\begin{align*}
[0,\infty)&=\bigcup_{n\geq 0}A_n\qquad \text{ with }A_n=[\sqrt{n},\sqrt{n+1})\\
(-\infty,0)&=\bigcup_{n\geq 1}B_n\qquad \text{ with }B_n=[-\sqrt{n},-\sqrt{n-1})
\end{align*}
The set $\{A_n,B_{n+1}|n\geq 0\}$ forms a partition of pairwise disjoint, non-empty, right half-open intervals with union equal $\mathbb{R}$ (and with different lengths).
\begin{align*}
\mathbb{R}&=\ldots\cup[-2,-\sqrt{3})\cup[-\sqrt{3},-\sqrt{2})\cup[-\sqrt{2},-1)\cup[-1,0)\\
&\qquad\qquad\cup[0,1)\cup[1,\sqrt{2})\cup[\sqrt{2},\sqrt{3})\cup[\sqrt{3},2)\cup\ldots
\end{align*}

We first calculate the limits in the interior of the intervals, then we'll have a look at the left endpoints of $A_n$and $B_n$.
Interior of $A_n$: ${A}^{\circ}_{n}=(\sqrt{n},\sqrt{n+1}), n\geq 0$
Let's fix $n_0\geq 0$ and consider the interior ${A}^{\circ}_{n_0}=(\sqrt{n_0},\sqrt{n_0+1})$. The function $f$ is given by
  $$f(x)=\frac{n_0}{x^2},\qquad \sqrt{n_0}<x<\sqrt{n_0+1}$$
  in the interior of $A_{n_0}$. Let  $x_0\in {A}_{n_0}^\circ=(\sqrt{n_0},\sqrt{n_0+1})$, then
  $$\lim\limits_{x\to x_0^-}\frac{n_0}{x^2}=\lim\limits_{x\to x_0^+}\frac{n_0}{x^2}=\frac{n_0}{x_0^2}$$
  Since the left- and right-hand limit of $x_0$ and the function value at $x_0$ coincide, the limit at $x_0$ exists and
  $$\lim\limits_{x\to x_0}f(x)=\lim\limits_{x\to x_0}\frac{n_0}{x^2}=\frac{n_0}{x_0^2} \qquad\qquad x_0\in {A}_{n_0}^{\circ}, n\geq 0$$

Interior of $B_n$: ${B}_n^\circ=(-\sqrt{n},-\sqrt{n-1}),n\geq 1$
Let's fix $n_0\geq 1$ and consider the interior ${B}_{n_0}^\circ=(-\sqrt{n_0},-\sqrt{n_0-1})$. The function $f$ is given by
  $$f(x)=\frac{n_0}{x^2},\qquad -\sqrt{n_0}<x<-\sqrt{n_0+1}$$
  in the interior of $B_{n_0}$. Let $x_0\in {B}_{n_0}^\circ=(-\sqrt{n_0},-\sqrt{n_0-1})$, then
  $$\lim\limits_{x\to x_0^-}\frac{n_0}{x^2}=\lim\limits_{x\to x_0^+}\frac{n_0}{x^2}=\frac{n_0}{x_0^2}$$
  Since the left- and  right-hand limit of $x_0$ and the function value at $x_0$ coincide, the limit at $x_0$ exists and
  $$\lim\limits_{x\to x_0}f(x)=\lim\limits_{x\to x_0}\frac{n_0}{x^2}=\frac{n_0}{x_0^2} \qquad\qquad x_0\in {B}_{n_0}^{\circ}, n\geq 1$$

Left endpoints of $A_n=[\sqrt{n},\sqrt{n+1})$: Points $x_0=\sqrt{n}, n\geq 1$
We exclude the interval $A_0$, since $f$ is not defined at the left endpoint of $A_0=[0,1)$. Let's fix $n_0\geq 1$ and consider the left endpoint $x_0=\sqrt{n_0}$ of $A_{n_0}$. We observe since $A_{n_0-1}=[\sqrt{n_0-1},\sqrt{n_0})$
  \begin{align*}
\lim\limits_{x\to \sqrt{n_0}^{\,-}}f(x)&=\lim\limits_{x\to \sqrt{n_0}^{\,-}}\frac{n_0-1}{x^2}=\frac{n_0-1}{n_0}=1-\frac{1}{n_0}\\
\lim\limits_{x\to \sqrt{n_0}^{\,+}}f(x)&=\lim\limits_{x\to \sqrt{n_0}^{\,+}}\frac{n_0}{x^2}=\frac{n_0}{n_0}=1\\
f(\sqrt{n_0})&=\frac{n_0}{n_0}=1
\end{align*}
  Since left- and right-hand limit of $x_0$ do not  coincide, the limit at $x_0=\sqrt{n_0}$ does not exist.

Left endpoints of $B_n=[-\sqrt{n},-\sqrt{n-1})$: Points $x_0=-\sqrt{n}, n\geq 1$
Let's fix $n_0\geq 1$ and consider the left endpoint $x_0=-\sqrt{n_0}$ of $B_{n_0}$. We observe since $B_{n_0+1}=[-\sqrt{n_0+1},-\sqrt{n_0})$
  \begin{align*}
\lim\limits_{x\to -\sqrt{n_0}^{\,-}}f(x)&=\lim\limits_{x\to -\sqrt{n_0}^{\,-}}\frac{n_0+1}{x^2}=\frac{n_0+1}{n_0}=1+\frac{1}{n_0}\\
\lim\limits_{x\to -\sqrt{n_0}^{\,+}}f(x)&=\lim\limits_{x\to -\sqrt{n_0}^{\,+}}\frac{n_0}{x^2}=\frac{n_0}{n_0}=1\\
f(-\sqrt{n_0})&=\frac{n_0}{n_0}=1
\end{align*}
  Since left- and  right-hand limit of $x_0$ do not  coincide, the limit at $x_0=\sqrt{n_0}$ does not exist.

Summary:

The function $f(x)=\lim\limits_{x\to x_0}\frac{\lfloor x\rfloor}{x^2}$ has discontinuities exactly at $x\in \mathbb{Z}\backslash\{0\}$
The limit $\lim\limits_{x\to x_0}\frac{\lfloor x^2\rfloor}{x^2}$ exists for all values $x_0\in \mathbb{R}\backslash\mathbb{Z}$ and
  $$\lim\limits_{x\to x_0}\frac{\lfloor x^2\rfloor}{x^2}=\frac{\lfloor x_0^2\rfloor}{x_0^2}$$
The function $f(x)=\frac{\lfloor x^2\rfloor}{x^2}$ has a removable singularity at $x=0$. Since
  \begin{align*}
\lim\limits_{x\to 0^-}\frac{\lfloor x^2\rfloor}{x^2}=\lim\limits_{x\to 0^-}\frac{0}{x^2}=0
\text{ and }
\lim\limits_{x\to 0^+}\frac{\lfloor x^2\rfloor}{x^2}=\lim\limits_{x\to 0^+}\frac{0}{x^2}=0
\end{align*}
  we can define a function
  \begin{align*}
&g:\mathbb{R}\rightarrow\mathbb{R}\\
&g(x)=
\begin{cases}
f(x)=\frac{\lfloor x^2\rfloor}{x^2}\qquad&x\ne 0\\
0&x=0
\end{cases}
\end{align*}
  which is continuous at $x=0$.


How do I separate my dataset into train and test set by using k-fold validation?

Question: I having a dataset ready for speech recognition.
I having 10 different speakers, each utterance English digit 0 to 9 with 5 samples of each digit.
So how do I validate my dataset by using k-fold cross validation?
Thank you.
Answer: If your sample space includes only 50 samples (5 per digit) then your dataset is too small , you need to get more data (or generate through data augmentation , even if its 500 - 5 per user per digit you'll need more data to get better accuracies but you can start experimenting !!  ).
More on the sizes of datasets on this discussion.Regarding k-fold cross validation you can follow this documentation if you use python.
Comment: Can I augmented my samples with different SNR value to expand my samples? for example: -10dB, -5dB, 0dB, 5dB, 10dB, 15dB and 20dB ?
Comment: I think that this is done mostly if you want to make your models more robust to noise ... that being said i think varying SNR wouldnt help you since without sufficient data it would not be able to become invariant to different types of utterances of the same word , this also depends on what model you are using..(It wouldnt hurt to try this though). There are other ways to augment dataset look at this [link] http://speak.clsp.jhu.edu/uploads/publications/papers/1050_pdf.pdf  eg changing the tempo . Hope this helps !
Comment: Thanks !! if this answer  solved your problem please accept it .. helps with the reputation :)


jQuery variable trouble

Question: I'm trying to load in some content with the .load() function, here's my code.
$(window).load(function() {

    $('.spotlight').append('

');
    $('.spotlight .caption').hover(function () {
         $(this).animate({ top : '-=50px' }, 150)}, function () {
         $(this).animate({ top : '+=50px' }, 150)}
    );

    $('.caption').load($(this).parent().data('who')+'.html');

});

but in the HTML I have

But it tries to load in undefined.html. How would I go about fixing this?
Here's a link to the page http://www.coralspringshigh.org/demo/
Comment: can you paste complete HTML with the element which has caption class
Comment: Can you give us the whole event that you are calling `.load()` from?  Its hard to know what `this` is without the context of that function...
Comment: Sorry about that, added the rest of the code.
Answer: Chances are this is returning undefined:
$(this).parent().attr('who')

Make sure that this parent has a value in the attribute who.
Comment: It does, but theres two parents with attribute who, making it undefined
Answer: First thought, you should be using data-who="student" instead of just who, that way you can use $(this).parent().data('who')+'.html'
Now that you've updated to include more of the code, the flaw is more obvious.  this in that context is actually window because you are inside of the $(window).load() handler.  Try doing something like this instead:
// fires on document ready, not quite window load, but better:
$(function() {
  $('.spotlight').each(function() {
    var spot = $( this ),
        caption = $("

").appendTo(spot);

    caption.load( spot.data('who') + '.html' );
    spot.hover(function() {
      caption.animate({ top : '-=50px' }, 150)
    }, function () {
      caption.animate({ top : '+=50px' }, 150)
    });
  });
});

Comment: Also I don't think the `who` attribute is valid on any element.  data-{anything here}, however, is.
Comment: @Koalatea - You need to give us more info in the original question - see the comments please....
Comment: Ahh, I just realized it was 'window.load()', that was a stupid mistake by me. but it still tries to load undefined.html, except instead of trying to load it once, it fails twice, so at least that's better.
Comment: @Koalatea did you switch to using the `data-who` attribute in the HTML instead of just `who` ???
Comment: Me being an idiot, forgot to do that part. Thanks for putting up with me! Working good now.
Answer: Try this:
$('.caption').each(function() {
                       $(this).load($(this).parent().attr('who') + '.html');
                   });

Comment: The problem with that is that it loads both .captions with the same file

jQuery variable trouble


Services module and hook_node_view

Question: When I view a node via Services in json or xml format a field I am adding via hook_node_view is unavailable. How could I add the field so it is available also when the node is viewed via Services?
I only seem to be able to access the node via hook_node_load
Answer: hook_node_view() is only invoked when a node is prepared for display (normally either through node_view() or node_view_multiple()).
Since the node isn't prepared for display when you request it via a services call, your hook won't be called. If you think about it this makes perfect sense; you're requesting a json/xml representation of the node so there's absolutely no reason why the node should be prepared for display.
The only way round this would be to move your logic into hook_node_load(), which is called for all node loads. The same data that you attach in hook_node_load() is available to you on the node object in hook_node_view(), so you'll be able to move your logic without any problem at all.
I suppose the other, more complicated method, would be to write your own Services resource that loads the node view as well as the node, so the extra data you're adding would get picked up.
But semantically speaking, unless the actions you're taking relate specifically to the HTML that will be output for the node, hook_node_view() is not the right place to add your extra data.

Services module and hook_node_view


How is feature importance calculated in an extra-tree?

Question: I am currently working with extra-trees in the sklearn package but was wondering how the feature importance (function) is calculating the importances of the features. Is it also calculated by the mean decrease Gini or is there another way?
Could not find anything in the source code on GitHub.
Comment: This sounds like it is just a question about the sklearn function. If so, it would be off topic here; you should read the documentation or contact the tech support somehow. If you have a machine learning question about the measurement of importance in extra trees, please edit to clarify.
Comment: Wow, the the "off-topic" crusaders are quick on the trigger.
Answer: Extra tree classifier in sklearn used Gini Importance for calculating the feature importance.
You can check the following link:
http://scikit-learn.org/stable/modules/generated/sklearn.tree.ExtraTreeClassifier.html


How to calculate backpropagation derivatives for 2 hidden layers?

Question: I am following this guide on calculating the partial derivatives of weights and biases:
https://www.datahubbs.com/deep-learning-101-the-theory/
Here it is using 1 hidden layer. How can I calculate the backpropagation if I add another hidden layer? Assuming it is using the sigmoid activation function same as the guide. Thanks!
Answer: Sadly it's extremely difficult to type out mathematical equations here, so I've linked some backpropagation derivation notes that I found useful.
Comment: Thank you! The link was helpful too.


In R, does randomForest use terms() of model.matrix?

Question: I am using the randomForest package in R with categorical co-variates. The documentation advises against the formula interface for large data.  Following this advice, I prepare the outcome variable and a model.matrix object, M.
My question is does the algorithm treat the columns of M independently, so the mtry variables chosen may be biased to selecting from a factor with many levels? Or is the original factor (available via terms(M)) used when selecting the mtry variables?
I am familiar with cforest and the papers by Strobl et al. that address the bias in randomForest based on the domain of the variables.  My question is does the choice of arguments (formula vs matrix) in randomForest exacerbate this bias.
thanks.
Answer: tl;dr
randomForest will include and exclude dummy-encoded columns independently if using a model matrix, and together if using a data.frame and formula. So yes, the treatment is different (better?) using the formula interface.
Evidence
randomForest under the hood doesn't break categorical variables into multiple columns. It encodes them as one numeric column with their factor code (using data.matrix). It uses ncat/cat internally to keep track of which variables are numeric and categorical.
For matrix input, this just gets set to 'numeric' for every variable.
mtry then causes the sampling of each column with equal probability.
Comment: Thanks for the source links.  This is a rather critical issue that should be called out in the documentation.
Comment: How could it be possible to jump over the less than 53 categories? Using model.matrix is an option?


Writing to wav file from a stream has no audio data

Question: I'm working on creating a wav file from a stream on iheartradio. I am able to get the stream url, but once I write the data to a wav file, I cannot play it on any media player I've tried. I don't have experience with wav files too much so any help would be greatly appreciated. This is what I've got so far from looking at similar posts:
import requests

stream_url = "http://stream.revma.ihrhls.com/zc2525"

r = requests.get(stream_url, stream=True)

with open('stream.wav', 'wb') as f:
    try:
        for block in r.iter_content(1024):
            f.write(block)
            print(block)
    except KeyboardInterrupt:
        f.close()

Answer: I've tested your code, and it seems to be working. I have no issue at all. The issue must be your audio player.
Have you tested it with a wav file you know is working?
Answer: You're making the assumption that the response contains a WAV header followed by PCM (Pulse Code Modulated) samples. That's not the case. If you print the response headers, you'll see that the response contains AAC (Advanced Audio Coding) audio data, which is a lossy compressed audio format - totally different from lossless WAV. AAC is pretty standard for internet radio streams.
That being said, your code works fine for me, and the generated ".wav" file does play in my Windows 10 Windows Media Player / VLC. However, Just because you gave your file the ".wav" extension, doesn't mean it's actually a WAV file. It could just be that your media players are more pedantic than mine, and refuse to play files where there's a discrepancy between the file's headers and the file's extension. My media players seem to ignore the extension, and attempt to determine the format by inspecting the file headers - you could even rename it to stream.mp3 or stream.foobar, and it will play just the same. Again, the file extensions don't really matter, what matters is the actual data (headers and samples) that you write to the file. Don't assume that everything is a WAV file.
Comment: You're actually right here. I looked at the response and it was sent in MPEG format. So reading that into a .wav file produced static audio for me. When I changed my file extension to mp3/MPEG, it all worked fine.


Dart: How to get a list of package's variables, functions, etc.?

Question: In python there is dir function that lists methods and variables of modules and classes. How to do the same in Dart?
I have to check whether a certain variable exists in an imported package. I tried to wrap it with try-catch block, but it crashes on compile-time with the following output:
ex_01_test.dart:9:19: Error: Getter not found: 'obj'.
    print(student.obj);

Comment: You would have to use reflection for something like that. Look into the mirrors package. That being said, reflection should be used sparingly. See if there are other ways to achieve the functionality you want without checking for the existence of variables at runtime. Also notably, the mirrors package is not available on flutter if you are building a flutter app.
Answer: Your IDE should already be informing you that something doesn't exist, as you discovered.  There's no "runtime check" for this, as Dart is fully compiled before executing a single line.
Comment: Even the official Dart compiler does not use full ahead-of-time compilation by default. Much of one's code is JIT compiled.
Comment: That last part of your answer regarding compilation is inaccurate. The Dart specification does not specify the time of compilation. Whether it is fully compiled before execution or not is up to the implementation.
Comment: And when there's a viable alternate implementation of Dart, suddenly your comment will make sense.  I'm talking about the current, and foreseeable future Dart ecosystem.


What does "Entity API" add to the Drupal API, and why would a module depend on it?

Question: The Entity API module extends the entity API defined in Drupal. In which cases should a module use the API provided from that module? Are modules that implement new entities easier to be written if they depend on the Entity API module?
By "easier to be written" I mean that modules using Entity API would require less code to be written compared to a module that doesn't use Entity API.
I read the project page, but I still don't completely understand the reason to prefer creating a module that depends on the Entity API module, rather than a module depending only from Drupal core code. I understand that a module extending rules and implementing an entity should use the Entity API module; in the first case, the reason is also that the Rules module depends on the Entity API module.
Comment: The project page you linked provides a fairly specific overview of what the module does. Do you have specific questions about why a module would depend on it other than what they lay out there?
Comment: If you don't use Entity API module, you end up writing a module like [this sandbox project](http://drupal.org/sandbox/Mile23/1289524).  Note that this sandbox project has no tests and only one contributor, whereas Entity API has many of both.
Answer: Not complete, but here are some advantages that I know of:

Drupal core only provides an EntityController for loading entities. For save, update and delete, you either need to write it yourself or use Entity API.
You you can expose the base properties of your entities wit hook_entity_property_info(), see privatemsg_entity_property_info() for an example. The advantage of this is that rules.module knows your entity properties and you read and write them with rules. And you also get token integration for free.
It can also automatically provide you with an administrative UI for your entities
Comment: Core provides an UI to configure fields and attach them to entities, entity API provides an UI to create and manage entities for custom entities, core does nothing like that.
Comment: not to forget the great metadata_wrapper http://drupalcontrib.org/api/drupal/contributions%21entity%21entity.module/function/entity_metadata_wrapper/7 that allows you to easily access the field's values in code
Comment: What do you mean by an admin ui? Some of this is handled by core.
Answer: Automatic Views integration, admin UI, exportable entities (all of this is optional).
Plus a lot of syntax sugar things that didn't make it into D7 and you need them (generic entity_save(), entity_create(), putting your custom logic in "entity classes"...)
Plus, modules (efq_views, rules) do really cool things with properties.
Answer: i do believe, the entity api (module) was basically removed from drupal 7 core prior to release because it was considered incomplete..  Only the basic entity api CRUD functions where left in drupal core for its GM release .


UMP level $\alpha$ test with distribution $f(x|\lambda) = \lambda x^{-2}$

Question: Suppose we have a random sample from the distribution $f(x|\lambda) = \lambda x^{-2}$ with $x > \lambda$. I want to find a UMP level $\alpha$ test for the hypothesis test $H_0: \lambda = \lambda_0$ and $H_1: \lambda = \lambda_1$, where $\lambda_1 > \lambda_0$.
I believe $\prod_{i=1}^n x_i$ is a sufficient statistic for $\lambda$, but I don't know what to do from here. What is the general strategy?
Comment: Cross-posted at https://math.stackexchange.com/questions/2767098/ump-level-alpha-test-with-distribution-fx-mid-lambda-lambda-x-2?noredirect=1&lq=1.
Answer: This distribution is a Pareto distribution with shape parameter equal to $1$.
While we are stepping through the derivation of the uniformly most powerful test, we'll make use of two facts about the Pareto distribution.
First, as it happens, the minimal sufficient statistics for the Pareto distribution with unknown lower bound $\lambda$ and unknown shape parameter $a$ are the minimum value of $x$ ($x_{[1]}$) and $\sum\log x$ (see Estimation of the parameters of the Pareto distribution.)  If $a$ is known, as it is in this case, then $x_{[1]}$ is sufficient for $\lambda$.
As a result, we will be interested in the distribution of $x_{[1]}$.  Our second fact is that the distribution of the minimum value from a collection of Pareto distributions with lower bound $\lambda$ and shape parameters $a_i, i=1, \dots, N$ is Pareto with shape parameter $a_0 = \sum_{i=1}^N a_i$ and lower bound $\lambda$.  For this problem this equates to a $\text{Pareto}(n,\lambda)$ distribution.
On to the question!  The Neyman-Pearson lemma tells us that the UMP test for a simple hypothesis and alternative, as in the problem statement, is a likelihood ratio test.  Since $x_{[1]}$ is sufficient for the parameter of interest and the other parameter is known, the test can be constructed using the distribution for $x_{[1]}$ under the null and alternative hypotheses.  Writing out the likelihood ratio gives us:
$$\Lambda = {\mathcal{L}(\lambda_0;x_{[1]}) \over \mathcal{L}(\lambda_1;x_{[1]}) } = {\lambda_0x_{[1]}^{-n-1}1(x_{[1]} \geq \lambda_0) \over \lambda_1x_{[1]}^{-n-1}1(x_{[1]} \geq \lambda_1)} = {\lambda_01(x_{[1]} \geq \lambda_0) \over \lambda_11(x_{[1]} \geq \lambda_1)}$$
where $1(x_{[1]} \geq \lambda_0)$ is the indicator function that takes on the value $1$ if the condition is true, $0$ otherwise.
Since $\lambda_1 > \lambda_0$, the likelihood ratio takes on the value $\lambda_0/\lambda_1$ when $x_{[1]} \geq \lambda_1$ and is undefined when $x_{[1]} < \lambda_1$.  In the latter case, we know that the alternative hypothesis is false, so we would not want to reject the null hypothesis.
Now for constructing an $\alpha$-level test.  We consider two cases:

$P(x_{[1]} < \lambda_1|H_0) \geq 1-\alpha$,
$P(x_{[1]} < \lambda_1|H_0) < 1-\alpha$

In the special case (as here) of $a = 1$, $P(x_{[1]} < \lambda_1 | H_0) = 1 - \lambda_0/\lambda_1$, and a small amount of algebra reveals that these conditions simplify to:

${\lambda_0 \over \lambda_1} \leq \alpha$,
${\lambda_0 \over \lambda_1} > \alpha$

In the first case, the probability of incorrectly rejecting $H_0$ is $\leq \alpha$ even if we reject 100% of the time that $x_{[1]} \geq \lambda_1$.  Therefore, the closest we can get to an $\alpha$ level test is to reject $H_0$ all the time.  The actual level of this test is $\lambda_0 / \lambda_1$.
In the second case, we need to construct a rejection region in $[\lambda_1, \infty)$ with the appropriate probability.  Usually we would take the region(s) with the lowest likelihood ratios, writing imprecisely, because this gives us the best type II error, but in this case the likelihood ratio is constant over the entire region, so no guidance is to be found there.  On the other hand, this fact means that any region with the appropriate probability under $H_0$ is as good as any other, so we may as well pick a region of the form $[\lambda_1, \tau]$.
We want our rejection region to satisfy:
$${P(\lambda_1 \leq x_{[1]} \leq \tau|H_0) \over P(\lambda_1 \leq x_{[1]} \leq \tau|H_0) + 1 - \lambda_0/\lambda_1}  = \alpha$$
Some algebra shows us that:
$$P(\lambda_1 \leq x_{[1]} \leq \tau|H_0) = {\lambda_0 \over \lambda_1} - {\lambda_0 \over \tau}$$
which, when combined with the above and a little simplification of the denominator, leads to:
$${{\lambda_0 \over \lambda_1} - {\lambda_0 \over \tau} \over 1-{\lambda_0 \over\tau}} = \alpha$$
Multiplying both numerator and denominator on the l.h.s. by $\tau$ gives us:
$${{\lambda_0 \over \lambda_1}\tau - \lambda_0 \over \tau - \lambda_0} = \alpha$$
and some further rearrangement gives us:
$$\tau_{\alpha} = {(1-\alpha)\lambda_0 \over {\lambda_0 \over \lambda_1} - \alpha}$$
The sign of the denominator need not worry us, as we know from case 2 above that $\lambda_0/\lambda_1 > \alpha$.
We can show that $\tau > \lambda_1$ easily enough by multiplying the top and bottom of the r.h.s. by $\lambda_1$ and observing that:
$$\tau > \lambda_1 \text{ iff } {(1-\alpha)\lambda_0\lambda_1 \over \lambda_0 - \alpha\lambda_1} > \lambda_1$$
We check whether the ratio:
$${(1-\alpha)\lambda_0 \over \lambda_0 - \alpha\lambda_1} = {\lambda_0-\alpha\lambda_0 \over \lambda_0 - \alpha\lambda_1} > 1$$
which, since $\lambda_1 > \lambda_0$, is clearly true.
So, in the case where $\lambda_0/\lambda_1 > \alpha$, the $\alpha$-level UMP is to reject the null hypothesis when $x_{[1]} \in [\lambda_1, \tau_{\alpha}]$, with $\tau_{\alpha}$ defined as above.


Cliente/Servidor (Windows) com Sockets em C

Question: Estou tentando elaborar um programa escrito em C, que seja capaz de fazer upload de um arquivo ou texto para um determinado servidor.
Procurei bastante na google mas a maior parte dos tutoriais é voltada para ambiente linux, ou não está tão completa ou então oferecem código pronto sem explicação alguma.
Tenho alguma noção de C, mas a parte de sockets é uma salada e cobra a utilização de diversos procedimentos encadeados. Preciso entender só essa questão de sockets e comunicação entre cliente/servidor.
Comment: Pedidos de recomendação não costumam funcionar bem aqui no site (geram muitas respostas e fica difícil/subjetivo julgar qual seria a melhor). Então removi essa parte da pergunta. Vamos ver se alguém consegue te explicar o caminho das pedras aqui mesmo, recorrendo a links externos apenas para referência/complementação da explicação.
Comment: Mais uma coisa: se possível, edite a pergunta incluindo detalhes sobre suas tentativas. Se as pessoas entenderem com mais precisão onde está sua dificuldade, é mais provável conseguir uma boa resposta.
Comment: Amigo, mesmo você sendo da área C, recomendo usar C++ e Boost.Asio
Comment: Especifique o tipo de servidor. Alternativas são WinHTTP e FTP com a referência: http://msdn.microsoft.com/en-us/library/ms905225.aspx
Answer: Vc deve ler a MSDN: WinSock 2
Lá vc encontra os tutoriais Using Winsock (Recomendo usar C++ para essas API's da Microsoft)
Tem esse tutorial do meu amigo Felix_Poison: Clique Aqui  (Esse tutorial é especificamente em C)
E agora segue um código de exemplo de cliente e servidor de WinSockets.
Servidor:
<code>/*
 * Servidor com WinSock 2
 *
 * Autor: Ighor Augusto Barreto Candido
 *
 * NOTA: compilado com cl.exe (compilador do Visual Studio)
 */

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void)
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    printf("\n\n\t\t\t\t\t Socket TCP/IP Server by Ighor Augusto\n");
    printf("\n\t-> Inicializando a biblioteca de Winsock...");
    // Inicializando a biblioteca de Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("\t\t[-] WSASturtup falhou! Erro: %d\n\n", iResult);
        return 1;
    }
    printf("\t\t[+] Biblioteca inicializada com sucesso!\n");

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    printf("\t-> Resolvendo endereco e porta do servidor...");
    // Resolvendo o endereco e porta do servidor
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }printf("\t\t[+] Sucesso!\n");

    printf("\t-> Criando SOCKET para conexao...");
    // Criando Socket
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("\t\t\t[-] Socket falhou! Erro: %ld\n\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
    printf("\t\t\t[+] Socket criado com sucesso!\n");

    printf("\t-> Setando TCP listening socket...\n\n");
    printf("\t-> bind()...");
    // Setup TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t\t[-] bind() falhou! Erro: %d\n\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t\t[+] Sucesso!\n");

    freeaddrinfo(result);

    printf("\t-> listen()...");
    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t\t[-] listen() falhou! Erro: %d\n\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t\t[+] Sucesso!\n");

    printf("\t-> Aguardando conexoes! accept()...");
    // Aceitando um cliente socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
            printf("\t\t\t[-] accept() falhou! Erro: %d\n\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t[+] Sucesso!\n");

    closesocket(ListenSocket);

    printf("\n\t[+] Servidor pronto para receber dados!!!\n\n");
    // Recebe ate o cliente encerrar a conexao
    do {

        printf("\t-> Aguardando...");
        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("\t\t\t\t\t[+] Bytes recebidos: %d\n", iResult);
            printf("\t-> Enviando um eco ao cliente...");
            // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("\t\t\t[-] send() falhou! Erro: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("\t\t\t[+] Sucesso! Bytes enviados: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("\t\t\t\t\t[-] Conexao fexada pelo cliente!\n");
        else  {
            printf("\t\t\t\t\t[-] recv() falhou! Erro: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    printf("\t-> Encerrando...");
    // Fexando a conexao quando terminarmos
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t[-] shutdown() falhou! Erro: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t[+] Encerrado!\n");
    printf("\n\n\t### Bye!!! ###\n");
    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;

}
</code>
Cliente:
<code>/*
 * Cliente com Winsock 2
 *
 * Autor: Ighor Augusto Barreto Candido
 *
 * NOTA: compilado com cl.exe (compilador do Visual Studio)
 */

 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN
 #endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

// Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv)
{
   WSADATA wsaData;
   SOCKET ConnectSocket = INVALID_SOCKET;
   struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;
   char *sendbuf = "this is a test";
   char recvbuf[DEFAULT_BUFLEN];
   int iResult;
   int recvbuflen = DEFAULT_BUFLEN;

// Usage
if (argc != 2) {
    printf("\n\n\t\tCliente Socket TCP/IP by Ighor Augusto\n");
    printf("\t\tUsage: %s endereco do host\n", argv[0]);
    return 1;
}

printf("\n\n\t\t\t\t\t Socket TCP/IP Server by Ighor Augusto\n");
printf("\n\t-> Inicializando a biblioteca de Winsock...");
// Initializando a biblioteca de Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("\t\t[-] WSASturtup falhou! Erro: %d\n\n", iResult);
    return 1;
}
printf("\t\t[+] Biblioteca inicializada com sucesso!\n");

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

printf("\t-> Resolvendo endereco e porta do servidor...");
// Resolvendo o endereco e porta do servidor
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
    printf("\t\t[-] getaddrinfo() falhou! Erro: %d\n\n", iResult);
    WSACleanup();
    return 1;
}
printf("\t\t[+] Sucesso!\n");

printf("\t-> Iniciando procedimento de conexao...");
// Lanca tentativas de conexao com o host até obter sucesso... ou nao.
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

    printf("\n\t-> Criando SOCKET para conexao...");
    // Criando socket
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
        ptr->ai_protocol);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("\t\t\t\t[-] Socket falhou! Erro: %ld\n\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    printf("\t\t\t[+] Socket criado com sucesso!\n");

    printf("\t-> Conectando ao host...");
    // Connect to server.
    iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        ConnectSocket = INVALID_SOCKET;
        continue;
    }
    break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
    printf("\t\t\t\t[-] Conexao com o server invalida!\n\n");
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Sucesso!!!\n");

printf("\t-> Enviando buffer inicial...");
// Enviando um buffer inicial
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
    printf("\t\t\t\t[-] send() falhou! Erro: %d\n\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Sucesso! Bytes enviados: %ld\n", iResult);

printf("\t-> Encerrando conexao...");
// Encerrando conexao desde que nao iremos enviar mais buffers
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("\t\t\t\t[-] shutdown() falhou! Erro: %d\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Encerrado!\n");

printf("\t-> Lendo a resposta do servidor...");
// Aguardando resposta do servidor
do {
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
        printf("\t\t\t[+] Sucesso! Bytes recebidos: %d\n", iResult);
    else if ( iResult == 0 )
        printf("\n\t[+] Procedimento finalizado!\n");
    else
        printf("\t\t\t[-] recv() falhou! Erro: %d\n", WSAGetLastError());

} while( iResult > 0 );

printf("\n\n\t### Bye!!! ###\n");
// cleanup
closesocket(ConnectSocket);
WSACleanup();

return 0;
}
</code>
Espero ter ajudado!!!
Abraço!
Comment: Valeu ighor, o tutorial me ajudou bastante!


Executing Android Lint on Windows by only using Android SDK tools (Without Android Studio or Android SDK)

Question: I'm trying to execute Android Lint tests on windows without using Android Studio or Android SDK.
I tried following approach as it is stated in the documentation that it's not required to have gradle or android studio. This requires to download command line tools for Android SDK. Then executing below,
cd C:\Users\User\Desktop\sdk-tools-windows-3859397\tools\bin
lint \path\to\project\location

Executing above results in,
myapp: Error: "myapp" is a Gradle project. To correctly analyze Gradle projects, you should run "gradlew :lint" instead. [LintError]
Then I tried using gradle,
cd \path\to\project\location
gradlew lint

Then it throws following error,
A problem occurred configuring project ':app'.
> The SDK directory 'C:\Users\Test\AppData\Local\Android\sdk' does not exist.

Is it not possible to execute Android Lint only using Android SDK command line tools?
Answer: I pointed ANDROID_HOME to the Android SDK tools directory in system variables.
Then executed below,
cd \path\to\project\location
gradlew lint

I'm following this approach for now. But this is confusing since the the official android developer documentation of lint, it mentions we can use "lint" as standalone with android projects. Here as the workaround i'm using "gradlew lint"


How to repeat the alarm for "n" days at a particular time

Question: This is my code to set the alarm for every 24 hours. How can I repeat this for 20 days only?
<code>alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
     calendar.getTimeInMillis(),
     24*60*60*1000,
     pendingIntent);
</code>
Answer: that will be repeating forever until you cancel it. So, what you can do, it's to fire something in 20 days,and when managing that event, cancel your alarm.


Accessing constraints/objective

Question: I'm using a toolbox that internally calls Pyomo to solve an optimization problem. I am interested in accessing the Pyomo model it constructs so I can modify the constraints/objective. So my question is, suppose I get the following output:
Problem:
Name: unknown
Lower bound: 6250.0
Upper bound: 6250.0
Number of objectives: 1
Number of constraints: 11
Number of variables: 8
Number of nonzeros: 17
Sense: minimize
Solver:
Status: ok
Termination condition: optimal
Statistics:
    Branch and bound:
    Number of bounded subproblems: 0
    Number of created subproblems: 0
Error rc: 0
Time: 0.015599727630615234
Solution:
number of solutions: 0
number of solutions displayed: 0
So the problem works well and I get a solution, the modeling was done internally via another too. Is it possible to access the constraints/objective so I can freely modify the optimization model in Pyomo syntax?
I tried to call the model and got something like this:
<pyomo.core.base.PyomoModel.ConcreteModel at xxxxxxx>
Comment: Include a code sample showing what you've tried so far and the full error message it generates.
Comment: I do not have an error message. I am trying to figure out how to access the model information and modify its constraints. Right now all I know is it is called 'network.model' and it is concrete. I did not construct the model, but I want to access it fully.
Answer: It sounds like network.model is the Pyomo model and yes, if you have access to it, you can modify it. Try printing the model or individual model components using the pprint() method:
network.model.pprint()
network.model.con1.pprint()

or you can loop over specific types of components in the model:
for c in network.model.component_objects(Constraint):
    print(c)  # Prints the name of every constraint on the model

The easiest way to modify the objective would be to find the existing one, deactivate it, and add a new one
network.model.obj.deactivate()
network.model.new_obj = Objective(expr=network.model.x**2)

There are ways to modify constraints/objectives in place but they are not well-documented. I'd recommend using Python's dir() function and playing around with some of the component attributes and methods to get a feel for how they work.
dir(network.model.obj)

Comment: Thanks! That's very helpful. I am able to re-define simple constraints/objective. Now,
I ran 'network.model.con1.pprint()' to see the constraint 'con1' and got the following:

con1: Size=2, Index=c1, Active=True
    Key: Lower: Body: Upper : Active
    ('gen 0', 'now') :   0.0 : 100.0*gen_status[gen 0,now] - gen_p[gen 0,now] :  +Inf :   True
    ('gen 1', 'now') :   0.0 : 50*gen_status[gen 1,now] - gen_p[gen 1,now] :  +Inf :   True

This is an indexed constraint. How can alter the first element? Let's say I only want to replace 100 with 25, without messing up with everything else?
Comment: Access a single index of an indexed components using square brackets `network.model.con1['gen 0','now']. The easiest way to change the value would be to modify the original Constraint rule to use a mutable Param in place of the numeric constant 100.0. Then you could change the value without directly modifying the constraint.
Comment: Thanks, Bethany. I cannot modify the original constraint because it came out of some other tool and unfortunately they did not use Param. I guess I'll build everything myself and use Pyomo directly. I love it so far! Big thanks to dev team.

Accessing constraints/objective


Lebesgue integration-- why are contours >t and not =t?

Question: I read the Wiki on Lebesgue integration (http://en.wikipedia.org/wiki/Lebesgue_integration) and it says that the integral can be rewritten as the sum of volumes of equal-height contours:

The volume of the (very thin) contour at height $t$ is defined as $f^*(t) = \mu(\{x | f(t) > t\})$.
Then you simply compute $\int_0^\infty f^*(t) \partial t$.

The second step makes perfect sense to me; however, the first step feels intuitively incorrect: the measure of the set $f^*(t)$ should be the width at height $t$ (otherwise it is not a true partition, and you are counting points multiple times). To me, it feels like then it would be $f^*(t) = \mu(\{x | f(t) = t\})$.
As defined in the Wiki, it feels like it would include the points at height $t=1$ when it computes $f^*(0.5)$. This would be a problem if you are computing the area under a right triangle of width 1:
$f(x) = x, x \in [0,1]$, otherwise $0$
$\int_0^1 f(x) \partial x = \frac{1}{2}$
As defined by the Wiki:
$f^*(t) = \mu(\{x | f(t) > t\})$
$\int_0^\infty f^*(t) \partial t = \int_0^1 f^*(t) \partial t$
But according to the Wiki $f^*(0)$ will be the measure of the set of $x$ points for which $f(x) > 0$, which is 1. In fact, this will be the case for all $t \in [0,1]$. So the integral will be 1 (when it should be 1/2).
Please let me know if you have any explanation for why I am incorrect about this.
Thanks a lot!
Oliver
Comment: It exactly corresponds -- look at the width of the block  at the bottom --isn't the width of the block same as the measure of values   whose image is greater than the height of the block?
Comment: f*($1$)$ = $$0$ and f*($0.7$)$=$$0.3$ Isn't it?
Comment: Note that in your version -- $f^*(t) = \mu(\{x | f(x) = t\})$. Many integrals would be $0$.
Comment: +1 Thanks, my mistake! But it's strange that $\{x|f(x)>t\}$ is used-- it doesn't seem to correspond to the second panel here: http://en.wikipedia.org/wiki/File:RandLintegrals.png
Comment: Ah, thanks. I see. I was thinking of a non-function (e.g. an hourglass), whereby the width would be counted as too large. But if there is exactly one y per x, then it would be OK.
Answer: $f^*(t) = \mu(\{x | f(x) > t\}) $
$f^*(t)=$$1-t$
$\int_0^\infty f^*(t)  dt = \int_0^1 f^*(t)  dt$$=$ $\int_0^1 [1-t] dt$ $ =1/2$
Note that $f^*(t)$ corresponds to the width at level t.


How can I show xib directly in xcode enviroment?

Question: I've been reading articles at raywenderlich.com and saw that they show an XIB being edited in Xcode directly:

https://i.stack.imgur.com/aCTSF.jpg
How can do this in Xcode?
Answer: That is a new feature of XCode 4 and onwards. If you have the Apple Developer Membership, you can download it at http://developer.apple.com/xcode/.
Answer: this is new version of xcode just download & install it :) u will have same editor in it :)


drupal_get_form -- How do I include a JavaScript onClick event into the function results?

Question: I have someone else's drupal_get_form code, where I was requested to have the form's button change color after clicking, while the user remains on that page.
The function's rendered output looks like this:
<form action="/mitreinstitute/my-institute" method="post" id="mi-custom-course-withdrawal-email-form-0" accept-charset="UTF-8">

  <input type="submit" id="edit-submit" name="op" value="Withdraw Me" class="form-submit" />
  <input type="hidden" name="form_build_id" value="form-rpHwdhyCJfun0lRObhtuMWjehzOeNTHOeL9YCY-jQ84" />
  <input type="hidden" name="form_token" value="0tnkm6jb6PhZnpTNI16SLMq0XrkhZGKsDax7d3S9hIk" />
  <input type="hidden" name="form_id" value="mi_custom_course_withdrawal_email_form_0" />

</form>

I cannot figure out to incorporate something like this JavaScript onClick function, so that it is merged into the form's rendered submit element:
Answer: You can add Javascript to a form using the #attached property. So either in the form definition, or a hook_form_alter if you're altering a form you didn't code:
$form['#attached']['js'][] = drupal_get_path('module', 'MYMODULE') . '/foo.js';

In the JS file add what you need to, wrapping it in a Behavior to ensure events are reattached following AJAX calls:
(function($) {
  Drupal.behaviors.MYMODULE = {
    attach: function(context, settings) {
      $('#form-id').once('MYMODULE').submit(function() {
        // Do what you need to here
      });
    }
  };
})(jQuery);


starting linux services delayed issue

Question: I have an issue where the bind9 service aka named in my ubuntu system is starting up before my openvpn service.
When this happens, the network interface that openvpn creates (tun0) is not found by bind upon its startup and thus doesn't include it in the list of adapters to bind to. I have to restart bind after the system has booted up and then everything works.
I've tried renaming the openvpn service to 0openvpn in /etc/init.d/. I've also tried renaming the bind service in /etc/rc0.d/ from K85bind9 to K20bind9 and K99bind9, I read somewhere that changing the number up or down can affect the order in which it starts services.
These methods did not work, I've reverted those changes since.
I know this is a basic question/problem but I believe I've been looking up the wrong terms or something, how do you re-order/delay bind9's starting up so that it starts after openvpn has initialized?
Thanks
Comment: Did you ever rename the OpenVPN service to `S0openvpn` instead of `0openvpn`?
Answer: If your issue is the service starting in a different order you should change the number in the other set of scripts, I mean, not the KXXscript, but the SXXscript since the scripts starting with S affect the start of said services. The K are related with the stop (Kill) of services, so basically you changed the order in which bind9 and openvpn are stopped, but not the order in which they start.
Comment: changing the names in rc2.d that started with 'S' did the trick. thanks.

starting linux services delayed issue


Why is python list showing slicing abnormality?

Question: I am trying to partition the list element recursively (like in divide and conquer) and consequently printing the sliced elements but suddenly sees unexpected abnormality(at line 6 and onwards in Output).
def Mergesort(a, l, r):
    if(l<r):
      mid = (r+l+1) // 2
      print(a)
      Mergesort(a[l : mid], l, mid-1)
      Mergesort(a[mid : r+1], mid, r)

a = [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
Mergesort(a, 0, len(a)-1)

Output:
[8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2]
[3, -2]
[6, 7, 4, 1]
[1]
[]
[2, -1, 0, 9, 12, 11, 5]
[]
[]
[]
[]
[]

Comment: What exactly was your expected output?
Comment: [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2]
[3, -2]
[6, 7, 4, 1]
[6, 7]
[4, 1]
[2, -1, 0, 9, 12, 11, 5]
[2, -1, 0]
[-1, 0]
[9, 12, 11, 5]
[9, 12]
[11, 5]
Answer: This is because your l, r in def Mergesort is not precise. When you Mergesort your RHS arraya=[2, -1, 0, 9, 12, 11, 5], it is actually running: Mergesort([2, -1, 0, 9, 12, 11, 5],7,10), but not Mergesort([2, -1, 0, 9, 12, 11, 5],0,3). Since len(a)=7, it will only return an empty array[].
I modified the codes:
def Mergesort(a, l, r):
    if(l<r):
        mid = (r+l+1) // 2
        print (a)
   #
        Mergesort(a[l : mid], 0, len(a)-1)
        Mergesort(a[mid : r+1],0, len(a)-1)

a = [8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
Mergesort(a, 0, len(a)-1)

Now it can split both right and left arrays. Output if you print (a) within if clause:
[8, 3, -2, 6, 7, 4, 1, 2, -1, 0, 9, 12, 11, 5]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2, 6, 7, 4, 1]
[8, 3, -2]
[8, 3, -2]
[8]
[3, -2]
[3]
[-2]
[]
[6, 7, 4, 1]
[6, 7, 4]
[6, 7]
[6]
[7]
[4]
[1]
[]
[2, -1, 0, 9, 12, 11, 5]
[2, -1, 0, 9, 12, 11, 5]
[2, -1, 0]
[2, -1, 0]
[2]
[-1, 0]
[-1]
[0]
[]
[9, 12, 11, 5]
[9, 12, 11]
[9, 12]
[9]
[12]
[11]
[5]
[]

Notice that is code is still not perfect and needs work (but it solves the splitting issue that you raised), I would suggest improvements in
1) definition of mid so it correctly split even-number array;
2) definition of l and r so that it would not split single-element array.
Answer: I found the solution.  Actually, while passing sliced list in function, index start from zero.


Negation of this logical statment (p and q) -> r

Question: I've been messing around with trying to negate this statement using DeMorgans laws and I keep ending up with incorrect answers such as (~p or ~q) and ~r. If someone could help me with the negation of compound statements.
Thank you.
Answer: $x\implies y$ means $y$ or $\lnot x$.  Take $x=p$ and $q$.
$\lnot(p $ and $q)$ means $\lnot p $ or $ \lnot q$.
$\lnot(a $ or $b)$ means $\lnot a $ and $\lnot b$.
Comment: @Spencer Can you try to take it from here? The purpose of this site is to aid in the education process, not to hand out answers to problems
Comment: Ok, I think I got it now [(p^q)and ~r], does this mean I only have to change the later half of this equation?
Comment: So how would you write the negation of (p and q)->r   ?
Answer: There is a very simple method to negate statements.

Rule:
Change implications to its disjunction form. $A\rightarrow B$ will be $\lnot A \lor B$
Rule: If you negate a bracket, you negate all the contents and change the logical connectives: $\lor$ will be $\land$ and $\land$ will be $\lor$.
Eliminate double negations and you're done.

Example: $\lnot ((\lnot p\lor q)\rightarrow \lnot s)$

$ \lnot(\lnot (\lnot p \lor q )\lor \lnot s)$
$ \lnot \lnot (\lnot p \lor q)\land \lnot \lnot s$
$(\lnot p \lor q)\land s$


convert the parametric equation $x = \cos (t) ; y = \sin (t)-t^2$ to rectangular form.

Question: I'm trying to convert the parametric equation $x = \cos (t) ; y = \sin (t)-t^2$ to rectangular form but have gotten stuck trying to eliminate the last $t$ from parametric form. I have gotten as far as: $y = \sqrt(1-x^2) - \arccos(x)^2$.
I know that $t = \arccos(x)$ but I have no idea how to square that quantity.
Comment: There isn't a simplification for that thing.
Comment: As I feared.... Thank you very much!
Answer: It becomes more complicated:
$x=\cos t   ⇒  t= Arc\ cos x $
$\sin t = \sqrt{1 - x^2}$
$y^2/25=sin^2 t - (32/5)t^2 \sin t+(256/25) t^4$
$x^2+y^2/25= cos^2t+ sin^2t  - (32/5)t^2 \sin t+(256/25) t^4$
$x^2+y^2/25=1-(32/5)(Arc \cos x)^2 \sqrt{1-x^2}+(256/25)(Arc\cos x)^4$


Google script, copy row from a sheet to another with condition and date

Question: In my google script, I try to copy some row, with a data condition from a sheet to another sheet
I have a problem with the date getting from a sheet
I tried the follow:
var date_check = new Date(data[i][4]);

where [i] is the index, and 4 the column where date is it.(log tell me just the relative number, so I tried to create new date from that number, but generates just a NaN variable.
this is all the code
function copy() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName('ISCRITTI');
  var sheet2 = ss.getSheetByName('2012');
 var todayDate = new Date('1/1/2012');
  var data = sheet1.getRange(2,1, sheet1.getLastRow(), sheet1.getLastColumn()).getValues();

  var dest = [];
  for (var i = 0; i < data.length; i++ ) {
    Logger.log(data[i][4]);// return a number not the date in the sheets
    var date_check = new Date(data[i][4]);
    Logger.log(date_check); // return NaN
     Logger.log(todayDate.getFullYear()); //return 2012.0
    if ( todayDate.getFullYear()===date_check.getFullYear()) {
     dest.push(data[i]);
    }
  } // here is the end of the for loop

  if (dest.length > 0 ) {
    sheet2.getRange(sheet2.getLastRow()+1,1,dest.length,dest[0].length).setValues(dest);
  }
}

What I missing? thanks for your time
Answer: It worked for me.  I modified it to work in my environment and I took out all of the date checking stuff and used getDataRange.
function copy()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getActiveSheet();
  var data = sheet1.getDataRange().getValues();
  var dest = [];
  for (var i = 0; i < data.length; i++ )
  {
     dest.push(data[i]);
  }
  sheet1.getRange(sheet1.getLastRow()+1,1,dest.length,dest[0].length).setValues(dest);
}


Qual é o papel e responsabilidade das tecnologias HTML, CSS e JavaScript na criação do front-end?

Question: Com essas três tecnologias HTML, CSS e JavaScript pode ser desenvolvido todo front-end ou client-side de um determinado site.
Sendo assim, eu gostaria de saber qual é o papel e responsabilidade que cada uma dessas tecnologias citadas acima desempenha na criação do front-end de um determinado site e quais são as diferenças delas em relação uma com a outra?
Answer: Resumidamente:
HTML - Configuração dos elementos
CSS  - Estilizar exibição dos elementos
JS   - Lógica e dinâmica dos elemento
Em um exemplo prático, se eu quiser ter um quadrado azul que tenha uma contagem de segundos de 1 até 50. Para isso, primeiro nomearia o quadrado no HTML, depois diria que ele tem a forma quadrada e a cor azul no CSS e faria a lógica de contagem de números no Javascript. Exemplificando, temos:

//JAVASCRIPT
var meuQuadrado = document.getElementById("meu-quadrado");
var contagem = 0
var repeticao = setInterval(function(){ //loop da contagem
  if(contagem == 100){ //se a contagem chegar a 100
    clearInterval(repeticao); //pára a contagem
  }
  meuQuadrado.innerHTML = contagem; //exibo a contagem dentro do quadrado
  contagem++;  //aumenta a contagem

},1000)
/* CSS */
#meu-quadrado{
  color: white; /*cor da fonte */
  font-size: 170px; /* tamanho do texto */
  text-align: center; /* posição do texto */
  background-color: blue;  /* cor do fundo */
  width: 200px; /* largura */
  height: 200px; /* altura */

}


Seasonal Data with GAMMs

Question: I'm interested in modelling a time series of temperature data across several years.  The data are on the level of hourly observations, so I have variables for year, month, day, and time.
I found a great example of doing this by Gavin Simpson (found here).  The blog only considers correlation within year, where as I have to deal with correlation within year and within day.
How can I best account for this correlation with gamm?  Gavin uses the following code
modar2 <- gamm(apparentTemperature ~ s(month, bs = "cc", k = 12) + s(time, k = 20),data = timetemp, correlation = corARMA(form = ~ 1|year, p = 2),control = ctrl)

Where should I pass variables to account for correlation within day?
For reference, here is a sample of my data:
tibble::tribble(
               ~created_at,            ~time, ~month, ~year,
~apparentTemperature,
     "2014-01-03 09:30:28",              9.5,      1,  2014,               -17.87,
     "2014-01-03 10:13:43", 10.2166666666667,      1,  2014,               -17.87,
     "2014-01-03 12:19:32", 12.3166666666667,      1,  2014,               -16.14,
     "2014-01-03 12:44:04", 12.7333333333333,      1,  2014,               -20.24,
     "2014-01-03 13:09:38",            13.15,      1,  2014,               -20.24,
     "2014-01-03 13:39:00",            13.65,      1,  2014,               -20.44
     )

Answer: Depends how you want nest the autocorrelation, within days?
modar2 <- gamm(apparentTemperature ~ s(year) + s(month, bs = "cc", k = 12) +
               s(time, k = 20), data = timetemp,
               correlation = corARMA(form = ~ 1|day, p = 2),
               control = ctrl)

would have smooth long term trend, smooth seasonal effect, smooth time of day effect, with autocorrelation nested within days (for which you'd need to create a new variable day which generates the day of year from the date time variable.
If you have a lot of data, you really don't want to use form = ~ obs_seq for the correlation structure, where obs_seq is a sequence 1, 2, ..., number of observations, as that will create a massive covariance matrix that lme() will need to invert at each iteration. Having fitted such a model to high frequency data, it took gamm() a week to converge on powerful multicore workstation.
The reason I nested the correlation within year in that example was partly for this reason; that's a long monthly record and fitting a full ARMA function across all timepoints is not quick.
Comment: Hmm, my data is nearly 30,000 observations, so I guess that is far too large.  I could summarize my data by day (e.g. mean apparent temperature for April 18 2018) which reduces my data to nearly 1,500 observations.  Then I could just use your approach from the blog, yes?  I'd have Year, month, and day of month, smoothing year and day with a seasonal effect of month.
Comment: Why do you want to have the autocorrelation operate at beyond the daily level? Do you have evidence of longer scale autocorrelation? The main issue is that you're likely to run out of RAM unless you have a lot of it available.
Comment: Start with the simpler model (nest the AR within day-of-year within year), use an AR(1) initially (`corAR1()`) rather than an ARMA as that is much more efficient. Then if that fits, look at the normalized residuals to see if you still have remaining autocorrelation. You could also fit without the AR and check that model's residuals. If you go that route, see `bam()` in **mgcv**.

Seasonal Data with GAMMs


In sand volleyball, if a ball hits the line but the mark is out, is it in or out?

Question: We play on the sand and there is a dispute as to how to judge a ball in or out.  If the ball hits the line, so that the line clearly moves, but then strikes the sand an inch out of bounds, is the ball in or out by official rules?  This happens all the time and we have always played "line is in" but recently many want to change to "go by the mark in the sand".  Which is correct?  Due to the contentious nature of this, I'd appreciate reference to official rules and standards with citations, more than personal opinions or anecdotes.
Comment: When you say "sand volleyball," is that the same as "beach volleyball" or is it a different variant?
Comment: It's a variant, so to be honest, the rules are taken with a grain of... sand but when possible we like to refer to an existing rule.  So let's say any version of volleyball played in the sand will do.  The point is there is a line that "floats" on the sand and it's not clear if it is to be respected like the line painted on a hard court.
Comment: Okay, I did retag as "beach-volleyball" as that tag is for "a variant of the sport of volleyball played on sand." So, if that's wrong, then feel free to roll back.
Answer: The FIVB Beach Volleyball rules are very clear on this. Quoting from Rule 8.3, Ball "in":

The ball is "in" when it touches the surface of the playing court including the boundary lines.

See also Section 5.1.2 in the 2015 Casebook which pretty much covers your situation precisely:

Referees should be aware that the ball may land out, but has struck the line, which is in a raised position. In  this case, the ball contacts the line and must be called "in".
Comment: Woot!  My favorite!  I got the answer that makes me right!  LOL  I can go strut out onto the court and be obnoxious now.  :-)  Thanks.


Splitting String in C procudes Segmentation fault (core dumped)

Question: I'm trying to read from the keyboard something like a command
e.g.
start game,info1,info2
and I want to split and save those two strings, one having to do with what kind of command the user,types in and the other having information about the command.
I have done this so far, which reads and prints the separated by space strings but after that it hits me with this Segmentation fault (core dumped) and the console program stops.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char *command;
    char *value;
} string;

string *allocate_memory();
void split_command(char* cmd_info, string **s);

int main(void) {
    char cmd[255];
    memset(cmd, 0, 255);
    do
    {
        // read command
        fgets(cmd, 255, stdin);
        cmd[strcspn ( cmd, "\n")] = '\0';

        string *str;
        str = allocate_memory();
        split_command(cmd, &str);

        puts(str->command);
        puts(str->value);

        if(!strcmp(str->command, "start"))
            printf("Starting...\n");

    } while(strcmp(cmd, "exit"));
    printf("Exiting the command line.");
    return 0;
}

string *allocate_memory() {
  string *p;
  if( (p = (string *) malloc(sizeof(string))) == NULL ) {
    printf("Memory allocation failed\n");
    exit(1);
  }
  return p;
}

void split_command(char* cmd_info, string **s) {

    string *new;
    new = allocate_memory();
    char *token;
    while ((token = strsep(&cmd_info, " ")) != NULL)
    {
      printf("%s\n", token);
      new->command = strdup(token);
    }
    new->value = strdup(token);
    puts(new->value);
    *s = new;
    free(cmd_info);

}

Compile
gcc cmd.c -o cmd.out

Output
./cmd.out
one two
one
two
Segmentation fault (core dumped)

I've tried other stuff as well but I'm keep getting the Segmentation fault, I'm really stuck.
Any help would be greatly appreciated.
Thanks
Comment: thanks for the comment, just removed that, although same issue. By the way where did the other answer go?
Comment: Well I expect to have only one space, so it's executed only once. If the token is null how does it print correctly the values?
Comment: indeed it does print it twice. Thanks a lot user3121023 !!!
Answer: strsep() sets token to NULL when no other delimiter is found. That NULL is then
passed to strdup(), causing your the segmentation fault.
I removed the while() in split_command() (I assumed that it is a simple command arg)
and added a check before the second strdup() and got it working. I also fixed some memory leaks:

you were allocating str in main() and then overriding it with new in
split_command() losing the reference to str.
you were allocating a new string every loop iteration without freeing the previous one
you weren't freeing the strings created using strdup()

Moreover, you were freeing cmd_info which is a buffer allocated statically on the stack.
This is my version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char *command;
    char *value;
} string;

string *allocate_memory();
void split_command(char* cmd_info, string *s);

int main(void) {
    char cmd[255];
    string *str = allocate_memory();
    memset(cmd, 0, 255);
    do {
        fgets(cmd, 255, stdin);
        cmd[strcspn(cmd, "\n")] = '\0';

        split_command(cmd, str);

        if(!strcmp(str->command, "start"))
            printf("Starting...\n");

        free(str->command);
        free(str->value);
    } while(strcmp(cmd, "exit"));
    free(str);
    printf("Exiting the command line.");
    return 0;
}

string *allocate_memory() {
    string *p;
    if( (p = (string *) malloc(sizeof(string))) == NULL ) {
    printf("Memory allocation failed\n");
    exit(1);
    }
    return p;
}

void split_command(char* cmd_info, string *s) {
    char *token = strsep(&cmd_info, " ");

    s->command = strdup(token);
    token = strsep(&cmd_info, " ");
    if (token)
        s->value = strdup(token);
    else
        s->value = NULL;
}

Remember that passing NULL to puts() and such leads to problems: always check for NULL!
Answer: I gave a try, But If your input string more than two spaces, You should definitely modify this code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct
{
    char *command;
    char *value;
} string;
string *split_command(char *cmd);

int main()
{
    char cmd[255];
    while (1)
    {
        fgets(cmd, 255, stdin);
        if (!strcmp(cmd, "exit\n"))
        {
            break;
        }
        cmd[strcspn(cmd, "\n")] = '\0';

        string *str = split_command(cmd);
        puts(str->command);
        puts(str->value);
    }
    return 0;
}

string *split_command(char *cmd)
{
    string *new_string = (string *)malloc(sizeof(string));
    if(new_string == NULL) {
        printf("MEMORY_ALLOCATION_FAILED\n");
        exit(-1);
    }
    char *token = strtok(cmd, " ");
    new_string->command = token;
    token = strtok(NULL, " ");
    new_string->value = token;
    return new_string;
}


Error while building CoinOR

Question: I'm trying to build CoinOR and I'm following the simple instructions on https://projects.coin-or.org/CoinBinary. Configuration is successful, so I should have all dependencies. But I come accross this error while running the 'make' command:

g++ -DHAVE_CONFIG_H -I. -I.
-I/home/user/CoinOR/COIN-1.8/Osi/src/Osi -I/home/user/CoinOR/COIN-1.8/CoinUtils/src -O3 -pipe -DNDEBUG -pedantic-errors -Wparentheses -Wreturn-type -Wcast-qual -Wall -Wpointer-arith -Wwrite-strings -Wconversion -Wno-unknown-pragmas -Wno-long-long -DFLOPCPP_BUILD -MT MP_boolean.lo -MD -MP -MF .deps/MP_boolean.Tpo -c MP_boolean.cpp  -fPIC -DPIC -o .libs/MP_boolean.o In file included from MP_boolean.cpp:12:
MP_set.hpp: In member function 'flopc::MP_domain&
flopc::MP_subset::operator()(const flopc::SUBSETREF&)':
MP_set.hpp:212:9: error: cannot bind non-const lvalue reference of
type 'flopc::MP_domain&' to an rvalue of type 'flopc::MP_domain'
return MP_domain(s);
     ^~~~~~~~~~~~

Does someone have an id or a solution, like just precompiled binaries? I'm running Arch Linux.
Comment: What exactly are you trying to use? Cbc (and it's dependencies)?  Or what else? Your link includes binaries.
Comment: I'm using the 'OptimizationSuite' from the svn. I think it includes everything... I'm just following the instructions in 'Building from Source'.

What I want to do is optimize a linear model in C# (or java).
Comment: This suite is huge and some projects might be in a bad shape. I mentioned those binaries available and as seen, those are from 2015 (an indication of: building everything is hard). Now: how would you use those projects from C#/java? Linear Model means Linear Programming? This is all very unclear. If you just need an LP or MIP solver, go to the specific project (LP: Clp; MIP: Cbc; the latter subsumes the former) and build this including it's dependencies (e.g. CoinUtils). This is not that hard (ignoring your C#/Java). A basic template is [here](https://github.com/h-g-s/lp/issues/1)
Comment: If your usage is cli-based, you can find recent binaries [here](https://ampl.com/products/solvers/open-source/). (people behind it have a lot of CoinOR insight). But i doubt those will help in cases, where some library-usage is needed (check yourself if those only provide the cli-solvers or also shared-libs: you can pick Cbc for LPs and MIPs).
Comment: Thanks for your answer. Yes. I mean linear programming. I have both boolean and integer variables in my model. Any good links for installing any of the packages? The links on the coin-or project homepage seem to be broken.
Comment: Bool and Int is not LP anymore, but (Mixed-)Integer-Programming (Clp not enough; Cbc is needed). I gave you a link describing the simple install. You just have to modify that for your system (it's ubuntu based; but changes should be trivial). This includes a link to Cbc's SVN trunk. The binaries work too. But still... not sure how you would use those (C++ based projects). The Cbc-enty on CoinORs website is [here](https://projects.coin-or.org/Cbc).
Comment: I've successfully installed CBC. Do you accidentaly have a tutorial how to use this library in java or c#? All I can find is c++ examples, but they don't really seem to work for me :(
Answer: Simply change the return type of the function on line 212 of the file MP_set.hpp.
MP_domain& operator()(const SUBSETREF& s) {
    return MP_domain(s);
}

becomes
MP_domain operator()(const SUBSETREF& s) {
    return MP_domain(s);
}

Error while building CoinOR


Simple calculus question

Question: Definition: $\Delta f(x) = f(x + \Delta x) - f(x)$. Find $\Delta^nf(x)$. My guess is
$$\Delta^nf(x)
 = f(x + n\Delta x) + \sum_{k=0}^{n}(-1)^kkf(x + (n-k)\Delta x) + (-1)^nf(x)$$
Is this guess correct?
Comment: Did you mean $\,\Delta^n f(x)\,$?
Comment: You may want to check N-th finite difference formula in: http://en.wikipedia.org/wiki/Finite_difference
Answer: Calculate the first few values:
$$\begin{align*}
\Delta^2f(x)&=\Delta\left(f(x+\Delta x)-f(x)\right)\\
&=\Big(f(x+2\Delta x)-f(x+\Delta x)\Big)-\Big(f(x+\Delta x)-f(x)\Big)\\
&=f(x+2\Delta x)-2f(x+\Delta x)+f(x)\;,
\end{align*}$$
$$\begin{align*}
\Delta^3f(x)&=\Delta\left(\Delta^2f(x)\right)\\
&=\Delta\Big(f(x+2\Delta x)-2f(x+\Delta x)+f(x)\Big)\\
&=\Big(f(x+3\Delta x)-2f(x+2\Delta x)+f(x+\Delta x)\Big)\\
&\qquad\quad-\Big(f(x+2\Delta x)-2f(x+\Delta x)+f(x)\Big)\\
&=f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\;,
\end{align*}$$
and
$$\begin{align*}
\Delta^4f(x)&=\Delta\left(\Delta^3f(x)\right)\\
&=\Delta\Big(f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\Big)\\
&=\Big(f(x+4\Delta x)-3f(x+3\Delta x)+3f(x+2\Delta x)-f(x+\Delta x)\Big)\\
&\qquad\quad-\Big(f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\Big)\\
&=f(x+4\Delta x)-4f(x+3\Delta x)+6f(x+2\Delta x)-4f(x+\Delta x)+f(x)\;.
\end{align*}$$
Now look at those sequences of coefficients:
$$\begin{align*}
&1,-2,1\\
&1,-3,3,-1\\
&1,-4,6,-4,1
\end{align*}$$

Do they match your formula?
Are they familiar from some other context?
Answer: Your formula gives $\Delta f(x) = f(x+\Delta x)-2 f(x)$, so it can't be right.
Try computing the formula for $\Delta^2 f, \Delta^3 f$ and see if you can spot the pattern. Then verify by induction.
Here is the correct formula:

 $$\Delta^n f(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} f(x+(n-k)\Delta x)$$
Comment: Did something change? I don't care about the points, but why did you 'unaccept' after two years?

Simple calculus question


error expected primary-expression before ' ' token

Question: Erro na linha 21.
#ifndef __STRING_H__
#define __STRING_H__

#pragma warning(disable: 4786)
#include <string>
#include <vector>

const int MAX_RESP = 4;

typedef std::vector<std::string> vstring;

bool isPunc(char c);
void cleanString( std::string &str );
void UpperCase( std::string &str );
void copy(char *array[], vstring &v);

template<typename T>
void shuffle(T &array, size_t size) {
    for(int i = 0; i < size; ++i) {
        int index =() % size;
        std::swap(array[i], array[index]);
    }
}

#endif

Comment: É sua segunda pergunta e ambas são erros de digitação. Seria bom prestar mais atenção ou começar fazendo coisas mais simples até se acostumar mais com a linguagem e os erros apresentados.
Comment: A resposta resolveu o seu problema? Acha que pode aceitá-la? Se não souber como faz, veja o [tour]. Isso ajudaria muito indicar que a solução foi útil para você e dar uma indicação que houve uma solução satisfatória. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando aceitar terá os  15 pontos necessários).
Answer: Acredito ter sido só um erro de digitação, já que o operador % precisa ter dois operandos, só tem um. Os parenteses estão ali sem sentido. Talvez a intenção era colocar uma expressão lá dentro e seu resultado ser usado como primeiro operando. Ou talvez seja algo mais simples. Troquei os () pela variável i e compilou, não sei se era a intenção:
#include <string>

template<typename T>
void shuffle(T &array, size_t size) {
    for (int i = 0; i < size; ++i) {
        int index = i % size;
        std::swap(array[i], array[index]);
    }
}
int main() {}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Evaluate $\lim_{x\to+\infty}(x+1)^{1+\frac{1}{x+1}}-x^{1+\frac{1}{x}}$

Question: How to prove that:
$$
\lim_{x\to+\infty}\left((x+1)^{1+\frac{1}{x+1}}-x^{1+\frac{1}{x}}\right)=1
$$
By MVT if $\displaystyle\lim_{x\to+\infty}f'(x)=L$ then $\displaystyle\lim_{x\to+\infty}\left(f(x+1)-f(x)\right)=L$ but I want to see if there are other ways, involving less sophisticated tools.
Any hint would be appreciated.
Comment: Can you give me an example of a less sophisticated tool than the MVT that applies to transcendental functions, just for comparison?
Answer: We have that
$$(x+1)^{1+\frac{1}{x+1}} = (x+1)\cdot(x+1)^{\frac{1}{x+1}}=(x+1)\cdot\left(1+\frac{\log x}x+O\left(\frac{\log^2 x}{x^2}\right)\right)$$
$$x^{1+\frac{1}{x}}=x\cdot x^{\frac{1}{x}}=x\cdot\left(1+\frac{\log x}x+O\left(\frac{\log^2 x}{x^2}\right)\right)$$
therefore
$$(x+1)^{1+\frac{1}{x+1}}-x^{1+\frac{1}{x}} =1+\frac{\log x}x+O\left(\frac{\log^2 x}{x^2}\right)\to 1$$

For the expansion we have used that
$$x^{\frac{1}{x}}=e^{\frac{\log x}x}=1+\frac{\log x}x+O\left(\frac{\log^2 x}{x^2}\right)$$
Answer: Let $$A=(x+1)^{1+\frac{1}{x+1}}\qquad\text{and} \qquad B=x^{1+\frac{1}{x}}$$ Taking logarithms
$$\log(A)=\log (x)+\frac{\log (x)+1}{x}-\frac{2 \log (x)-1}{2
   x^2}+O\left(\frac{1}{x^3}\right)$$
$$A=e^{\log(A)}=x+(\log (x)+1)+\frac{\log ^2(x)+2}{2
   x}+O\left(\frac{1}{x^2}\right)$$
$$\log(B)=\log (x)+\frac{\log (x)}{x}+O\left(\frac{1}{x^3}\right)$$
$$B=e^{\log(B)}=x+\log (x)+\frac{\log ^2(x)}{2   x}+O\left(\frac{1}{x^2}\right)$$
$$A-B=1+\frac 1x+O\left(\frac{1}{x^2}\right)$$
If you take more terms
$$A-B=1+\frac{1}{x}-\frac{(\log (x)-1)^2}{2x^2}+\cdots$$ which is a very good approximation as soon as $x \geq 2$. It shows a maximumn absolute relative error of $0.28$% for $x=4.07$.


What the best way to store value one time and reuse it

Question: In my default page, I take the user name and role, and I want to reuse it in all other pages. What the best practice to access this user name and role in every page. Is seesion the only solution for this or there is another way?
Comment: See this overview for all available options: [ASP.NET State Management Recommendations](https://msdn.microsoft.com/en-us/library/z1hkazw7.aspx)
Answer: You can either store that information in a Session or a Cookie. Both are served to store user-information data and have their pros and cons.
To read more about sessions & cookies, use the following links:
https://msdn.microsoft.com/en-us/library/ms178581.aspx
https://msdn.microsoft.com/en-us/library/ms178194.aspx
Answer: As you need user name and roles It will be already stored in some of the variables. Like User.Identity in MVC application. I would suggest to use already available data instead of storing it again.
Answer: Yes, one good solution exists.
You can make one class with getter and setter method of username and role within same namespace. ex.
<code>public class UserData
{
    public string UserName{ set; get; }
    public string Role { set; get; }
}
</code>
and now you can get and set value of both(username and role).
like,
<code>//Set both properties
UserData objUserData = new UserData();
objUserData.UserName = "set_user_name_you_want";
objUserData.Role = "set_role_you_want";
</code>
Now you can get that both properties anywhere you want within that same namespace.
<code>//Get both properties
UserData objUserData = new UserData();
String UserName = objUserData.UserName;
String Role = objUserData.Role;
</code>
I hope this will helpful to  you! :)
Comment: Can you explain more please, is there any tutorial for your idea
Comment: yes Check this example http://www.codeproject.com/Articles/615499/Models-POCO-Entity-Framework-and-Data-Patterns
Comment: if I set the value of UserName in page 1 , I will not be able to access the value of UserName in page 2 even if they both have same namespace!


if $\sinh(x)=\frac{x}{a}$ why isn't $\tanh(x)=\frac{x}{\sqrt{a^2-x^2}}$?

Question:
if $\sinh(x)=\frac{3}{5}$ why isn't $\tanh(x)=\frac{x}{\sqrt{a^2-x^2}}$?

According to the answer key it is actually $\tanh(x)=\frac{x}{\sqrt{a^2+x^2}}$
But I don't understand that because we see that when I draw out a triangle it shows otherwise
Comment: Please define $a$
Comment: Because $\sinh$ and $\tanh$ are not $\sin$ and $\cos$.
Comment: Tell us what you think $\cosh x$ is
Comment: Start with $\cosh^2 x$
Answer: Use
$\tanh(x)
= \dfrac{\sinh(x)}{\cosh(x)}
= \dfrac{\sinh(x)}{\sqrt{\sinh^2(x)+1}}
$
since
$\cosh^2(x)-\sinh^2(x)
= 1
$.
I also don't see where
"$a$" came from.
Answer: $\sinh(x)^2+1=\cosh(x)^2$.
Therefore, $\displaystyle \cosh(x)=\frac{\sqrt{34}}{5}$.
And then $\displaystyle \tanh(x)=\boxed{\frac{3}{\sqrt{34}}}$.
And guys, he meant $\displaystyle \frac{x}{a}$ probably, instead of $\displaystyle \frac{3}{5}$.
But then he should've used $t$ as an input or something.
Because if $\sinh(t)=x$, then $\displaystyle \cosh(t)=\frac{\sqrt{x^2+a^2}}{a}$.
Then $\tanh(t)=\displaystyle \frac{x}{\sqrt{x^2+a^2}}$, and it all makes sense.


Webform-CiviCRM integration: autocomplete employer

Question: I set up a Webform for a Membership Application. I followed the instructions on this page for setting up an Autocomplete for the Organization the new Member belongs to:
http://wiki.civicrm.org/confluence/display/CRMDOC/Webform+CiviCRM+Integration#WebformCiviCRMIntegration-CurrentEmployer
This works fine when I am logged in (as an administrator), and it auto completes the organization name with options from the database.
But when I test the form when I'm logged out, it doesn't recognize any organization names that I know are in the CiviCRM. Furthermore, when I try to add a new organization it doesn't get added to the database.
Any ideas why this might be happening?
Comment: Heh Christopher, you should ask or answer more questions to add to your reputation, since that will help the CiviCRM StackExchange proposal once you get to 200+ points.
Answer: The anonymous user does not have permission to view contacts in your database. Be thankful for this default, it can save you from accidentally exposing your entire database to the world!
You can override this default by editing the "existing contact" field (from the webform tab) and unticking "Enforce Permissions". Typically you would also set one or more filters on that form (e.g. pick a group) to limit the autocomplete to just the organizations you want to expose.
Comment: Yes it would just be the names (unless you are exposing other organization fields to the webform). I think the danger of not restricting it in some way is that if, in the future, you started using your db to store the names of organizations that you _don't_ want exposed, you might not remember about this webform. Not a huge risk admittedly but good to always think through your access control and make sure you don't leave loopholes lying around.
Comment: Thanks.
The idea with the Membership Application is that new applicants for membership can see, as they enter their organization, if their organization is already part of the database. Is there a danger to exposing all the organizations? Wouldn't it just be the organizations' names?
Comment: Just as a note for anyone still running into the problem with autocompleted organizations not getting saved in CiviCRM, it was necessary to set the type of hidden field of the organization name to "Hidden element" rather than "Secure value"


D-efficient balanced design with R

Question: I was wondering if there is any package for generating a D-efficient balanced design with R
I tried the AlgDesign package, but I did not manage to get a balanced design.
Not sure if this is because of the small full factorial of the attributes and levels I am considering (32) or because balanced designs are out of the scope of AlgDesign.
I have 3 attributes: two attributes have four levels, and 1 has 2 levels

att 1: 4 levels
att 2: 4 levels
att 3: 2 levels

I use the following R code:
library(AlgDesign)
#-----------------------------
# define attributes and levels
#-----------------------------
desVarNames <- c("esource", "certified", "cost")
desLevels <- c(4,2, 4)
n <- 6       #number of choice sets
desOpt <- 4  #num option per choice set

set.seed(123456)
#generate full factorial
dat<-gen.factorial(desLevels,length(desLevels),varNames=desVarNames, center=TRUE)

destT <- optFederov(~., dat, nTrials = (n*(desOpt)), criterion="D")
destT

Answer: First, when you say "balanced" design, I suspect you mean that each factor level should appear the same number of times in the final design. (Actually, your variable "dat" above is a balanced design, too, since each possible combination appears only once).
The way optFederov works is by randomly selecting and replacing trials using Federov's exchange algorithm. As such, everytime a trial is exchanged with another candidate trial, an initially balanced design will become unbalanced, since if a trial "balances" a design, replacing it with any other trial will unbalance the design. If the algorithm was forced to keep a balanced design at each step, no replacement would be possible, and it would get stuck.
Not only a balanced design is incompatible with the way Feverov's exchange algorithm works, it is actually not desirable from a D-efficiency point of view.
For instance, if you have 4 factors with 2, 3, 5 and 7 levels respectively, the only way to have a balanced design is to include all 2*3*5*7 = 210 trials, whereas AlgDesign only suggests 19.
data = gen.factorial(c(2,3,5,7), factors = "all")
trials = optFederov(data = data, center = FALSE, criterion = "D")

In short, the notion of a "balanced d-efficient" design is largely antagonistic.

D-efficient balanced design with R


Using Spring Boot 1.3, spring-boot-devtools and Thymeleaf templates won't do live reload when changed in IntelliJ 15

Question: Spring Boot 1.3 introduced spring-boot-devtools to provide similar functionality as Spring Reloaded to reload modified static resource templates (html, js) without having to re-run your application.
I have been using Spring Boot 1.2.7 before and I was able to modify my static resources on the fly without having to restart my Spring Boot application.
Same application is now not reloading my static resources.
I am using IntelliJ 15.1. The application is packaged as a WAR file.
I have the following dependencies in my pom.xml (including others, excluded for not being relevant):
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.3.2.RELEASE</version>
            </plugin>
        </plugins>
    </build>

I tried to use spring-boot-maven-plugin with version tag 1.3.2.RELEASE and suddenly changes to my html,js files are visible in browser when the template is saved. It seems that at least the problem is because of the spring-bot-maven-plugin.
I have also set the resource right:
<resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.html</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>

Could somebody please help me resolve this?
Answer: Did you make sure you were compiling your project? I know I've needed to do that in boot 1.2.x.
Otherwise, I'd check this duplicate-sounding post:
Using Spring Boot 1.3, spring-boot-devtools and Thymeleaf templates won't do live reload when changed in Netbeans


Define $this variable correct in Magento PHP script

Question: I have a unchangeable script, which does not work. But it's possible to add code on the beginning, or at the end.
This is the script:
$installer = $this;
$installer->startSetup();

$installer->setConfigData('general/country/default', 'DE');
$installer->setConfigData('general/country/allow','BE,BG,DK,DE,CY');
$installer->setConfigData('general/country/optional_zip_countries','IE');
$installer->setConfigData('general/country/eu_countries','BE,CY');

$installer->endSetup();

If I change the beginning of the script to:
$installer = $this;
$installer = Mage::getModel("eav/entity_setup", "core_setup");
$installer->startSetup();

It would work, but as I said its not possible to write inside the script. The error, that I receive is:
Fatal error: Call to a member function startSetup() on a non-object

Is there a way to make that script working?
It is a Magento script for importing system configuration.
Thank you in advance!
Comment: I'm guessing you are executing that code from outside a class member function (and from a class at all).

`$this` variable only makes sense within a class, The second approach works because `$installer` becomes an object after executing `Mage::getModel`
Comment: Thank you for your answer, is there a way to open the correct class on the beginning of the script? so that $this works?
Comment: Can't you use $installer = new yourClass() ?
Comment: If I use $installer = new Mage::getModel(); I receive no error anymore, but the script changes nothing.. Am I doing a mistake here?
Comment: What's the flow? If you're saying `$installer = Mage::getModel("eav/entity_setup", "core_setup");` would work, can't you just instead do `$this = Mage::getModel("eav/entity_setup", "core_setup");` to preempt the value of $this?
Comment: I cant get it to work...My class is "Mage" so I could create an object like "$object=new Mage". Now I could do "$object->Mage::getModel("eav/entity_setup","core_setup");" If I use now the $this variable I receive "Error: Using $this when not in object context". But why? I thought my object is declared?
Comment: @mattbryanswan I think you can't define $this like a normal variable (you can but it would not make sense)
Comment: @Vidarrus Depends on the scope. We don't know enough about how you're running this to know. OSdave's answer is how you would typically define it, but if you're not running your install scripts the typical way, that might not help. I would try both.
Answer: you can define the class to be used by the setup (aka $this) in your module's config.xml, like this:
<?xml version="1.0"?>
<config>
    <global>

        <resources>
            <namespace_module_setup>
                <setup>
                    <module>Namespace_Module</module>
                    <class>Mage_Eav_Model_Entity_Setup</class>
                </setup>
            </namespace_module_setup>
        </resources>

    </global>

</config>


When I add an emoji in full HTML with CKeditor 5, I get a PHP error

Question: I created a custom block with Full HTML text format and CKeditor 5. When I add an emoji, I have a PHP error in my Drupal 9 logs :
Drupal\Core\Entity\EntityStorageException : SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xF0\x9F\xAB\xB6 V...' for column z33ygz_app_drupal.ymce_block_content__body.body_value at row 1: INSERT INTO "ymce_block_content__body" ("entity_id", "revision_id", "bundle", "delta", "langcode", "body_value", "body_summary", "body_format") VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => 20 [:db_insert_placeholder_1] => 93 [:db_insert_placeholder_2] => basic [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => fr [:db_insert_placeholder_5] =>  Vous êtes producteur et vous proposez la vente à la ferme. [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => full_html ) dans Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (ligne 811 de /home/clients/588444ff5555fg4g4g4g5396/sites/www.example.com/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Why can't I use emoji in the text box ?
Comment: You need to change your tables' character set to `utf8mb4` and collation to `utf8mb4_unicode_ci`, or similar, to make them compatible with multibyte chars
Comment: You need to have a different DB collation for Emojis to work I think. Or workaround https://www.drupal.org/project/strip_utf8mb4.
Comment: @Clive https://ibb.co/263brfF It's weird because in PHPmyAdmin, I have utf8_general_ci and utf8mb4_general_ci I don't know if I should choose utf8mb4_unicode_ci or utf8mb4_general_ci it's for a French website with special characters and accents. Can I convert the tables with PHPmyAdmin or is there something else to do?
Comment: Also, I am certain "Invalid datetime format" is a PDO library bug as it is totally misleading. This is nothing to do with "datetime".
Comment: You can use the [CKEditor Emojione](https://www.drupal.org/project/ckeditor_emojione) module and configure the used text format to include emoji characters.
Answer: The problem is probably that the Drupal site was setup some years ago when they still used UTF-8 with three bytes per character because many versions of MYSQL didn't support more than that.
You need to change the column in the database to a mb4 collation for multibyte strings with 4 bytes per character, like this emoji \xF0\x9F\xAB\xB6.
Whether you use utf8mb4_general_ci or utf8mb4_unicode_ci doesn't matter for storing the emoji, this is important for sorting and filtering. The first one has a better performance, the second one can sort and filter in multiple languages. If in doubt use the second one because the performance disadvantage is negligible in most cases.
The current Drupal 9 version is using utf8mb4_0900_ai_ci if the MySQL database is supporting this, which has improved language support.
Example:
mysql -u mysqluser -p
Enter password:
use my_drupal_database;
ALTER TABLE block_content__body MODIFY body_value LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE block_content_revision__body MODIFY body_value LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/141003/discussion-on-answer-by-4uk4-when-i-add-an-emoji-in-full-html-with-ckeditor-5-i).