combining gridsearch with regression : how to estimate variance of residuals

Question: I'm trying to do measurements based on image processing : first I do some image processing to find detect the pixels that changed between the background and my image, and then I perform a linear regression to find the number of objects from the number of changing pixels.
The issue is that I have rather few samples (24 for now) because it is very time-consuming to get them.
I'm trying to find the optimal parameters (3 for the image processing + 2 for the regression) and to estimate the variance of the residuals.
For finding the optimal parameters, I do a grid search on the 3 image processing parameters, and for each I compute the regression (and estimate the variance of residuals).
The problem is that I'm not sure how best to estimate this variance :
- If I were to measure a fixed value + noise, I know that I take the sum of the squares of the residuals, and I divide by the number of samples minus 1
- If I make a linear regression, from what I understand I have to divide by the number of samples minus 2.
- But I'm not sure about my situation : should I divide by N-2 or by N-5? (ie do the parameters of the grid search count as lost degrees of freedom the same way as the parameters of the regression?)
Thank you very much in advance
Felix
PS : just to make sure, is it at all correct to try to estimate the variance this way or should I go for separated learning/testing sets and/or to cross validation?
Answer: I am not an expert, but the degrees of freedom is related only to the regression parameters, not hyperparameters on grid search. When thinking about degrees of freedom I like to make an analogy with simple mean and variance estimation. Since we have N data points, we use it to estimate mean, thus when calculating variance we have lost our freedom by one degree. In regression context, it is the same, we use data points to estimates the parameters, not the hyperparameters. Your samples does not have anything to do with your learning rate, or penalty criteria, this is something related in how your model will behave to estimate parameters. In conclusion, you should use N-2 if you have two features.
It is my first time answering a question, if I do not made myself clear enough, please, let me know.
Comment: Thanks for your answer.
I'm not sure however if we can really consider the image processing parameters as hyperparameters, because we are learning them too (it's not like choosing an arbitrary value as for the number of clusters in k-means for exemple).
Comment: Just to complement: I forgot to mention, but as you have such a few instances to train your model, it is good to try using bagging to test your performance as well.


Recaptcha not working on https

Question: i have a site in codeigniter,and that site working perfectly on http.
My client moved the site to https.
Then now when user registration is not working ,because there have a recaptcha used in it.
Now it displays Could not open socket error.
this is the recaptcha calling in my controller:
$privatekey = "my-key";
        $resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);

        if (!$resp->is_valid) {
        // What happens when the CAPTCHA was entered incorrectly
            die ("The reCAPTCHA wasn't entered correctly");
        }else{

            $data=$this->authmodel->addAccount();
            $this->session->set_flashdata('abc', 'User added successfully');
            echo "1";
        }

And this is the recaptchalib.php code:
<?php
/*
 * This is a PHP library that handles calling reCAPTCHA.
 *    - Documentation and latest version
 *          http://recaptcha.net/plugins/php/
 *    - Get a reCAPTCHA API Key
 *          https://www.google.com/recaptcha/admin/create
 *    - Discussion group
 *          http://groups.google.com/group/recaptcha
 *
 * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
 * AUTHORS:
 *   Mike Crawford
 *   Ben Maurer
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * The reCAPTCHA server URL's
 */
define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_VERIFY_SERVER", "www.google.com");

/**
 * Encodes the given data into a query string format
 * @param $data - array of string elements to be encoded
 * @return string - encoded request
 */
function _recaptcha_qsencode ($data) {
        $req = "";
        foreach ( $data as $key => $value )
                $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';

        // Cut the last '&'
        $req=substr($req,0,strlen($req)-1);
        return $req;
}

/**
 * Submits an HTTP POST to a reCAPTCHA server
 * @param string $host
 * @param string $path
 * @param array $data
 * @param int port
 * @return array response
 */
function _recaptcha_http_post($host, $path, $data, $port = 80) {

        $req = _recaptcha_qsencode ($data);

        $http_request  = "POST $path HTTP/1.0\r\n";
        $http_request .= "Host: $host\r\n";
        $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
        $http_request .= "Content-Length: " . strlen($req) . "\r\n";
        $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
        $http_request .= "\r\n";
        $http_request .= $req;

        $response = '';
        if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
                die ('Could not open socket');
        }

        fwrite($fs, $http_request);

        while ( !feof($fs) )
                $response .= fgets($fs, 1160); // One TCP-IP packet
        fclose($fs);
        $response = explode("\r\n\r\n", $response, 2);

        return $response;
}

/**
 * Gets the challenge HTML (javascript and non-javascript version).
 * This is called from the browser, and the resulting reCAPTCHA HTML widget
 * is embedded within the HTML form it was called from.
 * @param string $pubkey A public key for reCAPTCHA
 * @param string $error The error given by reCAPTCHA (optional, default is null)
 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)

 * @return string - The HTML to be embedded in the user's form.
 */
function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
{
    if ($pubkey == null || $pubkey == '') {
        die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create");
    }

    if ($use_ssl) {
                $server = RECAPTCHA_API_SECURE_SERVER;
        } else {
                $server = RECAPTCHA_API_SERVER;
        }

        $errorpart = "";
        if ($error) {
           $errorpart = "&error=" . $error;
        }
        return '

        <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
        <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
    ';
}

/**
 * A ReCaptchaResponse is returned from recaptcha_check_answer()
 */
class ReCaptchaResponse {
        var $is_valid;
        var $error;
}

/**
  * Calls an HTTP POST function to verify if the user's guess was correct
  * @param string $privkey
  * @param string $remoteip
  * @param string $challenge
  * @param string $response
  * @param array $extra_params an array of extra variables to post to the server
  * @return ReCaptchaResponse
  */
function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
{
    if ($privkey == null || $privkey == '') {
        die ("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create");
    }

    if ($remoteip == null || $remoteip == '') {
        die ("For security reasons, you must pass the remote ip to reCAPTCHA");
    }

        //discard spam submissions
        if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
                $recaptcha_response = new ReCaptchaResponse();
                $recaptcha_response->is_valid = false;
                $recaptcha_response->error = 'incorrect-captcha-sol';
                return $recaptcha_response;
        }

        $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
                                          array (
                                                 'privatekey' => $privkey,
                                                 'remoteip' => $remoteip,
                                                 'challenge' => $challenge,
                                                 'response' => $response
                                                 ) + $extra_params
                                          );

        $answers = explode ("\n", $response [1]);
        $recaptcha_response = new ReCaptchaResponse();

        if (trim ($answers [0]) == 'true') {
                $recaptcha_response->is_valid = true;
        }
        else {
                $recaptcha_response->is_valid = false;
                $recaptcha_response->error = $answers [1];
        }
        return $recaptcha_response;

}

/**
 * gets a URL where the user can sign up for reCAPTCHA. If your application
 * has a configuration page where you enter a key, you should provide a link
 * using this function.
 * @param string $domain The domain where the page is hosted
 * @param string $appname The name of your application
 */
function recaptcha_get_signup_url ($domain = null, $appname = null) {
    return "https://www.google.com/recaptcha/admin/create?" .  _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
}

function _recaptcha_aes_pad($val) {
    $block_size = 16;
    $numpad = $block_size - (strlen ($val) % $block_size);
    return str_pad($val, strlen ($val) + $numpad, chr($numpad));
}

/* Mailhide related code */

function _recaptcha_aes_encrypt($val,$ky) {
    if (! function_exists ("mcrypt_encrypt")) {
        die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
    }
    $mode=MCRYPT_MODE_CBC;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=_recaptcha_aes_pad($val);
    return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}

function _recaptcha_mailhide_urlbase64 ($x) {
    return strtr(base64_encode ($x), '+/', '-_');
}

/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($pubkey, $privkey, $email) {
    if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
        die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
             "you can do so at http://www.google.com/recaptcha/mailhide/apikey");
    }

    $ky = pack('H*', $privkey);
    $cryptmail = _recaptcha_aes_encrypt ($email, $ky);

    return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
}

/**
 * gets the parts of the email to expose to the user.
 * eg, given johndoe@example,com return ["john", "example.com"].
 * the email is then displayed as john...@example.com
 */
function _recaptcha_mailhide_email_parts ($email) {
    $arr = preg_split("/@/", $email );

    if (strlen ($arr[0]) <= 4) {
        $arr[0] = substr ($arr[0], 0, 1);
    } else if (strlen ($arr[0]) <= 6) {
        $arr[0] = substr ($arr[0], 0, 3);
    } else {
        $arr[0] = substr ($arr[0], 0, 4);
    }
    return $arr;
}

/**
 * Gets html to display an email address given a public an private key.
 * to get a key, go to:
 *
 * http://www.google.com/recaptcha/mailhide/apikey
 */
function recaptcha_mailhide_html($pubkey, $privkey, $email) {
    $emailparts = _recaptcha_mailhide_email_parts ($email);
    $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);

    return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]);

}

?>

So how can i solve this issue?
Comment: You probably shouldn't post your private key online.
Comment: Personally I would rewrite `_recaptcha_http_post` method and use curl to POST, tho a careless update my break it again. **Remove the error suppression `@` to get the proper error.**
Comment: @Lawrence this is the error i got now:
`A PHP Error was encountered

Severity: Warning

Message: fsockopen() [function.fsockopen]: unable to connect to www.google.com:80 (Connection timed out)

Filename: helpers/recaptchalib.php

Line Number: 80`
Comment: is there a reason you aren't making this easy on yourself and using a recaptcha spark? http://getsparks.org/packages/recaptcha_spark/versions/HEAD/show
Answer: I got the same error an tried a couple of suggestions, but nothing realy worked.
So I logged my network traffic and analyzed it. What it shows is that mid connection the servers changed from ipv4 to ipv6 and I remembered reading somewhere that recaptcha has a problem working on ipv6.
So I changed @fsockopen($host, [...] to @fsockopen(gethostbyname($host), [...] and recaptcha worked again.
Answer: For SSL (https) use:
echo recaptcha_get_html($publickey,true);

rather than:
echo recaptcha_get_html($publickey);

This is because recaptcha_get_html() in recaptchalib.php (which gets the distorted text image) defaults to http unless you tell it otherwise.
Comment: This worked for me. Thanks. Only slight change is that I needed echo recaptcha_get_html($publickey, NULL, true);
Answer: You need to tell the function "recaptcha_get_html()" that you want to use https. Replace recaptcha_get_html($publickey) with
echo recaptcha_get_html($publickey,null,1);

Answer: edit recaptchalib.php like this:
find this line - function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
change it to - function recaptcha_get_html ($pubkey, $error = null, $use_ssl = true)
argument $use_ssl is changed from false to true... rest will be taken care of by the script..
Answer: I got the same error an tried all suggestions but nothing work for me.
then i did analyzed the issue and then i got SSL certificate issue

this certificate is only valid for the following names: www.google.com
  (Error code: ssl_error_bad_cert_domain)

so i changed
echo recaptcha_get_html($publickey,,true);

@fsockopen($host, [...] to @fsockopen(gethostbyname($host), [...]

along with

define("RECAPTCHA_API_SECURE_SERVER",
  "https://api-secure.recaptcha.net");

to

define("RECAPTCHA_API_SECURE_SERVER",
  "https://www.google.com/recaptcha/api");

in recaptchalib.php and recaptcha worked again.
Comment: try echo recaptcha_get_html($publickey,,true); This worked for me.
Answer: You need to change all http:// urls to https:// in "recaptchalib.php" file, after that this will work.
Answer: Delete "http:" from script source url.
Change it:
from:

to:

Recaptcha not working on https


Estou tentando mandar como resposta um array de "tarefas"(bot do zap)

Question: To fazendo um bot para o zap, que recebe as tarefas e quando pede para ver as tarefas ele não quer mostrar o array
o codigo tá assim

client.on('message', msg => {
const content = msg.body
// const id = msg.id

if(content.startsWith('#')){
    messages.push(content)
    msg.reply("Anotado Chefe ")
    console.log(messages)
    // console.log(id)

}
if(content === "Minhas tarefas"){
    console.log(messages)
    msg.reply(messages)
}
// console.log(Messages)})

Erro

throw new Error('Evaluation failed: ' + helper_js_1.helper.getExceptionMessage(exceptionDetails));
^

Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'serialize')
Answer: O erro "TypeError: Cannot read properties of undefined (reading 'serialize')" está ocorrendo porque o método msg.reply requer um argumento válido para responder à mensagem. No caso, você está passando o array messages, mas ele não pode ser serializado para ser enviado como uma mensagem no WhatsApp.
Para corrigir isso, você pode transformar o array em uma string antes de enviá-la como resposta. Algo como:
if(content === "Minhas tarefas"){
    console.log(messages)
    msg.reply(messages.join('\n'))
}

Isso transformará o array messages em uma string separada por quebras de linha.
Comment: aaah entendi, tava pensando que poderia ser isso, funcionaria se eu usasse um map também? para listar cada item e enviar como mensagem?
Comment: Sim, você também pode usar o método map para formatar o conteúdo do array de mensagens.
Comment: Um exemplo de como usar:
```
if (content === "Minhas tarefas") {
    console.log(messages);
    msg.reply(messages.map((task, index) => `${index + 1}. ${task}`).join("\n"));
}
```
Neste exemplo, o método map é usado para transformar cada item do array em uma string no formato "número. tarefa". Em seguida, o método join é usado para juntar todas as strings em uma única string, separando-as por uma nova linha.
Comment: Pô cara muito obrigado, to fazendo aqui, tá ficando bacana, passa seu linkedin man


How to calculate the total number of possible triangles where the perimeter is given, and all sides are integers?

Question: How would I go about calculating the total number of possible triangles where the perimeter is given, and all sides are integers?
Exempli gratia:

$a + b + c = 15$
$d + e + f = 16$
$x + y + z = 100$
Comment: I don't remember how to do this problem, but the final form of the (generating function of the) solution turns out to be extremely nice. Is this up to relabeling of the sides or not?
Answer: This is given in A005044.  The generating function is $\frac{x^3}{(1-x^2)(1-x^3)(1-x^4)}$  Some other formulas and references are given as well
Answer: It rather depends on whether you regard 7,5,4 as the same triangle as 5,7,4 (edges in a different order), and whether you allow the triangles 8,8,0 (with a zero edge) or 8,5,3 (with a zero area).  Let's suppose not in what follows.
So start with the longest side: it cannot be longer than or equal to half the perimeter, but it must be at least a third of the perimeter.  So that gives you a limited set of values. Now consider the middle sized side: it must be at least half the difference between the perimeter and the longest side, but cannot be longer than the longest side. Together these will tell you the shortest side.  So just add up the number of different shortest sides for each possible longest side.
For example with a perimeter of 15, the longest side must be 5, 6 or 7.  If it is 5 then the middle side can be 5; if it is 6 then the middle side can be 5 or 6; if it is 7 then the middle side can be 4, 5, 6 or 7.  Adding those up gives 1+2+4 = 7.
Similar results can be found for other small perimeters. It is also possible to derive a general formula which has the curious property that $a(2n-3) = a(2n)$, or in other words, starting with a triangle with an odd perimeter, we can find a related triangle with a perimeter 3 more just by adding 1 to each side.
Comment: If all three sides are positive and the sum of any two sides is greater than the third then you have a real positive area triangle.
Comment: From what I gather, the problem does _not_ allow for zero edges and 7,5,4 is considered the same as 5,7,4. Thanks! What I don't understand though, is how to tell whether the three integers fit together to form said triangle, i.e., how can I know whether 32,33,34 forms a real triangle or not?
Comment: Now that I think of it some more, that last question was just silly, thanks though! @Henry
Answer: Let ${\cal S}_p$ be the set of ordered triples $(a,b,c) \in \mathbb{N}^3$ such that $c \ge b \ge a \ge 1$, $a+b+c=p$, and $a+b > c$ (the triangle inequality).  For instance, ${\cal S}_3 = \{ (1,1,1) \}$ and ${\cal S}_4 = \{ \}$.  Each triple in ${\cal S}_{p-2}$ gives rise to a triple in ${\cal S}_{p}$ under the transformation $(a,b,c)\rightarrow(a,b+1,c+1)$, and all triples in ${\cal S}_{p}$ are produced by this transformation except for those of the form $(a,a,c)$.  These latter triples can be counted directly: there is one for each value of $a$ for which $3a \le p < 4a$, and so there are exactly $I_p = \lfloor{p/3}\rfloor - \lceil{(p+1)/4}\rceil + 1$ of them.  So we have the recurrence $S_p = S_{p-2} + I_p$ for the values of $S_p = |{\cal S}_p|$, with initial conditions $S_0=S_1=0$.  The addend has period $12$, and takes on values
$$
I_{12k+(0,1,2,...,11)} = k + (0,0,0,1,0,0,1,1,0,1,1,1).
$$
We then have $S_{12(k+1)} = S_{12k} + 6k + 3$ and $S_{12(k+1)+1} = S_{12k+1} + 6k + 5$, leading to quadratic solutions $S_{12k} = 3k^2$ and $S_{12k+1} = 3k^2 + 2k$.  The full set of solutions is
$$
\begin{eqnarray}
S_{12k} &=& 3k^2 \\
S_{12k+1} &=& 3k^2 + 2k \\
S_{12k+2} &=& 3k^2 + k \\
S_{12k+3} &=& 3k^2 + 3k + 1\\
S_{12k+4} &=& 3k^2 + 2k \\
S_{12k+5} &=& 3k^2 + 4k + 1 \\
S_{12k+6} &=& 3k^2 + 3k + 1 \\
S_{12k+7} &=& 3k^2 + 5k + 2 \\
S_{12k+8} &=& 3k^2 + 4k + 1 \\
S_{12k+9} &=& 3k^2 + 6k + 3 \\
S_{12k+10} &=& 3k^2 + 5k + 2 \\
S_{12k+11} &=& 3k^2 + 7k + 4.
\end{eqnarray}
$$
Note that, as noted elsewhere, for all odd $p$ we have $S_{p} = S_{p+3}$.
Answer: No of possible triangles $n$ having perimeter $p= p^2/48$ if $p$ is even.
Answer: An efficient approach can be found with little algebraic manipulation :

Since $a + c > b$ or, $p – b > b$ or, $b < p/2$. Thus iterating $b$ from $1$ to $p/2$, calculating $a$ and storing only the whole number $a$ would give all solutions for a given $p$. There are no right triangles are possible for odd $p$.
Answer: How many isosceles triangles can be formed when all the sides are integers and perimeter is given

If two equal sides are $x$, $x$, then the third side will be $100-2x$. By triangle inequality, $$x+x > 100 - 2x$$
$$4x>100$$ $$x>25.$$ Hence $24$ triangles are possible.
Formula: When $p$ is even: $p/4 - 1$, (round off $p/4$ to the nearest integer and subtract $1$ if $p$ is even). In this question $100$ is divisible by $4$. So no need to round off.
When $p$ is odd:  $p/4$ (round off $p/4$ to the nearest integer or integral part of the decimal number if the quotient is decimal).


Module/Method to cleanup content of Drupal site?

Question: I have been assigned with the task of maintaining a specific Drupal site. The problem is that the person who created the website did not actually think it through. No input filters to be heard of, no restriction for images' placement, plain HTML everywhere.
I'm now on the spot, since I've promised to tidy up the website, and I've just realized how much work will it require. There are articles that are copy+pasted from wikipedia (the WYSIWYG editor kept all the formatting), random websites or (even worse) from MS Word.
I understand that I will have to do some manual editing and check the articles one by one, but I was wondering if there is some kind of a method that someone may have used in a similar situation. Perhaps a module that will cleanup the html of the various nodes?
Note: The website is built in Drupal 6, but if you have suggestions for Drupal 7, I guess that I could upgrade.
Comment: As for cleaning up the copy/pasted Wikipedia entries — to anybody that would need that these days, I'd recommend using the [Puzzler module](https://www.drupal.org/project/puzzler). It allows for clean retrieval of Wikipedia data elements (via their API), and it will also automatically keep them up to date. Puzzler is the terminator of copy/pasted data from Wikipedia :-)
Answer: Normally, when I have encountered this, there is too much variety to do much automated cleanup.  You can do something like this, though
<code>$sql = "
  SELECT n.nid
  FROM {node} n
";

$result = db_query($sql);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid, NULL, TRUE); // bypass internal cache
  $node->body = _filter_htmlcorrector($node->body);
  node_save($node);
}
</code>
Either stick this in a custom menu entry or make a simple script for it.  Depending on how many nodes you have, you may need to use the Batch API.
_filter_htmlcorrector will fix bad HTML to an extent, and I have also used check_markup with luck, too.  For check_markup, you just need to figure out the numeric filter number to use.
Other than that, you really do need to play with the processing you do in the loop.  This will give yourself a head start, but you still need to edit each article and manually check/fix things.
Comment: This is a pretty awesome way to handle it. If you want even MORE control on your html, use the same concept but filter your content using [php tidy extension](http://www.php.net/manual/en/tidy.getconfig.php). I have cleaned up *major* html static sites with this tool (thousands of pages) and once properly configured, it is quite efficient at what it does.
Comment: This sounds like a really interesting solution. I'll try this in a staging setup and see how it works. Thanks a lot for your reply.
Answer: I guess you need to use Input format in this issue. You need to create filter and set an allowed elements to avoid dirty inputs. In the wysiwyg settings admin/settings/wysiwyg/profile/ID/edit in the Cleanup and Output tab be sure to enable the Verify HTML, Apply source formatting, and Force cleanup on standard paste. If the old nodes are created using Full HTML then you need to apply the above conf in the Full HTML profile...please let us know if that helps you
Comment: I understand that for new content that will be added from now on it's pretty easy to enforce proper inputs. The problem with applying filters to the "Full Html" input format is that even though it may look OK in most of the cases, the content that is stored in my database will not be "clean". It will just display differently. Or am I missing something here? I want to "purify" the html that already exists in the website, even if that means that I will manually fix any mistakes during the purifying process. I hope that this makes sense.
Answer: If the text looks good with Full HTML, why don't just continue to go with that? At lease, you can switch to HTMLPurifier, which gives you total control of the HTML tags/attributes. Thus you could make sure that there is no security issue (no script tags).
Then I think you must manually edit each node, clear format, add custom CSS classes, semantic HTML tags... so that your content will be semantically correct. But I suggest you only do that if it is really needed.
Or, if you just want to remove extra inline CSS/JS, unnecessary class/id attributes, there are many tools to do that, and you should do directly on the database. A 3rd party tool might be faster and more mature. E.g. there is a bug in D6 HTML corrector filter.
Comment: I have a "psychological" issue with bad content being stored in my database. I guess that the chances of bad html being exploited somehow in the future are slim, but I still cannot deliver a website that will have bad content in it (with me knowing about it). The HTMLPurifier seems like a very good solution (I just took a quick look at it) so I will try it and see if it helps me out. In any case, +1 for your suggestions (and yes, I know that I will have to do a lot of manual work, but that's a common side-effect of OCDs)
Comment: The advantage of an "input filter" is that the input could contain malicious data.

However I don't know what do you want to clean: extra data (embedded CSS/JS, extra id/class that you'll never use) or non-semantic data (replace some B/STRONG tags with H4 tags for node section titles). Anyway, I'll add some tips in my above reply.
Comment: I know that input filters are designed to do exactly that: protect you from malicious data (even if they are stored in the database, they still can't hurt you). However, the content that I'm referring to, varies a lot: html code generated from Microsoft Word, copy/pasted code from random websites and every bad practice on the book.
Answer: I've not been in this situation, so just suggestions here! Obviously back up the db before anything. I'd try and see if you can find a filter that does a decent job of cleaning up (I know you want to clean the DB itself). I'd maybe take the worst offenders and see what markup comes out with a few different HTML correctors (eg htmLawed). If any of them consistently do an ok job, then you can use a drush script, or create an action to use with VBO, to run the filter on the bodies and teasers and then save them back to the db. Then take a look and see the damage :/ Good luck


Sigma-algebras. Countable intersections and distributivity

Question: It's kind of a classical problem with simple formulation but it turned out to be quite difficult for me.
$(\Omega,\mathscr{F},P)$ is a probability space. If $(\mathscr{D}_n,\;n\geqslant 0)$ is a decreasing sequence of sub-$\sigma$-fields of $\mathscr{F}$: $\mathscr{D}_0\supset\mathscr{D}_1\supset\ldots$, $\mathscr{C}$ is another sub-$\sigma$-field of $\mathscr{F}$ independent of $\mathscr{D}_0$, then
$$\bigcap\limits_n(\mathscr{C}\vee\mathscr{D}_n)=\mathscr{C} \vee \Bigl(\bigcap\limits_n\mathscr{D}_n\Bigr).$$
Note 1: $\mathscr{C}\vee\mathscr{D}_n$ is a $\sigma$-algebra generated by $\mathscr{C}\cup\mathscr{D}_n$.
Inclusion $\bigcap\limits_n(\mathscr{C}\vee\mathscr{D}_n)\supseteq\mathscr{C} \vee \Bigl(\bigcap\limits_n\mathscr{D}_n\Bigr)$ is obvious. But the other one is not.
Note 2: I found this problen in Revuz, Yor and there is a hint: show, that if $C\in\mathscr{C}$ and $D\in\mathscr{D}_0$ then $\lim\limits_{n\rightarrow\infty}P(CD|\mathscr{C}\vee\mathscr{D}_n)$ is $[\mathscr{C}\vee(\cap_n\mathscr{D}_n)]$-measurable.
First, I don't really understand how to prove that the limit will be [some $\sigma$-algebra]-measurable. Second, with martingale convergence $E(I_C I_D|\bigcap\limits_n(\mathscr{C}\vee\mathscr{D}_n))$  is $[\mathscr{C} \vee (\cap_n\mathscr{D}_n)]$-measurable, what's next?
Answer: The solution can be found on p.46 of the book "Exercises in Probability A Guided Tour from Measure Theory to Random Processes, via Conditioning" by L. Chaumont and M. Yor. I must notice that it's really a very interesting and useful book.
If we want to show that $\sigma$-algebras are equal up to $P$-negligible sets then  the equality
$$E(X|\mathscr{A})=E(X|\mathscr{B}),\;\forall X - \text{bounded}, \mathscr{A}\vee\mathscr{B}\text{-measurable r.v.}$$ is what we need (it's nearly obvious, try to replace $X$ with indicators).
So we want to show that
$$E(X|\cap_n(\mathscr{C}\vee\mathscr{D}_n))=E(X|\mathscr{C}\vee\mathscr{D}),\; \mathscr{D}=\cap_n\mathscr{D}_n$$
holds for all $\mathscr{C}\vee\mathscr{D}_0$-measurable r.v.  Using monotone class theorem for functions (Revuz, Yor p. 3) and the equality $\mathscr{C}\vee\mathscr{D}_0 = \sigma\{AB,\;A\in\mathscr{C},\,B\in\mathscr{D}_0\}$ we can show that it's enough to consider $X=fg$, $f$ and $g$ are bounded and respectively $\mathscr{C}$-measurable and $\mathscr{D}_0$-measurable.
\begin{multline}
E(X|\mathscr{C}\vee\mathscr{D}_n)=\text{$f$ is $\mathscr{C}\vee\mathscr{D}_n$-measurable}=fE(g|\mathscr{C}\vee\mathscr{D}_n)
\end{multline}
Again, using monotone class theorem and conditional independence of $\mathscr{C}$ and $\mathscr{D}_0$ given $\mathscr{D}_n, \forall\,n$, which holds because $\mathscr{D}_n\subset \mathscr{D}_0$, we can show that $E(g|\mathscr{C}\vee\mathscr{D}_n)=E(g|\mathscr{D}_n)$. So we have
$$E(X|\mathscr{C}\vee\mathscr{D}_n)=fE(g|\mathscr{D}_n).$$
By martingale convergence theorem $E(g|\mathscr{D}_n)\rightarrow E(g|\mathscr{D})$, therefore $$E(X|\mathscr{C}\vee\mathscr{D}_n)\rightarrow fE(g|\mathscr{D})=E(X|\mathscr{C}\vee\mathscr{D}),$$ because $\mathscr{C}$ and $\mathscr{D}_0$ are independent conditionally on $\mathscr{D}$. Martingale convergence theorem implies that
$$E(X|\mathscr{C}\vee\mathscr{D}_n)\rightarrow E(X|\cap_n(\mathscr{C}\vee\mathscr{D}_n))$$
We deduce the equality from the uniqueness of limit in $L^1$.


cannot find symbol error in super constructor call

Question: Compilation fails at line 8.  It says the "s" in "super" is wrong.
<code>public class BasePlusCommissionEmployee extends CommissionEmployee {
  private double baseSalary;

  //constructor
  public BasePlusCommissionEmployee( String first, String last, String ssn, int mth,
          int day, int yr, double sales, double rate, double salary )
  {
     super( first, last, ssn, mth, day, yr, sales, rate );
     setBaseSalary( salary );
  }
</code>
Error message:
Comment: Also "The code compiles except for line 8" just means the code doesn't compile at all ;)
Comment: can you cut'n'paste the error message and show the relevant code for the CommissionEmployee class
Comment: Yes, you need to show the actual error message as it usually will tell you *exactly* what is wrong.
Comment: @Shinobi1173 - You should read SO's [Markdown Editing help](http://stackoverflow.com/editing-help) or use [the Formatting Reference provided when you are asking questions](http://codinghorror.typepad.com/.a/6a0120a85dcdae970b0120a86e29f4970b-pi) to ensure that your code snippets are readable.
Comment: Are you having constructor with same number of arguments in your base class?? What exactly the Compiler says..
Comment: @llya.. copy 'n' paste you mean ?? :)
Comment: possible duplicate of ["Cannot find symbol" error message calling super-class constructor](http://stackoverflow.com/questions/5276239/cannot-find-symbol-error-message-calling-super-class-constructor)
Answer: In all likelihood,  you're not calling the super constructor, the constructor for the CommissionEmployee class, correctly, and are probably passing in the wrong parameters. Fix that and your error will likely go away.
Comment: @Shinobi1173: no, I didn't know, but the Java compiler did, and that's what matters! Glad you've got things working!
Comment: @Shinobi1173 imagine a function `drawRectangle(int x1, int y1, int x2, int y2) {...`. And in the call: `drawRectangle(1,1,2,2);` If the order of the parameters would not be important, how should the compiler know which integer goes where?
Cheers!
Comment: Yeah, the problem is (and I'm pretty sure I'm blind right now), I cannot seem to find the dang thing
Comment: @Shinobi1173: then open your eyes. All you have to do is to inspect what parameters are needed for the CommisionEmployee constructor and only use those parameters when calling this constructor. The code is there for you to see (but not available to us at the moment).
Comment: Alright.  Found the problem.  Apparently, the order of listed arguments really matters.  Who knew?  Probably you.


Inequality $\sum^{k}_{i=1}\sum^{n}_{j=k}{{1}\over{j - i + 1}} \le n$

Question: I was proving a statement and have finished all the other part, the remaining boiling down to proving the inequality below (if I proved the other part correctly):
$$\sum^{k}_{i=1}\sum^{n}_{j=k}{{1}\over{j - i + 1}} \le n$$
where $1 \le i \le k \le j \le n$.
I wrote a simple function taking $k$ and $n$ as parameters to compute the left side and the result never exceeds $n$. Also it seems that the maximum is reached when $k = n / 2$. Any ideas would be appreciated!
Thanks...
Comment: Do you mean to say that the maximum, instead of minimum, is reached at $k=\frac{n}{2}$? Bounding the summation with integral which is a sum of $x\ln(x)$ may work. There are a few small correction terms need to be taken care of...
Comment: @Hans Thanks for pointing that out, Hans! Sorry for the typo... Corrected.
Answer: Proof: Define $s=\sum^{k}_{i=1}\sum^{n}_{j=k}{{1}\over{j - i + 1}}$. We prove the required inequality by factoring out common and distinct summand $\frac{1}{d+1}$, where $d=j-i$. The region of summation $\{1,2,...,k\}\times\{k,k+1,...,n\}$ is partitioned into 3 parts, with 2 isosceles right triangles sandwiching 1 parallelogram with two 45 degree angles. We distinguish 2 cases:
1) $n\le 2k-1$
The summation over the 3 partitions are:
$$\begin{align}
s_1 &= \sum_{i=0}^{n-k}\frac{d+1}{d+1}, \\
s_2 &= \sum_{d=1}^{2k-n-1} \frac{n-k+1}{n-k+1+d}, \\
s_3 &= \sum_{d=1}^{n-k} \frac{n-k+1-d}{k+d} = (n+1)\sum_{d=1}^{n-k}\frac{1}{k+d} - (n-k).
\end{align}$$
Since the summands are decreasing function of d, we bound the summations by the integration of the summands.
$$s_2 < (n-k+1)\int_0^{2k-n-1}\frac{1}{n-k+1+x}=(n-k+1)\ln\frac{k}{n-k+1},$$
and
$$s_3+n-k < (n+1)\int_0^{n-k}\frac{1}{k+x}dx=(n+1)\ln\frac{n}{k}.$$
2) $n\ge 2k-1$
$$\begin{align}
s_1 &= \sum_{i=0}^{k-1} \frac{d+1}{d+1} = k, \\
s_2 &= k\sum_{d=1}^{n-2k+1} \frac{1}{k+d} <k\int_0^{n-2k+1}\frac{1}{k+x}dx = k\ln\frac{n+1-k}{k}, \\
s_3 &= \sum_{d=1}^{k-1} \frac{d}{n-d+1} = (n+1)\sum_{d=1}^{k-1}\frac{1}{n+1-i}-(k-1) \\
&<(n+1)\int_1^k \frac{1}{n+1-x}dx = (n+1)\ln\frac{n}{n+1-k}-(k-1).
\end{align}$$

For both cases, put the parts $s_1, s_2, s_3$ together, we get the same expression
$$\begin{align}s &=s_1+s_2+s_3 \\
&= (n+1)\ln n - \big(k\ln k + (n+1-k)\ln(n+1-k)\big)+1 \\
&< (n+1)\ln n - (n+1)\ln\frac{n+1}{2} +1 \\
&\text{by the convexity of the function } x\ln x \\
&< (n+1)\Big(\ln 2-\frac{1}{n+1} \Big)+1 \\
& = (n+1)\ln 2 \\
&< 0.7(n+1).
\end{align}$$
This actually gives a slightly tighter bound for $s$. We only need to check the inequality for $n\in\{1,2\}$ to complete the proof.
Also, this proof points the way to showing $s$ achieves maximum at $k \cong \frac{n+1}{2}$ for fixed $n$.
QED
Comment: Thank you so much, Hans! Like in your solution, bounding with $xln x$ at the right time is important. One of my previous trials involves replacing each item with the maximum one and then apply the logarithm bounding, which exceeds the RHS of the inequality. Yes, as you have pointed out, maximum is reached when $k$ is in the middle - sorry for the typo. All in all, a brilliant and meticulous solution!
Answer: Denote your sum by $s$. After some rewriting of summation variables one has
$$s=\sum_{i=0}^{k-1}\sum_{j=0}^{n-k}{1\over i+j+1}\ .$$
Now the function
$$(x,y)\mapsto{1\over x+y+1}\qquad(x+y>-1)$$
is convex. It follows that
$${1\over i+j+1}\leq\int_{i-1/2}^{i+1/2}\int_{j-1/2}^{j+1/2}{dx\>dy\over 1+x+y}\ .$$
Summing all these integrals up one obtains
$$s\leq \int_{-1/2}^{k-1/2}\int_{-1/2}^{n-k+1/2}{dx\>dy\over 1+x+y}=:J\ .$$
Mathematica  computes the last integral to
$$J=(n+1)\log(n+1)-k\log k-(n+1-k)\log(n+1-k)\ .$$
I leave it to you to analyze this expression. The case $n=50$ and $1\leq k\leq n$ is shown in the following figure. It corroborates the findings of @Hans.
Comment: Thank you for this alternative and more general approach, @Christian! Both of you made use of logarithm functions' convexity, which turns out to be crucial to the proof. $J'|_k = 0$ when $k = {n + 1 \over 2}$, where the maximum is reached. Substituting $k = {n + 1 \over 2}$ back yields $J = (n + 1) \ln {(n + 1)}$, same as @Hans's result. Thanks again for taking your time looking at this problem!
Comment: (By the way, I will vote up this answer after I am eligible to do so, which requires 15 reputation points... Sorry about that...)


Prove that if $3\mid n$ and $5\mid n$, then $15\mid n$

Question:
Prove that if $3\mid n$ ($n$ is a multiple of $3$) and $5\mid n$, then $15\mid n$.

So far I have the following incomplete proof:
Suppose that $3\mid n$  and $5\mid n$, then $∃k,l∈ℤ$  such that $n=3k$ and $n=5l$.
Now, $3k=5l$ $...?$
From here, I struggle to deduce further to show that the conclusion is true. I know that I should show that $n$ is a multiple of $15$ in some way.
Comment: **Hint:** According to Euclid's lemma, if a prime $p\mid ab$ then $p\mid a$ or $p\mid b$. Since $5l=3k$, we know that $3\mid 5l$. Can you show now that $3\mid l$ and hence $n=5l=15q$ for some $q\in\Bbb Z$ ?
Comment: $$\frac1{15}=\frac25-\frac13.$$
Comment: What can you conclude from $5\mid 3k$ and the fact that $5$ is prime?
Comment: What happens when $k <5$ or $l < 3$ in your analysis?
Comment: In lack of something better, did you try induction?
Answer: $\dfrac{n}{3}=m$ is an integer, and $\dfrac{n}{5}=k$ is another integer.
From this we can conclude that $m-k = \dfrac{5n-3n}{5\cdot3} = \dfrac{2n}{15}$ is also an integer, and 2 and 15 have no common factors.
Answer: Let the prime factorisation of $n$ be $p_1^{a_1}p_2^{a_2}\cdots p_k^{a_k}$ where $p_i$ are primes and $a_i\ge0$ for $i=1,\cdots,k$.
Since $3\mid n$ and $3$ is prime, without loss of generality, we have $p_1=3$ and $a_1\ge1$.
Similarly, since $5\mid n$ and $5$ is prime, without loss of generality, we have $p_2=5$ and $a_2\ge1$.
Hence $$n=3\cdot3^{a_1-1}\cdot5\cdot5^{a_2-1}\cdots p_k^{a_k}=15(\color{red}{3^{a_1-1}\cdot5^{a_2-1}\cdots p_k^{a_k}})$$ and since the expression in red is an integer, we must have that $15\mid n$.
Answer: $3$ does not divide $5$ and vice versa,
$\rightarrow n = 3^a \cdot5^b \cdot.......$, as:

If n did not have $3$ as a prime factor then, as no primes divide each other, $n$ would not divide $3$. If it didn't have any prime factors of 3 then $n= 3k + 2$ or $n= 3k +1$ for integer $k$, and hence dividing by $3$ wouldn't give an integer.

-If $n$ did not have $5$ as a prime factor (the same logic can be applied)
Therefore $n = 3\cdot 5\cdot $(other prime factors)
Therefore $n= 15\cdot ......$
Answer: $n=5k=3l$ so that $3|5k$ (and $5|3l$). Hence $3|k$ (and $5|l$).
Comment: `\mid` is a good replacement for `|`.
Answer: As $n$ is divisible by $3$, it can be expressed as $3k$, where $k$ is some integer.
As $n$ is divisible by $5$, it can be expressed as $5k$, where $k$ is some integer.
Since $3$ and $5$ are relatively prime, if a number is divisible by $5$ and $3$, then it must be divisible by $15$.
To go in to a bit more detail:
$15k$ expresses a number $n$ which is divisible by $15$.
$15k=5\cdot 3\cdot k$
Therefore, a number which is divisible by $15$ must be divisible by $5$ and $3$.
Answer: Below is an easier approach to the solution that some has given to me.


Derive the variance of the standardized normal of sample mean

Question: I have solved the following problem and felt a little bit uncertain about the my answer.
Here is the problem.
Let $Y_i \in L_{2}$ for $i=1,2,...,N$  be a scalar random variable with iid with $\mu_Y=E(Y_i)$ and $\sigma_Y^2=var(Y_i) \lt \infty$. The sample average is defined as $\overline{Y_N}=\sum Y_i/N$.
Suppose that $Z_N= \frac{\overline{Y_N}-E(\overline{Y_N})}{\sqrt{(var(\overline{Y_N}))}}$
Derive $Var(Z_N)$
If the limit of $Z_N$ exists, it will be nondegenerate. How can I derive $Var(Z_N)$?
At first glimpse, I think $Var(Z_N)$ is equal to 1.
1.) However, can we use the moment generating function to prove that $Var(Z_N)$=1. If yes, what I have to do is just to show that the moment generating function of $Z_N$ is similar to the moment generating function of the standard normal?
2.) Is this also a link to Chi square?
Helps and comments are highly appreciated.
Comment: Because variance is bilinear and invariant under additive shifts, $$\operatorname{Var}(Z_N)=\left(\frac{1}{\sqrt{\operatorname{Var}(\bar Y_N)}}\right)^{2}\operatorname{Var}(\bar Y_N)=1.$$
Answer: Indeed, $Var(Z_N) = 1$.
Here is the proof:
First,
$$
\begin{align}
E[\bar{Y_N}] &= E[\frac{1}{N} \sum Y_i] \\
             &= \frac{1}{N} \sum E[Y_i] \\
             &= \frac{1}{N} N\mu = \mu,
\end{align}
$$
since the expectation operator $E[]$ is linear.
Next:
$$
\begin{align}
Var(\bar{Y_N}) &= Var(\frac{1}{N}\sum_i Y_i)\\
               &= \frac{1}{N^2} \, Var(\sum_i Y_i)\\
               &= \frac{1}{N^2} \, N \, Var(Y_i)\\
               &= \frac{1}{N} \, \sigma^2,
\end{align}
$$
where the third equation follows because the Bienayme's identity and because the sample is iid.
Thus we have:
$$
Z_N = \frac{\bar{Y_N} - \mu}{\frac{\sigma}{\sqrt{N}}}.
$$
The variance of $Z_N$ can now be computed as follows:
$$
\begin{align}
Var(Z_N) &= Var\left(\frac{\frac{1}{N}\sum_i Y_i - \mu}{\frac{\sigma}{\sqrt{N}}}\right)\\
         &=Var\left(\frac{\frac{1}{\sqrt{N}}\sum_i Y_i - \sqrt{N}\mu}{\sigma}\right)\\
         &= \frac{1}{\sigma^2} Var\left(\frac{1}{\sqrt{N}} \sum_i Y_i\right)\\
         &= \frac{1}{N\sigma^2} N \sigma^2\\
         &= 1.
\end{align}
$$
The third equation follows because the variance is quadratic w.r.t. constant factors and invariant w.r.t. simple shifts (here we have a shift by $\sqrt{N}\mu$). In the fourth equation we used, again, Bienaymé's identity.
Comment: This answer doesn't need more than a single line of algebra and, because it is so unnecessarily involved, really obscures the point.  See my comment to the question.
Comment: Thank you every one.


Modification of Minkowski sum

Question:
As shown in the illustration, there are two regions A and B, each consists of a set of vectors. For each vector (point) in A, you can pick a vector (point) in B and find there middle point (i.e. the vector obtained by halving the sum of the two vectors from A and B respectively). My question is, how do I generate and visualize the region consisting all possible middle points generated by all possible combinations of vector pairs from A and B. On top of that, if we account for the possible overlappings (the same middle point generated by different vector pairs), the resultant region can be thought of as a probability distribution of all possible combinations. Is there a way to obtain/visualize this distribution?
Edit: I looked it up. It should actually be half if their Minkowski sum. The distribution part I am still not sure though. The reason that I want to consider distribution is that, the typical Minkowski sum does not account for which point in the summed up region is formed by how many pairs of vectors from A and B, since it is a set. I want to consider the situation where even if A and B are 'uniform', the sum will account for the multiplicity of each element (in the sense a modification of Minkowski sum to be a multiset)
Comment: What you are looking for is a convolution (w.r.t. abelian group $\mathbb{R}^{n}$) of $1_{A}$ and $1_{B}$ - uniform distributions on sets $A, B$.
Comment: To get help in this forum it's important that you show your work on the problem. For example, have you tried calculating this sum for simple shapes? It shouldn't be hard to calculate some examples of you choose the sets simple enough.
Comment: I have tried some simple examples. Unfortunately even for shapes as simple as squares I am not able to get any useful insights... the reason being the cardinality of A and B are both infinite, therefore it is hard to visualize. the only insights I have so far is the multiplicity is not equal for each element if you sum up all possible pairs.
Answer: Here are some examples using Monte Carlo method:
Two segments

A segment and a square

A square and a disk

Modification of Minkowski sum


How to estimate a probability?

Question: Let's assume that we have a random variable $X$ that takes integer values from the range $[0, b]$, the left boundary $b$ is not precisely defined, but on practice $b<10,000$.
x <- c(rep(7, 2), rep(9, 163), rep(11,231), rep(13,343), rep(15, 211),rep(17, 159),rep(19,  27))

I need to estimate a probability $Pr(X0$ and $a << b$.
In order to estimate the probability, I propose to plot a probability densities, so that the histogram has a total area of one.
hist(x, freq = FALSE, label = TRUE, breaks = c(seq(7, 19, 1)))

Than I can find the sum of corresponded densities, for example, for the  random variable $X$ generated above: $Pr(X<a=10)=0.002+0.143$.
Question: Is proposed approach correct?
Comment: If your variable is not continues there is no densities, but you have probabilities.
Comment: @Tim In a measure-theoretic treatment of probability, probability mass functions are just a special class of probability density functions that are integrated with respect to the counting measure, as opposed to the Lebesgue measure used for continuous random variables.
Answer: The easiest approach is to calculate the so-called empirical distribution function $\hat{F}$ of your sample.  This function is calculated as
$$
\hat{F}(s) = \frac{1}{n} \sum_{i=1}^{n} I(x_i \leq s)
$$
where $I(x_i \leq s) = 1$ if $x_i \leq s$ and otherwise $I(x_i \leq s) = 0$, so for each value $s$ the function $\hat{F}(s)$ tells you the proportion of the sample that is less than or equal to $s$, and we use this to estimate $P(X \leq s)$
In R you could create your own function to do this:
edf <- function(sample, s) {
    mean(sample <= s)
}

Now just insert your data into the sample argument and specify the value for s and you have an estimate of the probability you want.
Answer: Using a histogram is unnecessarily coarse. A better approach is to use the empirical CDF, by simply counting the number of values in your sample that are below $a$ and dividing this count by the sample size. In R, this is sum(x < a)/length(x) or mean(x < a).
Comment: i have tried sum(x <= a)/length(x) and sum(x < a)/length(x). Results are same. What is correct '<=' or '<'?
Comment: @Nick Depends on what you want. Using `<=` estimates $p(X ≤ a)$ whereas using `<` estimates $p(X < a)$.

How to estimate a probability?


Como setar uma Struct como NULL em C?

Question: Estou querendo verificar se ha conteúdo algum na struct então queria inicializar as variáveis como NULL, pois se fossem iguais a NULL saberia que não foram criadas.
trechos:
Struct:
struct  Fila
{

    int         capacidade;
    float       *dados;
    int         primeiro;
    int         ultimo;
    int         nItens;

};

inicialização:
struct  Fila
PPFila          =   (Fila)NULL,  <--- Erro de incompatibilidade
AUTFila         =   (Fila)NULL;  <--- Erro de incompatibilidade

Criação:
if(PPFila   ==  (Fila)NULL)
{

    //
    //  Cria as filas que gerencias as o envio das threads
    //
    criarFila(&PPFila,  20);
}

Alguém tem alguma dica como posso fazer isso?
Comment: Lucas, por favor, use a tag "c++" apenas para problemas de C++. C é uma linguagem diferente.
Comment: @bigown O título da pergunta pede uma solução em C. Além disso, C++ tem jeitos diferentes de lidar com coisas que estão sendo feitas no código. Uma resposta em C++ tenderia a educar o AP sobre essas diferenças, e isso pode ser uma perda de tempo caso a tag tenha sido colocada por ignorância.
Comment: @bigown pode deixar assim, meu interesse é mesmo em C
Comment: @PabloAlmeida o problema também cabe para C++, se ele deseja uma solução tanto para C, quanto para C++, ele pode fazer isto.
Comment: @LucasFernandes você quer que fique a *tag* C++?
Answer: stddef.h define NULL como:
#define NULL ((void *)0)

Por isso fazer um cast de NULL para Fila, que nem é um tipo neste código, ou atribuir NULL para uma variável de tipo primitivo é "errado". "NULL não é um valor", é um ponteiro sem tipo para o endereço 0.
Use um ponteiro para a sua estrutura, assim pode inicializá-la como nula.
struct Fila * PPFila = NULL;

Answer: Não é possível setar uma struct com NULL da forma como está declarada.
Fila f = NUll;

error: invalid initializer.

Se quiser atribuir NULL à uma struct deve declará-la como ponteiro:
Fila * PPFila = NULL,
     * AUTFila = NULL;

Comment: Usando o gcc e clang, ao atribuir um NULL a um inteiro, ele só me manda um warning, mas cria um executável assim mesmo (_**warning**: incompatible pointer to integer conversion initializing 'int' with an expression of type 'void *' [-Wint-conversion]_)
Comment: @Amadeus Qual é o comando que está utilizando para compilar o programa? estou usando o gcc e não deu esse warning, poderia postar o código que está usando para aparecer esse warning?
Comment: Primeiramente, o meu gcc é a versão 6.1.1. Segundo, usei o básico mesmo `gcc -o x x.c`, mas vc pode tentar com a opção `-Wall`. No [ideone](http://ideone.com/sK50r0) nem mesmo gera warning
Comment: A única diferença que é que meu gcc está na versão 4.9.2, poderia mostrar o código que está usando para gerar esse warning?
Comment: desculpe, não tinha visto o código. Então, como falei no post para usar o NULL deve-se declarar a váriavel como ponteiro. Ponteiros são declarados com '*' antes do nome. Neste código a varável está declarada como inteiro, não suportando o uso do NULL.
Comment: Para mais informações sobre a utilização de ponteiros recomendo a leitura [deste artigo](http://www.cprogressivo.net/2013/03/Como-declarar-inicializar-e-usar-ponteiros-e-a-constante-NULL-em-C.html)
Comment: Você não entendeu a colocação. É errado colocar NULL para variáveis primárias, exemplo `int`. O que estou colocando é que o compilador nem sempre vê isso como um erro. No caso do ideone, conforme colocado no comentário acima, não gerou nem mesmo o **warning**. Então, a expressão "Não é possível atribuir NULL à este inteiro" não é verdade. É possível sim, só que não é correto
Comment: Sim, pode-se atribuir, pois o endereço de memória, em um programa de 32 bits, é um inteiro. pode-se inclusive usar o seguinte comando: numero = (int) № para guardar na variável o endereço dela. Não saberia dizer um uso prático para isso. mas é possível
Comment: A discussão já está ficando longa e logo vão cortar todos os comentários, por isso, vou apenas reafirmar o que já disse: Sua colocação no post está errada. É possível atribuir NULL a uma variável do tipo int, por exemplo. Mas **não é correto**. Infelizmente o compilador nem sempre vai te ajudar nisso. Até agora, só vi um _warning_ sendo gerado. Comentando o seu último comentário, endereços de memória normalmente são do tipo `unsigned int` para evitar problemas com extensão do sinal.
Comment: Entendi o problema, editei a resposta. Obrigado
Answer: Bom, para a inicialização, o que gosto de fazer é usar o memset para colocar todas as variáveis em ZERO.
Exemplo:
struct  Fila PPFila, AUTFila;
memset(&PPFile, 0, sizeof(PPFila));
memset(&AUTFile, 0, sizeof(AUTFila));

Para saber se tá inicializado ou não, vc pode usar algum parâmetro de sua estrutura que diz isso, ou criar um específico para dizer se já foi inicializado. No seu caso, parece que o campo nItens faz exatamente esse papel. Assim, para a verificação:
if(PPFila.nItens == 0)
{
    //
    //  Cria as filas que gerencias as o envio das threads
    //
    criarFila(&PPFila,  20);
}

Comment: Obrigado, ajudou bastante
Comment: O que fazer no caso de a fila já estar criada e tiver 0 itens? Isso é possível? vai precisar ter um controle rigoroso à isso.
Comment: Para se ter uma ideia, acesse '*PPFila.dados' no if, isso acaba gerando um erro de execução, e travando o programa.
Comment: olhando por esse ponto, parece fazer todo sentido
Comment: e o que acontecera se tentar cria-la novamente se estiver ja criada mas com 0 elementos?
Comment: @Pilati Por isso que disse na resposta: "ou criar um específico para dizer se já foi inicializado". Se na estrutura não existe uma variável que pode ser utilizada para esse papel, crie uma, talvez algo do gênero `int inicializada;` e depois verifique se é zero, se for, inicialize e coloque 1. Dei apenas uma sugestão no caso dele, que, agora, me parece que é melhor usar a variável `capacidade`
Comment: @Amadeus Realmente a capacidade parece ser o melhor campo criado para essa finalidade, não tem sentido uma fila ter uma capacidade 0.
Comment: @LucasFernandes Pelo que notei a estrutura tem um ponteiro para float, então se já tiver sido criada a fila e for criar novamente a referencia para o ponteiro antigo será perdida, ocasionando assim os famosos vazamentos de memória

Como setar uma Struct como NULL em C?


Repeated measures ANOVA or MANOVA (SPSS)

Question: I have an experimental design of two independent groups (pregnant/non-pregnant), in which each person has described past memories and future episodes on different variables on a scale from 1-7. Therefore I have the same variable (vividness for example) measured during remembrance and during construction of the future scenario. I treat the past and future as two separate variables. In this case with two groups, who differ on one categorical variable would it be best to use repeated measures ANOVA or MANOVA?
Comment: Read, for example, this question: http://stats.stackexchange.com/q/13197/3277.
Answer: You have one input (2 categories).

If one output variable, then you may use t-test or ANOVA.
If 2 (or more) output variables, then you may use MANOVA.


Custom view with selective PDF output

Question: I'm hitting a blank, I need to be able to offer a print option on some views (a pdf) and not on others.
Does anyone have an elegant way of doing this?
Thanks for looking, I appreciate your time.
Answer: Take a look at the Views PDF module.  It will allow you to add a "PDF" display to the views you choose.  From the project page:

With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.
Comment: Thanks Laxman13, I was being dim and that's just what I needed.
Comment: No problem at all, glad to help

Custom view with selective PDF output


How was this changed to get $r_p$

Question: $$ \frac{G \,m_p \,m_{*}}{r_p^2} =\frac{m_p\,v_p^2}{r_p}$$
$$ r_p =\frac{G\,m_{*}}{v_p^2}$$
(Image)
Can someone help me with the steps to get the equation like this? I want to know the process of how they changed the equation for it to equal $r_p$.
Comment: Write down the equation *here*. That link looks pretty suspicious...Showing some self work won't hurt, too.
Comment: It's very elementary algebra ! Cancel $r_p$ and $m_p$...
Comment: I want to know how he cancelled out and rearranged the top equation to get rp to equal g mstar / Vp^2
Comment: Looks like a physics question involving planet surrounding stars on a circular orbit with radius $r_p$ at speed $v_p$?
Comment: Yes frenzy it is that, but I'm not looking at that aspect I'm just confused to how he got the equation to be like that.
Comment: Jean. I have gotten up to that step so far but I'm unsure of how he go the V little p ^2 on the bottom etc
Comment: @LiamB Multiply both sides of the first equation by $r_p^2$. Which side has $r_p$ left? Where is $v_p^2$, is it on the same side? If so, do you now know why the $v_p^2$ is now on the bottom in equation 2?
Comment: Thank you frenzy. I didn't really get what you said but then I was able to use a part of what you said to get it. What I did first was cancel the m_p then the r_p^2 so it would be G M_* / r_p = V_p^2 then I times both sides by r_p then dividing both sides by V_p^2
Comment: Thank you guys and sorry for bad formating.
Answer: The first expression seems to be:
$$\frac{Gm_pm_*}{r_p^2}=\frac{m_pv_p^2}{r_p}$$
Multiply both sides by $\;r_p^2\;$ and also divide both sides by $\;m_p\;$ and get
$$Gm_*=r_pv_p^2\;\;\implies\;\;r_p=\frac{Gm_*}{v_p^2}$$
Comment: Thanks but I don't know how you removed the ^2 from the r_p
Comment: When you multiplied *the right* side by $\;r_p^2\;$ you got $$\frac{r_p^2\cdot m_p\cdot v_p^2}{r_p}=r_pm_pv_p^2$$ because it is just like $\;\frac{a^2}a=a\;$ ...This seems to be some calculation with gravity, mass, radius and stuff. This looks like high school physics. It could help to know what is your mathematics level.

How was this changed to get $r_p$


How does pm2 knows what to load?

Question: I am still trying to understand pm2.
I have a autodeploy.sh file that contains this:
#! /bin/bash
cd /home/ubuntu/cab_01
sudo -H -u ubuntu bash -c 'git pull origin master'
sudo -H -u ubuntu bash -c '/usr/bin/npm install'
/usr/lib/node_modules/pm2/bin/pm2 startOrGracefulReload ecosystem.json --update-env

How does pm2 knows what environment to use in the ecosystem.json:
 "apps": [
    {
      "name": "cab01",
      "script": "./app.js",
      "env": {
        "environment": "production",
        "NODE_ENV": "production"
      },
      "env_uat":{
        "environment": "uat",
        "NODE_ENV": "uat"
      }
    }
]

Answer: By default, pm2 uses NODE_ENV in the env object.
To override this default behavior and use the NODE_ENV that is in the env_uat object, open your terminal and launch your app using the command below:
pm2 start ecosystem.config.js --env env_uat
To learn more about this, checkout this pm2 environment explanation: https://pm2.keymetrics.io/docs/usage/environment/

How does pm2 knows what to load?


How should I calculate $\lim_{n\to\infty}\left(\frac{2n-3}{3n+4}\right)^{n+1}$?

Question: I have been studying for my Analysis exam but I have problem that can't solve.
Original:
$$\lim_{n\to\infty}\left(\dfrac{2n-3}{3n+4}\right)^{n+1}$$
What I did trying to solve it making it looks like a sequence to e:
$$\lim_{n\to\infty}\left(\frac{3n+4}{3n+4}+\frac{-n-7}{3n+4}\right)^{n+1}$$
That made into:
$$\lim_{n\to\infty}\left(1+\frac{-n-7}{3n+4}\right)^{n+1}$$
I don't know what to do with -n to dissappear from the equation.
And this is what I should get in the end
$$\lim_{n\to\infty}\left(1+\frac{a}{n}\right)^{n} = e^a$$
I hope it is detailed enough.
Comment: It's a sequence converging to e and I have to calculate limn->infinite and that expression.
Comment: Welcome to MSE!  To learn how to type pretty math, please see [the MathJax Guide](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), which allows you to write interesting things.  $$\overbrace{\left(\ddot{\stackrel{\quad>}{\smile}}\right)}_{\begin{align}\hline\qquad\end{align}}$$Cheers!
Comment: What was the last step before you got stuck?
Comment: I don't know what to do with -n. All other steps are clear. This picture made after I made some changes.
Comment: BTW, in that link that you have provided (and please refrain from doing so next time, just add it directly to your question) - there's absolutely no sequence, and no problem to solve. Just an expression.
Comment: What do you mean "all other steps"? There are no steps listed there either!
Comment: It doesn't tend to $e$
Comment: There's no sequence there, only an expression. If you meant to ask about $\lim\limits_{n\to\infty}$ of that expression, then please be advised that it is not shown in that linked image. And again - none of the steps that you have made in order to solve it are listed there either.
Comment: This sequence goes to zero.
Comment: This question has been changed by OP. Orginally, it was about calculating $\lim_{n\to \infty} \biggr(\dfrac{-n-3}{3n+4}\biggr)^{n+1}$.
Answer: Observe:
$$\frac{n+3}{3n+4}=\frac13\,\frac{n+3}{n+\frac43}=\frac13\left(1+\frac{\frac53}{n+\frac43}\right)=\frac13+\frac5{9n+12}$$
and thus
$$1-\frac{n+3}{3n+4}=\frac23-\frac5{9n+12}=\frac23\left(1-\frac5{6n+8}\right)$$
Can you take it from here?
Comment: @Rinner This is a *hint* and because of that the "can you take it from here?" Complete it and you'll see the limit is zero...
Comment: It's also not the same, has no exponent.
Answer: You have
$$\lim_{n\to \infty} \frac{-n-3}{3n+4}=-\frac 13.$$
So
$$\lim_{n\to \infty}\left( 1+\frac{-n-3}{3n+4}\right)=\frac 23.$$
Now you know because
$$0<\frac 23<1$$
that
$$\lim_{n\to\infty }\left(\frac 23\right)^n=0.$$
So the limit you are looking for is $0$.
Comment: @Rinner You should really think a little more deeper before you write a comment. This answer, just as mine, requires from you thing, justify and complete.
Comment: That is not the case: It's not that simple: it is exponential.
Comment: Add parenthesis in second limit.
Comment: @Rinner I agree with DonAntonio.
Answer: [This question has been changed by OP. Orginally, it was about calculating $\lim_{n\to \infty} \biggr(\dfrac{-n-3}{3n+4}\biggr)^{n+1}$.]

Your attempt is in the wrong track. The strategy should be very different from considering
$$
\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n\tag{1}
$$
because they are two different types of problems. In your case
$$
\frac{2n-3}{3n+4}\to\frac{2}{3}<1\quad \textrm{as } n\to\infty,
$$
 but in (1),
$$
1+\frac{1}{n}\to 1 \quad \textrm{as } n\to\infty
$$
In the later case, you have the form $1^\infty$ while in your question, you don't.

Note that
$$
\left(\frac{2n-3}{3n+4}\right)^{n+1}=\exp\left((n+1)\cdot\log\biggr(\frac{2n-3}{3n+4}\biggr)\right).
$$
What can you say about
$$
\lim_{n\to\infty}(n+1)\log\biggr(\frac{2n-3}{3n+4}\biggr)?
$$
Note in particular that
$$
\lim_{n\to\infty}\log\biggr(\frac{2n-3}{3n+4}\biggr)=\log\biggr(\frac23\biggr)<0.
$$
Answer: I get the impression that you are not convinced of the fact that your limit is evidently 0, perhaps this alternative (longer) way can show you why.
$$
\lim_{n\to\infty}\left(\dfrac{2n-3}{3n+4}\right)^{n+1}=
$$
consider:
$$
\frac{2n-3}{3n+4}=\frac{2n-3-\alpha(3n+4)+\alpha(3n+4)}{3n+4}=\frac{2n-3-\alpha(3n+4)}{3n+4}+\alpha
$$
if $\alpha$ is chosen to be $\alpha\to\frac{2}{3}$ then by some elementary algebra:
$$
\frac{2n-3}{3n+4}=\frac{2}{3}-\frac{17}{9n+12}=\frac{2}{3}\left(1-\frac{17}{6n+8}\right)
$$
which means that your limit now is:
$$\lim_{n\to\infty}\left(\frac{2}{3}\right)^{n+1}\left(1-\frac{17}{6n+8}\right)^{n+1}$$
now by a simple substitution $n\to \frac{1}{6} (17 t-8)$ you get:
$$\lim_{n\to\infty}\left(\frac{2}{3}\right)^{n+1}*\lim_{t\to\infty}\left(1-\frac{1}{t}\right)^{\frac{1}{6} (17 t-2)}=e^{-17/6}\lim_{n\to\infty}\left(\frac{2}{3}\right)^{n+1}=0$$


MVC5 - EF6 - The  field is required

Question: I'm doing a method that inserts entities into DB via EF.
My problem is that i need to insert addresses to those entities and i can't get it to work.
Address Model:
public class Address
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AddressId { get; set; }

    [Required]
    [MaxLength(300)]
    public string AddressName { get; set; }

    [MaxLength(30)]
    public string PhoneAddress { get; set; }

    [MaxLength(30)]
    public string FaxAddress { get; set; }

    [MaxLength(50)]
    public string CountryCode { get; set; }

    [MaxLength(150)]
    public string Local { get; set; }

    [MaxLength(150)]
    public string PostalCode { get; set; }

    [ForeignKey("CountryCode")]
    public virtual Country Country { get; set; }
}

Address Connection Model:
public class AddressConnection
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public int AddressId { get; set; }

    [MaxLength(50)]
    public string SROCID { get; set; }

    [MaxLength(50)]
    public string ROCID { get; set; }

    public int? EntityID { get; set; }

    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

    [ForeignKey("SROCID")]
    public virtual SROC SROC { get; set; }

    [ForeignKey("ROCID")]
    public virtual ROC ROC { get; set; }

    [ForeignKey("EntityID")]
    public virtual Entity Entity { get; set; }
}

Program:
#region Address

string AddressName = _item.address1_line1Field;
string PostalCode = _item.address1_postalcodeField;
string CountryCode = _item.address1_countryField != null ? _item.address1_countryField : null;
string Local = _item.address1_cityField;
int ID = model.ID;
string Phone = _item.address1_telephone1Field;
string Fax = _item.address1_faxField;
bool added = true;

if (string.IsNullOrEmpty(AddressName) || string.IsNullOrEmpty(PostalCode) || string.IsNullOrEmpty(Local))
    added = false;

if (added)
{
    Address add = db.Address.FirstOrDefault(x => x.AddressName == AddressName && x.PostalCode == PostalCode && x.CountryCode == CountryCode && x.Local == Local);

    if (add == null)
    {
        add = new Address();

        add.AddressName = AddressName;
        add.CountryCode = CountryCode;
        add.Local = Local;
        add.PostalCode = PostalCode;
        add.PhoneAddress = Phone;
        add.FaxAddress = Fax;
        db.Entry<Address>(add).State = EntityState.Added;
    }
    else
    {
        add.PhoneAddress = Phone;
        add.FaxAddress = Fax;
        db.Entry<Address>(add).State = EntityState.Modified;
    }

    AddressConnection con = db.AddressConnection.FirstOrDefault(x => x.AddressId == add.AddressId &&
        x.EntityID == ID);

    if (con == null)
    {
        con = new AddressConnection();

        con.Address = add;
        con.EntityID = model.ID;

        db.Entry<AddressConnection>(con).State = EntityState.Added;
    }

    if (add != null)
    {
        AddressConnection con2 = db.AddressConnection.FirstOrDefault(x => x.EntityID == ID && x.AddressId != add.AddressId);
        if (con2 != null)
        {
            db.Entry<AddressConnection>(con2).State = EntityState.Deleted;
        }
    }
}

if (!added)
    LogExtensions.InsertQueueLog("SyncESR", "NO ADDRESS AT Item:" + ESRId, "NOADDRESS", Membership.CurrentUserId, EntryNo);

#endregion

db.SaveChanges();

The problem is that the AddressConnection (con) needs a foreign key id to Address (AddressId)
con.Address = add;

i already tried
con.AddressId = add.AddressId

but it doesn't seem to work...
It keeps giving me the "The AddressId field is required." because the Id is 0. It seems that EF foreign key isn't working.
Any thought?
Comment: You are missing a navigation property from `Address` to `AddressConnection`.
Comment: @DavidG Is it really needed? I only used the navigation properties in one project but then i saw that it keeps working without it... I will give it a try
Comment: @DavidG oh, and i have a similar method that is working, without navigation property
Comment: @DavidG ok, even with navigation property it doesn't work...
Answer: OK, somehow the EF didn't map the foreign key in the migration...
I removed the foreign key property from the AddressConnection Model and updated the database and then i added the foreign key to the model and updated, it started working.

MVC5 - EF6 - The  field is required


Shared module with angular d'ont work

Question: In fact I have 2 modules in my application apart from the main module:
- A module called Global.module: which contains sharable modules;
- And the other module called Pages.modules which contains my pages;
I want the modules in the global.module to be visible by pages.modules;
The problem I encountered that with the page module fails to retrieve the existing modules in Global.module see my source code; I also try exports: [NgaModule.forRoot ()] on modules to share but it seems that exports does not support ModuleWithProviders
Global.module
export const MODULES=[ BrowserModule,
  BrowserModule,
  FormsModule,
  HttpModule,
  NavbarModule,
  FooterModule,
  SidebarModule,
  RouterModule,
  LbdModule,ModalModule, BrowserAnimationsModule, ToastModule,NgbModule,
  FroalaEditorModule,
  FroalaViewModule,
  AceEditorModule,UiSwitchModule,TooltipModule,ChartsModule]
  export const SERVICES=[
    RouteGuard,BsModalService,LynkService,SharedService,Data,{provide: ToastOptions, useClass: CustomOption}, {
      provide: Http,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerUrlInterceptorService]
    } ,ServerUrlInterceptorService
  ]
@NgModule({
  exports: [
    ...MODULES
  ]

})
export class GlobalModule {
  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders> {
      ngModule: GlobalModule,
      providers: [
        ...SERVICES
      ],
    };
  }
}

Pages.module
@NgModule({
  imports: [CommonModule, routing,FormsModule,GlobalModule],
  declarations: [
    HomeComponent,
    DefaultComponent,
  ],
})
export class PagesModule {
}

App.module
@NgModule({
  imports: [
....
,GlobalModule.forRoot()],
  declarations: [
    ...
  ],
})
export class AppModule {
}

Comment: what specific error message do you see?
Answer: You can not export modules, which you didn't import before.
You will have to add
imports: [ ... MODULES ]
to your GlobalModule.
Comment: I added it but it tells me that some modules are not yet existing

Shared module with angular d'ont work


Contour integration with 2 simple poles on contour

Question: Ok for this one I would appreciate if someone could give me a conceptual answer first. I am supposed to integrate $\int_{-\infty}^{\infty} \frac{e^{-i q t}}{p^2 - q^2} dq$ along a half circle C (whose radius goes to infinity), which comprises a horizontal path along the real line circumventing the two real poles -p & +p with a semicircle in the upper half plane, just as in part (a)

I am to prove that the result is 0 if t<0 and $2 \pi i (-\frac{i}{p} ) \sin{pt}$ if t>0.
Now I don't quite understand why the sign of t would change anything. Can someone enlighten me?
Comment: You add to your initial contour of integration something which was not there (a semi circle). Now for this to make sense, one must prove that the corresponding semicircle integral goes to zero as the radius increases. That is usually done with [Jordan's lemma](http://en.wikipedia.org/wiki/Jordan%27s_lemma). The sign of $t$ will really matter for how one will apply it.
Answer: The sign of $t$ determines which contour you use. The idea is that the integral over the large circular arc shall tend to $0$ when the radius tends to $\infty$, and for that, the integrand must become small, in particular the exponential factor $e^{-iqt}$. We have $\lvert e^z\rvert = e^{\operatorname{Re} z}$, and $\operatorname{Re} (-iqt) = t\cdot \operatorname{Im} q$. For $t > 0$, that becomes negative, and hence the integrand small if $q$ is in the lower half plane, for $t < 0$, the integrand becomes small when $q$ is in the upper half plane.
The contour in the upper half plane does not enclose a pole, hence by the Cauchy integral theorem, the integral is $0$. The contour with the large semicircle in the lower half plane encloses the two poles, and by the residue theorem, it is then $-2\pi i$ times the sum of the residues in the poles ($-2\pi i$ because the contour is negatively oriented).


Are stereo speakers suitable substitutes for studio/rehearsal monitor? What amps/preapms are required?

Question: first time posting.
I have an old JVC player, model: MX-V508T. It has two unit, a CD/AMP/DECK TUNER UNIT and a Speaker unit. The CD/AMP/DECK TUNER UNIT is getting beyond repair. So, I want to dispose it and use the speakers for group practicing and starting a home studio for recording.
My intended inputs for practice/rehearsal include synthesizer keyboard, a bass, 1-2 guitars, acoustic and/or electric, and 1-3 vocals.
I intend to get a 8/10 channel analog mixer with USB interface which will be able to serve both practice and recording.
Question 1: Are the speakers suitable substitutes for studio/recording monitor and as full range practice monitors?
Question 2: if applicable, what type amp/preamp is required for connecting the speakers with the mixer output?
CD/AMP/DECK TUNER UNIT Amplifier section SPECIFICATIONS
CA-V508T
Output Power (IEC 268-3/DIN): 27 watts per channel, min. RMS, both channels driven, into 6 ohms at 1 kHz, with no more than 0.9% total harmonic distortion.
Input Sensitivity/Impedance (1 kHz): 300 mV/50 kohms
AUX: 300 mV/500 kohms
MIC 1: 3 mV/4.7 kohms
MIC 2: 3 mV/4.7 kohms
Speaker terminals: 6 - 16 ohms
Video out (composite): 1.0Vp-p (75 )
Speaker Specifications
SP-V608
Speaker: 3-way, 3-speaker bass-reflex type (Magnetically-shielded type)
Tweeter: 2 cm (13/16 inches) dome 1
Mid range: 5 cm (2 inches) cone 1
Woofer: 16 cm (6-5/16 inches) cone 1
Power Handling Capacity: 80 Watts
Impedance: 6 ohms
Frequency Range: 46 - 20,000 Hz
Sound Pressure Level: 87 dB/w • m
Power Specifications
Power Requirements: AC 110/127/220/230-240 V, adjustable with the voltage selector, 50/60 Hz
Power Consumption: 85 watts
Max. Power Comsumption: 12 watts (in standby mode), 185 watts (Taiwan only)
For Additional info for the player, manual.
Answer: You could replace the JVC with something similar and limp along.  But I think you'd blow up the speakers pretty soon if used as recording monitors.   And as a practice PA system - forget it!  Sorry.
Comment: Blow them up using the as recording monitors? How? The volumes used may well not even be as great as when listening to music. However, as a practice p.a., totally agree!
Answer: Depending on what kind of music you wish to play and how loud you wish to play it, it may work just fine but you'll need to test it out in you're own situation. I've had acoustic jams at the house that my little 3o watt stereo handled just fine, but I only used it for vocals. I seriously doubt it could have handled instrumentation and vocals. I was also careful not to push anything into distortion and I wasn't trying to blast out the neighbors. My set-up had a small mixer plugged into the auxiliary inputs on my stereo, simple as that!


Induction proof: sum of binomial coefficients

Question: Prove by mathematical induction for all natural numbers $n$:
$$\sum_{k=0}^{n}   \binom{n}{k}=2^n$$
thus is it sufficient to show that (but I think I made a mistake) thus how to do it properly?
$$2^n+\binom{n+1}{n+1}=2^{n+1}$$
Comment: The problem is that the first part of your sum does not add up to $2^n$.
Comment: how come? the first part is copied directly from the question
Comment: See the answer below
Comment: The assertion that $2^n + \binom{n + 1}{n + 1} = 2^{n + 1}$ is incorrect: $2^n + \binom{n + 1}{n + 1} = 2^n + 1$.
Answer: Not quite, because ${n+1\choose n+1}=1$. Combinatorically, is it easy to see that ${n+1\choose k}={n\choose k}+{n\choose k-1}$ (we either include the last element or we don't). From here on the proof is easy because (using the induction hypothesis):
$\sum_{k=0}^{n+1} {n+1\choose k}=\sum_{k=0}^{n+1} {n\choose k}+{n\choose k-1}=\sum_{k=0}^{n+1} {n\choose k}+\sum_{k=0}^{n+1} {n\choose k-1}=2^n+2^n=2^{n+1}$
Because ${n\choose -1}={n\choose n+1}=0$ (it's impossible to choose -1 or n+1 elements out of n).
Answer: Note that $$\sum_{k=0}^{n+1} \begin{pmatrix} n+1 \\ k\end{pmatrix} = \begin{pmatrix} n+1 \\ n+1\end{pmatrix} + \underbrace{\sum_{k=0}^n \begin{pmatrix} n+1 \\ k\end{pmatrix}}_{\neq 2^n}.$$
Alternatively, note that $\begin{pmatrix} n+1 \\ n+1\end{pmatrix} = 1$, and that $2^{n+1} \neq 2^n + 1$.
Comment: thus how to approach the inductional proof?
Answer: See the answer of Arkamis to find your mistake.
Under the convention that $\binom{n}{k}=0$ if $k\notin\left\{ 0,\dots,n\right\} $
we have:
$$\sum_{k\in\mathbb{Z}}\binom{n+1}{k}=\sum_{k\in\mathbb{Z}}\left[\binom{n}{k-1}+\binom{n}{k}\right]=\sum_{k\in\mathbb{Z}}\binom{n}{k-1}+\sum_{k\in\mathbb{Z}}\binom{n}{k}=2^{n}+2^{n}=2^{n+1}$$
Answer: Not quite because you are missing the $n+1$ in all the sum. Anyway $2^n+1\neq 2^{n+1}$. The key is to use $\binom{n+1}{k+1}=\binom{n}{k+1}+\binom{n}{k}$.


Normal subgroups index$[G:H]$ = prime number

Question: The question states: Let $G$ be a group and let $H$ be a normal subgroup of $G$. Assume that index$[G:H] = p$ is a prime number. Let $a \in G$, but $a \notin H$, and prove that $a^p \in H$ and $a^m \notin H$, for $m=1,2,\dots,p-1$.
What I have so far:
Let $k=$ord$(Ha)$, with $Ha \in G/H$. This implies $(Ha)^k=e$ and this implies $H(a^k)=e$. Now, if $m=kq$
$(Ha)^{kq}=e$ implies $(Ha)^m=e$.
If $(Ha)^m=e$, then $m$ is a multiple of ord$(Ha)$ and ord$(Ha)$ is a divisor of $m$, so $(Ha)^m =H(a^m)=e$
Let $|G|=p$ (prime). If $a \in G$ and $ a\neq e$, then ord$(a)=m(\neq 1)$ and $\langle a \rangle=(a_1 a_2 a_3 \dots a_{m-1})$, so $m$ must be a factor of $p$, but $p$ is prime, so $m=p$.
Am I even close to the correct answer?
Comment: For a basic tutorial on how to use Latex code to type Math on this page, see http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference. It would improve the readability of your question.
Comment: I edited this, did not alter anything of the sloppy way this is written down. E.g. your $e$ must be $H$ when you are making calculations in $G/H$. So user105108, please try to improve and learn some Latex on the side through my editing!
Answer: Hint: What can you say about cyclic subgroups of a group with $p$ elements (like $G/H$)?


CSS inadvertently affects brother div

Question: I have the following HTML and CSS files, where the class "table" div is affected by the css for its brother div of class "login", as the dashed border encloses both divs.
What could be the problem and the solution? Many thanks!!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <link rel="stylesheet" type="text/css" href="welcome.css">
  <title>Vokabeltrainer</title>

VokabelTester

   <form action="http://localhost:8080/vokabulary/Welcome" method="get">

Sprachen

Englisch<input type="checkbox" value="englisch" name="language" checked="checked"/>

Französisch<input type="checkbox" value="franzoesisch" name="language" checked="checked"/>

Italienisch<input type="checkbox" value="italienisch" name="language" checked="checked"/>

Spanisch<input type="checkbox" value="spanisch" name="language" checked="checked"/>

Portugiesisch<input type="checkbox" value="portugiesisch" name="language" checked="checked"/>

Anmeldung

     Name:<input type="text" name="name"/>

     Passwort:<input type="password" name="password"/>

     Login<input type="radio" name="login" value="login" checked="checked"/>

     Registration<input type="radio" name="login" value="registration"/>

     <input type="submit" value="LOS GEHT'S"/>

   </form>

CSS:
body{background-color: #6cc034; margin: 0; font-family: Calibri}
h1{margin: 0px;}
.left{display: block; margin: 0;height: 100%; width: 30%; float: left; background-color: green;}
.form{float: left; background-color: orange; width: 50%; border-style: dotted;}
.table{float:left; width:200px; display: block;}
th{font-size: 16pt; width: 150px; text-align: left; height: 60px;}
h2{font-size: 16pt; display: block; background-color: red;}
td{text-align: right; font-size: 14pt;}
.login{font-size: 14pt; display: block; background-color: blue; height: 200px; border-style: dashed;}

Comment: your second (login) table is hovering the first one.. remove the `float:left` from the `.table` style. you'll see that `.table` div is taking the right style. for some reason the 2nd table covers the 1st one
Comment: The border is still only around the `.login` div – the effect you are seeing is a result of `.table` being `float`ed … only inline content floats around a floated element, block elements are still laid out "behind" the floated element as if the latter wasn't even there.
Comment: yes, but i wanted the login div to be next to the table div
Answer: Remove the float:left from your .table declaration like so: http://jsbin.com/wanuyewewome/1/edit
Answer: I added float: left for the login div which fixed the problem.

CSS inadvertently affects brother div


How to get tfs build associated changeset and workitem?

Question: I want the value of tfs build associated changeset and work item for two reason -
1) Report/email confirmation through my custom proj file
2) Check out files which are related to changeset and work item
How can i do that? Any one can please give me a detail solution?
Comment: Please don't just ask us to solve the problem for you. Show us how _you_ tried to solve the problem yourself, then show us _exactly_ what the result was, and tell us why you feel it didn't work. See "[What Have You Tried?](http://whathaveyoutried.com/)" for an excellent article that you _really need to read_.
Comment: I just wants a detail instruction or related links thats how i do that not step by step instructions ... thanks
Comment: What does that have to do with my comment? Have you tried to accomplish this?
Comment: i get tfs build properties by the help of tfs GetBuildProperties Task .... but there is no idea about build associated changeset and work item. Then i found GenCheckinNotesUpdateWorkItems Task. But i didn't get build associated changeset and work item. I need those value to check out files which are related to changeset and work item. As i am new in this field , i haven't much knowledge about tfs.
Comment: Why are you using the tasks, in any case? What exactly are you trying to accomplish? Start from the beginning: Tell us what kind of user does what kind of thing, _and then you want the changesets and work items_. For instance, "An administrator goes to a web page, chooses the build from a dropdown, _and then you want the changesets and work items_.
Comment: i have a nant script for build which i called from a .proj file (this .proj file is used in "Items to build" in tfs build definition) so that the whole build process works from the nant file. In that case, i use getbuildproperties task to get build related propertise for build and i have done that with my necessary properties except changeset and workitem. So i stack on that stage and searching a way to do that.
Comment: In the future, please _tell us_ things like this. Your question made little sense if you were using the latest version of TFS.
Comment: yes, i am using tfs 2012
Comment: And, which build process did you start with? The update process? In other words, why are you using MSBUILD tasks at all, and not workflow activities?
Comment: I am using the default build process and as i wrote to you that i have to use nant script(which is called from .proj file in build definition) as build process for some reason, i use msbuild task to get the desired values in .proj file and pass to nant. Another reason to use msbuild task is that i found as a solution. As i am new to tfs, i haven't prpper knowledge about workflow activities.
Comment: So, I take it that you're not the person who created this build process?
Comment: Yes, right. It was a huge build script that was wrote many years ago that i modified to use for tfs. I follow this way because that was recommended.
Answer: If you have "create report" permission, it is easy.
Try it, If you have problem, I help you.
Answer: Get the msbuild community tasks and try this:
<code><MSBuild.Community.Tasks.Tfs.TfsVersion LocalPath="$(MSBuildProjectDirectory)">
  <Output TaskParameter="Changeset" PropertyName="Changeset" />
</MSBuild.Community.Tasks.Tfs.TfsVersion>
</code>


[SIP]How to verify that the other peer has answered the call

Question: I'm developping a SIP application and want to do some treatment when the other peer has answered an outgoing call.
A is calling B. If B answered the call make some treatment in A

I verified the documentation and i'm not finding a solution:
Link1
Link 2
Any idea please of how solve this problem ?
Thank you very much.
Answer: part of sample code SipDemo
A call B
call = manager.makeAudioCall(me.getUriString(), "b-username@domain", listener, 30);

When B answer
SipAudioCall.Listener listener = new SipAudioCall.Listener() {

    @Override
    public void onCallEstablished(SipAudioCall call) {
        Log.v("call","b answering");
        call.startAudio();
    }

Answer: Okay i've found it, but i have a question
public int getState ()

Since: API Level 9
Gets the session state. The value returned must be one of the states in SipSession.State.
Returns

the session state

How to put the constant INCOMING_CALL_ANSWERINGin the gesState() ?
if (call.getState(INCOMING_CALL_ANSWERING))

??
It's not working.
EDIT: okay , i ahve to do like this:
if (call.getState()== 4)


Creating Inherited classes in Packages

Question: I am working on an existing project. There is a package of a dozen classes which I need to refactor into base classes and two sets of derived classes.
I tried creating a new package of derived classes, but I get errors when attempting to inherit from a different package.
I don't want to put all the classes in the root of a package, but can't create sub-packages.
How do I arrange this in Netbeans?
It is easy in Visual Studio :-)
Comment: Right click on an existing package and choose "New -> Package".
Comment: I did that, but new package was alongside existing one, not under/within it....
Answer: It's so easy in NetBeans too. For example, assuming you have one package and there is a class in it (MyClass1.java):
package overstack;
...

public class MyClass1 {

}

When you create a new file in the current package, for example, MyClassInherited1.java,  you will have:
    package overstack;
    ...
public class MyClassInherited1 {

}

No, when you want to move it in other package, you can change the name of package, like here:
package overstack.inh;
...

public class MyClassInherited1 {

}

you will get a mistake in the code line:     package overstack.inh;
Now, clicking the left button of mouse beside this line you will get a proposition to "move class to accessible place". When you click, you will have two packages. NetBeans will execute it automatically. For example, you can look for in the folder:
overstack
   MyClass1.java
overstack.inh
   MyClassInherited1.java

Comment: From this reason you find here more: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
and
https://www.tutorialspoint.com/java/java_inheritance.htm
Comment: Vasyl, this creates two packages ok, but they are alongside each other. I want one below the other (so that inherited classes are under the base classes, as described in the OP).

Creating Inherited classes in Packages


How to limit disk performance?

Question: I am load-testing a web application and studying the impact of some config tweaks (related to disk i/o) on the overall app performance, i.e. the amount of users that can be handled simultaneously.
But the problem is that I hit 100% CPU before I can see any effect of the disk-related config settings. I am therefore wondering if there is a way I could deliberately limit the disk performance so that it becomes the bottleneck and the tweaks I am trying to play with actually start impacting performance. Should I just make the hard disk busy with something else? What would serve the best for this purpose?
More details (probably irrelevant, but anyway): PHP/Magento/Apache, studying the impact of apc.stat. Setting it to 0 makes APC not checking PHP scripts for modification which should increase performance where disk is the bottleneck. Using JMeter for benchmarking.
Answer: Virtualization. I don't know about VMWare, but Hyper-V now - 2012 R2 - allows one to set IOPS Limits for a virtual machine. Handy to put in some really low number.
Answer: You can try ionice -c3 yourjob .
This will limit the io to when the system is idle.
See also AskUbuntu link.

How to limit disk performance?


Can the finite series $\sum_{k=1}^K \bigg(\frac{(m+k)!}{k!}\bigg)^2\bigg(\frac{1}{5}\bigg)^{2k}$ be approximated or bounded?

Question: In my previous question I asked about methods of evaluating the following infinite series:
$$
\sum_{k=1}^\infty \frac{(m+k)!}{k!}\frac{1}{5^k}.
$$
I now have a somewhat related question. This time I am interested in the following finite series:
$$
\sum_{k=1}^K \bigg(\frac{(m+k)!}{k!}\bigg)^2\bigg(\frac{1}{5}\bigg)^{2k}.
$$
I am interested in methods of finding a good approximation or tight bound for this series?  Note that $m$ is an integer and $m > K \gg 1$, but I don't know if this is any use. So is is possible to get an accurate approximation/bound for this series?
Comment: @metamorphy Ok, I see if I multiply my series by $1/(m!)^2$ I get the infinite series on the left hand side of your expression. But I don't see how that helps me as (i) I am dealing with a finite series and (ii) the series on the right hand side of your expression looks just as hard to approximate/bound as my original series.
Comment: You can use my method to do the same thing by letting $$ f(x,y)=\sum_{k=1}^\infty \left(\frac{(m+k)!}{k!}\right)^2x^ky^k.$$
Comment: @metamorphy To be more specific, $m > K \gg 1$. I would like to have a function (that doesn't feature a series) that accurately approximates the series, i.e. a function $f(m,K)$ such that $f(m,K) \approx \sum_{k=1}^\infty \frac{(m+k)!}{k!}\frac{1}{5^k}$. But if an approximation isn't possible an upper bound would be a good alternative.
Comment: @xpaul But this question is about a finite series. You have specified a method for an infinite series, unless I'm missing something?
Comment: Oh, that's a completely different story.
Answer: Let
$$ f(x,y)=\sum_{k=1}^K \left(\frac{(m+k)!}{k!}\right)^2x^ky^k.$$
Then integrating $M$ times w.r.t $x$ and $y$, respectively gives
\begin{eqnarray}
F(x,y)&:=&\int\cdots\int\int\cdots\int f(x,y)dx\cdots dxdy\cdots dy\\
&=&\sum_{k=1}^K (xy)^{m+k}+\sum_{j,k=0}^mC_jD_kx^jy^k\\
&=&\frac{(xy)^{m+1}(1-(xy)^K)}{1-xy}+\sum_{j,k=0}^{m-1}C_jD_kx^jy^k\\
&=&\frac{1}{1-xy}\bigg[\sum_{k=0}^{m+1}\binom{m+1}{k}(xy-1)^{k}-\sum_{k=0}^{m+K+1}\binom{K}{k}(xy-1)^{k}\bigg]+\sum_{j,k=0}^{m-1}C_jD_kx^jy^k\\
&=&-\bigg[\sum_{k=1}^{m+1}\binom{m+1}{k}(xy-1)^{k-1}-\sum_{k=1}^{m+K+1}\binom{K}{k}(xy-1)^{k-1}\bigg]+\sum_{j,k=0}^{m-1}C_jD_kx^jy^k\\
&=&-\bigg[(xy)^m-\sum_{k=m+1}^{m+K+1}\binom{K}{k}(xy-1)^{k-1}\bigg]+P(x,y)
\end{eqnarray}
where $P(x,y)$ is a polynomial of $x$ and $y$ of degree $m-1$. Repeating the method in Methods of evaluating $ \sum_{k=1}^\infty \frac{(m+k)!}{k!}\frac{1}{5^k}$? I used, you can do the rest.
Comment: I don't see how this will lead to the result as [Wolfram Alpha](https://www.wolframalpha.com/input/?i=sum+%28%28m%2Bk%29%21%2Fk%21%29%5E2+*+%281%2F5%29%5E%282k%29%2C+k+%3D1..K) says the result features the hypergeometric functions ${}_{2}F_1$ and ${}_{3}F_2$ so this is a much more complicated evaluation than my previous question.
Comment: Your series is finite and hence you can't use the hypergeometric functions 2F1 and 3F2 s.
Comment: Wolfram Alpha gives the result in terms of these functions. Actually 2F1 arises for the infinite series, and then for the truncated series (if we ignore multiplying factors) WA gives 2F1 minus 3F2. So it seems the 3F2 term represents the truncated part of the infinite sum, i.e. $\sum_{k=K+1}^\infty$.
Comment: In any case, this 2F1 - 3F2 representation from WA is not useful as the 3F2 is way too complicated, I don't we can get an asymptotic approximation for it (we can for the 2F1).
Comment: See the update.
Comment: Ok thanks, I am attempting it now, it would be pretty amazing if this series could be evaluated into closed form. There seems to be a slight error in your answer in the 'methods of evaluating...' question, I'm not sure what it is yet but differentiating the expression $m$ times does not lead to the correct answer, although it is relatively similar to it.


Using HSQL for .NET development and related questions of process

Question: My team uses a shared instance of Oracle for development using C#, NHibernate and ASP.NET, and we occasionally step on each others toes when making data or schema changes holding up everyone.
On another project I'm using Java and  HSQL in 100% in-memory mode and just have Hibernate launch a script to import enough data to test with. It also creates and drops the schema. I considered using the same approach in .NET-land. With everything temporary and independent it would be impossible to step on each others toes, and we could still integrate our schema and data on the shared Oracle box.
I looked for HSQL on .NET and SharpHSQL seems to be a dead project (last release 2005).
Is there an active project equivalent to HSQL for .NET, or anything close enough to be used this way?
How have you got on using this approach in a team environment? Any issues?
How do you manage and version control data for populating the database? Is there a cross-platform solution for importing data?
Answer: With something like Sqlite, you could take the same approach in your .NET applications as with your Java applications - creating the schema and populating test data via NHibernate schema export / NHibernate population code is a good way to manage this scenario (NHibernate works fine with Sqlite). If you chose to, you could potentially standardise on Sqlite with your Java applications too.
Comment: +1 I use Sqlite for testing and development at my job from Java and have used it from an ASP.NET environment as well. Works great.
Answer: See the HSQLDB.org web site. There is now a .NET implementation.
Edit: The implementation is for HSQLDB 1.8.0.x and is in the SVN repository. Needs to be compiled for use.
Comment: I couldn't find the .net implementation on the web site. Could any one point me in the direction please?
Answer: Take a look at Effort

It is basically an ADO.NET provider that executes all the data
  operations on a lightweight in-process main memory database instead of
  a traditional external database.

I used it in my latest project and really like it. Easy to set up.