Nginx can't serve more than 40 concurrent users

Question: I'm testing my Nginx web server (configured with CentminMod) with https://www.blitz.io/ and the server returns timeouts when the connected users are about 40.
I can't understand why! It's Nginx, not Apache! Can anyone help me?
This i my nginx.conf:
user nginx nginx;
worker_processes 1;
worker_priority -10;

worker_rlimit_nofile 260000;
timer_resolution 100ms;

error_log         logs/error.log;

pid               logs/nginx.pid;
pcre_jit on;

events {
    worker_connections  2048;
    accept_mutex on;
    accept_mutex_delay 100ms;
    use epoll;
    #multi_accept on;
}

http {
    include /usr/local/nginx/conf/pagespeedadmin.conf;
    include /usr/local/nginx/conf/fastcgi_param_https_map.conf;

    log_format      main    '$remote_addr - $remote_user [$time_local] $request '
    '"$status" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for" "$gzip_ratio"'
    ' "$connection" "$connection_requests" "$request_time"';

    access_log logs/access.log combined buffer=32k;

    index  index.php index.html index.htm;
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;

    sendfile on;
    #sendfile_max_chunk 1m;
    tcp_nopush  on;
    tcp_nodelay off;
    server_tokens off;
    server_name_in_redirect off;

    keepalive_timeout  10;
    keepalive_requests 100;
    lingering_time 20s;
    lingering_timeout 5s;
    keepalive_disable msie6;

    gzip on;
    gzip_vary   on;
    gzip_disable "MSIE [1-6]\.";
    gzip_static on;
    gzip_min_length   1400;
    gzip_buffers      32 8k;
    gzip_http_version 1.0;
    gzip_comp_level 5;
    gzip_proxied    any;
    gzip_types text/plain text/css text/xml application/javascript application/x-javascript application/xml application/xml+rss application/ecmascript application/json image/svg+xml;

    client_body_buffer_size 256k;
    client_body_in_file_only off;
    client_body_timeout 60s;
    client_header_buffer_size 64k;
    ## how long a connection has to complete sending
    ## it's headers for request to be processed
    client_header_timeout  20s;
    client_max_body_size 10m;
    connection_pool_size  512;
    directio  4m;
    ignore_invalid_headers on;
    large_client_header_buffers 8 64k;
    output_buffers   8 256k;
    postpone_output  1460;
    proxy_temp_path  /tmp/nginx_proxy/;
    request_pool_size  32k;
    reset_timedout_connection on;
    send_timeout     60s;
    types_hash_max_size 2048;
    server_names_hash_bucket_size 64;

    # for nginx proxy backends to prevent redirects to backend port
    # port_in_redirect off;

    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 120s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;
    open_log_file_cache max=4096 inactive=30s min_uses=2;

    ## limit number of concurrency connections per ip to 16
    ## add to your server {} section the next line
    ## limit_conn limit_per_ip 16;
    ## uncomment below line allows 500K sessions
    # limit_conn_log_level error;
    #######################################
    # use limit_zone for Nginx <v1.1.7 and lower
    # limit_zone $binary_remote_addr zone=limit_per_ip:16m;
    #######################################
    # use limit_conn_zone for Nginx >v1.1.8 and higher
    # limit_conn_zone $binary_remote_addr zone=limit_per_ip:16m;
    #######################################

    include /usr/local/nginx/conf/conf.d/*.conf;
}

And this is my server block:
server {
    listen 8080;
    server_name beta.architetturaecosostenibile.it www.beta.architetturaecosostenibile.it;

    #pagespeed off;

    # ngx_pagespeed & ngx_pagespeed handler
    #include /usr/local/nginx/conf/pagespeed.conf;
    #include /usr/local/nginx/conf/pagespeedhandler.conf;
    #include /usr/local/nginx/conf/pagespeedstatslog.conf;

    # limit_conn limit_per_ip 16;
    # ssi  on;

    access_log /home/nginx/domains/beta.architetturaecosostenibile.it/log/access.log combined buffer=32k;
    error_log /home/nginx/domains/beta.architetturaecosostenibile.it/log/error.log debug;
    rewrite_log on;

    root /home/nginx/domains/beta.architetturaecosostenibile.it/public;

    # PageSpeed enhancements
    pagespeed EnableFilters remove_comments,collapse_whitespace;

    include /usr/local/nginx/conf/staticfiles.conf;
    include /usr/local/nginx/conf/php.conf;
    include /usr/local/nginx/conf/drop.conf;
    #include /usr/local/nginx/conf/errorpage.conf;
    }

Comment: You still didn't include **full** nginx config. Where is server blocks?
Comment: Added also the server block (nothing in particular)
Comment: Still not full. But I guess it's your PHP limit
Comment: How did you measure the limit of 40 concurrent users?
Comment: With the service http://blitz.io.
@AlexeyTen the max_execution_time is set to 60 seconds. What do you need for the full configuration?
Comment: Time is not relevant. See http://php.net/manual/en/install.fpm.configuration.php#pm.max-chidlren and it's friends.
Answer: nginx is merely a messenger vehicle and is unable to help your system to scale if the backend application itself is heavy. 40 concurrent users would be peanuts to any web server, after all.
Are you sure that the limit is not in your database / application level? I'm 100% sure the limit is there. Go find it.
Comment: I can share the php info report? Mysql timeout is set on 60 seconds, PHP execution time set to 60... And I configured Varnish in front on Nginx, but timeouts reimains. Only 4 requests per second
Comment: Just as an example: if processing the request takes two seconds and the requests come in at 100 requests per second, you will hit some limit, somewhere very soon. Varnish might or might not help you, depending on how dynamic your site is. phpinfo() itself does not help us very much. Does your site run some heavy stuff such as WordPress, Drupal, Magento...? Do you use PHP frameworks such as CakePHP?
Comment: I run Joomla with Memcached. The homepage opening requires 400ms


Windows 7 Requires ARP for UDP?

Question: Seems like my Windows 7 box (with 2 NICs if that's relevant) requires an ARP response before it sends packets to a certain IP address. The specific context I'm in is running a TFTP server (TFTPD32). The server hears the request, sends out an ARP request, but never sends a response to the TFTP client, presumably because the client doesn't respond to ARP (I can't change that unfortunately). Is there a work around to this miserable situation? This "just worked" on previous versions of Windows.
Comment: Windows 7 doesn't accept the source mac/IP in the clients initial TFTP packet and add that to its ARP table?  Do you have some sort of static route pointing the client IP out the other interface on your Windows 7 machine?
Comment: @cpt_fink that's right, Windows 7 doesn't register a new ARP entry (or update an existing one) on the initial RRQ (as insane as that sounds)
Answer: I don't see how it could have ever worked if the client doesn't respond to ARP.  You can't send packets to the IP address without knowing the MAC address, and that's where ARP comes in.  If the client doesn't respond to ARP then it's broken.
Comment: if all you ever do is *respond* to messages, you can get the destination MAC from the incoming packet...
Comment: Software programs should follow standards, not implement their own methods for performing various tasks. ARP MUST be used to resolve IP addresses to MAC addresses. Retrieving the MAC address from an incoming IP packet may work in certain situations, but will not work when the response needs to be sent via a different gateway, for example. *IF* the client really does NOT respond to ARPs, then it is in fact broken. But I would be very surprised if this was truly the case. It may be worth investigating the possibility of the ARP response getting dropped somewhere, possibly by your Windows 7 box.
Answer: You can add a static entry to your ARP table:
Example:
<code>:: Add a static entry.
arp -s 22.214.171.124 00-aa-00-62-c6-09

:: Displays the arp table.
arp -a
</code>
Comment: unfortunately, I can't presume the MAC address at a given IP address is always the same... that is to say, the computer I plug into a given port always gets the same IP address (statically assigned), but I plug in different computers (with different MAC addresses) into that port
Comment: @vicatcu what type of clients are these?
Comment: embedded systems, not under my control, probably not running an operating system, just acting as TFTP clients downloading a file at startup from a pre-configured TFTP server IP address
Comment: @vicatcu Is this tftp server application being run with elevated privliges? It would need to in order to alter the arp table.
Comment: @MDMoore313, it's not the TFTP server that would be altering, or even being aware that there is an ARP table.  He's saying the IP layer should update the ARP table when it receives the packet.
Comment: @psusi that's true, my mistake I'm thinking about the routing table.

Windows 7 Requires ARP for UDP?


Problem book,typing error?

Question: I have the following problem :
Let $f:(0,\infty)\rightarrow \mathbb R$ be an arbitrary function satisfying the hypothesis, $\lim_{x \rightarrow 0} x(f(x)-1)=0$. Show that $\lim_{x \rightarrow 0 } f(x)$ exists.
The problem has also other parts and 2 other hypothses on $f$. But  the solution starts like this: by hypothesis one it follows $\lim_{x \rightarrow 0} xf(x)=1$... So it doesn't use the other two hypothesis ( why would he explicitly state that the result follows from hyp. one if the others are also used?).
But than $ \ \sin(\frac{1}{x}):=f(x) \ $ would be a conter example.
Can somone say if my counterexample is right?I can't see the error. And I'm pretty sure he doesn't use the other hypotheses since he doesn't state them in the problem.
here are the other two conditions on $f$ (wich i didn't use in the counterexample by the reasons explained above)
two : $f(1)=2$
three: $(x+2)f(x+2)-2(x+1)f(x+1)+xf(x)=0$
Comment: your counter example is right
Comment: Your counterexample is correct. (Beaten!)
Comment: thanks for the confirmations!
Comment: You're welcome! Thanks for the accept. :)
Answer: Your counterexample is correct. (Converting to an answer.)

Problem book,typing error?


How to interpret "rank" of a matrix intuitively?

Question: What is the physical interpretation of "rank" of a matrix ? Why is it called "rank" ?
Answer: The rank is the dimension of the image of the matrix. A 3x3 matrix with rank 2 sends all vectors in 3-dimensional space into a 2-dimensional subset of 3-dimensional space.
See also this answer https://math.stackexchange.com/a/39902/64062
Answer: Regarding the importance of the "rank" of a matrix, and help to understand what this is, intuitively, you'll find some wonderful answers here, to a previous post at math.se:

Importance of rank of a matrix

A wonderful website for origins of mathematical terms is found here:

Earliest known uses of some of the words in mathematics.

Click on "[R]"...scroll down to:
"Rank (of a matrix or determinant)":

RANK (of a determinant or matrix) was coined by F. G. Frobenius, who used the German word Rang in his paper "Uber homogene totale Differentialgleichungen," J. reine angew. Math. Vol. 86 (1879) p.1. This is according to C. C. MacDuffee, The Theory of Matrices, Springer (1933). Frobenius was defining the rank of a determinant but the term travelled.
In English, rank (of a matrix) is found in the monograph "Quadratic forms and their classification by means of invariant factors", by T. J. Bromwich, Cambridge UP, 1906. This citation was provided by Rod Gow, who writes that it is possible that an earlier book c. 1900 by G. B. Mathews, a revision of R. F. Scott's 1880 book on determinants, contains the word.
Rank is also found in 1907 in Introduction to Higher Algebra by Maxime Bôcher: where it is defined in the same way as in Frobenius:
Definition 3. A matrix is said to be of rank r if it contains at least one r-rowed determinant which is not zero, while all determinants of order higher than r which the matrix may contain are zero. A matrix is said to be of rank 0 if all its elements are 0. ... For brevity, we shall speak also of the rank of a determinant, meaning thereby the rank of the matrix of the determinant.
Comment: This is a nice explanation. :-)
Comment: @amWhy: I totally agree with Babak! +1


Como posicionar o formulário no centro de uma DIV?

Question:

body{
 background: #EFEFEF;
 font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, "sans-serif;
}
.create-box{
 background: #DF5B5D;
 border: 10px dashed #FEFEFE;
 max-width: 550px;
 min-height: 88px;
 text-align: center;
 margin: auto;
}
.create-box form{
 width: 100%;
 text-align: center;
 margin: 0 auto;
}
.create-box form input{
 display: block;
 margin: 5px 10px;
 vertical-align: middle;
 text-align: center;
 font-size: 22px;
 font-weight: bold;
 color: #43A8C7;
}
<!DOCTYPE html>

  <title>Trash [coder]</title>
  <meta charset="utf-8" />

   <form>
    <input type="text" id="titulo" placeholder="Digite o título" />
    <input type="text" id="conteudo" placeholder="Digite o conteúdo" />
    <input type="submit" value="Criar Boxer's" />
   </form>

Porque não consigo centralizar o formulário na DIV? oque está errado? solução?
Comment: Porque ele ocupa toda a largura da div.
Comment: Se eu removo ou altero a largura do .crate-box, ela também não posiciona..
Answer: Pelo que entendi da sua pergunta o seu problema é com essa margem
.create-box form input { margin: 5px 10px;}

Ela deveria ser assim:
.create-box form input { margin: 5px auto;}

Veja no Snippet como ficou com a alteração

body{
 background: #EFEFEF;
 font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, "sans-serif;
}
.create-box{
 background: #DF5B5D;
 border: 10px dashed #FEFEFE;
 max-width: 550px;
 min-height: 88px;
 text-align: center;
 margin: auto;
}
.create-box form{
 width: 100%;
 text-align: center;
 margin: 0 auto;
}
.create-box form input{
 display: block;
 margin: 5px auto;
 vertical-align: middle;
 text-align: center;
 font-size: 22px;
 font-weight: bold;
 color: #43A8C7;
}

    <form>
        <input type="text" id="titulo" placeholder="Digite o título" />
        <input type="text" id="conteudo" placeholder="Digite o conteúdo" />
        <input type="submit" value="Criar Boxer's" />
    </form>

Comment: vaLew - Ajudou Muito


Meta-analysis in R without control group? Purely improvement of symptoms

Question: I'm currently trying to perform a meta-analysis in R via the metafor package using data that does not have a control group. In this case, I am looking to see whether or not a type of surgical intervention improves symptoms in these unique type of patients. Essentially, the only data I have from these studies is whether symptoms of their certain pain has improved.
Would this be a meta-analysis of proportions? Or would I do a standard REML in metafor: For example, one paper gives the data that 20/25 patients had symptoms that improved. Thus, would I have 4 data points, "creating" my own control group?:

Surgery_improvement: 20 patients
Surgery_no_improvement: 5 patients
No_surgery_improvement: 0 patients (obviously, as this doesn't even exist)
No_surgery_no_improvement: 25 patients

And then perform a standard meta-analysis?
Answer: You suggestion that this is a meta-analysis of proportions is correct. If each study gives you the number treated and the number of those who improved then you an analyse those. You second suggestion is flawed because the last group (4) should read no surgery no improvement 0 as that is all you know.
You will probably want to choose one of the options for transforming proportions before doing the meta-analysis especially if they are close to zero or one.
Note that you meta-analysis will be open to the criticism that this is just observational but if that is what the studies available to you have then that would be an unfair criticism.


Get array of items from phpAdmin Wordpress

Question: In my phpAdmin I have a list of arrays that I need to be able to access in php Wordpress.
I need to get these two arrays and the variables associated with them but I can't find anywhere how to access this type of information.
Essentially I would like to loop through all these items and match one of their variables with the ID of specific posts - I have the post part.
wp_learnpress_sections
wp_learnpress_section_items

Basically the item_type is an lp_lesson which is a custom post type. I am able to grab all the posts from wp_posts so I figured I would be able to grab these other arrays?
Edit:

My theme function. This works for all the posts. However, I want to be able to find out which section_id a post belongs to.
add_action( 'wp_enqueue_scripts', 'win_9388244_format_lp_lesson' );

function win_9388244_format_lp_lesson() {
  //Get post type of lp_lesson
        $args = array(
         'post_type' => 'lp_lesson',
         'numberposts' => 99999
        );
        $posts = get_posts($args);
  foreach($posts as $post) {
    update_post_meta( $post->ID, 'wpk_icon_text', 'Test' );
  }
}

Comment: PhpMyAdmin is for administering your DB - not PHP arrays or any of that sort.
Comment: show all info, which may help. how do you saved that arrays in the db? what is the structure of table, where you serve arrays? where you defined the `the variables associated with them`? where do you want access( from which file ) to that arrays?
Comment: My apologies. I added more information on what I am trying to accomplish (if it's possible).
Answer: Full function that does it:
function win_9388244_format_lp_lesson() {
  //Get post type of lp_lesson
  $args = array(
    'post_type' => 'lp_lesson',
    'numberposts' => 99999
  );
  $posts = get_posts($args);
  global $wpdb;
  $sections = $wpdb->get_results( "SELECT section_item_id, section_id, item_id FROM wp_learnpress_section_items", ARRAY_A );
  $items = $wpdb->get_results( "SELECT section_course_id, section_id FROM wp_learnpress_sections", ARRAY_A );
  foreach($posts as $post) {
    $lesson_id = $post->ID;
    foreach($sections as $section) {
      if($section['item_id'] == $lesson_id) {
        $currentSection = $section['section_id'];
        foreach($items as $item) {
          if ($item['section_id'] == $currentSection) {
            $course = $item['section_course_id'];
            //switch $course with predefined variables for courses
          }
        }
      }
    }
  }
}


Show $ 1 + a + a^2 + a^3 + \ldots + a^n = \frac{a^{n+1}-1}{a-1}$ by induction

Question: How can we show by mathematical induction that the following holds for $ n \ge 0$ and $a \ne 1$?
$$ 1 + a + a^2 + a^3 + \ldots + a^n = \frac{a^{n+1}-1}{a-1}$$
I understand the principle of mathematical induction, but I've no idea how to apply it here.
I know in general I have to prove it for $n = 1$ and then assume $n = k$ is correct. Then prove $n = k+1$ is true.
But what about $a$?
I've watched a load of YouTube videos on the subject, and I've read a few questions here but it's not helping. The videos make sense while I'm watching them, but I don't know how to apply it.
This question appeared on my discrete math exam last week. I did not do well. I think I'm missing something fundamental in my understanding of this subject.
Answer: If $n=0$, we must prove $1=\frac{a-1}{a-1}$ which is trivial.
Assume that it holds for $n=k$, that is: $$1+a+...+a^k=\frac{a^{k+1}-1}{a-1}$$ We must prove that it holds for $n=k+1$ or in other words that
$$1+a+...+a^k+a^{k+1}=\frac{a^{k+2}-1}{a-1}$$
But this is simple to prove with our assumption: $$1+a+...+a^k+a^{k+1}=\frac{a^{k+1}-1}{a-1}+a^{k+1}=\frac{a^{k+1}-1+a^{k+2}-a^{k+1}}{a-1}=\frac{a^{k+2}-1}{a-1}$$
Comment: Note that he is supposed to start at $n=0$ (which is even easier to start with), not at $n=1$.
Comment: Thank you, I will study this and come back to you.
Comment: Hi Nameless, thank you for your help.
Answer: Let $P(n)$ be the statement that $1+a+...+a^n=\frac{a^{n+1}-1}{a-1}$. Since $1=\frac{a-1}{a-1}$, $P(0)$ is true.
Suppose $P(k)$ is true for some non-negative integer $k$. Then $1+a+...+a^k=\frac{a^{k+1}-1}{a-1}$, so that $1+a+...+a^{k+1}=\frac{a^{k+1}-1}{a-1}+a^{k+1}=\frac{a^{k+1}-1}{a-1}+\frac{a^{k+2}-a^{k+1}}{a-1}=\frac{a^{k+2}-1}{a-1}$, so that $P(k+1)$ is true.
Hence we have $P(n)$ for all non-negative integers $n$.
Note that in this example, you are asked to start at $n=0$ and not $n=1$ and thus prove the statement for all non-negative integers and not just positive integers. Also note that here $a\neq 1$ is fixed and we are doing induction on $n$ and not on $a$.
Comment: Hi Jasper, did you lose a $-1$ term in the final numerator?
Comment: Hi Jesper, thank you for your help.


Multiplying independent conditional probabilities

Question: If we know A and B are independent such that $P(A,B) = P(A)P(B)$, does $P(A|C)P(B|C)=P(A,B|C)$?
Intuitively, it seems like this should be true, but I don't know how to prove this formally.
Answer: Nope. Consider a chessboard and pick a square at random. Let A be "on an even-numbered row" and B be "on an even numbered column" and C be "the square is white".
A and B are independent, but $P(A|C)=P(B|C)=0.5$ and $P(A,B|C)=0$
Comment: Nice example (+1). Indeed, independence does not imply conditional independence.


Non-trivial bound for $E[\exp(Z^2)]$ when $Z \sim {\rm Bin}(n, n^{-\beta})$ with $\beta \in (0,1)$

Question: How to find a non-trivial upper bound on $E[\exp(Z^2)]$ when $Z \sim {\rm Bin}(n, n^{-\beta})$ with $\beta \in (0,1)$? A trivial bound is obtained for substituting $Z$ with $n$.
A background on this question. In the paper by Baraud, 2002 -- Non-asymptotic minimax rates of testing in signal detection, if one is to substitute the model in Eq. (1), by a random effects model, then the above quantity appears in the computation of a lower bound.
Comment: This question is for Mathoverflow: http://mathoverflow.net/. Seems to be a good question anyway. I remember I saw a generalization of the results in Baraud's paper done by Rozenholc an other collaborators but I can't find the paper anymore...
Comment: Do you want a lower or a upper bound? The first sentence says upper but the last sentence mentions lower.
Comment: @Srikant: you should read the mentionned paper by Barraud which is great to understand the whole thing... heuristically lower bounds are larger (testing is more difficult) when distributions (from the null and alternative) are close. Hence the upper bound asked by mkolar is related to the chi square distance between two distributions (the least favorable in the alternative and the null) if this distance is small the minimum error will be large...
Comment: @srikant an upper bound is needed here. The last sentence just states that an upper bound on the desired quantity will be used for proving the minimum error in the testing problem, as @robin explained.
Comment: Link to the paper http://math.unice.fr/~baraud/publications/min-rev1.pdf
Comment: Can you give us the hypothesis you want to test ?
Answer: (I will delete my other non-answer, the edit of which had this nugget in it)
No. Asymptotically, the 'trivial' upper bound is the least upper bound. To see this, Let $P_n = P(Z = n)$. Trivially, $E[\exp{(Z^2)}] \ge P_n \exp{(n^2)} = L$, where $L$ is the lower bound of interest. Since $Z$ is binomial, we have $P_n = {n\choose n} (n^{-\beta})^n (1-n^{-\beta})^0 = n^{-n\beta}$. Then $\log{L} = -\beta n \log{n} + n^2$. It is easily shown that this is $\Omega{(n^2)}$, and thus, $L$ is $\Omega{(\exp{(n^2)})}$. Thus the trivial upper bound is, asymptotically, the least upper bound, i.e. $E[\exp{(Z^2)}] \in \Theta{(\exp{(n^2)})}$.
Comment: @shabbychef - given that the reference provided speaks of *non-asymtotic* minimax rates... then no asymptotics should be done.  But you essentially have the answer anyway, just $L=n^{-n\beta}exp(n^{2})$.  So (+1) from me
Comment: You're correct for the case beta = 0, but not for positive values of beta: you lost everything by throwing away the -beta*n*log(n) term.
Comment: uhh, no, not really. I assumed the OP was interested in an asymptotic (in $n$) bound. the worst case for my lower bound is $\beta = 1$. Then for, say, $n > 35$, we have $\log{n} < 0.1 n$, and thus $\log{L} = -n\log{n} + n^2 > 0.9 n^2$. Using L'Hopital's rule, you can show that $\log{L} \ge (1 - \epsilon) n^2$, asymptotically in $n$, for every $\epsilon >= 0$.
Comment: oops, should be $\epsilon > 0$; letting $\epsilon = 0$ is right out.
Comment: The point is that O(n^2) is too crude.  You obtained the next term, -beta*n*log(n), but then threw that away.  So your answer, O(exp(n^2)), is correct but it's not best.
Comment: It is not clear what kind of bound the OP is looking for. Because the free variable was given as $n$, I assume a bound asymptotic in $n$ is desired. In my answer I note that this is an asymptotic bound. (the big-O notation is another hint that this is the case.) The bound that I showed is an asymptotic *lower bound*. I am not 'throwing away' the log term: $\Omega{(n^2 - n\log{n})}$ is $\Omega{(n^2)}$. Then since this lower bound is the same as the trivial upper bound, the trivial upper bound is optimal.
Answer: Numerical experiments (for 2 <= n <= 4000 and all values of beta) indicate the estimate n^2 - (n Ln(n))*beta exceeds the logarithm of the expectation by an amount on the order of beta*Exp(-n).  The error appears to increase monotonically in beta for each n.  This should provide some useful clues about how to proceed (for those with the time and interest).  In particular, an upper bound for the expectation exists of the form Exp(n^2 - (n Ln(n))*beta + C*Exp(-n)*beta) with C << 1.
Update
After staring at the summation expression for the expectation, it became evident where the nLn(n)*beta term comes from: break each binomial coefficient Comb(n,k) into its sum Comb(n-1,k) + Comb(n-1,k-1) and write Exp(k^2) = Exp((k-1)^2)*Exp(2k-1).  This decomposes the expectation e(n,beta) into the sum of two parts, one of which looks like the expectation e(n-1,beta) and the other of which is messy (because each term is multiplied by Exp(2k-1)) but can be bounded above by replacing all those exponential terms by their obvious upper bound Exp(2n-1).  (This is not too bad, because the last term with the highest exponent strongly dominates the entire sum.)  This gives a recursive inequality for the expectation,

e(n,beta) <= (n^-beta * Exp(2n-1) + 1 - n^-beta) * e(n-1,beta)

Doing this n times creates a polynomial whose highest term is in fact Exp(n^2)*n^(-n*beta), with the remaining terms decreasing fairly rapidly.  At this point any reasonable bound on the remainder will produce an improved bound for the expectation essentially of the form suggested by the numerical experiments.  At this point you have to decide how hard you want to work to obtain a tighter upper bound; the numerical experiments suggest this additional work is not going to pay off unless you're interested in the smallest values of n.
Answer: This answer is inspired by shabbychef's answer using the median. By definition:
$E[exp(Z^2)] = \sum_{z=1}^{z=n} exp(z^2) P(z;n,n^{-\beta})$
where,
$P(z;n,n^{-\beta})$ is the binomial probability.
Denote the mode of this binomial distribution by: $m(n,n^{-\beta})$. Thus, by definition we have:
$P(z;n,n^{-\beta}) \le P(m(n,n^{-\beta});n,n^{-\beta}) \ \ \forall z$
Let,
$\bar{P} = P(m(n,n^{-\beta});n,n^{-\beta})$
Thus,
$E[exp(Z^2] \le \sum_{z=1}^{z=n} exp(z^2) \bar{P}$
This upper bound is a function of $n$ and $\beta$ as desired.
Hopefully, this in the right track unlike my previous attempt.
This approach is technically not ok as $Z$ is a discrete variable but can be justified if we take the normal approximation to the binomial.
I am not sure to what extent this is a better bound then the trivial bound but here is one approach. Take the taylor series expansion of $exp(z^2)$ and ignoring terms higher than the second term, you get:
$\int e^{z^2} f(z) dz < \int (1 + z^2) f(z) dz$
Now,
$\int (1 + z^2) f(z) dz = 1 + \int z^2 f(z) dz$
But, we know that:
$\int z^2 f(z) dz = Var(z) + E(z)^2$
Substituting for the variance and mean of the binomial distribution and simplifying, we get:
$\int e^{z^2} f(z) dz < 1 +  n^{1-\beta} (1-n^{-\beta} + n^{1-\beta})$
PS: Please check the math as I corrected one error.
Comment: Given that $z^2$ can be quite large, ignoring higher order terms in the Taylor expansion is pretty fishy.
Comment: hmm on second thoughts I may have my inequality reversed. The bound I computed is a lower bound and not a upper bound. Please vote it down to oblivion. :-)
Comment: by pigeonhole principle, $\bar{P} >= 1/(n+1)$, thus I think your proposed upper bound based on the mode is going to be, asymptotically, the same as the trivial upper bound.


Default groups assigned to the first user in Ubuntu Server 8.04?

Question: I just made a silly mistake on my Ubuntu Server box:  I added myself to a group using usermod -G, after which I discovered the -a option...
The result is that I am now out of the admin group, and lost my sudo rights.  I can sort that out, but I want to know what other groups I may been removed from?  My user was the first one so what I'm looking for is a list of groups that the first user gets added to at installation time.
Comment: For different Ubuntu versions: [Default groups for user in Ubuntu?](https://askubuntu.com/q/219083/1060743)
Answer: Michael's answer was the closest, but I wanted to be sure, so I installed a fresh copy of Ubuntu Server 8.04.2 (Hardy Heron) in a virtual machine to get the official group list.  The installation was a basic one with no specific server roles selected.  These are the first groups, assigned by default, to the first user:

$USERNAME (e.g. wayne) (primary group - the rest are supplementary groups)
adm
dialout
cdrom
floppy
fuse
audio
dip
video
plugdev
sambashare
lpadmin
admin

To assign these groups to a given user, issue the following command:
sudo usermod -a -G adm,dialout,cdrom,floppy,audio,dip,fuse,video,plugdev,scanner,sambashare,lpadmin,admin

The -a switch means "append" so that existing supplementary groups are not overwritten.
To get a list of groups assigned to a particular user:
cat /etc/group | grep <username>

or for the current user:
groups

Comment: To get the groups of a user you can also do:
groups
Answer: From here, the default groups for the first user on an Ubuntu box are:

$USERNAME (Primary)
adm
dialout
cdrom
floppy
audio
dip
video
plugdev
scanner
netdev
lpadmin
powerdev
admin
Comment: I forgot to mention that I don't have an Ubuntu box to verify this or know what version of Ubuntu these default groups belong to. It's a good starting point though.
Answer: For Ubuntu 14.04 LTS:
$USERNAME adm cdrom sudo dip plugdev lpadmin sambashare
Comment: Exact same as for Ubuntu 12.04 LTS, (which is in another answer), by the way.
Comment: Exact same? The answer for Ubuntu 12.04 LTS has "disk". There is no "disk" in my Ubuntu 14.04 LTS setup. Even if it's the exact same, I don't see providing the info as doing any harm :)
Answer: The default group should be the same as the user name. So if you created user1, his default group would be user1.
[Edit]
Here you have an explanation of the group memberships.
Comment: So just admin and the username?  Is that all for sure?
Comment: On a standard install that's all there is. At work we use Fedora and I know for sure that's all there is. And on my Ubuntu box here I only have my username and adm that I added after.
Comment: That guy's book is based on Ubuntu 7.10. Probably you have something different.
Comment: You're right. here are the groups I have on my desktop at the office: username adm dialout cdrom plugdev lpadmin admin sambashare dev . It looks like I killed all the groups on my home box. I probably forgot the -a on a usermod too. I do that all the time, but usually I print out the groups I have before the usermod to be able repair any screw up I might make.
Answer: Ubuntu Server 9.10 (samba, openssh instaled)
$username, adm, dialout, cdrom, plugdev, sambashare, lpadmin, admin
Answer: Ubuntu 12.04 LTS:
$USERNAME adm disk cdrom sudo dip plugdev lpadmin sambashare


How to show $\mathbb{A}_k^2 - \{ (x,y) \}$ is not an affine scheme

Question: I am reading Ravi Vakil's notes and on page 137 (June 11, 2013 ver.) he explains why
$U = \mathbb{A}_k^2 - \{ (x,y) \}$ is not an affine scheme in the following way (Please note I am paraphrasing it here):
Suppose $(U, O_{\mathbb{A}^2}|_U)$ is an affine scheme, then
we have $ (U, O_{\mathbb{A}^2}|_U) = (Spec $A$, O_{Spec A})$.
By considering the global sections we have
$$
A = \Gamma(U, O_{\mathbb{A}^2}|_U) \equiv k[x,y].
$$
So if $U$ is affine, then $U \cong \mathbb{A}^2$.
The prime ideal $(x,y)$ of $A$ should cut out a point in Spec $A$
by taking the generic point of V((x,y)). However, on $U$, $V(x) \cap V(y) = \emptyset.$
Contradiction.
I don't quite understand the last part of the argument here. Do we know that the
closed subset $V(x)$ on $U$ correspond to $V(x)$ on $\mathbb{A}^2$? I would appreciate if someone could explain me in more detail how we obtain the conclusion at the end. Thanks!
Please note the following was my original question posted:
Let $\mathbb{A}_k^2$ be the affine scheme Spec $k [x,y]$, where $k$ is a field.
Could someone please explain me how to show $\mathbb{A}_k^2 - \{  (x,y) \}$ is not an affine scheme?
Comment: Possible duplicate of [Coordinate ring of affine variety](http://math.stackexchange.com/q/654029/115654) (although this question is phrased in scheme language, the proof is the same)
Comment: Well, it is a matter of fact that the inclusion induces an isomorphism of coordinate rings. So if both the domain and the codomain were affine then it would have to be an isomorphism, but it isn't even bijective on points.
Comment: I see. Let me change the question in this case... Thanks!
Comment: @zcn I also have a question to your answer to the link you have given me (I can't put it on there because I don't have enough poitns..). Why is it that you only have to consider the inclusion $i$? I guess is it obvious that any other possible map will not work? Thanks!
Comment: @user181350: (Just to repeat what Zhen Lin said) The point is that if $U$ were affine, then the inclusion would necessarily induce an isomorphism, which it does not. It's not necessary to consider other possible maps
Comment: @zcn So for affine schemes, two affine schemes are isomorphic if and only it induces an isomorphism between the global sections? (Would this be the correct way to turn the result stated in the link to scheme language?) Thanks!
Comment: @user181350: Yes, this is part of the statement that $\text{Spec}$ is an anti-equivalence from rings to affine schemes, with inverse given by the global section functor
Comment: @zcn I see. Thank you! Could you possibly tell me what anti-equivalence is?
Comment: @user181350: An equivalence that reverses arrows, i.e. an equivalence with the opposite category
Answer: Here is a more detailed explanation whose actual content amounts to just what Vakil says. Suppose that $X = \mathbb{A}^2 \setminus \{0\}$ were affine. Then by what you said about its coordinate ring implies we have an isomorphism $X \overset{\phi}{\to} \mathbb{A}^2$. This induces an isomorphism $\phi^{\#} : \mathcal{O}_X(X) \to k[x, y]$ of coordinate rings. But we know by the earlier computation of the coordinate ring of $X$ that $\mathcal{O}_X(X) \cong k[x', y']$ via some other isomorphism $f$. This means $g := \phi^{\#} \circ f^{-1}$ is an isomorphism $k[x', y'] \to k[x, y]$ (writing $f$ in this way is unusual, and we usually just make this identification implicitly). As this is an isomorphism, the prime ideal $(x', y')$ must map to some prime ideal $\mathfrak{p} \subset k[x, y]$. But we understand the isomorphism $f$ very well, having constructed it by patching functions on open sets of $X$ together. In particular, we know that $V(f^{-1}(x', y')) = V(f^{-1}(x'))\cap V(f^{-1}(y'))$ is empty. But by the correspondence between maps of rings and maps of affine schemes, we get that this (empty) set must be in bijection with $V(\mathfrak{p}) \subset \mathbb{A}^2$. But this latter set cannot be empty, and so we've reached a contradiction.


Retirar "disabled" com JavaScript

Question: Boa noite. Eu queria retirar o atributo disabled de uma tag quando certa condição for cumprida, mas não encontrei nenhuma ideia de como fazer isso. Abaixo o HTML:
Escreva aqui: <input type="text" id="text1" autofocus>

Depois aqui: <input type="text" id="text2" disabled>

Agora o JavaScript:
const t = document.querySelector("#text1")
t.addEventListener('keyup', function(e){
  var key = e.which || e.keyCode;
  if (key == 13) {     //quando a tecla enter é apertada a função abaixo acontece
    //aqui deveria entrar a função de tirar o disabled do input#text2
}});

Se alguém puder, por favor, me ajudar.
Answer: Basta setar o atributo disabled para false.
const t = document.querySelector("#text1")
t.addEventListener('keyup', function(e){
var key = e.which || e.keyCode;
if (key == 13) {     //quando a tecla enter é apertada a função abaixo acontece
    document.getElementById("text2").disabled = false;
}});

Comment: Já tentei fazer isso e não funcionou ainda.
Comment: Ele está entrando dentro do `if(key == 13)` ? Se tiver como você testar e falar pra nós.
Comment: Está sim, igual a como comentou.
Comment: Tenta dar um `console.log(document.getElementById("text2"))` pra ver se ele tá conseguindo pegar o elemento.
Answer: Para retirar o atributo disabled basta usar o método removeAttribute de Element. Este recebe uma string indicando o nome do atributo a remover, e não gera erro mesmo se o atributo não existir.
A utilização no seu exemplo ficaria:
document.querySelector("#text2").removeAttribute("disabled");

Veja a funcionar:

const t = document.querySelector("#text1")
t.addEventListener('keyup', function(e){
  var key = e.which || e.keyCode;
  if (key == 13) {
      document.querySelector("#text2").removeAttribute("disabled");
  }
});
Escreva aqui: <input type="text" id="text1" autofocus>

Depois aqui: <input type="text" id="text2" disabled>
Answer: E se formos além da necessidade simples?
Uma sugestão (de várias) seria:

Quando houver o disparo do Enter no <input> atual, passamos para o próximo e "desativa" o disabled, caso tenha;
Quando não houver um próximo, volta ao primeiro;
Sem necessidade de adicionar um identificador em cada <input>.

//usando es6
    const inputs = document.querySelectorAll('div input') //pega todos os 'inputs' dentro de 'div'

    inputs.forEach((input, index) => {

        input.dataset.index = index // attr 'data-index'
        input.addEventListener('keyup', (e)=>{
            let _this = e.target
            let _index = parseInt(_this.dataset.index, 10) //converte string em numero
            let keycode = e.keyCode || e.which
            if(keycode === 13) { //is Enter
                let nextSibling = inputs[_index+1]
                if(nextSibling !== undefined) {
                    nextSibling.disabled = false //remove o disabled
                } else nextSibling = inputs[0] // volta para o primeiro input

                nextSibling.focus() // autofoco
                // nextSibling.select() // caso precise fazer selecionar todo o valor
            }

        })

    })
input{margin-bottom:5px}

        a: <input type="text" autofocus>

        b: <input type="text" disabled>

        c: <input type="text" disabled>

        d: <input type="text" disabled>

        e: <input type="text" disabled>

        [...]

obs: o js tem que estar no final de todo o código. -antes do fechamento   -

Retirar "disabled" com JavaScript


Timeouts on Cloud SQL and other external services when using NAT + IP Masquerade on GKE

Question: I have to configure a static IP in one of my PODs because a remote service (outside of my cluster) requires trusted IP whitelisting.
I followed the documentation provided by Google:
https://cloud.google.com/nat/docs/overview?hl=es-419
https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent
But when trying to configure egress traffic using Google cloud NAT service in my GKE cluster plus masquerading using the ip-masq-agent I start getting timeouts and problems when accessing remote services outside of the cluster.
My Cluster is in version 1.19.10-gke.1600.
I have tried these config files with the following results:
resyncInterval: 60s

Result:
Chain IP-MASQ (2 references)
target     prot opt source               destination
RETURN     all  --  anywhere             10.0.0.0/8           /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             172.16.0.0/12        /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             192.168.0.0/16       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
MASQUERADE  all  --  anywhere             anywhere             /* ip-masq-agent: outbound traffic is sub
ject to MASQUERADE (must be last in chain) */

The services keep using the wrong IP.

resyncInterval: 60s
masqLinkLocal: true

Chain IP-MASQ (2 references)
target     prot opt source               destination
RETURN     all  --  anywhere             169.254.0.0/16       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             10.0.0.0/8           /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             172.16.0.0/12        /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             192.168.0.0/16       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
MASQUERADE  all  --  anywhere             anywhere             /* ip-masq-agent: outbound traffic is sub
ject to MASQUERADE (must be last in the chain) */

The same effect, my outside services get the wrong IP.

nonMasqueradeCIDRs:
  - 0.0.0.0/0
resyncInterval: 60s
masqLinkLocal: true

Chain IP-MASQ (2 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere             /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
MASQUERADE  all  --  anywhere             anywhere             /* ip-masq-agent: outbound traffic is sub
ject to MASQUERADE (must be last in the chain) */

It looks this works better because the external services receive the correct IP but I get connection problems and timeouts.

This is my NAT configuration:
NAT mapping
- High availability: Yes
- Source subnets & IP ranges: All subnets' primary and secondary IP ranges
- NAT IP addresses: static-egress-ip XXX.XXX.XXX.XXX

I'm out of ideas, can someone give me any advice?

After the response got here I updated my config file to add the ips following google cloud documentation, the file goes like this:
nonMasqueradeCIDRs:
  - 10.0.0.0/8
  - 172.16.0.0/12
  - 192.168.0.0/16
  - 184.108.40.206/10
  - 192.0.0.0/24
  - 192.0.2.0/24
  - 220.127.116.11/24
  - 198.18.0.0/15
  - 198.51.100.0/24
  - 203.0.113.0/24
  - 240.0.0.0/4
resyncInterval: 60s
masqLinkLocal: true

The result of this in the iptables is:
Chain IP-MASQ (2 references)
target     prot opt source               destination
RETURN     all  --  anywhere             10.0.0.0/8           /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             172.16.0.0/12        /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             192.168.0.0/16       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             220.127.116.11/10        /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             192.0.0.0/24         /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             192.0.2.0/24         /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             188.8.131.52/24       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             198.18.0.0/15        /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             198.51.100.0/24      /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             203.0.113.0/24       /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
RETURN     all  --  anywhere             240.0.0.0/4          /* ip-masq-agent: local traffic is not sub
ject to MASQUERADE */
MASQUERADE  all  --  anywhere             anywhere             /* ip-masq-agent: outbound traffic is sub
ject to MASQUERADE (must be last in chain) */

But if I run a curl checkip.amazonaws.com to see what IP is being used by the node I get a different IP from the one defined in my NAT Cloud configuration and the external services reject request as non trusted from my cluster.
Answer: It seems you have set the nonMasqueradeCIDRs: as 0.0.0.0/0 thereby preventing Masquerading of all the CIDR traffic, so to fix this issue, in the config file update the nonMasqueradeCIDRs: key with the IPs mentioned in Defaut non-masquerade destination paragraph [1]  as given below.
nonMasqueradeCIDRs:

172.16.0.0/12
192.168.0.0/16
220.127.116.11/10
192.0.0.0/24
192.0.2.0/24
188.8.131.52/24
198.18.0.0/15
198.51.100.0/24
203.0.113.0/24
240.0.0.0/4
10.0.0.0/8

Also please note that the IPs referred in the screenshot were not wrong IPs but those are ranges reserved by RFC 1918/link-local i.e., the IPs 10.0.0.0/8, 172.16.0.0/12 192.168.0.0/16 are reserved for RFC 1918 and the IP range 169.254.0.0/16 is reserved for link-local and these are non-masqueradable and hence these IPs are being displayed with the description 'ip-masq-agent: local traffic is not subject to masquerade'[2].
[1] https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent#default-non-masq-dests
[2]
https://kubernetes.io/docs/tasks/administer-cluster/ip-masq-agent/#ip-masquerade-agent-user-guide
Regards,
Anbu.
Comment: Hi @Anbu, thanks a lot for the help. I followed your instructions and instead of using 0.0.0.0/0 as masq I put the ranges defined in the documentation. You can see the editions made to my question to see the output of the commands but I still have the problem that my nodes and pods are calling the external services using an IP that I don't control. The NAT fixed IP I configured in GOOGLE CLOUD NAT is ignored. I'm testing this with a curl directly from the node ssh or calling my external services wich return IP unallowed. Any Ideas?
Answer: Finally we were able to diagnose the problem. Our cluster was created some time ago when GCP didn't supported private clusters so our clusted is public.
Each node have a public ephemeral IP thus the NAT rules are being ignored.
The solution was setting a node with a static IP and not ephemeral and configuring the workload that requires trusted auth to always deploy on that specific node. This is not a perfect solution but is what we can do quickly to solve the problem.
The real solution would be migrating to a private cluster and configuring the NAT but sadly GCP does not support migration from a public cluster to a private one. The only option would be creating a new cluster an migrate the workloads to the new cluster, process that we will need to execute in the short term.
Maybe it is a good moment to test autopilot which does not support automate migration too.


HashWithIndifferentAccess when saving array of objects

Question: Ok so I have these 2 classes
class Interface < ActiveRecord::Base
  belongs_to :hardware
end

and
class Hardware < ActiveRecord::Base
  has_many :interfaces
end

I have a form for a predefined @hardware.interfaces which includes array of Interfaces which is handled like below
<%= text_field_tag "hardware[interfaces][][name]",interface.name %>
<%= text_field_tag "hardware[interfaces][][ip]",interface.ip %>

Now I try to do...
@hardware = Hardware.find(params[:id])
@hardware.update_attributes(params[:hardware])

and it throws the error
Interface(#37298420) expected, got HashWithIndifferentAccess(#24204840)

Could someone clue me in on what's going on? and how to solve this problem?
Answer: update_attributes updates the model attributes.. and you are trying to update another model attributes (the Interface class)
you want to use nested form & accepts_nested_attributes_for - you can see how in this guide
Comment: Don't forget to use :interface_attributes instead of interfaces[] in your forms.


Calculate integration with Euler integration

Question: Calculate:
$$\int^{\pi /2}_{0}\tan ^{\alpha} x dx$$
with $| \alpha|<1$
Answer: $\pi/(2 \cos \frac{\alpha \pi}{2})$

In $B$ function or integral, we have $B(x,y)=\int^{1}_{0}t^{x-1}(1-t)^{y-1}dt$ which is defined on interval $(0,1)$, but the problem listed above seems out of range with $\alpha$ uncertain. Thank you for your help.

Edit: The previous one seems broken... thanks for @curiousguest
Comment: You don't need Euler's beta function to evaluate this one: $\int\tan\alpha x\,dx=-\frac{1}{\alpha}\ln|\cos\alpha x|+C$. Maybe you mean something else?
Comment: Oh, I know what's wrong. I can get $- \frac{1}{\alpha} \ln(|\cos \frac{\pi}{2} \alpha|)$ as result. But how could it be the same as the answer listed above?
Comment: It's actually not the same, that's why I asked if you have written the right integral.
Comment: Yes that's what is given on book. Maybe we should ignore it? Thank you anyway :)
Comment: Oh, I got it. The function should be $\tan^\alpha x$, then your answer is right.
Answer: First, show that $$\int_0^{\pi/2}\sin^\alpha x\cos^\beta x\,dx=\frac12\mathrm{B}\left(\frac{1+\alpha}{2},\frac{1+\beta}{2}\right)$$ by substitution $t=\sin^2 x$. Then your integral is $$I=\frac12\mathrm{B}\left(\frac{1+\alpha}{2},\frac{1-\alpha}{2}\right)=\frac{\Gamma(\frac{1+\alpha}{2})\Gamma(\frac{1-\alpha}{2})}{2\Gamma(1)}=\frac12\Gamma\left(1-\frac{1-\alpha}{2}\right)\Gamma\left(\frac{1-\alpha}{2}\right)=\frac{\pi}{2\sin\pi(\frac{1-\alpha}{2})}$$ by Euler's reflection formula.


Ruby on Rails End of File with SMTP

Question: Apologies if the answer is out there, but in the many similar posts I've browsed, I haven't found the answer I'm looking for.
I've inherited a Ruby on Rails application, and it recently began failing to send emails. From what I can gather, this is due to an smtp failure.
I want to send emails from "email@example.com" using "firstname.lastname@example.com" for the SMTP settings.
In .../config/environments/production.rb I have
ActionMailer::Base.smtp_settings = {
    :enable_starttls_auto => true,
    :address                        => 'smtp.gmail.com',
    :port                           => 587,
    :authentication         =>  :plain,
    :user_name                      => '<firstname.lastname@example.com>'
    :password                       => '<mygmailpassword>'
}

and in .../app/models/ I have a file called user_notifier.rb which contains
class UserNotifier < ActionMailer::Base
    def signup_notification(user)
        setup_email(user)
        @subject += 'Please activate your new account'
        @body[:url] = "<mydomain.com>:8080/activate/#{user.activation_code}"
    end

    def activation(user)
        setup_email(user)
        @subject += 'Your account has been activated'
        @body[:url] = "<mydomain.com>:8080"
    end

    def reset_notification(user)
        setup_email(user)
        @subject += 'Link to reset your password'
        @body[:url] = "<mydomain.com>:8080/reset_password/#{user.reset_password_code}"
    end

    def login_reminder(user)
        setup_email(user)
        @subject += 'Login Reminder'
        @body[:url] = "<mydomain.com>:8080"
    end

    protected

    def setup_email(user)
        @recipients = "#{user.email}"
        @from = "<email@example.com>"
        @subject = "<subject>"
        @sent_on = Time.now
        @body[:user] = user
        bcc ["<email@example.com>"]
    end
end

All of this code once worked, so I'm not sure what has changed. As I write this, I'm realizing that the sudden failure might have corresponded to some maintenance on the network, so I don't know how that might affect things.
EDIT: Added the entire UserNotifier class as requested in the comments
Comment: could you post your complete `UserNotifier` class
Comment: Sure. I just added it.
Answer: Well, I actually managed to solve this one myself.
I needed to add the :domain option in .../config/environments/production.rb
Why it once worked without :domain I still don't know, but I'll take just having the functional product.
The working setup was
ActionMailer::Base.smtp_settings = {
    :enable_starttls_auto => true,
    :address                        => 'smtp.gmail.com',
    :port                           => 587,
    :authentication                 =>  :plain,
    :domain                         => "gmail.com",
    :user_name                      => '<firstname.lastname@example.com>'
    :password                       => '<mygmailpassword>'
}

Ruby on Rails End of File with SMTP


Where to place the IIS module dll file?

Question: I have created an IIS module with a class implementing IHttpModule. In my localhost, I just copy its dll to the bin folder of the testing web app project, and then add the module in web.config.
<modules runAllManagedModulesForAllRequests="true">
  <remove name="AppendOutput" />
  <add name="AppendOutput" type="AppendOutput.AppendOutputModule" />
</modules>

Now I need to deploy the dll to my IIS server, where other web apps can use the module also. What is the shared or common folder to place that dll? And how should I revise the add module line to point to the correct path?
  <add name="AppendOutput" type="AppendOutput.AppendOutputModule" />

I was reading Walkthrough: Creating and Registering a Custom HTTP Module, but it appears it does not tell us how to deal with the dll deployment.
Another tech net article on Add a Managed Module (IIS 7) tells about how to add Managed Module. But the there is nothing in my Type drop down list.
Comment: I've added .dll to bin folder and I am able to see my module in Type dropdown. But I also looking for more elegant way.
Answer: You can register a Native Module with the path of your dll
(Available at Modules over IIS home, not Sites)

Where to place the IIS module dll file?


Android Activity losing GL Context

Question: I have spent a few days reading and implementing various solutions to this and so far absolutely none of them work, so I am now thinking I have a different problem here.
When my device (Nexus 4) rotates or I leave the app before returning, the screen goes to the clear-colour of my GL view.
This uses NDK to do the OpenGL drawing.
I have one class, the MainActivity (Pastebin as quite sizable):
http://pastebin.com/ZP2hhxpA
(I did recreate the GLSurfaceView class as recommended by some solutions, didn't solve the problem)
If I start up the app and not rotate/leave it, everything is fine, I have a nice 3D graphics engine I have ported to Android and it works brilliantly until the device is rotated, according to people the context is simply lost.
What my native code does is call GLES 2.0 functions, doesn't do any context creation, doesn't do anything special, if I wanted to I can move the functions into Android's Java side in the onDrawFrame() and I still have this problem.
I have tried:
 - Setting the GLSurfaceView to not lose context on pause (Changes nothing)
 - Recreating GLSurfaceView as a new class (Changes nothing)
 - Disabling rotation (Not a valid solution, problem is still there when pausing)
A lot of people say the solution is load the textures and create the shader in the onSurfaceCreated() method, which is exactly what I am doing. This isn't a case of textures not loading, when using a shader that has no textures the screen still goes white, it's as if my object disappears.
I cannot figure out how to retain the context manually, I have failed to find any sample code and while this problem is well known and documented there seems to be little code for actual solutions.
I have noted one warning message, when rotating the device the Nexus 4 GPU driver reports either of these two errors (Changes with each relaunch of app) within the glDrawArrays() call each time the screen is rotated:
<core_glHint:84>: GL_INVALID_ENUM
<gl_draw_error_checks:575>: GL_INVALID_OPERATION

This leads me to presume that my vertex arrays and invalid for the current context, however I can guarantee that the vertex arrays are destroyed and rebuilt on the onSurfaceCreated() call within the activity.
On a Nexus 7 every once in a while after rotating/pausing it will come up with the error:
call to OpenGL ES API with no current context

So it's certainly a context problem.
I'm pulling my hair out over this.
Comment: Did you hook up the `onPause()` and `onResume()` between the activity and the `GLSurfaceView`?
Comment: I have pasted my code onto the paste bin which has these methods set, they are definitely called at the correct times.
Comment: GLSurfaceView explicitly destroys the context when the app is paused.  You can try to override this with http://developer.android.com/reference/android/opengl/GLSurfaceView.html#setPreserveEGLContextOnPause(boolean) , but it's usually easier to just tear everything down and bring it back up on pause/resume.
Comment: Tearing it down and bringing it back is what I am already doing, I am still getting GL errors about missing contexts.

I have found that if I add a delay of 1 second during the creation I can reliably recreate everything perfectly fine, without the delay I get the context problems. Weird considering this app has no multi-threading.
Answer: From what I can see in your code, you are destroying the context when the app pauses.
Refer to renderer.Destroy()
@Override
public void onPause() {
    super.onPause();

    if (renderer != null) {
        glSurfaceView.onPause();
        renderer.Destroy(); // Deconstruct the native objects + gl textures
    }
}

I would try to remove that call, since otherwise the glSurfaceView will have a reference to a renderer which is destroyed.
Comment: renderer.Destroy() is my own method for dealing with the NDK shutdown, it doesn't touch the context
Comment: Well your resources will be destroyed looking at your comment. So you would be using invalid or no resources
Comment: The OpenGL resources are destroyed, am I not supposed to do this? I was under the impression that the GL handles are not transferred between contexts

Android Activity losing GL Context


repeat step algorithm react javascript

Question: I want to make a repeated array like this
 1->2->3->1->2->3.....

 const [current,setCurrent] = useState(0);
 const [direction,setDirection] = useState()
 const prevCurrent = usePrevious(current)
 const maxData = 3;
 function handler(val){
    if(val==='plus'){
      current !== maxData ? setCurrent(prev=>prev+1):setCurrent(0)
    }else{
      current !== 0 ? setCurrent(prev=>prev-1):setCurrent(maxData)
    }
 }
 useEffect(()=>{
   if(current>prev){
     setDirection('next')
   } else{
     setDirection('prev')
   }
 },[current])

 return

          <button onClick={()=>handler('plus')}>+</button>
          <button onClick={()=>handler('min')}>-</button>
          {direction}

In this case, I always want to repeat my current, example if the new current is 2 and prev current is 1 then the direction will be next, but when the current is the last step and the current will set to 0, but the direction will be set to 'prev' because current < prev, but I want my direction still set to next.
Is there some algorithm to fix this one?
Answer: I think I understand what you are looking for.  If so, then you should be able to simply call setDirection from your handler, something like this:

const {useState, useEffect} = React;

const MyComponent = () => {
  const [current, setCurrent] = useState (0)
  const [direction, setDirection] = useState ('?')
  const maxData = 3
  function handler (val){
    if (val === 'plus'){
      setDirection ('next')
      current !== maxData ? setCurrent (prev => prev + 1) : setCurrent (0)
    } else {
      setDirection ('prev')
      current !== 0 ? setCurrent (prev => prev - 1): setCurrent (maxData)
    }
  }
  return

    <button onClick={() => handler ('plus')}>+</button>
    <button onClick={() => handler ('min')}>-</button>

{current} ({direction})

}

ReactDOM.render(
  <MyComponent />,
  document.getElementById("react")
)

But I think you can also clean this up more doing two things.  First, skip the "plus" and "min" strings, and use +1 and -1 instead.  Second, keep an array of values that you want to loop, and make current track the index into that array, using a true modulus function to wrap around to the beginning/end of the array..  Note that the remainder operator - % is not a true modulus, as it doesn't work correctly with negative operands.

const {useState, useEffect} = React;
const mod = (n, m) => ((n % m) + m) % m

const MyComponent = () => {
  const [current, setCurrent] = useState (0)
  const [direction, setDirection] = useState ('?')

  const options = [1, 2, 3]

  const handler = (delta) => {
    setCurrent ((prev) => mod (prev + delta,  options .length))
    setDirection (() => delta > 0 ? 'next' : 'prev')
    console .log ({delta, current, option: options[current]})
  }

  return

    <button onClick = {() => handler (+1)}>+</button>
    <button onClick = {() => handler (-1)}>-</button>

{options [current]} ({direction})

}

ReactDOM.render(
  <MyComponent />,
  document.getElementById("react")
)

repeat step algorithm react javascript


Filter 2 lists over one pass (log(N) complexity)

Question: I have two lists similar to these (equal length and populated with string values):
a = ["W", "", "X", "", "Y", "Z"]
b = ["a", "b", "c", "d", "e", "f"]

I want to remove the elements from list a, if the element is an empty string. In addition, I want to remove corresponding elements from the b list (with same index). So the desired resulting lists for the example above would be:
a = ["W", "X", "Y", "Z"]
b = ["a", "c", "e", "f"]

I can do this with a couple of for loops but I wonder if it can be done in a more efficient way (list comprehensions)? The reason for this is that I'm working with very large lists (~ 4.5 million elements) and efficiency is critical.
Answer: You could use zip() to transform your data twice:
>>> a, b = zip(*((av, bv) for av, bv in zip(a,b) if av))
>>> a
('W', 'X', 'Y', 'Z')
>>> b
('a', 'c', 'e', 'f')

Comment: Can you briefly explain how to read that line? I see that you're unpacking with zip(*()), but what is happening inside those brackets?
Comment: @BourbonCreams it's a generator expression, a bit like a list comprehension
Answer: a = ["W", "", "X", "", "Y", "Z"]
b = ["a", "b", "c", "d", "e", "f"]

aNew,bNew = zip(*[(a[i], b[i]) for i in range(len(a)) if len(a[i]) > 0])

print(aNew)
#('W', 'X', 'Y', 'Z')
print(bNew)
#('a', 'c', 'e', 'f')


Theme seems complete enough, but Variations seem to need that extra harmony, what should I do?

Question: So, I'm composing a Theme and Variations based off of the La Folia progression and I started really basic for the Theme so that I would have some more wiggle room for Variations. I've even considered possibly ending with a fugue for a knockout punch(I've heard of composers doing that in their Theme and Variations pieces, ending with a fugue). It isn't the first time I've done Theme and Variations, it isn't even the second or third time. It is however the first time I've done it based off of a chord progression. This is my theme as it is right now:

And I've run into a bit of a conundrum. The Theme seems complete enough ending on the dominant as is, but as soon as I start doing rhythmic intensification(which is what my first few variations are going to be, and is very common for Variations 1-3 in a Theme and Variations piece(Variation 4 is usually where I see it break away from simple rhythmic intensification)), it seems as though that extra tonic harmony is necessary for completion. Yes, I'm aware that there are parallel fifths in between my D minor and C major chords, and I was told that depending on the style, this may or may not be an issue. Anyway, I can think of 3 things to do as far as this harmonic conundrum is concerned.
Option 1: End the Theme on D minor
This would mean me adding an extra bar to turn my 8 bar theme into a 9 bar theme. And I wonder if this would make it feel too complete. It's one thing making it feel complete enough, it's a totally different thing prematurely ending it.
Option 2: First and Second endings for Variations
I have repeats going on anyway, so I could have the first ending just end on the dominant like my theme does and the second ending end on the tonic with a bit of a melodic lead into the next variation if I want to make things sound as seamless as possible. Salieri does this if I recall correctly in his own 26 Variations on La Folia that I have been listening to, the first and second endings with a seamless lead into the next variation in the second ending or something along similar lines.

And while I don't know if I will quite reach 26 variations since my piece is for solo piano, I do think it will surpass my previous maximum of 9 variations for string quartet.
Option 3: End Variations on the Dominant anyway
This is my third option. Again, with the repeat, it feels somewhat more complete than if it just was played once and since the next variation would start on D minor(or D major if I decide to do a Majore variation), do I really need to end the Variations on the tonic? No. But for some reason, this feels like the wrong option, it feels too incomplete for me to just end the variations on the dominant, especially if I want to do like canon and fugue variations(which I have thought of doing both or at least a canon variation).
So what should I do to resolve this harmonic conundrum? Extend my theme by a bar to have it end on the tonic? Have a first and second ending for the variations? Or just end the variations on the dominant and deal with it? Perhaps a combination of ending on the dominant and the first and second endings?
Answer: Your third option is fine; ending on the dominant gives you a trivial segue into the next variation. You can change the rhythm though and use a half measure dominant and half measure tonic. There is no rule about keeping the same number of measures though. The website "La Folia, a Musical Cathedral" has lots of Folias and a good set of references.
You can correct the parallels by using inversions.
Answer: "Version 2" is how folia is typically played, so what you wrote seems like half of theme. Note hemiola in the second part of the theme, a very characteristic element.
This is of course your composition and it's up to you what choices you make, but I would assume the listeners may appreciate respect to the original form.
There were many folias written in variation form, so there is plenty of sources for inspiration.
Answer: I'll have to disagree with you about an A7 chord being a satisfactory completion!   You HAVE written a 9-bar theme. But you're at liberty to omit the final bar (which would probably be a Dm chord in a stand-alone version of the theme) and dovetail straight into the next variation.
The fifths in the Dm-C progression might be excused.   But I suggest you re-examine the octaves between bass and melody in bar 2.
Comment: I've heard people mention those octaves and I'm like "Why is it a problem? It's bound to happen when the bass is block chords and the basic melody is mostly chord tones with a few passing tones, that there will be octaves between melody and bass. And at least the octaves don't occur on the same beat, the D octave is on beat 1 and the C# octave is on beat 3."
Comment: You can get away with breaking a lot of the rules of counterpoint when using block chords.  But try to avoid consecutives between the lowest note and the melody.They do rather stick out!
Comment: But again, why are you considering them consecutives? The intervals from bass to soprano are: octave, 9th, 10th, 10th, octave. It's like saying parallel thirds are consecutives, it doesn't make any sense to me, unless you are inverting at the tenth, which I'm not.
Comment: From the end of bar 2 into bar 3 the intervals are octave, octave.   C# to D.
Comment: Oh, I thought you were talking about bar 1 to bar 2.
Answer: There are a number of examples where the theme is played as a period, with alternate endings. If that is what you're after, the theme isn't complete, it's a harmonic change to your theme. Once that is set it shouldn't really be a matter of the variations needing extra harmony. The rest is essentially figuration of the chords. A very common thing to do, especially with ground basses like La Folia, is to gradually build up speed and complexity rhythmically.


How to display/hide a field only if has a certain value?

Question: I am working on an event content type.
It contains a date field that lets users input the date in which their event will take place.
But sometimes the date of the event isn't known at the time the node is created. Users just need to create the event and discuss with other users (in the comments section) then decide when to organize it and add the date then.
So the date field has no default value and I created another boolean field that controls whether the date field is displayed or not using the conditional fields module.
The boolean field has two values, TRUE = « I know the date of my event ».
FALSE = « I will pick a date later »
The field is set to TRUE « I know the date of my event » by default.
If the user picks False « I don't know the date of my event yet », then the date field is hidden and no value is input.
The problems i'm facing are :
When displaying the event as a node and when listing all the events in a view :
If the user knows and inputs the date of the event :
- How to only display the date and hide the TRUE/I know the date of my event label/value of the boolean field
If the user chooses to pick a date later :
- How to display a « Date to Be Determined » message and hide the empty date field.
If you have ideas or a better way to handle this, you're welcome
Comment: Are you not able to exclude the boolean field in the view, under fields? Can you add a screengrab of your view?
Comment: Here are some screenshots of the two cases http://i.imgur.com/WsjcQlz.png
Comment: can you take a screenshot of the view's configuration page, ie. /admin/structure/views/view/YOUR_VIEW/edit
Comment: Here it is : http://i.imgur.com/U4wuotg.png ; (had some health issues these last few days, that's why i'm replying a little late.)
Answer: Hope youre feeling better! You should be able to achieve this by:

exclude the Date field from view.
in the Later Date field, under "rewrite results" check "Rewrite the output of this field. at the bottom of that fieldset expand Replacement patterns to see all the tokens available.  You should see somethine like [Date] to indicate the content from the Date field. Enter that into your text.
In the "no results behavior" section, enter "Date to Be Determined" in the "No results text" box. check Count the number 0 as empty (so when the box isn't checked it will show your "Later" message) and check "Hide rewriting if empty"
Save view and refresh caches
Comment: It works for the view, thanks ! If you have an idea on how to do this when viewing the event node, your suggestion will be welcome. When a date is picked, the two fields are displayed; The date of the event & the field label "I know the date of the event"
Comment: Glad it worked! You can modify the output of specific fields by using the template file of your event node's content type.


Closed or open if it's continuous and not surjective?

Question: If $f:[0,1]\rightarrow [a,b]$ is a continuous function, and $f([0,1])=(c,d)\subset [a,b]$. Is $f^{-1}([a,b])$ open or closed in $[0,1]$?
If open: Since $[a,b]$ is closed so is $f^{-1}([a,b])$; contradiction.
If closed: Since $(c,d)$ is open so is $f^{-1}([a,b])=f^{-1}((c,d))$; contradiction.

Def. for a continuous function in general topology:

Let $X$ and $Y$ be topological spaces. A function $f : X \rightarrow Y$
  is continuous if $f^{-1} (Y)$ is open/closed in $X$ for every open/closed set $V$ in $Y$.
Comment: Why do you think you have a contradiction?
Comment: $f^{-1}([a,b])=[0,1]$ so it's both open and closed.
Comment: @Michael Albanese: Because when I suppose it to be closed/open it comes to be open/closed!
Comment: @HIP13044b: A set can be both open and closed, which is the case here. In fact, for any topological space $(X, \tau)$, $X$ is always open and closed (as is $\emptyset$).
Answer: The image of a closed bounded interval under a continuous function is closed and bounded (follows from Bolzano intermediate value theorem, and the fact that f atteins a min and a max, in $\mathbb{R}$)! Further, in the image of any compact (ie sequentially compact) metric space is also compact. How can you have a continuous function with this property? If a function satisfies $f([0,1])=(c,d)$ then it's not continuous.
Comment: Thank you very much! Finally I got it.
Answer:
If $f:[0,1]\rightarrow [a,b]$ is a continuous function, and $f([0,1])=(c,d)\subset [a,b]$. Is $f^{-1}([a,b])$ open or closed in $[0,1]$?

The answer is that it is closed and not open. It is also open and not closed. It is also neither open nor closed. It is also both open and closed. How can this be?
Well, the problem is that you have assumed that $f$ is a function that cannot exist. In particular, if $f$ is a continuous function on $[0,1],$ then since $[0,1]$ is compact, we have that $f\bigl([0,1]\bigr)$ is also compact, so will be open only if it is empty.$ However, the image of a non-empty set cannot be empty!
Why can we draw all of the strange conclusions mentioned above, then? The Principle of Explosion.


Undefined variables in PHP after sending data via Ajax

Question: I am trying to send data via Ajax to my php file and process it, I don't know where is the error Ajax seems to be Okay but after receiving data via $_POST in php file but when I am trying to echo my variables I am getting errors.
I am sending data using a POST;
here is my frontend code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

        wowowo

    Article title:
    <input id="ArticleTitleInputField" type="text" name="">

    Enter article:
    <textarea id="ArticleContentTextArea"></textarea>
    Enter file name(save as):
    <input id="ArticleFileNameInputField" type="text">
    <button id="SubmitButton"  name="submitButton">Submit</button>

and here is my PHP code:
<?php

ini_set('display_errors', 'On');    //to get errors displayed

$ArticleTitle = "";
$ArticleContent = "";
$ArticleFileName = "";

if(isset($_POST['ArticleTitleData'])){
    $ArticleTitle = $_POST['ArticleTitleData'];
}else {
    echo("no var artn ");
}

echo("data was entered successfully  following data was entered:  Title: " . $ArticleTitle );
?>

where is the error in this script.
the response text I am seeing on browser screen is:
data was entered successfully following data was entered: Title: undefined
Comment: `console.log(ArticleTitle)` in js first ands see what it gives you
Comment: @delboy1978uk it is saying Cant find variable.
Comment: Yea, it looks like you're sending it an empty variable.
Answer: The problem is that some of the variables you are using, are undefined in the scope you are trying to use them in:
        function CheckFields() {
            // The variables defined with `var` exist in the scope of this function
            var warningsDiv = document.getElementById('warningsDiv');

            var ArticleTitle = document.getElementById('ArticleTitleInputField');
            var ArticleContent = document.getElementById('ArticleContentTextArea');
            var ArticleFileName = document.getElementById('ArticleFileNameInputField');

            if (ArticleTitle.value == "") { warningsDiv.innerHTML += " Enter article Name "; } else { return true; }
            if (ArticleContent.value == "") { warningsDiv.innerHTML += " Enter article content "; } else { return true; }
            if (ArticleFileName.value == "") { warningsDiv.innerHTML += " Enter article file name (save as) "; } else { return true; }

        }

        if (CheckFields == true) {
            // No `ArticleTitle`, etc. here...
            var articleTitle = ArticleTitle.value;
            var articleContent = ArticleContent.value;
            var articleFileName = ArticleFileName.value;
        }

Note that you are defining your variables using var in the CheckFields() function. So the scope of these variables is that function and anything in it, they will not be available outside of the CheckFields() function.
To solve that, you can return them from or define them before the function.
For example:
        var ArticleTitle = document.getElementById('ArticleTitleInputField');
        var ArticleContent = document.getElementById('ArticleContentTextArea');
        var ArticleFileName = document.getElementById('ArticleFileNameInputField');

        function CheckFields() {

            var warningsDiv = document.getElementById('warningsDiv');

            if (ArticleTitle.value == "") { warningsDiv.innerHTML += " Enter article Name "; } else { return true; }
            if (ArticleContent.value == "") { warningsDiv.innerHTML += " Enter article content "; } else { return true; }
            if (ArticleFileName.value == "") { warningsDiv.innerHTML += " Enter article file name (save as) "; } else { return true; }

        }

        // etc.

Note that if you need the warningsDiv outside of the function as well, you would need to treat it the same.
Comment: I moved it out of the CheckFields() function I am able to log it but response is same ("undefined").
Comment: @Techguy So what does `dataToSend` contain right before you send it?
Comment: I did console.log(dataToSend);   output was: ArticleTitleData=undefined&ArticleContentData=undefined&ArticleFileNameData=undefined
Answer: Yes, I figured out what was the problem
short answer:
when I was not calling the CheckFields(); properly
long answer:
Instead of if(CheckFields() == true){ //something } I was doing if(CheckFields == true){ //something }
I came to know this because when I was submitting the input field empty there was no change in warningsDiv as it was supposed to be when CheckFields(); function is called.
Thanks everyone for helping me...


Bound on truncated trigonometric polynomial

Question: Let $p(\theta)$ be a real trigonometric polynomial of degree $N>0$
$$
p(\theta) = \sum_{j=-N}^N a_{|j|}e^{\text ij\theta}
$$
and for any $0\le s<N$ define the left trucation of $p$ as
$$
p_s(\theta):= \sum_{j=-s}^N a_{|j|}e^{\text ij\theta}.
$$
Is it true that, for any $s$,
$$
\|p(\theta)\|_\infty \le 1 \implies \|p_s(\theta)\|_\infty \le 1?
$$
(Here the infinity norm is just the sup of the absolute value of the funtion on $[-\pi,\pi]$)
I verified by hand that it is true for $N=1$, but I am quite sure there exists a counterexample..
Answer: No, it fails for $p(\theta) = P(e^{i\theta})$ where $P(x) = 1/x^3 + 1/x^2 - 1/x + 1 - x + x^2 + x^3$ and $s=2$. Expecting it to be rarely true, I just did trial and error a few times.
Comment: that is not possible. $|p(\theta)|$ is surely less than 7
Comment: I computed the square of the magnitude so it was a real function that Mathematica was happier with. The code should be relatively idiomatic.
Answer: Take $N=3$ and a polynomial $$p(\theta)=a+be^{i\theta}+be^{-i\theta}+ce^{2i\theta}+ce^{-2i\theta}=a+2b\cos\theta+2c\cos2\theta$$
$$p_1(\theta)=a+be^{i\theta}+be^{-i\theta}+ce^{2i\theta}=a+2b\cos\theta+c\cos2\theta+ic\sin2\theta$$
Basically, the question is asking whether by transferring a $\cos2\theta$ to $i\sin2\theta$, is it possible to increase the maximum value of the polynomial. Simplifying drastically for intuition, let's seek real numbers $x,y$, such that $|x+y|\le1$, $|x+iy|>1$. Expanding out shows that we need $y<0$, $x^2+y^2>1>(x-y)^2$.
A quick search with $a=1=b$ and negative $c$ gives this counterexample, $$p(\theta)=\alpha(1+\cos\theta-0.2\cos2\theta)$$
$$p_1(\theta)=\alpha(1+\cos\theta-0.1(\cos2\theta+i\sin2\theta))$$ where $\alpha$ is the a normalizing factor, in this case $\alpha=1/1.85$.
Here is a plot of the two functions against $\theta$:


How can I make a Pandas data_frame column based on "If any observation in a particular column meets a condition, then True?"

Question: I have a variable that I want to define as True if any item in its containing group meets the condition.  For example, in the below .csv frame, a column D corresponding to the condition I'm looking at would be True for all rows where A==1 because it's true in the first row, False for A==4 because it's False in the only row there, True for A==6 because two values are True, and False for all rows where A==8 because none are true.
A,B,C
1,2,True
1,4,False
1,5,False
4,5,False
6,7,True
6,4,False
6,5,True
8,9,False
8,11,False
8,20,False

I've tried using the .any() method, but it keeps returning an empty data frame.
Answer: You could try
In [7]: df.C.groupby(df.A).max()
Out[7]:
A
1     True
4    False
6     True
8    False
Name: C, dtype: bool

Your question didn't specify what should happen if some of the rules contradict others, e.g., if there's also a row
1,2,False

The code above would still decide that the value of 1 is True, as some of the rows had
1,2,True

You can change it to require that all of the rows must be True, by changing max to min in the above.

Finally, to add a new column based on the results, you can merge:
pd.merge(
     df,
     df.C.groupby(df.A).max().reset_index().rename(columns={'C': 'is_true'}))

Comment: If there's a row `1,2,False`, then I'd still mark it True because one of them is true.
Answer: You can group on A and then use transform which keeps the the same shape as the original dataframe. Apply a lambda function where you test if any member of the corresponding group in column C is True.
df['D'] = df.groupby('A').C.transform(lambda group: group.any())

>>> df
   A   B      C      D
0  1   2   True   True
1  1   4  False   True
2  1   5  False   True
3  4   5  False  False
4  6   7   True   True
5  6   4  False   True
6  6   5   True   True
7  8   9  False  False
8  8  11  False  False
9  8  20  False  False

Comment: This seems to be what I'm looking for.  If instead of `C` being pure boolean values it was a bunch of integers and I wanted to check for `C==2` for that condition, how would I do that?  I haven't been able to figure out how to put those arguments in the `any()` function.
Comment: `lambda group: group == 2`.  Wouldn't `df.C == 2` also work?
Comment: Perfect.  This is exactly what I was looking for.  Thanks!  And I don't think so  because it needs to be true for each group, not for the data frame as a whole.


Apache Velocity foreach loop #continue

Question: Is there a #continue command for jump to next iteration in foreach loop?
Answer: I have a bunch of velocity code but I don't think I've ever seen this.  I believe you have to use a #foreach and then use and #if to check your skip condition within the loop. The VTL guide doesn't seem have a better approach.
Comment: Having #break doesn't make it a full scripting language where you can expect all the standard features. Velocity is extensible, though, so you can make your own #continue directive. It's also open source, so you can lobby to have your #continue added by default.
Comment: Correct.  Velocity is a simple template engine, not a full scripting language.
Comment: Problem was i've a lot of #if, so like in switch-case construct, i wanto to skip to end after the first match.
Comment: @NathanBubna Ok, but it has break for example.
Answer: Based on the documentation, Apache Velocity does not appear to have a #continue function for its foreach loop.
In case it might help, it does have a foreach break directive, added in 2008.

Apache Velocity foreach loop #continue


Reference with distributions with various properties

Question: I often find myself asking questions like, "I know this variable $x$  lies in $(0,1)$ and most of the mass lies in $(0,.20)$ and then declines continuously towards 1.  What distribution can I use to model it?"
In practice, I wind up using the same few distributions over and over again simply because I know them.  Instead, I'd like to look them up in a more systematic way.  How do I go about accessing the wealth of work that probabilitists have done developing all of these distributions?
Ideally I'd like a reference organized by properties (region of support, etc.), so I can find distributions by their characteristics and then learn more about each distribution based on the tractability of the pdf/cdf and how closely the theoretical derivation fits the problem I'm working on.
Does such a reference exist, and if not, how do you go about choosing distributions?
Comment: See also http://cran.r-project.org/web/views/Distributions.html
Comment: Related: [Comprehensive list of distributions?](http://stats.stackexchange.com/q/110235/22228); [Where can I get information about relationships among probability distributions in statistics?](http://stats.stackexchange.com/q/234903/22228)
Answer: The most comprehensive collection of distributions and their properties that I know of are
Johnson, Kotz, Balakrishnan: Continuous Univariate Distributions Volume 1 and 2;
Kotz, Johnson, Balakrishnan: Continuous Multivariate Distributions;
Johnson, Kemp, Kotz: Univariate Discrete Distributions;
Johnson, Kotz, Balakrishnan: Multivariate Discrete Distributions;
The books have a broad subject index. All books are from Wiley.
Edit: Oh yes and then there also is the nice poster displaying properties and relationships between univariate distributions. http://www.math.wm.edu/~leemis/2008amstat.pdf This might be of further interest.
Comment: I think if you got the univar book, drilled a hole through it, mounted it to one end of a pole, and did the same with the multivar book on the other side, you'd have a nice zombie sledgehammer.
Comment: (+1) These are the classical references and a great place to start. I'm also a big fan of the poster, especially when printed at actual poster size. I've seen a few different incarnations of it.
Comment: You should find all of them on Google books for a peek.
Comment: The poster looks awesome. :-).  The books look...intimidating.
Comment: @gsk3: The books are desk references. They're intended to be (somewhat) comprehensive.
Comment: @gsk3: They are intimidating. And huge. I plan to use them as weapons of choice in the upcoming Zombie Apocalypse. ;)
Answer: honestly, there are way too many distributions that I have no idea about. I do believe however that knowing them is not an asset, one must know how to use them.
Anyway, back to your question, I always find this diagram quite informative and useful, it's like probability distributions cheatsheet.

http://jonfwilkins.com/wp-content/uploads/2013/06/BaseImage.png
Comment: +1 I was thinking this would be useful: you saved me having to search for the link!
Comment: @whuber you're welcome, we also came across this for a statistics course and Glen_b is right that it's originated from a research paper, which I'm not sure which one! But I found this diagram kinda embaressing as I have no clue about many of its distributions
Comment: I believe that diagram is originally from a paper in American Statistician.
Comment: @Gleb_b: You are right, I came across that diagram the other day: http://www.math.wm.edu/~leemis/2008amstat.pdf
Comment: Along the lines of your diagram, I highly recommend this blog post by @JohnD.Cook: [Clickable diagram of probability distribution relationships](http://www.johndcook.com/blog/2008/10/12/clickable-diagram-of-probability-distribution-relationships/).
Comment: Wow, +1 for the diagram.  First time I've seen it but it is packed full of information.  Just don't use that when designing traffic patterns!
Answer: No book could cover all distributions, as it is always possible to invent new ones. But
Statistical distributions by Catherine Forbes et al. is a concise book covering many of the more commonly used distributions
while
A primer on statistical distributions by N. Balakrishnan and V.B. Nezvorov
is also fairly concise, but rather more mathematically oriented.
The nearest approach to a treatise is the series started by N.L. Johnson and S. Kotz, being continued by A.W. Kemp and N. Balakrishnan, and currently published by John Wiley.
This isn't a complete list even of surveys of distributions, but Googling your local Amazon site easily gets you other ideas.
Comment: +1 Johnson & Kotz has been a great resource for me for decades, but the price is appalling.  It would be nice to find an affordable version.
Comment: @whuber A new edition of one of the volumes http://www.amazon.com/Continuous-Univariate-Distributions-Probability-Statistics/dp/0471752878 is cited for publication in August 2014. Wiley are currently charging more for a copy of the 1994 edition.
Comment: Thanks for the links. 'Statistical distributions' seems to be more student friendly book
Answer: Merran Evans, Nicholas Hastings, Brian Peacock - Statistical distributions - John Wiley and Sons
I have the second edition and the distributions are in simple alphabetical order (from Bernoulli to Wishart central distribution).
Answer: The Hand-book on Statistical Distributions for Experimentalists by Christian Walck at the University of Stockholm is pretty decent....and FREE!! It covers over 40 distributions from A to Z, with each distribution described with its formulas, moments, moment generating function, characteristic function, how to generate a random variate from this distribution, and much more. Very nice for a free pdf.
Comment: @gung sure thing. I'll do a little more "marketing" for it, although following the link and seeing it will speak for itself.
Comment: Thanks for the link. Although this is a free resource, it is hard to understand because everything is explained using maths. Even the text uses maths terminology.
Answer: Ben Bolker's  "Ecological Models and Data in R" has a section "bestiary of distributions" (pp 160-181) with descriptions of the properties and applications of many common and useful distributions.
It is written at the level of a grad level course in ecology, so it is accessible to non-statisticians. Less dense than the Johnson, Kotz et al references in the answer by @Momo, but gives more practical details than a list or appendix might.
Answer: The Loss Models by Panjer, Wilmot and Klugman contains a good appendix regarding distribution pdf, their support and parameter estimation.
Answer: The series of books by Johnson, Kotz & Balakrishnan (edit: which Nick has also mentioned; the original books were by the first two authors) are probably the most comprehensive. You probably want to start with Continuous Univariate Distributions, Vols I and II.
A couple more:
Evans, Hastings & Peacock, Statistical Distributions
Wimmer & Altmann, Thesaurus of univariate discrete probability distributions
There's also many other books, sometimes for more specialized applications.
Comment: Evans, Hastings and Peacock is a previous edition of the book now first authored by Catherine Forbes, which I mentioned. _Continuous univariate distributions_ is the exact title.
Comment: @Nick Thanks on the title thing. That was a typo resulting from moving words around in edit. Sorry about not spotting I had duplicated that other one.
Comment: You're welcome. We're all duplicating a previous answer. (I did check first, but did not find it.)
Answer: A study of bivariate distributions cannot be complete without a sound background knowledge of the univariate distributions, which would naturally form the marginal or conditional distributions. The two encyclopedic volumes by Johnson et al. (1994, 1995) are the most comprehensive texts to date on continuous univariate distributions. Monographs by Ord (1972) and Hastings and Peacock (1975) are worth mentioning, with the latter being a convenient handbook presenting graphs of densities and various relationships between distributions. Another useful compendium is by Patel et al. (1976); Chapters 3 and 4 of Manoukian (1986) present many distributions and relations between them. Extensive collections of illustrations of probability density functions (denoted by p.d.f. hereafter) may be found in Hirano et al. (1983) (105 graphs, each with typically about five curves shown, grouped in 25 families of distributions) and in Patil et al. (1984).
This is from Chapter 0 of a book on continuous bivariate distributions, which provides an elementary introduction and basic details on properties of various univariate distributions. I remember I enjoyed reading Ord (1972) very much, but I can't now remember why.


Modal Boostrap reduz o tamanho do corpo do site

Question: Meu modal está diminuindo o tamanho da página horizontalmente quando aberto, ao fechar ele volta a página ao normal, é algo que chega a ser estranho.
Aqui o código:

    Posição: <?php echo date("d/m/Y H:i:s", strtotime($rslt_query_time['data'])); ?>

MPF - Gestão de Convênios

                Convênio
                Ag. Ctrl.
                Nome
                Situação
                Bloqueio

    <?php do{?>
            <tr style="cursor:pointer" id="<?php echo $rslt_query['id'];?>" onclick="contato(this)">
                <?php echo $rslt_query['id']; ?>
                <?php echo $rslt_query['centralizadora']; ?>
                <?php echo $rslt_query['nome']; ?>
<?php               if($rslt_query['situacao'] == 0){
                        echo "
                              	";
                    }else if($rslt_query['situacao'] == 1){
                        echo "
                              	";
                    }?>
                <?php
                    $txt_temp = "";
                    if ( $rslt_query['A'] || $rslt_query['B'] || $rslt_query['C'] || $rslt_query['D'] || $rslt_query['E'] || $rslt_query['F']){
                        if($rslt_query['A'] == 1){$txt_temp .= "...
";}
                        if($rslt_query['B'] == 1){$txt_temp .= "...
";}
                        if($rslt_query['C'] == 1){$txt_temp .= "...
";}
                        if($rslt_query['D'] == 1){$txt_temp .= "...
";}
                        if($rslt_query['E'] == 1){$txt_temp .= "...
";}
                        if($rslt_query['F'] == 1){$txt_temp .= "...
";}

                    }
                    $txt_temp .= "";
                ?>
                <td style="text-align: center;" <?php if($rslt_query['A'] || $rslt_query['B'] || $rslt_query['C'] || $rslt_query['D'] || $rslt_query['E'] || $rslt_query['F']){ echo "data-content=\"".$txt_temp."\" data-html=\"true\" rel=\"popover\" data-placement=\"top\" data-toggle=\"popover\" data-original-title=\"Motivo\" data-trigger=\"hover\" data-container=\"body\" "; }?>>
                <?php if($rslt_query['A'] || $rslt_query['B'] || $rslt_query['C'] || $rslt_query['D'] || $rslt_query['E'] || $rslt_query['F']){ ?>
                    <?php }?>

<?php }while($rslt_query = mysql_fetch_assoc($query_db)); ?>

<?php $rslt_query = mysql_data_seek($query_db, 0);

    do{ ?>
    <div id="modal-<?php echo $rslt_query['id'];?>" class="modal fade">

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<?php echo $rslt_query['nome']; ?>

                                    Nº Convênio: <?php echo $rslt_query['id']; ?>

                                    MCI: <?php echo $rslt_query['mci']; ?>

                                    Gestor do Convênio: <?php echo $rslt_query['nome_func']; ?>

                                    Chave: <?php echo strtoupper($rslt_query['chave_func']); ?>

                                    Responsável Financeiro: <?php echo $rslt_query['resp_fin_nome']; ?>

                                    Telefone: <?php echo $rslt_query['resp_fin_fone']; ?>

                                    Responsável Técnico: <?php echo $rslt_query['resp_tec_nome']; ?>

                                    Telefone: <?php echo $rslt_query['resp_tec_fone']; ?>

                                    Fluxo agência:
 <?php echo nl2br($rslt_query['fluxo_agencia_propria']); ?>

                                    Fluxo outras agências:
 <?php echo nl2br($rslt_query['fluxo_outras_agencias']); ?>

                                <?php if((isset($_SESSION['prefDep']) && $rslt_query['centralizadora'] == $_SESSION['prefDep']) || (isset($_SESSION['prefDep']) && $_SESSION['prefDep'] == "8501") ){
                                        echo "<form class=\"form-inline\" id=\"id".$rslt_query['id']."\" action=\"form_convenio_alterar.php\" method=\"post\">";
                                        echo "<input type=\"hidden\" name=\"id\" value=\"" . $rslt_query['id'] . "\">";
                                        echo "</form>";
                                        echo "<button type=\"button\" class=\"btn btn-danger\" onClick=\"document.getElementById('id".$rslt_query['id']."').submit()\" >Editar</button>";
                                      }
                                 ?>
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>

<?php
    }while($rslt_query = mysql_fetch_assoc($query_db));
?>

O CSS que uso é o que o Bootstrap disponibiliza, sem nenhuma modificação.
O body está assim:

E aqui o que ocorre:
Comment: Se vc retirar o style do body fica normal? Pode ser uma incompatibilidade entre o modal e esse style no body... Postar a parte de cima do código da página principal pode ajudar.
Comment: Mesmo retirando o Style e jogando as configurações pro CSS ele continua reduzindo de tamanho, só que agora em ambos os lados
Comment: Então, mas sem essas configurações de estilo (nem no CSS) fica certo? Se ficar, dá pra fazer o mesmo efeito desse estilo sem mexer na tag body (na tag ou por css), apenas trabalhando com os grids. Acho que não é muito "natural" pro bootstrap que vc faça esta estilização do `body`. Mas não tenho certeza, poste o código todo que pode ajudar a entender o que está havendo...
Comment: @gustavox http://pastebin.com/CWb86975 parte inicial do código, o conv_table_results.php está postado acima!
Comment: Coloca o script do modal entre as tags `head`, ele tá fora do head e fora do `body`, pode ser isso.
Answer: Consegui resolver meu problema, não sei se futuramente pode me acarretar algum prejuízo, porém, por hora é aceitável
No arquivo bootstrap.js na linha 964
Na parte da function
Modal.prototype.show

Há esta parte
this.setScrollbar()

Comentei ela e meu problema foi resolvido, toda vez que o modal é aberto ocorre a inserção de um padding-rigth: 15px no body, achei a solução olhando o código com o inspetor de código do Opera!
Answer: Boa tarde galera, resolvi o problema adicionando:

a resposta anterior do amigo me ajudou muito. obrigado mesmo.