Pq a barra de navegação está se sobrepondo no header?

Question:
Como vocês podem ver a barra de navegação está cobrindo o header(que o banner como background), porém em teoria (com base nos meus conhecimentos, é claro) o header deveria começar logo após a nav.
OBS: Tentei dar um margin-top no header só para testar e a nav desceu junto com ele. Tentei usar z-index e continuou na mesma.
Enfim, aí está o meu código HTML e CSS, respectivamente:
HTML:

Início

Organização

Parceiros

Programação

Hospedagem

Trabalhos Cientifícos

            <button>Inscreva-se</button>

CSS:
/*barra de navegação*/

nav {
    height: 124px;
    width: 100%;
    background: #c4322e;
    position: fixed;
    opacity: 0.6;
    display: block;
}

.logo{
    height: 124px;
    width: 205px;
    display: inline-block;
}

.logo img{
    width: 100%;
    margin-top: 2.2rem;
}

.nav-main{
    display: inline-block;
}

nav ul{
    float: left;
    list-style: none;
    color: white;
}

nav li{
    font-size: 30px;
    display: inline-block;
    margin-right: 33px;
}

.inscreva-nav {
    float: right;
}

nav button {
    font-size: 30px;
    width: 285px;
    height: 62px;
    background: none;
    border: solid white 3px;
    border-radius: 3px;
    color: white;
    margin-top: 1.8rem;
    margin-right: 23px;
}

/*barra de navegação - fim */

/* header*/
header{
    background: url(../img/teaser.jpg) no-repeat fixed;
    width: 100%;
    height: 464px;
    display: block;
}

Answer: Como o nav tem posição fixed você precisa colocar um top no header igual a altura do nav.
header {
    position: relative;
    top: 124px;
}

Comment: Eu tinha tentado tirar o fixed da nav, mas continuava a mesma coisa. Mas deu certo, nem parei pra pensar nisso. Muito obrigado, cara!
Answer: Você pode utilizar um float: left no header e dar um margin-top: 124px;

/*barra de navegação*/

nav {
    height: 124px;
    width: 100%;
    background: #c4322e;
    position: fixed;
    opacity: 0.6;
    display: block;
}

.logo{
    height: 124px;
    width: 205px;
    display: inline-block;
}

.logo img{
    width: 100%;
    margin-top: 2.2rem;
}

.nav-main{
    display: inline-block;
}

nav ul{
    float: left;
    list-style: none;
    color: white;
}

nav li{
    font-size: 30px;
    display: inline-block;
    margin-right: 33px;
}

.inscreva-nav {
    float: right;
}

nav button {
    font-size: 30px;
    width: 285px;
    height: 62px;
    background: none;
    border: solid white 3px;
    border-radius: 3px;
    color: white;
    margin-top: 1.8rem;
    margin-right: 23px;
}

/*barra de navegação - fim */

/* header*/
header{
    background: url(../img/teaser.jpg) no-repeat fixed;
    width: 100%;
    height: 464px;
    display: block;
    float: left;
    margin-top: 134px;
}

Início

Organização

Parceiros

Programação

Hospedagem

Trabalhos Cientifícos

            <button>Inscreva-se</button>

    dsada


Passing a variable from $_GET to another page

Question: So, I have am trying to do a simple search bar. The query that is entered into the search is pulled to another page. That works perfectly fine. The problem occurs when I try to use that variable in a script that increments the query's row in the database table. Everything works fine when I just put the name of a table element in instead of the variable, but I need to grab what they searched for to be able to get it to work properly.
I think you can do this with a session, but I don't want to bother with sessions for such a small project.
This is how I pull the variable from the search bar:
$query = $_GET['query'];

That works fine, but I can't get it to a new page to use in this piece of code:
mysql_query("UPDATE inventory SET Sold=Sold+1 WHERE Brand='Skittles' OR Type='Candy'");

Comment: You would have to update all links on the page to include that in the query string
Comment: probably less work to use sessions than the above.
Comment: We need more background information on this.  Can you provide more details on the type of query you are working with and how it ties into your search and db query?
Comment: Are sessions really that big a deal?
Comment: Remember parsing your query will be harmful
Answer: Sessions are fairly easy to work with.
<?php

    session_start();

    $_SESSION['query'] = $_GET['query'];

?>

That would store it, then to retrieve it use it just like you would $_GET['query'] but use $_SESSION['query'].  It'll persist until the session expires or is destroyed.
Answer: You would need to pass the query as a parameter to the other page if you really want to use it there :
next_page.php?query=something

Answer: If you want the query on say nextpage.php from currentpage.php
currentpage.php:
$query = $_GET['query'];
echo "";
This url can be used when you refer to nextpage.php and the value can then be accessed in nextpage.php as:
$query = $_GET['query'];

Setting unnecessary data as session variable is not a good idea. For more see:
https://softwareengineering.stackexchange.com/questions/160947/should-session-variables-be-avoided


How can I get the selected nodes in the jstree?

Question: i am using dynamic value for initially_select & open which is checked_id. in checked_id, i have assigned '"skillTree_1576","skillTree_1573"' value but its not working... if the same value i pass statically then its working fine.... following is source code
$("#"+node_id+"Edit").live("click", function(){
            $('#'+node_id+'Lookup').show();
            $('#'+node_id+'Values').hide();
            $("#"+node_id).bind("check_node.jstree", function (e, data) {//check all parent nodes
                var currentNode = data.rslt.obj.attr("id");
                var parentNode =  data.rslt.obj.attr("parent_id");
        $("#"+node_id).jstree("check_node", "#"+parentNode);
            }).bind("uncheck_node.jstree", function (e, data) {//uncheck all child nodes
                var currentNode = data.rslt.obj.attr("id");
                var allChildNodes = data.inst._get_children(data.rslt.obj);
        allChildNodes.each(function(idx, listItem) {
        var nid = $(listItem).attr("id");
        $("#"+node_id).jstree("uncheck_node", "#" + nid);
            });
        }).jstree({"0":"","plugins":["themes","json_data","ui","search","hotkeys","checkbox"],"checkbox":{
                "real_checkboxes":true,"two_state":true,"checked_parent_open":true,"override_ui":true
            },"themes":{"theme":"classic","dots":true,"icons":false},"json_data":{
                "ajax":{"url":baseUrl+url,"data":function (n) {
                        return {'node_name': node_id, 'operation' : 'lookup_children', 'id' : n.attr ? n.attr('id').replace(/[a-z0-9A-Z]+_/g,'') : 0 };
                        $('#'+node_id+'emptySearch').hide(); },"success":function(){}}},"search":{
                        "show_only_matches":false,"ajax":{
                            "url":baseUrl+url,"data":function (str) {if(str.length > 2 ) {
                                    return {'node_name': node_id, 'operation' : 'search', 'search_str' : str}; } },"success":function (data) {
                                if(data.length == 0) { $('#'+node_id+'emptySearch').show();
                                } else {
                                    $('#'+node_id+'emptySearch').hide();}}}},"ui":{"initially_select":[checked_id] },"core":{
                                    "initially_open":[checked_id],"load_open":true,"open_parents":true}});
                           // alert ('hello : '+checked_id);
                        });

if any one have idea about it please help me.. thanks in Advance
Answer: For selecting multiple id you can use as below:
 $("input[id^='skillTree_']")....

^ is used for starting with define string.
Reference
Comment: in jstree there is option for multiple selection which is called initially_select.. if i pass static value in this field its working fine but if i pass variable cheked_id its not working... so that i want how can i figure-out this problem?
Comment: @ratneshdwivedi If you set fiddle then I will help.


Is it possible to lose points while playing table tennis?

Question: Can you be deducted points for conduct during a table tennis match?
Also, if you are deducted points are you allowed a negative score?
Answer: It is not really possible to lose points that you have earned in a table tennis match.
If you foul during a serve, then you don't earn the point that you would have gotten if the serve had been an ace, and your opponent gets a point.  Sometimes you might hear this referred to as a point deduction, but it's not really a point deduction, since the server never really earned the point.
In the ITTF rankings, you earn points for wins, and lose points for losses.  But these are ratings points, not points during a table tennis match.
Answer: Ben Miller is right that when a "point deduction" is levied against a player, that player doesn't actually lose a point.  Instead, the opposing player is awarded a point.
I found an example of this in the women's singles gold medal match for table tennis in the 2012 London Olympic Games.  A Huffington Post article mentions three point deductions against China's Ding Ning in that match:

Bongelli penalized Ding three points — two for an illegal serve — and one for using a towel when it was not authorized. Two of the point deductions came in the critical fourth game with Ding trailing two games to one and trying to rally.
Behind 2-6 in the fourth game, Bongelli penalized Ding for failing to toss the ball correctly before serving it. The toss is supposed to go straight up, and the Italian referee said she was tossing it at an angle. The penalty made it 2-7.
Angered, Ding went and grabbed a towel. That cost her another point, since towel breaks are allowed only every six points.
That made it 2-8. Ding lost the game 11-6, and the fifth 11-5 and it was over.


Which of these constructions are left adjoints?

Question:
A groupoid can be regarded as a small category in which every arrow is an isomorphism
A monoid can be regarded as a small category with only a single object
A preorder can be regarded as a small category in which each hom-set has at most one element.

Hence in each case there is an inclusion functor between the corresponding category and the category of small categories. I wonder which of these inclusion functors have a left adjoint, and how to construct them.
To map an arbitrary small category to a groupoid, I would like to just omit all arrows which are not isomorphisms. Even so this seems to be a canonical construction, it doesn't seem to be a functor. After all a functor should map every arrow somewhere, but what to do with the omitted arrows? (Looks like I fell into a trap, the "internal" arrows are not the relevant morphisms here.) But maybe there is a completely different ("Grothendieck group" like) construction, which actually works and is a left adjoint?
To map an arbitrary small category to a monoid, I would like to single out one object. However, this doesn't seem to be a canonical construction. But perhaps the following construction works. If the category has more than a single object, then I add ("adjoin") a new bottom element (or "morphism"), and define every undefined composition to give the bottom element. The resulting binary operation is total and associative, so this seems to be a canonical construction. It maps each object to the single monoid object and each morphism to an element of the monoid, so it seem to be a functor. But is this functor a left adjoint of the inclusion functor?
To map an arbitrary small category to a preorder, I could just replace each non-empty hom-set by a hom-set with a single element. This construction should give the left adjoint functor of the inclusion functor, no?
Comment: Freyd's theorem constructs it explicitly.
Comment: The inclusion functor $\mathbf{Grp}\to\mathbf{Cat}$ doesn't preserve colimits...
Comment: @MartinBrandenburg  I mean if it satisfies the conditions (which apparently holds), Freyd's theorem shows an explicitly construction.
Comment: Yes, if you read the proof carefully there is explicit construction. So, apparently, for grupoids it does not hold.
Comment: @Oskar Could please show a counter-example? I'm very interested in it.
Comment: Sorry, I read the question inattentively. But the statement in my comment is correct(I was talking about $\mathbf{Grp}$ instead of $\mathbf{Grpd}$). Anyway, the same argument can be applied to $\mathbf{Mon}$(as Martin wrote in his answer).
Answer: You have correctly described the right adjoint of $\mathsf{Gpd} \to \mathsf{Cat}$. It maps a small category to its core. It is a functor $\mathsf{Cat} \to \mathsf{Gpd}$. Given a functor between small categories, it maps isomorphisms to isomorphisms, hence restricts to a functor between the cores.
The functor $\mathsf{Mon} \to \mathsf{Cat}$ has no right adjoint because it does not preserve colimits. In fact, already the initial object is not preserved (the initial monoid is $\{1\}$, whereas the initial category is empty). However, this functor has a left adjoint: We map a category $C$ to the free monoid generated by $\mathrm{Mor}(C)$ modulo the relations $[f] * [g] = [f \circ g]$ if $f,g \in \mathrm{Mor}(C)$ and $\mathrm{cod}(g)=\mathrm{dom}(f)$. In some sense this is the category with all objects contracted to a single object.
The functor $\mathsf{PreOrd} \to \mathsf{Cat}$ has a left adjoint: It maps a small category $C$ to the preorder on $\mathrm{Ob}(C)$ given by $X \leq Y$ iff there is a morphism $X \to Y$. But it has no right adjoint.
Comment: It also exists. One adjoins inverses to every morphism.
Comment: Nice, but what about the left adjoint of $\mathbf{Gpd} \rightarrow \mathbf{Cat}$?
Answer: Besides Martin's answer, you might enjoy adding - or should I say adjoining :-) - another adjunction to your already fine collection.
It's actually an adjunction quadruplet!
$$Comp \dashv D \dashv Ob \dashv Ind$$
where:
$Comp: \mathsf{Cat} \to \mathsf{Set}$, $C \mapsto $set of connected components of $C$
$D: \mathsf{Set} \to \mathsf{Cat}$, $S\mapsto $discrete category of $S$
$Ob: \mathsf{Cat} \to \mathsf{Set}$, $C \mapsto $set of objects of $C$
$Ind: \mathsf{Set} \to \mathsf{Cat}$, $S\mapsto $indiscrete category of $S$
$Ind(S)$ is the category with objects $S$ and exactly one arrow in every hom-set. It is a preorder, a groupoid and, if $S$ is not-empty, it is equivalent to the terminal category
All this can be read in CWM 2nd ed. page 90 exercise 9.
Comment: @ThomasKlimpel Good catch! I edited.
Comment: I would call $TC(S)$ the *indiscrete* category on $S$.
Comment: @MartinBrandenburg Thank you, I edited.
Comment: These adjunctions are also adjunctions between $\mathsf{PreOrd}$ and $\mathsf{Set}$. All functors factor through the adjoint functors between $\mathsf{Cat}$ and $\mathsf{PreOrd}$. Only $D \dashv Ob$ is a "genuinely new" adjunction between $\mathsf{Set}$ and $\mathsf{Cat}$, because the corresponding functors between $\mathsf{PreOrd}$ and $\mathsf{Cat}$ are not adjoint in the same sense.


CodeBuild with VPC settings fails to download CodeCommit source

Question: I originally had a simple CodePipeline setup triggered by commits to a CodeCommit repo, with a "Stage" that output the source code as an artifact and another "Stage" using CodeBuild to run some code from that source output. Now I want to access RDS in that CodeBuild "Stage", so I added my RDS's VPC settings to my CodeBuild project.
The problem is that now CodeBuild can no longer access the CodeCommit source. I am receiving the following error:
CLIENT_ERROR: RequestError: send request failed caused by: Get https://mypipeline-artifactstorebucket-twlrq7tj45fq.s3.amazonaws.com/MYPipeline-data-pipe/RepoSource/PKGw3xs: dial tcp 126.96.36.199:443: i/o timeout for primary source and source version arn:aws:s3:::mypipeline-artifactstorebucket-twlrq7tj45fq/MYPipeline-data-pipe/RepoSource/PKGw3xs

Does adding a VPC to a CodeBuild project also remove whatever the default settings are? (maybe it was originally using the default VPC?)
How can I allow CodeBuild to access both RDS and CodeCommit?
Comment: Yep, but you only need a private subnet+natgw if you configure it to use a VPC. You're not required to use a VPC unless the build needs access to a resource in that VPC.
Comment: From what I see now, AWS forces you to run CodeBuild on a private subnet with a default route to NAT Gateway.
Comment: @jweyrich Yep, that's what I found too. I mentioned in a comment on MLu's answer, there is a great AWS training video that explains setting up subnet + NAT Gateway. If you're not already an expert on those topics, I highly recommend it: https://www.aws.training/learningobject/video?id=16490
Comment: Alternatively, you can now use a VPC endpoint to publish the S3 route to the private subnets. It currently costs 1/4 of what a NAT gateway costs.
Answer: What a VPC-based CodeBuild can access depends on the subnet configuration that you're using for the CodeBuild container.
If you're placing it in a Private subnet make sure that the subnet is configured for internet access through NAT Gateway.
If you're running it in a Public subnet make sure that it is configured to assign Public IP by default.
Refer to this answer for more info: Public and private subnet in VPC
And also make sure that there are no other restrictions in place, e.g. the Security Group permits outbound access to the internet, there are no NACLs in place, etc.

Simple test: is to spin up a tiny EC2 instance in the same subnet where you're running your CodeBuild containers and test from there if it can reach the codebuild endpoint (e.g. curl https://mypipeline-artifactstorebucket.../PKGw3xs).
In other words: Yes, CodeBuild can be run in a VPC and still have access to CodeCommit but your subnet network config must be correct.
Hope that helps :)
Comment: Thanks! I think this pointed me in the right direction, but now I am wondering if this can also be accomplished using a "VPC Endpoint" for S3: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html

I'm experimenting with it, but haven't yet had success. Do you have any insight about using endpoints to accomplish this?
Comment: So I did eventually get this working. This answer was really helpful, but has a couple issues. Apparently AWS prevents CodeBuild from working on public subnets, so you need to use a private one. Testing on EC2 is a good suggestion, but it is a bit  complicated since it needs to be on a private subnet. Also, I think maybe my question doesn't have a definite answer beyond "setup your VPC correctly". If anyone is confused about VPCs like I was, I highly recommend watching the AWS training video "Subnets, Gateways, and Route Tables Explained" at https://aws.training
Answer: I had this same problem, trying to have CodeBuild retrieve code from CodeDeploy so it could deploy code to RDS in a VPC. When CodeBuild was outside the VPC it could connect to CodeCommit fine, but once I put CodeDeploy into VPC the error message was
CLIENT_ERROR: Get https://git-codecommit.ap-southeast-2.amazonaws.com/v1/repos/repo-name/info/refs?service=name: dial tcp 126.96.36.199:443: i/o timeout for primary source and source version refs/heads/master
I couldn't find any documentation about this at all, so I resorted to trial and error based on what is written above. I went through quite a few combinations of things to work out what worked and what didn't. Here's what I found:

CodeBuild needs to be associated with a VPC. I imagine that CodeBuild allocates an ENI (private IP address, effectively) in the VPC.
CodeBuild needs to be associated with a security group that allows egress to the VPC CIDR range. It doesn't seem to need ingress rules, which makes sense, as nothing is calling into CodeCommi.
You need a git-codecommit interface endpoint ( com.amazonaws.ap-southeast-2.git-codecommit )
The git-codecommit endpoint needs to be associated with a security group that allows ingress from CodeBuild. The easiest way to do this is probably just to allow ingress from the VPC range, but you can probably just reference the security group that CodeBuild uses for ingress.
It makes no difference whether an internet gateway / route to the internet is present. I was initially doing this in a private subnet with no internet access, but then added an internet gateway, associated it with the VPC, then routed the subnets to the internet gateway (0.0.0.0/0)

Hopefully this helps someone else connect CodeBuild or CodePipeline to a VPC to deploy to EC2, RDS, ECS, or other services.
Comment: Thank you very much. That was super helpful.

Any idea why I can't see any build logs when have the build project in. VPC?
Comment: Note: you will need to create another endpoint with com.amazonaws..logs if you want to see your build logs
Answer: I had such error when I condfigured
    Type: AWS::CodeBuild::Project
    Properties:
        Source:
            BuildSpec: buildspec-ProdCf.yml
            ....

but in fact the yml file was in a subdirectory.


Finding the limit of a function $\frac{x}{x^{2n}+1}$

Question: $$
f(x)=\lim_{n\to\infty}\frac{x}{x^{2n}+1}
$$
Domain of f(x) is $\Bbb R$.Find the value of $f(1^+ )$
I am not able to understand how to solve it. Please help me.
Comment: It will help a great deal if you were to try to write the math instead using MathJax and $\LaTeX$.  Instructions on how to do so [can be found here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).  It sounds like you are asked to find $\lim\limits_{n\to\infty} \frac{x}{x^{2n}+1}$.  You then make a reference to some $f$ which hasn't been mentioned yet.  What is this $f$?  Are you perhaps asking for $\lim\limits_{x\to 1^+} \left[ \lim\limits_{n\to \infty} \frac{x}{x^{2n}+1}\right]$?
Comment: $$\lim_{n\to\infty}\frac{x}{x^{2n}+1}$$? The copy and paste did not work i guess.
Comment: No JMoravitz sir. Thank you for your comment.I have done some edits.Please verify it
Comment: yeah Chinny84 sir.  The copy and paste did not work.
Comment: What is the domain of definition of $f$?
Comment: @AlexM., the points where the limit exists.
Comment: @Martín-BlasPérezPinilla: Ahh, my mistake: what is the domain of $\frac x {x^{2n} + 1}$? Is it considered defined on the whole $\Bbb R$?
Comment: @AlexM., yes. $2n$ is even, so $x^{2n}+1>0$.
Comment: Domain is R sorry I didn't mention in the question Alex sir
Answer: $$x>1 \implies\lim_{n\to\infty}\frac{x}{x^{2n}+1} = 0\implies
\lim_{x\to 1^+}\lim_{n\to \infty} \frac{x}{x^{2n}+1} = 0.$$
Answer: The given domain of definition of $f_n = \frac x {x^{2n} + 1}$ is $\Bbb R$. Note that if $x \in (-1, 1)$, then $\lim \limits _{n \to \infty} x^{2n} \to 0$, so $f_n(x) \to x$. If $x = \pm 1$, then $x^{2n} = 1$, so $f_n(x) = \frac x 2$. Finally, if $x \in (-\infty, -1) \cup (1, \infty)$, then $x^{2n} \to \infty$, so $f_n (x) \to \frac x \infty = 0$. To summarize:
$$f (x) = \left\{ \begin{eqnarray}
0, & x<-1 \\
-\frac 1 2, & x = -1 \\
x, & -1 < x < 1 \\
\frac 1 2, & x = 1 \\
0, & x > 1
\end{eqnarray} \right. .$$
This shows that
$$f(1^+) = \lim \limits _{x \to 1, x > 1} f(x) = \lim \limits _{x \to 1, x > 1} 0 = 0 .$$
Comment: @saisaandeep: How intelligent to unaccept an answer 6 months after having accepted it, only to accept an answer with fewer details! Bravo!


change of Public file system path

Question: how can i change Public file system path in drupal 8 ? And can you tell more about how to increase the storage of database?
Answer:
How can i change Public file system path in Drupal 8?

You can add the following line to either your settings.php file, or your settings.local.php file. E.g. docroot/sites/default/settings.php
$settings['file_public_path']  = '/sites/default/files/my_custom_folder';

And can you tell more about how to increase the storage of database?

I have no idea what this means.

change of Public file system path


Hypothesis tests for Rayleigh variables

Question: Given samples from two Rayleigh-distributed random variables with unknown parameters, $X \sim R(\sigma_x), Y \sim R(\sigma_y)$, what tests can we use to determine if and to what extent their parameters ($\sigma_x, \sigma_y$) are different?
For Rayleigh variables we have a closed-form unbiased MLE for the parameter $\sigma$, as well as for confidence intervals on the estimate.  We also have the convenient fact that the Rayleigh parameter squared is a variance, so presumably we could employ general tests for homoscedasticity.
Are there any tests or techniques specific to the Rayleigh distribution?
Answer: "Determine to what extent they're different" seems to be more suggesting a problem in estimation rather than testing. I will proceed to discuss tests, but this consideration may suggest you want to do something else.
I'll presume you want independence both within and across groups.
Since $X^2$ and $Y^2$ are Exponential, the likelihood-ratio test for the exponential should yield an equivalent test to the LR test for the Rayleigh. We should then (with a little algebraic manipulation) end up with something equivalent to a test based on the ratio of the means of the squared-observations.
For a one-tailed test an $F$-test would then be obtained pretty directly from the ratio of the likelihoods (that is, a test based on $F=\frac{\overline{x^2}}{\overline{y^2}}$) with $2n_x$ and $2n_y$ df should be equivalent to a likelihood ratio test). For the two tailed case, the "best" test based on the likelihood ratio ($\Lambda$) won't be equal-tailed though for $n$ large it won't matter.
The equal-tail ($α/2$) version of a two-sided test is (in general) not strictly an LRT, (not rejecting the set of smallest values of the likelihood ratio given $α$), since in general one tail will have values of the LR that are smaller than the smallest value in the other tail;
you could typically get better power if you actually do the LRT (albeit that may be slightly more complicated to do). See the plot below.
However, a small caveat; from a scientific standpoint you might sometimes prefer to have an equal tail test in spite of this potential loss of power. A critic might say that you're "favouring" one direction of the alternative over the other because it's easier to reject there.
Note that $Λ=\mathcal{L}_0/\mathcal{L}_1$ is the likelihood ratio calculated here under the Rayleigh assumption. You reject when the likelihood under $H_0$ is small relative to the likelihood under $H_1$ – i.e. for small values of the likelihood ratio.
In the case where both $n$'s are large enough that we don't care about giving up a smidge of power for some added convenience, a simple "symmetric" (equal tail) F test would result. While you can do better in terms of power, it is exact and still pretty powerful.
See some discussion of that choice of test here. Note that the  df  are  double the sample sizes. See also Scortchi's answer there for additional enlightening information.
Here's a plot that illustrates the distinction. It is based on 100000 pairs of samples from an exponential(1) (i.e. the squares of your Rayleigh values). The simulation is conducted under $H_0$ here and the specific value of the parameter is immaterial (it cancels). Here the x-sample values are a sample of size 8 and the y-sample values are a sample of size 12. The red values indicate the lower 2.5% and upper 2.5% of an F test (the rejection region for F). The blue dashed horizontal line is the 5% critical value for the likelihood ratio test (estimated here by simply taking the sample quantile from the simulation, though it shouldn't be that hard to actually compute it for this case).

R code used to generate the plot is appended below. I generated a new plot because the old one (by chance it seems) showed an unusually large difference between the tests; typically they're fairly close as with the current plot.
Edit: extra detail where the action is, log-log scale:

The likelihood ratio test rejects some cases in the left tail of the F that the F test does not (i.e. it would place more than 2.5% of the null distribution in the rejection region corresponding the left tail of the ratio of means), and it fails to reject some cases that the F test would reject in the right tail (placing less than 2.5% of the null distribution in the rejection region corresponding the right tail of the ratio of means).
I think the two tests will always correspond when the sample sizes are equal.
However you could also do a permutation test on $Λ$ (i.e. directly on the likelihood ratio), and so still have an exact test even if the Rayleigh assumption wasn't quite right.
A permutation test is straightforward in two-sample test since under $H_0$ observations are directly exchangeable and gives you an exact test in small samples whether or not it's actually Rayleigh but at the same time it should be asymptotically efficient if it is Rayleigh. Doing a permutation version of a likelihood ratio test is not something you see often – to my surprise given it seems to offer a convenient way to have your cake (good power when your distributional model is right) and eat it too (correct significance level even if it's wrong).
If you're not so worried about small-sample exactness, you can use the chi-squared asymptotic null distribution for $-2\log\Lambda$ from likelihood ratio tests, or when working on a computer, you can just fit either a gamma GLM to the square (with appropriate choice of dispersion parameter in the test), or use parametric survival regression and fit a Weibull (again, with one parameter "known").
If you're not at all confident of the Rayleigh (so it might not be "close"), maybe consider a Wilcoxon-Mann-Whitney. If you're nevertheless interested in an interval for the change in the ratio of scales, there's always the possibility of taking logs and getting an interval the shift of the log (which good WMW implementations will give you) and back out interval for the ratio from that.
There's many other things that could be done, but I think these points cover the main things I'd worry about in practice.

Summary
If you're confident it's really Rayleigh, and the sample sizes are very  similar or at least not small, use the ratios of the means  of the squared data in an F test ($F=\frac{\overline{x^2}}{\overline{y^2}}$) with $2n_x$ and $2n_y$ df.
Note also that there's additional details on this in an answer to this followup question: What is a likelihood ratio test for a specific distribution, and how does it related to hypothesis tests?

Quick bit of R code for the plot:
n1=8; n2=12
nsim=100000

res=replicate(nsim, {
  x=rexp(n1); y=rexp(n2)
  mx=mean(x); my=mean(y)
  m0=mean(c(x,y))
  # Log likelihood of these samples under null hypothesis of equal means:
  logL0 = sum(dexp(c(x,y), 1/m0, log=TRUE))
  # Log-likelihood of these samples under the alternative hypothesis of different means:
  logL1 = sum(dexp(x, 1/mx, log=TRUE)) + sum(dexp(y, 1/my, log=TRUE))
  # Log-likelihood ratio and F-statistic for this simulation:
  c(logLam=logL0-logL1, F=mx/my)
 })

between = function(x,v) ((x>v[1])&(x<v[2]))
FC = qf(c(.025,.975), n1*2, n2*2)  # F-test critical values
plot(res[2,],exp(res[1,]),col=2-between(res[2,],FC),xlab="F",ylab="LR",pch=16,cex=.1)
q=quantile(exp(res[1,]),p=.05)  # estimate 5% point of LR under H0
abline(h=q,col=4,lty=2)

feetwet (the OP) suggested (via an edit) adding the following Python code. I have accepted the edit, but I HAVE NOT CHECKED THIS CODE, so please keep that in mind.
Same in Python:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import expon, f
n1 = 8
n2 = 12
nsim = 100_000
L = np.zeros(nsim)  # Likelihood ratio
F = np.zeros(nsim)  # F-statistic (ratio of sample means)
for i in range(nsim):
    x = np.random.exponential(size=n1)
    y = np.random.exponential(size=n2)
    mx = np.mean(x)
    my = np.mean(y)
    m0 = np.mean(np.concatenate((x, y)))
    # Likelihood of these samples under null hypothesis of equal means:
    L0 = np.prod(expon.pdf(np.concatenate((x, y)), scale=m0))
    # Likelihood of these samples under the alternative hypothesis of different means:
    L1 = np.prod(expon.pdf(x, scale=mx)) * np.prod(expon.pdf(y, scale=my))
    L[i] = L0 / L1  # Likelihood ratio for this simulation
    F[i] = mx / my  # F statistic for this simulation:
FC = f.ppf([0.025, 0.975], n1*2, n2*2)  # 95% confidence region for F-test
plt.scatter(F, L, c=['k' if FC[0] < x < FC[1] else 'r' for x in F], s=0.1)
plt.xlabel('F')
plt.ylabel('LR')
plt.axhline(y=np.quantile(L, q=0.05), color='b', linestyle='--')  # 5% critical value for LRT
plt.show()

Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/150020/discussion-between-feetwet-and-glen-b).

Hypothesis tests for Rayleigh variables


EclipseLink concurrency exception

Question: When looking through some logs after a glassfish server was being unresponsive, I came upon this error :
{{[#|2016-06-02T08:37:51.737+0200|WARNING|oracle-
glassfish3.1.2|org.restlet.Component.ServiceDispatcher|_ThreadID=165;_ThreadName=http-thread-pool-37860(5);|Exception or error caught in status service
javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5236)
at com.sun.ejb.containers.BaseContainer.checkExceptionNoTx(BaseContainer.java:5065)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4900)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2046)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1995)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at com.sun.proxy.$Proxy228.getKpiValuesFlat(Unknown Source)
at com.business.renderer.TopSuppliers.getData(TopSuppliers.java:174)
at com.business.renderer.TopSuppliers.getDataAsJSONTopSuppliers.java:179)
at com.business.renderer.TopSuppliers.render(TopSuppliers.java:107)
at com.ui.renderer.engine.AbstractRenderingEngine.render(AbstractRenderingEngine.java:140)
at com.services.filter.ContainerAdapter.represent(ContainerAdapter.java:311)
at org.restlet.resource.Resource.getRepresentation(Resource.java:259)
at org.restlet.resource.Resource.handleGet(Resource.java:425)
at org.restlet.resource.Finder.handle(Finder.java:470)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Router.doHandle(Router.java:497)
at org.restlet.routing.Router.handle(Router.java:737)
at com.servlets.ServiceDispatcher$1.handle(ServiceDispatcher.java:55)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:151)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.engine.ChainHelper.handle(ChainHelper.java:111)
at org.restlet.engine.application.ApplicationHelper.handle(ApplicationHelper.java:72)
at org.restlet.Application.handle(Application.java:388)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Router.doHandle(Router.java:497)
at org.restlet.routing.Router.handle(Router.java:737)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.routing.Router.doHandle(Router.java:497)
at org.restlet.routing.Router.handle(Router.java:737)
at org.restlet.routing.Filter.doHandle(Filter.java:156)
at org.restlet.routing.Filter.handle(Filter.java:203)
at org.restlet.engine.ChainHelper.handle(ChainHelper.java:111)
at org.restlet.Component.handle(Component.java:387)
at org.restlet.Server.handle(Server.java:488)
at org.restlet.engine.ServerHelper.handle(ServerHelper.java:71)
at org.restlet.engine.http.HttpServerHelper.handle(HttpServerHelper.java:150)
at org.restlet.ext.servlet.ServerServlet.service(ServerServlet.java:1037)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1554)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:339)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.jamonapi.JAMonFilter.doFilter(JAMonFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:278)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:334)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:230)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:311)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:189)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:850)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:747)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1032)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:231)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:745)
Caused by: Exception [EclipseLink-2004] (Eclipse Persistence Services - 2.3.4.v20151027-346465e): org.eclipse.persistence.exceptions.ConcurrencyException
Exception Description: A signal was attempted before wait() on ConcurrencyManager. This normally means that an attempt was made to
commit or rollback a transaction before it was started, or to rollback a transaction twice.
at org.eclipse.persistence.exceptions.ConcurrencyException.signalAttemptedBeforeWait(ConcurrencyException.java:84)
at org.eclipse.persistence.internal.helper.ConcurrencyManager.releaseReadLock(ConcurrencyManager.java:489)
at org.eclipse.persistence.internal.identitymaps.CacheKey.releaseReadLock(CacheKey.java:386)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.cloneAndRegisterObject(UnitOfWorkImpl.java:1018)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.cloneAndRegisterObject(UnitOfWorkImpl.java:929)
at org.eclipse.persistence.internal.sessions.UnitOfWorkIdentityMapAccessor.getAndCloneCacheKeyFromParent(UnitOfWorkIdentityMapAccessor.java:181)
at org.eclipse.persistence.internal.sessions.UnitOfWorkIdentityMapAccessor.getFromIdentityMap(UnitOfWorkIdentityMapAccessor.java:120)
at org.eclipse.persistence.internal.sessions.IdentityMapAccessor.getFromIdentityMap(IdentityMapAccessor.java:380)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerExistingObject(UnitOfWorkImpl.java:3899)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerExistingObject(UnitOfWorkImpl.java:3854)
at org.eclipse.persistence.mappings.CollectionMapping.buildElementUnitOfWorkClone(CollectionMapping.java:267)
at org.eclipse.persistence.mappings.CollectionMapping.buildElementClone(CollectionMapping.java:279)
at org.eclipse.persistence.internal.queries.ContainerPolicy.addNextValueFromIteratorInto(ContainerPolicy.java:213)
at org.eclipse.persistence.mappings.CollectionMapping.buildCloneForPartObject(CollectionMapping.java:205)
at org.eclipse.persistence.internal.indirection.UnitOfWorkQueryValueHolder.buildCloneFor(UnitOfWorkQueryValueHolder.java:51)
at org.eclipse.persistence.internal.indirection.UnitOfWorkValueHolder.instantiateImpl(UnitOfWorkValueHolder.java:161)
at org.eclipse.persistence.internal.indirection.UnitOfWorkValueHolder.instantiate(UnitOfWorkValueHolder.java:222)
at org.eclipse.persistence.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:88)
at org.eclipse.persistence.indirection.IndirectList.buildDelegate(IndirectList.java:244)
at org.eclipse.persistence.indirection.IndirectList.getDelegate(IndirectList.java:414)
at org.eclipse.persistence.indirection.IndirectList$1.<init>(IndirectList.java:542)
at org.eclipse.persistence.indirection.IndirectList.listIterator(IndirectList.java:541)
at org.eclipse.persistence.indirection.IndirectList.iterator(IndirectList.java:505)
at com.business.frontend.facade.impl.FrontEndBFBean.combineAllContainerKpis(FrontEndBFBean.java:515)
at com.business.frontend.facade.impl.FrontEndBFBean.getKpiValuesFlat(FrontEndBFBean.java:405)
at sun.reflect.GeneratedMethodAccessor237.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5409)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.GeneratedMethodAccessor170.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5381)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5369)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
... 75 more

On further inspection I notised the lines :
_ThreadID=165;_ThreadName=http-thread-pool-37860(5);

and
Exception [EclipseLink-2004] (Eclipse Persistence Services - 2.3.4.v20151027-346465e)

My initial thought were that that the HTTP thread timeouted waiting for the DB call to complete, and then the HTTP thread interrupted the EclipseLink leaving  behind a ConcurrencyManager in an unexpected state (with a DeferredLock not in fact released after use). I made a small app, testing my hypothesis by tweking the server settings and making long calls to the DB and terminating the http call before the DB call was ready, but this doesn't seem to reproduce the problem.  There is also the fact that the method called when the exception occurs does not use any kind of JPA(ORM), the call uses JDBC. Most of the application uses EclipseLink and JPA, but not this part. Also it is not uncommon for the application to be under heavy database usage.
So I was thinking, what can be the reason behind this error appart from the descriptive (This normally means that an attempt was made to
commit or rollback a transaction before it was started, or to rollback a transaction twice), I'm pretty sure the code is not doing such a thing.
So it must be some lazy loading conflict, but I have no idea what conditions can cause this problem.
I have no idea where to investigate from this point forward. Any ideas are well welcomed :)
Comment: The error is coming from JPA - you are triggering a lazy relationship on an entity read in from an EntityManager.  This triggers it to re-use the context the entity was read from to fetch the data, and gives you this exception.  Check your FrontEndBFBean to see how it is reading in the data it is using in the combineAllContainerKpis method - you might want  to use a fetch join over this relationship so that it is eagerly fetched.  You might also be using this data in a multithreaded environment - EM and the fetched entities are not really thread safe.
Comment: @Chris That seems to be the rational problem, because there is lazy loading there. Could you be more specific about how the lazy loading triggers the 'A signal was attempted before wait() on ConcurrencyManager' error. I can't figure out why some some simple reading (there is no writing) triggers such an error.  Also `FrontEndBFBean` is just a staless bean, so the container handles two invocations of methods on the bean at the same time on separate instances.

You can post it as an answer so I can mark it as the correct one.
Comment: @Chris 'This triggers it to re-use the context the entity was read from to fetch the data, and gives you this exception.' Could you clarify this ? Thank you :)
Comment: The EntityManager is not concurrent, and entities read from it should not be shared among threads.  What those threads are actually doing to get this exception I can't say - the EntityManager is meant to be a transactional context, so that is likely the reason for the wording of the exception.  The original thread may have read in these entities within a transaction, and that transaction handling may have interfered with this thread's attempts at reading.  I can only guess though until you trace where this object was read from.
Comment: @Chris Thanks. Can you post this as an answer so I can reward you the bounty.
Answer: In this error case, the exact reason for the concurrency exception isn't known - we can only see the one thread accessing the context, by triggering a lazy relationship on an entity. How this entity was read in and what happened in other threads that might also be using this EntityManager the entity was read from (directly or indirectly by accessing entities read from it) requires tracking down, but can usually be avoided.
EntityManagers are not meant to be accessed by multiple threads, and so do not handle concurrent access.  Entities read in from EntityManagers have many hooks to the context they were read from; these hooks allow for lazy relationships, change tracking etc to occur transparent to the application. This has the consequence though that these entities too cannot be concurrently accessed - they should not be cached or passed around by the application without careful consideration.  In many cases, applications might be better off letting JPA handle caching, and access entities as needed from a context.

EclipseLink concurrency exception


Data leakage when using walk forward optimization

Question: I am setting up a neural network that will predict the incoming customers at a store for the next seven days (the output is a list with seven numbers, one for each day). As input, I will give the neural network the last x weeks of data. The data contains the number of visitors for each day and information about that date, like what day it was (Monday, Tuesday, etc.). The optimal x has yet to be determined.
I split the data in a training- (80%) and testset (20%).
For training the neural network I am now using walk forward optimization where I take the first x weeks of the trainingset as input and use the next seven days after that as output. This is one input-output pair. For the next pair, I move the window one day. The input loses the first day, but gains the first day of the output of the previous pair. The output gains a whole new day. I hope the picture clarifies what I am talking about.
.
I wonder if this method will cause data-leakage, since I am giving the neural network output that it has already seen, one input-output pair before. I guess this would be solved by shifting the pairs by seven days instead of one, but this leaves me with very little data to train on. Keep in mind that I use this method for training the network. When testing the method, I am using data that the neural network has never seen before.
Comment: What you have written doesn't seem to align with the diagram provided. Could you clarify what is meant by "When testing the method, I am using data that the neural network has never seen before" as the diagram seems to show that the testing set in the top row is contained in the training set in the second row.
Comment: Yeah the diagram doesn't represent what I am doing exactly, my bad. In the diagram it says "training set" while for me it should say "input for training". "Testing set" should be "output for training". Also, in my case I am not moving the window with the size of the "output for training"-set, but with one day.

I hope this also clarifies what I mean with "When testing the method, I am using data that the neural network has never seen before". When the network is done training the way I just described, I test with the test-set (last 20% of the original data).
Answer: Your approach seems perfectly valid. Since you don't train your model on future data reserved for testing you avoid the problem of look-ahead bias.
You don't have to shift your training window forward by the seven days covered by your test period because even when you walk forward by only one day you are not using any future observations for training and constructing the forecast (apart from deterministic features such as day of week etc.).
A nice description of this procedure (also known as time series cross-validation) is given in the blog post Cross-validation for time series by Robert Hyndman.


How to simulate data for an interaction?

Question: I'd like to simulate data for an interaction / moderation with a continuous exposure and outcome and binary moderator. For example, for the association between X and Y to be 0.1 when moderator = 0 and 0.2 when moderator = 1. This seems very simple but for some reason I'm struggling to do this in R.
Any help would be much appreciated.
Answer: I see it as a question of how to generate data from a (linear?) model with interaction. See below for the R code where y is the response, x is the covariate and z is the binary moderator.
set.seed(12)

n <-  1000
# simulate a covariate
x <- rnorm(n)

# simualte a binary moderator
z <- sample(c(0,1),size = n, replace = T)
beta0 <- 1
beta1 <- 2
sigma0 <- 1

# mu
mu <- beta0 + beta1*z + 0.1*x*z + 0.1*x

y <- rnorm(n, mu, sigma0)
dd <- data.frame(y=y, x=x, z=z)
summary(lm(y~x*z, data = dd))
Call:
lm(formula = y ~ x * z, data = dd)

Residuals:
     Min       1Q   Median       3Q      Max
-3.11036 -0.63836 -0.00177  0.64706  3.00070

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.98525    0.04612  21.364  < 2e-16 ***
x            0.15460    0.04985   3.101  0.00198 **
z            2.02830    0.06320  32.092  < 2e-16 ***
x:z          0.04727    0.06632   0.713  0.47615
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.9966 on 996 degrees of freedom
Multiple R-squared:  0.5137,    Adjusted R-squared:  0.5123
F-statistic: 350.7 on 3 and 996 DF,  p-value: < 2.2e-16

Comment: [Here](https://gist.github.com/galenseilis/c37d74a82dd2721b96fd7edb73ed7c73) is a Python gist performing a similar simulation.


Why is percentage change as an outcome variable not appropriate in regression?

Question: I have the task of building a linear regression model. I have some baseline measures, including pre-treatment clinical scale, and would like my response variable to be the change in clinical scale scores. Based on some resources I came across:

https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/1471-2288-1-6
http://hbiostat.org/doc/bbr.pdf

it seems as though I should have the post-treatment scale score as the response variable, while including the pre-treatment scale score as a covariate.
However, I am wondering why can't percentage change be used as the response variable beyond poor power as spoken about in the Vickers paper.
Any references on this would be greatly appreciated as well.
Comment: Percentage changes are routinely used as response variables in other domains, e.g. economics and finance. So it must be something related to the domain of research
Comment: I am asking if there are any strict violations in the context of regression modelling that come from using percentage change as the response variable? The Vickers resource focuses on power, and the Harrell arguments against seem focused on when there are multiple time points (I have only 2: baseline and post-treatment). I am curious if there are other arguments to be made against percentage change being used.
Comment: I don't understand the question; in what way are the references you provide insufficient to answer your questions?
Answer: If you think of the before and after measurements made on subjects, they are two separate observations made at different times - which are correlated.  Instead of the delta as the outcome, one option would be to use the baseline values as a predictor in the regression model to "adjust" for baseline effect, and then use the follow-up values as the outcome dependent variable.  In this fashion, the baseline value would be "controlled for."
I would analyze the repeated measures, i.e., longitudinal data, using something like GEE regression (generalized estimating equations) for longitudinal data analysis.  Here, you stack multiple observations for subjects in "long format" like:

where in your data you only have e.g. baseline values at months=0, and say the 3-month values.  When running GEE, you have to first specify that ID is the cluster (subject) variable, and month is the time variable.  Then, regress score on months, and if months is significant and the regression coefficient is positive the mean values (delta) for score were significantly greater at 3 months.  Vice versa for significantly lower at 3 months.  If there is a treatment variable (0-placebo, 1-treatment), you would regress score on trt(0,1), months, and an interaction term for trt*months.  If the interaction term was significantly positive, then scores were significantly greater among the treated at 3 months compared to placebo.
The main reason why I got away from delta used as an outcome variable is because:

A delta implies 2 repeated measurements on the same subject
Repeated measurements are correlated
Correlated (repeated) measurements as an outcome can be analyzed using a variety of longitudinal regression approaches (GLM-mixed, GEE, etc. )
Answer: I don't see any major violations of a regression model when using percentage change as an endpoint.  I think the ultimate reason for choosing one of these endpoints over another should be interpretation.
As user0123456789 demonstrated (+1), a common approach particularly in clinical drug development is to model the post-baseline measurements longitudinally.  This allows for the comparison of the mean endpoint between treatments at each time point, i.e. the average disease activity score at week 52 when treated with the active therapy is 20 units lower than when treated with placebo.  Without the luxury of randomization one might be interested in adjusting for the baseline measurement.
If percentage change is the endpoint this allows for the comparison of mean percentage change in the endpoint between treatments at each time point.  For the purposes of comparative effectiveness this works just fine.  For the purposes of providing an interpretable treatment effect, it is not very helpful, i.e. the average percentage change in disease activity score at week 52 when treated with the active therapy is 30 percentage change points lower than when treated with placebo.  Here we are not comparing mean scores between groups, we are comparing mean rates of change between groups.
There are other options such as modeling change from baseline in clinical score or modeling the clinical score longitudinally with baseline scores as a dependent variable.  These approaches allow for the comparison between treatments of mean differences, but can lead to slightly different results depending on missing data.


How to interperet calculus thing

Question: I have $\nabla \times (f\mathbb{F})$ where $f$ is a twice continuously differentiable scalar field and $\mathbb{F}$ is a twice continuously differentiable vector field.
Is it right to interpret $f$ as $ax+by+cz$ where $a,b,c\in \mathbb{R}^3$ and $\mathbb{F}$ as $(\alpha,\beta,\gamma)\in\mathbb{R}^3$
Hence $\nabla \times (f\mathbb{F}) = \nabla \times (\alpha fi+\beta fj + \gamma f k) $?
Not sure how to treat the form of any of these three, or how the operators will apply.
Comment: This is an interpretation, but there could be many more... twice differentiable does not mean that the second derivative must be zero..
Answer: No, it is not. You have to use a general interpretation as $f(x,y,z)$ twice continuously differentiable. Your interpretation assumes that $f$ is a linear functional, putting a strong unnecessary restriction.
If $$\overrightarrow{F} = P(x,y,z) \overrightarrow{i} + Q(x,y,z) \overrightarrow{j} + R(x,y,z) \overrightarrow{k}$$ then $$f \cdot \overrightarrow{F} = f(x,y,z) P(x,y,z) \overrightarrow{i} + f(x,y,z) Q(x,y,z) \overrightarrow{j} + f(x,y,z) R(x,y,z) \overrightarrow{k}.$$
I've explicitly written all dependences. In order to make sense of $\nabla \times (f \overrightarrow{F})$, think of the following:

Your operation has to return a vector.
You have to apply a differential operation to $f$ and $\overrightarrow{F}$ while combining them to result in a vector.
What differential operator can you apply to $f$ to turn it into a vector?
What differential operator can you apply to $\overrightarrow{F}$ while keeping it a vector?
What kind of product can you have between $f, \overrightarrow{F}$ and their transformations and resulting in vectors?
Notice that you are applying a differential operator in a product, therefore you should apply a product rule. What should it look like?

How to interperet calculus thing


Removing Unwanted Characters from String

Question: Little bit of backstory:
I am reading a SAV file into R using read_sav() from haven. I am taking the labels found in the SAV file (accessed by attr(sav_file, "label")). I would like to use these section labels as headers in a Latex document.
Here's the issue: Latex does not accept certain characters. Rendering rMarkdown produces the error "Package inputenc Error: Unicode char € (U+80)
(inputenc) not set up for use with LaTeX."
Here's a small string sample that's causing the problem and examples of some of things I have tried:
unencoded_string <- "following statement? "Tourism is good"

Others have fixed this problem using methods like:
Encoding(unencoded_string) <- "UTF-8"

and
iconv(unencoded_string, to = "UTF-8")

These function calls result in removing bits of the unwanted characters, but I am still left with characters I do not want:
"following statement? "Tourism is good"
Other regular expression methods do not work.
Does anyone have something that might help, or point me in the right direction? I've run into this kind of problem before, but have always found a work-around.
Comment: You can take a look [here](http://stackoverflow.com/questions/2124010/grep-regex-to-match-non-ascii-characters) on how to remove non-ASCII characters.
Answer: It seems to work. Try this
txt = "following statement? "Tourism is good"
gsub("[^\\x00-\\x7F]+", "",txt, perl = TRUE)

> gsub("[^\\x00-\\x7F]+", "",txt, perl = TRUE)
[1] "following statement? Tourism is good"

Comment: @jonathande4 check out hackerrank's regex course. It goes into a lot of detail and is very easy to follow.
Comment: This worked beautifully! Thank you. But I don't really understand the Perl syntax. If you have happen to have any recommended reading on that subject, that would be great.


Getting LCD message through IPMI form Dell Server (Poweredge R710)

Question: I'm exploring the IPMI interface (using ipmitool on ubuntu 11.10, remotely over LAN) and can perform various operations however, I can't view the status message displayed on the LCD.
ipmitool supports delloem lcd subcommands. These subcommands unfortunately primarily only allow me to set data to the lcd, but I can't read from the lcd.
The message currently displayed on the LCD relates to the loss of power redundancy (Dell orange error). For testing purposes I manually removed the redundant power supply and have been trying to read the message.
Any suggestions?
Answer: This may not get you the text off the LCD, but have you tried the chassis and power subcommands?  It's been a while since I had Dell equipment, but I believe one of these has power supply status information.
Alternatively you can install the OpenManage SNMP agent and query this information (and a lot more) via SNMP without having to parse ipmitool's output yourself.
Comment: They do provide power status information, however I am explicitly interested in what the LCD is showing.


True or False: A line is a parabola.

Question: It is known that a line is a degenerate parabola. But if asked as above, what is the better answer?
Context: This question appeared on a quiz recently given in our Precalculus class. It is not clear to me and my classmates if the answer is True or False. Our book says the following.

Comment: @HenryRazon: The textbook *explicitly states* that degenerate cases are included in the classification of second-degree $xy$ polynomials. If the textbook *defines* a conic as the graph of such a polynomial, then the degenerate cases count. Now, if the textbook *defined* conics by other means, then degeneracies may-or-may-not be included for whatever reason. Even then, your instructor may have opted to promote an alternative view, and the quiz may reflect that view. (When I teach, I very often think outside-the-book.) This is really a discussion/debate you should be having with your instructor.
Comment: Almost always. .
Comment: Why not always?
Comment: Where did you get that definition? A parabola is the set of points equidistant from a point (focus) and a line (directrix). What are the focus and directrix of a line?
Comment: All parabola are similar to one another.  And lines are not similar to parabola.  A degenerate parabola is not a parabola.
Comment: @JohnDouma You could take any point on the line as "focus" and the perpendicular through that point as "directrix". But unlike a proper parabola, the "degenerate parabola" has more than one choice of "focus" and "directrix". It also fails to have other properties that all proper parabolas have.
Comment: @JohnDouma, that is exactly what I was thinking. My answer is false because the focus-directrix definition of a parabola will not work for a line. The first sentence in the question above is not really a definition, but is simply a special case.
Comment: @DavidK, can you cite a property of all nondegenerate parabolas that lines do not satisfy?
Comment: I tend to favor "inclusive" definitions, so I'd say: *True, degenerate parabolas are parabolas.* That said, it's perfectly reasonable to have an "exclusive" view; indeed, I suspect that *most* discussions *implicitly assume* it. (When discussing parabolas/circles/triangles/whatever here, I almost-never even think to qualify my remarks as applying only to "non-degenerate" instances. It can be instructive to see what happens when figures degenerate, though.) In any case, anyone who ends such a conversation at "true or false" is doing an intellectual disservice to the topic and the conversers.
Comment: Related: [Is the conjugate axis of a hyperbola itself a trivial hyperbola](https://math.stackexchange.com/q/3292478/409). I have some additional comments there about degeneracy.
Comment: Don't let language define reality.  Let reality define language.
Answer: No, in almost all contexts. Very occasionally you might encounter a family of parabolas one of which is degenerate; then it might be acceptable.
If you have been asked this question, tell us the context.
Answer: The parabola is $y^2=4ax$, if you put $a=0$, it becomes a line $y=0$. So one may say that a line is a parabola whose length of latus-rectum is zero. This is how a parabola degenerates to a line. A line is the thinnest parabola.
Answer: Consider the parabola $~y=a~x^2~$.
All parabolas can be rotated and translated to arrive at this form. Hence this equation covers all possible parabolas in the $2$D plane for the purpose of this problem.
Now, for a straight line to exist, we should be able to find a point where $~\frac{dy}{dx}~$ does not change.
But, $~\frac{dy}{dx}=2ax~$
The derivative is different for all points on the parabola since it is dependent on $~x~$ and there is only one $~y~$ for each $~x~$.
So we can conclude that the statement is false.
**************-
see https://www.quora.com/How-do-you-prove-that-there-are-no-straight-lines-in-a-parabola
Comment: But what if $a=0$?

True or False: A line is a parabola.


Covariance formula

Question: I'm struggling to understand this presentation of covariance. It says:

The variance-covariance matrix (or simply the covariance matrix ) of a random vector $\overline{X}$ is given by:
$$Cov(\overline{X})=E[\overline{X}\overline{X}^T]-E\overline{X}(E\overline{X})^T$$

First of all , what does he/she mean with covariance MATRIX of A VECTOR ? Variance of a vector (covariance with itself) ? But isn't that supposed to be a scalar, not a matrix ?!
Second, if you multiply $\overline{X}$ with $\overline{X}^T$, you get a matrix. How do you get the expected value ($E[\overline{X}\overline{X}^T]$) of that matrix?? It doesn't have multiple layers!!
Then, if you take the expected value ($E\overline{X})$ of $\overline{X}$, it's a scalar! What is the point in multiplying it with its transpose? The transpose of a scalar is itself!
I know that the usual definition of covariance is
$$cov(x.y)=\frac{\sum_{i=1}^{n}(x_i-\overline{x})(y_i-\overline{y})}{N-1}$$
THIS makes perfect sense, but the earlier presentation with expected values and vectors is confusing!
Answer: The expected value of a matrix is defined as the matrix of expected values. Let $\mathbf{M}$ a $p\times q$ matrix, the expectation of $M$ is defined as follows
$$
\mathbb{E}\left[\mathbf{M}\right] = \mathbb{E}\left[M_{i,j}\right]\qquad i\in [1,p], j\in[1,q]
$$
so, for example, you can define the expectation of the sum of two matrices
$$
\begin{align*}
            \mathbb{E}(\mathbf{X}+\mathbf{Y}) &= \mathbb{E}([X_{i,j}]+[Y_{i,j}])\\
&= \mathbb{E}[(X_{i,j}+Y_{i,j})]\\
&= [\mathbb{E}(X_{i,j})+\mathbb{E}(Y_{i,j})]\\
&= [\mathbb{E}(X_{i,j})]+[\mathbb{E}(Y_{i,j})]\\
&= [\mathbb{E}(\mathbf{X})]+[\mathbb{E}(\mathbf{Y})]
\end{align*}
$$
So, since the covariance is defined by the expectation, you can define a covariance also for a vector $\mathbf{X}=[X_1, X_2,\dots, X_n]$ of $n$ jointly distributed random variables $X_i$ (in particular for a vector with itself).
So I think that $Cov(\mathbf{X})$ is a shorthand to write the covariance of two random variable vectors, so $Cov(\mathbf{X})=Cov(\mathbf{X}, \mathbf{X})$.
You can find it by the definition. Let $\mathbf{C}_{\mathbf{X}}$ the covariance matrix
$$
\begin{align*}
            \mathbf{C}_{\mathbf{X}} &= \mathbb{E}\left[(\mathbf{X}-\mathbb{E}\mathbf{X})(\mathbf{X}-\mathbb{E}\mathbf{X})^\top \right] \\
&=\mathbb{E}\left[(\mathbf{X}-\mathbb{E}\mathbf{X})(\mathbf{X}^\top-\mathbb{E}\mathbf{X}^\top) \right]\\
&=\mathbb{E}\left[\mathbf{X}\mathbf{X}^\top\right] - \mathbb{E}\mathbf{X}\mathbb{E}\mathbf{X}^\top- \mathbb{E}\mathbf{X}\mathbb{E}\mathbf{X}^\top+\mathbb{E}\mathbf{X}\mathbb{E}\mathbf{X}^\top\\
&=\mathbb{E}\left[\mathbf{X}\mathbf{X}^\top\right] - \mathbb{E}\mathbf{X}\mathbb{E}\mathbf{X}^\top
\end{align*}
$$
Let me know if it's clear. Hope it will help you.
Bibliography:
Random Vectors
Wikipwdia - Covariance
Comment: Thank you for your response. I think the problem lies in that I dont understand what a random vector is. Am I right that it is something else than a regular vector like [5 8 1]'
Comment: A random vector of size $n$ is a vector composed of $n$ random variables.
So it's not just a regular vector, but a vector where each entry is a stochastic variable, so each entry depends on random events.
You can see it also as an array of functions.
I hope now the term sounds better.
Check the first bibliography link

Covariance formula


MYSQL modeling relationships: Design and UPDATE/DELETE

Question: I am trying to understand relationships fully, and have gone through alot of tutorials. Still i linger on a few things (using MySQLWORKBENCH):

1. Every user can upload a product
2. Every product can have multiple categories, bids, ratings, etc
3. Every user can have multiple phonenumbers
(there are more, but this is the basic setup)
Is this correct?:
1 - I used a 1:n relationship, since every user can upload multiple products.
2 and 3. I used n:m relationship, since there can be multiple products with multiple categories, bids, ratings, etc.
DELETE/UPDATE:
I used ON UPDATE CASCADE and ON DELETE CASCADE everywhere where there is a foreign key...that being 'product', 'category_tags_has_products', 'bid_price_has_product', 'phone_has_user'.
I tried to delete a product like this (php): mysql_query("DELETE FROM product WHERE id='$id'");
I get a 1054 error, which is a foreign key error.
What are the best practises here? It is to my understanding that i shouldn't need to do deletions in any other than the parent-table?
Thanx!
Answer: The relations look correct.
To find out what is wrong with your query check the <code>$id</code> variable.
Or check the whole query and then run it in the console/phpMyAdmin/etc:
<code>$query = "DELETE FROM product WHERE id='$id'";
var_dump($query);
mysql_query($query);
</code>
P.S.: and don't forget to escape all data got from the users! Like this:
<code>$id = mysql_real_escape_string($_GET['id']);
</code>
Comment: Thanks. But, this still doesn't work. I tried deleting using phpmyadmin, but i get this error:
Comment: #1451 - Cannot delete or update a parent row: a foreign key constraint fails (`databasename`.`category_tags_has_product`, CONSTRAINT `fk_category_tags_has_product_product1` FOREIGN KEY (`product_id`, `product_user_id`) REFERENCES `product` (`id`, `user_id`) ON DELETE NO AC)
Comment: Put `ON UPDATE CASCADE` and `ON DELETE CASCADE` on `category_tags_has_product.product_id`. Currently you seem to have no action for `ON DELETE` and when you are trying to delete the product from the `product` table, the corresponding records stays in the `category_tags_has_product` table and you get error, because the  record in `category_tags_has_product` tries to point to deleted row in the `product` table.
Answer: You have a lot of identifying relationships, which mean that the foreign key form part of the primary key on the second table.  This is not necessary in most instances, and is only really useful in instances such as link tables.
To this end I would change the user->product link to be non-identifying, which will make user_id a Foreign Key instead of being part of the Primary Key.  In workbench the shortcut for a 1:n non-identifying relationship is key '2' (where as '4' is identifying).  This in turn should remove the user_id fields from the tables which product links onto.
When you delete a product, it should cascade to the 3 link tables that it links to.  At present it may be that it is trying to delete from users also depending on how the FK is set up.  The following should cascade deletions (assuming a deletion is permanent and you just want to clear out all linked records)
DELETE FROM product -> deletes from any table with product_id in
DELETE FROM user -> deletes from any table with user_id in
The same applies for phone, rating, bid_price, category_tags.
I hope this if of use, if you need any further pointers feel free to shout :)
Comment: Changed user->product link to non-identifying.
Comment: I am deleting like this:            $query = "DELETE FROM product WHERE id='$id'";
        var_dump($query);
        mysql_query($query);
Comment: I tried deleting directly in phpmyadmin, and it gives me the same error. I randomly delete the record in category_tags_has_product, and then i was able to delete the product! strange. any ideas what i'm doing wrong?
Comment: Can you update the schema diagram attached to the question?  Without the identifying link `user_id` should be out the product PK, and `product_user_id` should no longer be a field in `category_tags_has_products`, `rating_has_products`, and `bid_price_has_product`.  In theory it should function now, else will need further information.  Also you can use `"DELETE FROM product WHERE id = $id"`, because id is numeric you don't need to quote it, quotes are for strings.
Comment: You need to remove the product_user_id PK fields from the link tables still - Workbench isn't good at cleaning up after itself.  Simplest to delete the links + remake them now that the products table is correct + then sync structure changes to the database.
Comment: Updated the diagram. This is really frustrating...cleaned the tables, but still i get the same 1451 error :/


Intercepting when a page is requested

Question: I am trying to call a function every time a page is loaded. With Drupal 7, I used hook_init, now I'm using a subscribed event.
  public function logRegEntry(GetResponseEvent $event) {
    $request = $event->getRequest();
    $method = $request->getMethod();
    $path = $request->getPathInfo();
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (($method == 'GET') && ($path == '/')) {
      // do it just for this module
      \Drupal::service('wdocsDebug')->logSiteEntry();
    }
  }

This works fine for the home page, but I want it for every page a user requests. This is getting called four times; first for the page I'm requestings, and then for:
/admin/coffee/get-data
/history/5/read
/quickedit/attachments
I did notice that on the first request, the $route_name is set to "entity.node.canonical" -- might this be a better way to check for a page? Probably not, since it would only get triggered by node pages.
I'm looking for a better way to do this, not sure why there are four request events. Thanks.
Answer: Your event subscriber is also picking up AJAX requests (e.g. /admin/coffee/get-data is an endpoint the Coffee module uses when it's needed in the client browser) which explains why you're seeing multiple events for a page request.
You can filter out those events with the logic best fits your needs (e.g. a $request->isXmlHttpRequest() call to check for AJAX requests, or a route whitelist as you mentioned).
Comment: Thanks, just what I was looking for.

Intercepting when a page is requested


Possible way to find Username from 1000,000 Users entries

Question: I have Db of 100,000 users in MYSQL.  In that DB i am having column ID,username,Fname,Lname, etc..
When www.example.com/Jim or www.example.com/123 (Where JIM is username and 123 is ID in the users table)
I am using MYSQL query : select * from users where ID = 123 OR username = Jim
I am executing above query in PHP.
Output of the above query is :
| ID | Username | fname  | lname   |
+----+----------+--------+---------+
|123 |   jim    |  Jim   | Jonson  |

My Problem is its taking huge time to select username or ID in the DB.
I have used following query
SELECT * FROMusersUSE INDEX (UsersIndexId) where id=123
Is this right way to call Index ?
EXPLAIN SELECT * FROM  `users` WHERE ID =327

OP
id  select_type  table    type    possible_keys        key      key_len ref rows Extra
1     SIMPLE       users  Const  PRIMARY,UsersIndexId  PRIMARY     4   const

1
Comment: What are your index's ?

Post the output from explain select * from users where ID = 123 OR username = Jim
Comment: Indexing, Caching....there are many ways to improve performance. What have you tried?
Comment: If you dont already have indexes on ID and username I suggest adding them.
Comment: Hmmm I tried nothing .. I am trying search Best possible way to select username
Comment: @StevenFarley Can Link me for indexes ? I am using ID as Index (Primary key)
Comment: @SandeepKamble Take a look at this http://stackoverflow.com/questions/3002605/how-to-add-indexes-to-mysql-tables it will help you to add indexes to your tables.
Comment: You need to decide if the username or the ID was passed and just search on one, not both. Should be easy since your user ID is numeric.
Comment: @MrCode In php code i am obvious searching only one . :)
Answer: I sugest you take a look at this: How MySQL Uses Indexes
Quoting from the first paragraph:

Indexes are used to find rows with specific column values quickly.
  Without an index, MySQL must begin with the first row and then read
  through the entire table to find the relevant rows. The larger the
  table, the more this costs. If the table has an index for the columns
  in question, MySQL can quickly determine the position to seek to in
  the middle of the data file without having to look at all the data. If
  a table has 1,000 rows, this is at least 100 times faster than reading
  sequentially.

That should help speed up your search.
(Edit: Updated the link to a newer version of the SQL docs)
PS: More specifically, column indexes might be what you want.
You can find more info about adding indexes here: Create Index Syntax
Comment: I think i am going to add the Indexes . Thanks for the information .
Answer: To complete @Kjartan answer, you can try the following :
ALTER TABLE users ADD INDEX id_i (`ID`);
ALTER TABLE users ADD INDEX username_i (`Username`);

Your queries should be faster.
Comment: Of course it will take more storage! That is the trade off with indexes - more storage, more overhead to add and change data, but potential for much, much faster retrieval.
Comment: Hmm I think It will take more storage ?
Comment: ID should be PRIMARY KEY or UNIQUE INDEX
Comment: SELECT * FROM `users` USE INDEX (UsersIndexId) where id=123 Is this right way to call it ?
Comment: No need to `USE INDEX`, MySQL will do it automatically. Use `EXPLAIN SELECT * FROM users ...` to see if your indexes are uused by MySQL correctly.


Aproximação de casa decimal em JavaScript

Question: Qual o motivo do comportamento abaixo? Porque não dá 3.3?
Estou executando no console o JavaScript e está retornando esse resultado.
<code>Number(1.1)
1.1

Number(1.1) + Number(1.1)
2.2

Number(1.1) + Number(1.1) + Number(1.1)
3.3000000000000003

Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1)
4.4

Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1)
5.5
</code>
Comment: Qual comportamento?
Comment: O 3.3000000000000003 ao invés de 3,3... @MiguelNeto
Answer: Isto acontece devido a erros de precisão da vírgula flutuante, uma vez que não é possível mapear 1.1 para um valor binário finito. Uma questão semelhante pode ser vista aqui.
Este comportamento pode ser alterado através da função toFixed().
Exemplo:
<code>(1.1 + 1.1 + 1.1).toFixed(2)
</code>
Sendo 2 o número de casas decimais.
Answer: Number é uma função javascript que Converte a string num valor ponto flutuante
Veja que dentro do parenteses tem .(ponto), então a string dentro do parenteses é convertida para ponto flutuante.


FTP passive mode connection refused

Question: I'm creating an ftp client and I have a problem.
First, I create a socket where I sent USER and PASS then PASV a receive IP and PORT and then create a second data socket and try to connect, but there is a problem.
It will connect 5 times of 6, but on the 6th time I got error 111 Connection Refused and I have no idea how to fix this.
Answer: The response text to PASV does not have a standardized format (EPSV does, though), so make sure you are parsing the IP/Port correctly, as you may receive one of many different formats used by real-world servers:
227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
227 Entering Passive Mode (h1,h2,h3,h4,p1,p2
227 Entering Passive Mode. h1,h2,h3,h4,p1,p2
227 =h1,h2,h3,h4,p1,p2

Just to show a few possibilities.
If you are parsing the IP/Port correctly and still not able to connect, then either the server has too many client connections on the IP/Port and ran out of available slots for you to connect to, or else the IP/Port is being blocked by a firewall/router that the server does not know about when it reported the IP/Port to you.
Unfortunately, a connection refused error does not offer any way to differentiate between those conditions, so all you can do is attempt to connect a few times before failing the transfer, or else send an ABOR to inform the server to close the current passive IP/Port and then send a new PASV to get a new IP/Port.
Comment: Im parsing correctly, because it will connect sometimes. Anyway Ill try that ABOR.

FTP passive mode connection refused


Backpropagation through time: dimensions in the chain rule

Question: Take the first step $t=1$ for simplicity,
\begin{align}
h_1 &= \text{tanh}(W_{hx}^T e_1 + W_{hh}^T h_0)
\end{align}
Usually it is written in convention:
\begin{align}
\frac{\partial L_1}{\partial W_{hx}} &= \frac{\partial h_1}{\partial W_{hx}} \frac{\partial L_1}{\partial h_1}
\end{align}
where $e_1$ is the first-step input of shape $(n_i,1)$, $W_{hx}$ is the input-to-hidden matrix of shape $(n_i, n_h)$, $W_{hh}$ the hidden-to-hidden matrix of shape $(n_h, n_h)$.

$L_1$ is the first-step cross-entropy scalar, $h_1$ is the hidden state of shape $(n_h,1)$.
It can also be expressed as
\begin{align}
\frac{\partial L_1}{\partial W_{hx}} &= \sum_{i=1}^{n_h} \frac{\partial h_1^i}{\partial W_{hx}} \frac{\partial L_1}{\partial h_1^i}
\end{align}
where $h_1^i$ is the $i$-th unit in vector $h_1$. On the RHS each term is a $(n_i, n_h)$ matrix multiplied by a scalar $\frac{\partial L_1}{\partial h_1^i}$.
$\frac{\partial L_1}{\partial W_{hx}} $ should have the same shape as the weight matrix, thus $(n_i, n_h)$.
$\frac{\partial L_1}{\partial h_1}$ as I understand has the same shape as $h_1$, thus $(n_h,1)$.

In particular the dimension of $\frac{\partial h_1}{\partial W_{hx}}$ is confusing.
The term $\frac{\partial h_1^i}{\partial W_{hx}} $ seems to be an element in the Kronecker product $\frac{\partial h_1}{\partial W_{hx}} $. I would like some help sorting out this term.

My attempt:
Let $f= W_{hx}^T e_1$.
\begin{align}
f &= I_{n_h} W_{hx}^T e_1 \\
&= (e_1^T \otimes I_{n_h}) \text{vec}(W_{hx}^T) \\
&= (e_1^T \otimes I_{n_h}) w \\
\frac{\partial f}{\partial w} &= e_1^T \otimes I_{n_h}
\end{align}
Then
\begin{align}
\frac{\partial h_1}{\partial w} &= (e_1^T \otimes I_{n_h}) \text{ diag}( 1- h_1^2)
\end{align}
where $a_1 = W_{hx}^T e_1 + W_{hh}^T h_0 $.
But the problems with this are:

This is $\frac{\partial h_1}{\partial \text{ vec}(W_{hx})}$, not $\frac{\partial h_1}{\partial W_{hx}}$.

How do I understand $e_1^T \otimes I_{n_h}$?
Comment: Your last expression is correct
Comment: In your edit, why did you introduce $h_1^T$ in the chain rule, instead of $h_1$?
Answer: The first multiplicand in the chain rule is a vector derivative by a matrix, which is a 3D tensor, and its product is not well defined. This situation is usually resolved by flattening the matrices and reformulating the equations using Kronecker products as you did in the second part of your post, or the derivatives are expressed in an element-wise fashion, then combined together.
From your equations, it can be deduced that you've chosen denominator layout. In this layout, the following derivative is $$\frac{\partial (Ax)}{\partial x}=A^T$$
so, it's not $A$, (see here), which means
$$
\begin{align}
\frac{\partial h_1}{\partial w} &= (e_1^T \otimes I_{n_h})^T \text{diag}( 1- h_1^2)\\&= (e_1 \otimes I_{n_h})\text{diag}( 1- h_1^2)
\end{align}
$$
This equation is consistent with the inner dimensions, unlike the version in your post. When multiplied with ${{\partial L}\over{\partial h_1}}$, this corresponds to the same formula as the summation you've included, just a reshaped version.
If matrix equations is chosen, the derivative should be reshaped back into its original form (i.e. de-vec operation).


Continued fractions

Question: I'd really love with concluding that for given integers $a_0,a_1,...a_N$ with $a_i>0$ for $i>0$, representing the continued fraction $[a_0; a_1,....,a_N]$, with the following recursion:
$p_{-1}=1, q_{-1}=0, p_o=a_0, q_o=1, p_s=a_sp_{s-1}+p_{s-2}, q_{s}=a_sq_{s-1}+q_{s-2}$
we can get that $[a_0; a_1,....,a_N]=\frac{p_s}{q_s}$.
I tried to do that with induction, the basic step for $s=0$ is trivial, assuming that it is correct for $n$ , how do I prove it for $n+1$? I tried to use the data that was given, but I'm not sure how.
Thank you very much
Comment: +1 This is a very pertinent question, which I find very little addressed in texts about continued fractions: if you want to compute successive convergents, you can do this with minimal calculation passing from one approximation to the next, without having to re-evaluate to continued fraction from the inside out at one level deeper. I'd have to think a bit for the right formula; I'm not sure it's the one you give (try and show some examples please). Careful study of the Stern-Brocot tree is the key.
Comment: [Related...](http://math.stackexchange.com/questions/61785)
Answer: I think the easiest approach to this question is to associate to each finite continued fraction symbol $[a_0; a_1,....,a_N]$ not just a rational number, but a $2\times 2$ matrix with natural number entries, namely the matrix product
$$
  M(a_0,a_1,....,a_N)=
\pmatrix{a_0&1\\1&0} \cdot \pmatrix{a_1&1\\1&0} \cdots \pmatrix{a_N&1\\1&0}
$$
The first column of this matrix (its value when applied to $\tbinom10$) gives numerator and denominator of the value of the continued fraction $\alpha=[a_0; a_1,....,a_N]$, as follows from the definition of continued fractions by an immediate induction on $N$. But the matrix gives more information about the position of $\alpha$ in the Stern-Brocot tree, or more precisely that of its descendant $\alpha'=[a_0; a_1,....,a_N,1]$ "continuing in the same direction" (which serves as starting point for continued fractions that start with $[a_0; a_1,....,a_N,\ldots]~$). The sum of the columns of $M(a_0,a_1,....,a_N)$ (its value on $\tbinom11$) gives the numerator and denominator of $\alpha'$, while the second column (its value on $\tbinom01$) gives the closest ancestor of $\alpha'$ at the opposite side  with respect to $\alpha$, which is also (if $N>0$) the previous convergent $\beta=[a_0; a_1,....,a_{N-1}]~$.
Personally I think these matrices are the most useful objects to work with; lots of stuff is easy in terms of them, for instance the fact that their determinant is $(-1)^{N+1}$ is immediate from the definition. Also descending to a next convergent needs just one previous matrix, and involves a simple right multiplication. From this one can easily deduce a recurrence formula of order $2$ for the convergents in reduced form. Indeed if these convergents are $\frac{p_i}{q_i}$ in reduced form as in the question, then by the above description
$$
  M(a_0,a_1,....,a_{s-1})=\pmatrix{p_{s-1}&p_{s-2}\\q_{s-1}&q_{s-2}}
$$
for $s\geq2$, and
$$
  M(a_0,a_1,....,a_{s-1},a_s)=\pmatrix{p_s&p_{s-1}\\q_s&q_{s-1}}
  = M(a_0,a_1,....,a_{s-1})\cdot \pmatrix{a_s&1\\1&0}
$$
from which one easily deduces $p_s=p_{s-1}a_s+p_{s-2}$ and $q_s=q_{s-1}a_s+q_{s-2}$.
Answer: Check pp. 4–5 in Khinchin's book
(in Google Books).

Continued fractions


NUSOAP - WSDL STYLE DOCUMENT/LITERAL

Question: Atualmente possuo 2 webservices rodando em hospitais que funcionam perfeitamente com o STYLE RPC/ENCODED porém vamos implementar em um software para uma fabrica e lá eles tem problema para consumir esse tipo de serviço.
Acontece que ao mudar para DOCUMENT/LITERAL simplesmente não acontece nada, não tem nada no cabeçalho de envio e nem no de retorno. Já tentei utilizar o soapUI porém ele só fala que tem um erro no WSDL e continua em branco.
Depois de muito pesquisar cheguei a conclusão de que ele não aceitava um complexType com a SOAP-REF:arrayType que é onde posso utilizar de array associativos.
Também depois de muita pesquisa achei esse tópico: http://www.ibm.com/developerworks/library/ws-whichwsdl/#listing6
que mostra uma estrutura WSDL com style DOCUMENT/LITERAL e a diferença para o meu estruturado hoje é que eu não consigo encapsular o element do modo que é feito no exemplo:
<element name="myMethod">
            <complexType>
                <sequence>
                    <element name="x" type="xsd:int"/>
                    <element name="y" type="xsd:float"/>
                </sequence>
            </complexType>
        </element>
        <element name="myMethodResponse">
            <complexType/>
        </element>

O que eu consigo fazer é criar complexType e referenciar no element mais ou menos desse modo:
<element name='Pedido' type='tns:LayoutPedido' />
<complexType name='layoutPedido'>
<all:sequence>
<element name='id' type='xsd:string' />
</all:sequence>
</complextType>

o que não sei dizer se esta atrapalhando a leitura do mesmo.
Desculpe não poder postar o WSDL original.
Comment: e porque nao pode postar o WSDL original?
Answer: O pessoal que não queria liberar ai como vai ficar intranet eu consegui pegar o arquivo.
Segue:
<?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:Integrate" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:Integrate">
<types>
<xsd:schema elementFormDefault="qualified" targetNamespace="urn:Integrate"
>
 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
 <xsd:complexType name="itemLayoutStruct">
  <xsd:sequence>
   <xsd:element name="itemLayoutArrayElement" type="tns:itemLayoutArray" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
 </xsd:complexType>
 <xsd:complexType name="itemLayoutArray">
  <xsd:sequence>
   <xsd:element name="coditem" type="xsd:string" minOccurs="0"/>
   <xsd:element name="descitem" type="xsd:string" minOccurs="0"/>
   <xsd:element name="unidade" type="xsd:string" minOccurs="0"/>
   <xsd:element name="dtinclusao" type="xsd:string" minOccurs="0"/>
   <xsd:element name="dtalteracao" type="xsd:string" minOccurs="0"/>
   <xsd:element name="nomeabrev" type="xsd:string" minOccurs="0"/>
   <xsd:element name="descfornec" type="xsd:string" minOccurs="0"/>
   <xsd:element name="status1" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="status2" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="status3" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="origem" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="stintegr" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="gramatura" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="largura" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="comprimento" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="compxlarg" type="xsd:string" minOccurs="0"/>
   <xsd:element name="pesoliq" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="cor" type="xsd:string" minOccurs="0"/>
   <xsd:element name="prodlinhadagua" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="tipo" type="xsd:string" minOccurs="0"/>
   <xsd:element name="segmento" type="xsd:string" minOccurs="0"/>
   <xsd:element name="grupoprod" type="xsd:string" minOccurs="0"/>
   <xsd:element name="caracteristica" type="xsd:string" minOccurs="0"/>
   <xsd:element name="fabricante" type="xsd:string" minOccurs="0"/>
   <xsd:element name="agrupgtplan" type="xsd:string" minOccurs="0"/>
   <xsd:element name="fabricanteERP" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="nrfolha" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="nisuzano" type="xsd:string" minOccurs="0"/>
   <xsd:element name="tubete" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="codagrup1" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup2" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup3" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup4" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup5" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup6" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup7" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup8" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup9" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup10" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup11" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codagrup12" type="xsd:string" minOccurs="0"/>
   <xsd:element name="codfornec" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="familia" type="xsd:string" minOccurs="0"/>
   <xsd:element name="famcomer" type="xsd:string" minOccurs="0"/>
   <xsd:element name="grestoque" type="xsd:string" minOccurs="0"/>
   <xsd:element name="depositopad" type="xsd:string" minOccurs="0"/>
   <xsd:element name="fator_conversao" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="codemitente" type="xsd:decimal" minOccurs="0"/>
   <xsd:element name="embalagem" type="xsd:string" minOccurs="0"/>
   <xsd:element name="pesobruto" type="xsd:decimal" minOccurs="0"/>
  </xsd:sequence>
 </xsd:complexType>
 <xsd:complexType name="itemLayoutReturn">
  <xsd:all>
   <xsd:element name="STATUS" type="xsd:string"/>
   <xsd:element name="SUCCESS" type="xsd:string"/>
   <xsd:element name="ERRORS" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
   <xsd:element name="coditem" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:all>
 </xsd:complexType>
 <xsd:complexType name="Integrate.itemRequestType">
  <xsd:all>
   <xsd:element name="itemLayout" type="tns:itemLayoutArray" form="unqualified"/>
   <xsd:element name="action" type="xsd:string" form="unqualified"/>
  </xsd:all>
 </xsd:complexType>
 <xsd:complexType name="Integrate.itemResponseType">
  <xsd:all>
   <xsd:element name="return" type="tns:itemLayoutReturn" form="unqualified"/>
  </xsd:all>
 </xsd:complexType>
 <xsd:element name="Integrate.item" type="tns:Integrate.itemRequestType"/>
 <xsd:element name="Integrate.itemResponse" type="tns:Integrate.itemResponseType"/>
</xsd:schema>
</types>
<message name="Integrate.itemRequest">
  <part name="parameters" element="tns:Integrate.item" /></message>
<message name="Integrate.itemResponse">
  <part name="parameters" element="tns:Integrate.itemResponse" /></message>
<portType name="IntegratePortType">
  <operation name="Integrate.item">
    <input message="tns:Integrate.itemRequest"/>
    <output message="tns:Integrate.itemResponse"/>
  </operation>
</portType>
<binding name="IntegrateBinding" type="tns:IntegratePortType">
  <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
  <operation name="Integrate.item">
    <soap:operation soapAction="urn:Integrate#Integrate.item" style="document"/>
    <input><soap:body use="literal" namespace="urn:integrate"/></input>
    <output><soap:body use="literal" namespace="urn:integrate"/></output>
  </operation>
</binding>
<service name="Integrate">
  <port name="IntegratePort" binding="tns:IntegrateBinding">
    <soap:address location="http://ecopack2/gtplan/webServiceDocument/item.php?wsdl"/>
  </port>
</service>
</definitions>

NUSOAP - WSDL STYLE DOCUMENT/LITERAL