Problema com @media query

Question: Estou com um problema serio com o Media Query, eu estou testando nesse codigo e não muda o estado de jeito nenhum, reduzo a tela ao maximo e as cores continuam sem mudar; HELP

 .box{
  width: 200px;
  height: 200px;
  background-color: red;
}
.box2{
  width: 250px;
  height: 250px;
  background-color: blue;
}
.box3{
  width: 150px;
  height: 150px;
  background-color: pink;
}
@media screen (min-width:480px){
  .box{
    width: 200px;
    height: 200px;
    background-color: black;
  }
  .box2{
    width: 250px;
    height: 250px;
    background-color: green;
  }
  .box3{
    width: 150px;
    height: 150px;
    background-color: grey;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Teste</title>
  <link rel="stylesheet" href="css/main.css" media="screen" title="no title" charset="utf-8">

Answer: Troque esta linha @media screen (min-width:480px){ por:
@media screen and (min-width:480px){

EXEMPLO no jsfiddle
Atenção que assim os estilos que estiverem definidos em dentro desse media querie são aplicados quando a janela for maior que 480px. Caso queira que eles aconteçam quando o tamanho da janela for inferior a 480px:
@media screen and (max-width:480px){

EXEMPLO no jsfiddle
Comment: Muitíssimo obrigado, deu super certo.
Comment: De nada @FilipeTrader
Answer: Você precisa declarar a viewport no head do html:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Aí a partir disso, você pode definir as media queries no css normalmente.
E lembrando que é necessário colocar "and" depois de screen, como na resposta acima
@media screen and (min-width:480px)

Mais sobre viewport na w3cSchools
Comment: Muito obrigado meu bom, deu certo.

Problema com @media query


How do you play far-away notes?

Question: I've been learning a new song and it has a part where I need to play two notes an octave away.
I can just about reach it if I use my thumb and middle finger, but it's close and my middle finger keeps slipping down onto a lower note. Are there stretches or tips for how to play this?
Edit: I didn't make this clear before, but the notes have to be played together.
Comment: Why do you use middle finger rather than pinky?
Comment: My pinky slips even more than my middle finger.
Comment: Using 1-3 and 1-4 is common and often appropriate when you have to play black key octaves.
Comment: Wait, how big are your hands? I *must* use 1-5 or use both hands to play any octaves on the piano.
Answer: So, assuming those are the only two notes you have to play with that hand, I think almost any pianist would choose to play with thumb and pinky. Not that it means you have to play it that way, but as you keep practicing you'll notice that certain intervals (the octave you mentioned is an example of an interval) start to feel natural to play with certain fingers. Getting used to way that your hand feels when you play C and C (up an octave), or F and C is part of what makes you a better player. So I would encourage you to practice playing with your thumb and pinky until you get used to it.
You can practice it by playing those two notes by themselves with your thumb and pinky, then take your hand off of the piano and try to put it back down in the exact same place. Once you can do that pretty easily, then start playing the notes in the song that come before the octave part.
Also, just curious, you say your fingers "slips". Do you mean that you start by playing both notes correctly but then your finger slips over to a different note?  Or do you mean that as you set your hand down your pinky touches the C key but doesn't get a chance to push it down before it slips to a different note?
Comment: When I say my finger slips, I mean that while I'm distracted by my left hand, instead of using my right hand to play two Gs, I play a G with my thumb and an F with my other finger. I think you're right though, I just need to practice. Thanks!
Answer: Why not 1 and 5?
But, generally, if you get stuck with an impossible stretch, DON'T stretch.  Just move the hand.
Try this.  Put your hand on your left knee.  Move it to your right knee.  Then back again.  Very easy to do almost instantaneously, right?
Now put your thumb on middle C.  Hand relaxed and not stretched.  Move your hand up an octave, play the next C up with your thumb.
Sometimes you connect.  Sometimes you just move.

How do you play far-away notes?


Attribute using method name

Question: I'm thinking you can't but is there a way to reference a method as a parameter on an attribute? I.e. something like below? I can fall back to use strings, but prefer to use compiler time to verify the types are correct.
<code>[LinkToAction(Something)]
public void SomethingElse()
{

}

public static void Something()
{

}

public class LinkToActionAttribute : Attribute
{
    public LinkToActionAttribute(MethodInfo info)
    {

    }
}
</code>
Comment: _I can fall back to use strings, but prefer to use compiler time to verify the types are correct._ => C# 6 introduced the nameof expression, giving you back a string but with compiler/refactoring. support.https://msdn.microsoft.com/nl-be/library/dn986596.aspx
Answer: Sorry, but you can't. Just these can be passed as arguments for attributes:

One of the following types: bool, byte, char, double, float, int, long, short, string.
The type object.
The type System.Type.
An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
Single-dimensional arrays of the above types.

This question is similar to yours: Is it possible to have a delegate as attribute parameter?. There, a workaround is available which can be useful to you.
Comment: Cheers, that would work, but I think i'll just go for passing in the type (as Type) and method name as string. I'm only processing the attributes at startup, so can process into MethodInfo then via reflection.
Answer: Not directly no.
You could pass it as a string and then use reflection to generate a MethodInfo, or better still, mark the methods with LinkedFrom and LinkedTo attributes.
It's not efficient though, validating it would be a bit of work as well, which sort of makes you wonder if attributes are the correct solution.

Attribute using method name


Prevent onmouseout from firing on child elements

Question: Given the following:
render() {

  const onMouseOver = (event) => {
    this.setState({ isHovering: true });
  };

  const onMouseOut = (event) => {
    this.setState({ isHovering: false });
  };

  const open = this.state.isHovering ? true : false;

  return (

      <NavDropdown
        className={dropDownClasses}
        eventKey={1}
        open={open}
        title="Cards"
        id="nav-dropdown"
        onMouseEnter={onMouseOver}
        onMouseOut={onMouseOut}>
        <MenuItem eventKey="1.1">Action</MenuItem>
        <MenuItem eventKey="1.2">Another action</MenuItem>
      </NavDropdown>
      <NavItem className={styles.navLink} eventKey={2}>Blog</NavItem>

  );

How do I prevent onMouseOut firing when the mouse is over a child of NavDropdown.
Can I detect if I am over a child in onMouseOut?
Answer: This is not React specific. mouseover and mouseout events bubble, so the handler also triggers for children of the element. mouseenter and mouseleave don't bubble.
So you should listen to mouseleave instead.
Comment: Thanks. For bonus points you could answer my even more specific question that needs the same answer: http://stackoverflow.com/questions/34047269/how-to-create-a-hover-dropdown-in-react-bootsrap
Comment: Should be closed as a duplicate IMO.
Comment: I've never done that before. I've initiated the process.
Comment: I didn't think it was a duplicate. I have the same need and it would have been nice to have a very specific answer.


Base R horizontal legend - with multiple rows

Question: I wish to create a horizontal legend with multiple rows using base R (not ggplot).
There is an option for multiple columns but not multiple rows in legend(). Is there a way to do this? Example to play with below where the horizontal legend it too wide for the plot.
MyCol <- topo.colors(20)
barplot(rep(1,20), yaxt="n", col=MyCol)
x <- 1:20
MyLab <- paste("Zone",x)
legend("bottom",MyLab,fill=MyCol,horiz=T)

Answer: You can use the ncol = parameter instead of horiz to get the layout you want. Note that horiz overrides ncol, so don't use both together. Although, this does not specify the number of rows directly, it does do so indirectly, because the number of rows is determined by the number of columns and factors.
MyCol <- topo.colors(20)
barplot(rep(1,20), yaxt="n", col=MyCol)
x <- 1:20
MyLab <- paste("Zone",x)
legend("bottom",MyLab,fill=MyCol,ncol=5)

If you want to arrange the legend items ordered along rows, you can do this by indexing them in the order you want.  E.g.
MyOrder = matrix(1:20, nrow = 4, ncol = 5, byrow = T)
legend("bottom",MyLab[MyOrder], fill=MyCol[MyOrder] ,ncol=5)

To generalize for different numbers of rows and factors, we can do something like
Nfact = 21
Nrows = 5
Ncols = ceiling(Nfact / Nrows)
MyOrder = matrix(1:(Nrows*Ncols), nrow=Nrows, ncol=Ncols, byrow=T)

MyCol <- topo.colors(Nfact)
x <- 1:Nfact
MyLab <- paste("Zone",x)

barplot(rep(1,Nfact), yaxt="n", col=MyCol)
legend("bottom", MyLab[MyOrder], fill = MyCol[MyOrder], ncol = Ncols, border=NA)

And a final extra trick: In the previous plot, we set border=NA. This is to prevent borders being drawn around empty legend items (those at the bottoms of incomplete columns).  If you want borders, then we should also create a vector of border colours that is NA only in the locations we don't want to draw.
MyBorders = rep("black", Nrows*Ncols)
MyBorders[MyOrder > Nfact] <- NA
legend("bottom", MyLab[MyOrder], fill = MyCol[MyOrder], ncol = Ncols, border=MyBorders)


Filter View on Partial Term Name Across All Vocabs

Question: Hello im sure i used to be able to do this with D6 and Views 2. Struggling to achieve it now.
I was wanting to create a content view that is filtered on partial matches of a term name across ALL my vocabs. Say i filtered on 'science' then the view will show content tagged 'science videos' from my Video Vocab and also, for example 'science chat' from my 'tags' Vocab.
Using D7 and Views 3 i dont seem to have the option to filter on name only ID and ID is limited to one vocab.
Does anyone know if i am missing something here?
Thanks
Answer: sorted. Add relationship Taxonomy term: Name in a TERM view and viola
Comment: now if only i could work out how to show the group name in the same View ill be there.


Degree of a map between product of manifolds

Question: Let $M^m$ and $N^n$ be compact, oriented smooth manifolds without boundary. Then what is the degree of the map
$$ f: M\times N \to N \times M$$
given by $f(x,y) = (y,x)$? I have the feeling it should be $(-1)^{mn}$ (would fit in with some proof I have to give), but the result I come up with is $1$.
My reasoning: If $w_1, \dots, w_m$ and $v_1, \dots, v_n$ are positively oriented ordered bases for $T_pM$ and $T_qN$, then $w_1, \dots, w_m, v_1, \dots, v_n$ is a positively oriented ordered basis on $T_{(p,q)}(M \times N)$ (where $T_{(p,q)}(M \times N) \simeq T_pM \oplus T_qN$).
Similarly, $v_1, \dots, v_n, w_1, \dots, w_m$ is a postiviely oriented basis for $T_{(q,p)}(N \times M)$. Now $df(p,q)(w_1, \dots, w_m, v_1, \dots, v_n) = (v_1, \dots, v_n, w_1, \dots, w_m)$, so $f$ is order preserving. And since it is a diffeomorphism, it's degree is $1$.
Now since the above would contradict another statement I have to prove, I must be making a mistake. I would be very glad if someone could help me out here. :-)
Best Regards,
S.L.
Answer: When you say $df(p,q)(w_1,\ldots, w_m,v_1,\ldots, v_n) = (v_1,\ldots, v_n,w_1,\ldots, w_m)$, what exactly do you mean?  My guess is that you're looking at the image of an ordered basis.  I think it might be better if you look at each individual basis vector in $T_{(p,q)}(M\times N)$ and see what its image is instead of trying to take them all at once, so that you can be sure of what you're doing.  Then, the question is not whether the map is order-preserving, but whether the image of your oriented basis has the right or wrong orientation.  You can check this by checking the sign of the permutation that brings it back to your original choice of ordered basis.
Comment: Sure!  I've found that when I'm stuck, especially on differential geometry type stuff, usually my problems stem from not totally understanding the symbols I'm throwing around.  I think it can be especially easy to fool yourself into thinking you understand something that you don't in this field.
Comment: "... and see what its image is instead of trying to take them all at once, so that you can be sure of what you're doing". Very good advice, indeed. I'm such an id... :) Thanks a lot!
Answer: Since $f$ is one to one, then its degree is $-1$ or $1$ (also because $f\circ f=Id$, then $(\mathrm{deg}\,f)^2=1$).
if $\{e_1,...,e_{n+m}\}$ denote the canonical basis of $\mathbb{R}^{n+m}$ then
$\det D(x,y)f=\det(e_{n+1},...,e_{n+m},e_1,...,e_n)=(-1)^{mn}\det(e_1,...,e_n,e_{n+1},...,e_{n+m})=(-1)^{mn}$.
So $\mathrm{deg}\,f=(-1)^{mn}$.


Find the factors of $(a+b+c)^3-(b+c-a)^3-(c+a-b)^3-(a+b-c)^3$

Question: Find the factors of

$$(a+b+c)^3-(b+c-a)^3-(c+a-b)^3-(a+b-c)^3$$

the answer is $24abc$
Let $E = (a+b+c)^3-(b+c-a)^3-(c+a-b)^3-(a+b-c)^3$
Since $b+c = a $ makes $E = 0, \therefore (b+c-a)$ is one factor, similarly $(c+a-b)$ and $(a+b-c)$ are factors, but can not proceed further :(
Comment: If you expand it out, you get exactly 24abc.
Comment: Is $b+c = a$ given in the problem?
Comment: @user230452, No
Comment: $E = 24abc$ . That's it.
Comment: Can you explain why$  b+c = a $makes $E = 0$?
Comment: @SS_C4 Is there any enlightened way to expand this other than brute force?
Comment: I used brute force.(At least my computer did)
Comment: @user230452, please see my answer below.
Comment: @Vikram, let $a=0$, etc instead.
Answer: @user230452 asks for an enlightened way of doing this.
The expression
$$
E = E(a, b, c) = (a+b+c)^3-(b+c-a)^3-(c+a-b)^3-(a+b-c)^3
$$
is symmetric in $a, b, c$, and homogeneous of total degree $3$, so it must be an integral combination of the elementary symmetric polynomials in $a, b, c$, of the form
$$
E = x \sigma_{1}^{3} + y \sigma_{1} \sigma_{2} + z \sigma_{3},
$$
for suitable integers $x, y, z$. Here $\sigma_{1} = a + b + c$, $\sigma_{2} = ab + ac + bc$, $\sigma_{3} = a b c$ are the elementary symmetric polynomials in $a, b, c$.
Set in order

$a = b = c = 1$,
$a = b = 1$, $c = 0$,
$a = 1$, $b = c = 0$

to get
$$
\begin{cases}
3 x + 9 y + z &= E(1, 1, 1) &=24\\
2 x + 2 y &= E(1, 1, 0) &=0\\
x &= E(1, 0, 0) &=0\\
\end{cases}
$$
Hence $x = y = 0$, $z = 24$, and the expression evaluates to $$E = 24 \sigma_{3} = 24 a b c.$$
Comment: This is the way! A possibly interesting modification to the ending is to observe that the substitution $a\mapsto -a$ alters the sign of that sum of cubes (the same holds for $b$ or $c$). I think that rules out the possibilities other than a constant multiple of $abc$. Not sure it's worth our while to look at that closer, because we still need to figure out the constant $24$, and plugging in suitable values for $a,b,c$ is fast anyway :-)
Comment: @JyrkiLahtonen, I think yours is **the** way (the one in **The Book**). I thought *very vaguely* in the same direction, but then went the lazy way ;-)
Answer: Let $\displaystyle b+c-a=x,c+a-b=y,a+b-c=z\implies x+y+z=a+b+c$
We need $\displaystyle(x+y+z)^3-x^3-y^3-z^3=\{x+(y+z)\}^3-x^3-y^3-z^3$
$\displaystyle=x^3+(y+z)^3+3x(y+z)\{x+(y+z)\}-x^3-y^3-z^3$
$\displaystyle=3yz(y+z)+3x(y+z)\{x+(y+z)\}$
$\displaystyle=3(y+z)\{yz+x(x+y+z)\}$
$$\displaystyle\implies(x+y+z)^3-x^3-y^3-z^3=3(y+z)(z+x)(x+y)$$
Now $y+z=2a$ etc.
Can you take it from here?
Answer: This technique comes from A Course in Pure Mathematics by Margaret M. Gow:
$E=(a+b+c)^{3}-(b+c-a)^{3}-(c+a-b)^{3}-(a+b-c)^{3}$
$c=0 \implies E=(a+b)^{3}-(b-a)^{3}-(a-b)^{3}-(a+b)^{3}=0$
$\therefore c$ is a factor of $E$.
By symmetry, $a, b$ also are factors of $E$.
Since $E$ is cubic, let $E=kabc$ where $k$ is a constant.
Take $a=b=c=1$, $E=24=k$.
$\therefore E=24abc$
Comment: I am looking at the book's content, don't know why an algebra book is titled "pure" ?
Comment: @Vikram That's a text book for Pure Mathematics of Advanced Level.  It also concludes Calculus and Coordinate Geometry.  It really is a classic.


Host flapping between switchport and Etherchannel

Question: I've got 2 stacks of Catalyst 4506-E switches (Core01 & Core02) with a 4 link port channel  (Po1) configured between them. I've got 2 routers, a 3845 and a 7206VXR connected to both Core01 & Core02 at ports Gi4/45 and Gi2/11 on both switches. A quick diagram:

While trying to chase down a different(?) issue, I noticed in the output of show logging from Core01 and Core02 was:
Oct 19 15:16:24.807: %C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80
in vlan 999 is moving from port Gi4/45 to port Po1 Oct 19
15:16:24.807: %C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80 in vlan
999 is moving from port Po1 to port Gi4/45 Oct 19 15:16:34.188:
%C4K_EBM-4-HOSTFLAPPING: Host 00:22:0D:92:B0:1B in vlan 999 is moving
from port Gi2/11 to port Po1 Oct 19 15:16:34.236:
%C4K_EBM-4-HOSTFLAPPING: Host 00:22:0D:92:B0:1B in vlan 999 is moving
from port Po1 to port Gi2/11 Oct 19 15:16:35.080:
%C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80 in vlan 999 is moving
from port Gi4/45 to port Po1 Oct 19 15:16:35.128:
%C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80 in vlan 999 is moving
from port Po1 to port Gi4/45 Oct 19 15:16:44.189:
%C4K_EBM-4-HOSTFLAPPING: Host 00:22:0D:92:B0:1B in vlan 999 is moving
from port Gi2/11 to port Po1 Oct 19 15:16:44.189:
%C4K_EBM-4-HOSTFLAPPING: Host 00:22:0D:92:B0:1B in vlan 999 is moving
from port Po1 to port Gi2/11 Oct 19 15:16:45.081:
%C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80 in vlan 999 is moving
from port Gi4/45 to port Po1 Oct 19 15:16:45.125:
%C4K_EBM-4-HOSTFLAPPING: Host 00:25:84:EA:60:80 in vlan 999 is moving
from port Po1 to port Gi4/45

Over and over again. Those 2 MAC addresses,00:25:84:EA:60:80 & 00:22:0D:92:B0:1B correspond to BVI1 on the 3845 and the 7206VXR, respectively.
Output of sh vlan id 999:
VLAN Name                             Status    Ports
---- -------------------------------- --------- ------------------------------- 999  Core                             active    Gi1/3, Gi1/4, Gi2/11, Gi2/25, Gi2/31, Gi3/18, Gi3/20,
Gi3/22, Gi3/24, Gi3/26, Gi3/28
                                                Gi3/32, Gi4/4, Gi4/7, Gi4/11, Gi4/15, Gi4/27, Gi4/45, Gi5/2, Gi5/3, Gi5/4, Gi5/5
                                                Gi5/10, Gi5/25, Gi5/26, Gi5/27, Gi5/28, Gi5/34, Gi5/36, Po1

VLAN Type  SAID       MTU   Parent RingNo BridgeNo Stp  BrdgMode
Trans1 Trans2
---- ----- ---------- ----- ------ ------ -------- ---- -------- ------ ------ 999  enet  100999     1500  -      -      -        -    -        0      0

Remote SPAN VLAN
---------------- Disabled

Primary Secondary Type              Ports
------- --------- ----------------- ------------------------------------------

So, port channel Po1 is in vlan 999, as are Gi2/11 and Gi4/45, Which I'm assuming is a problem, and is causing these messages. My question is this; I inherited this setup, I didn't build it,but I also haven't changed it. I've built a Debian Rancid server thats handling configuration diffs, so if this was something that was new, I'd have gotten an email about it. I admit I haven't gone back and looked at every config diff I've received in the past year, but I went back far enough to know this isn't a new change, I can assume it has been doing this for a while now. However, I see that message, I think loop.
Is it incorrect to have Po1 and the interfaces that are connected to the routers in the same vlan? Also, those ports are access ports, should I not trunk them? Any ideas would be appreciated.
Thanks,
Comment: That is definitely loop, and it works without problems just because Cisco manages it.
It is hard to say anything about your port-channel, as we don't know, what traffic do you send through it, but as you have two uplinks for each stack, it is most likely the traffic between the stacks, so it should be in different VLAN from uplinks.
Answer: Yes there is a problem and you are one step away from making a loop, but its not because of keeping Po1 and interface connected to the router in the same VLAN. When you Stack two switches, They work as one even if they are part of VSS(Virtual Switching System). The brain of the two switches become one and all the switching decisions are made by one switch(which is the active among two).
Now what happens when you connect two cables from a router to a switch and in same VLAN?
Yes, thats right it will get same MAC from both ports.

Is it incorrect to have Po1 and the interfaces that are connected to the routers in the same vlan?

Absolutely not. You are making it more secure and its good. :)

Also, those ports are access ports, should I not trunk them?

No, You should rather turn the two ports connected to the router into a port-channel respectively. As I said after stacking they behave as one, Hence you should port channel both Gi2/11 as(lets say) Po2 and both Gi4/45 as Po3. Keep both port-channels in Vlan 999, Also Ether-channel the ports on the router(but I think that is already done, as you are getting MAC from both interfaces) and I am sure the logs will vanish.
Hope this Helps!
Comment: Thanks- I think I explained this incorrectly, though. Core01 and Core02 aren't stacked together, they are 2 separate stacks of 4506 switches with a port channel between them. Technically they operate independently. After looking at this for a while, I realize I can "fix" this by removing one link from each router, but I imagine this was originally set up for redundancy. Would I achieve the same result following your instructions if I had both links coming the 3845 connected to 2 ports on, say Core01 and both links from the 7206 connected to 2 ports on Core02?.
Comment: I though Core1 and Core2 are stacked, Sorry for that. Are the two interfaces on 3845 and the two interfaces on 7206 bonded respectively on their routers?
Comment: I meant to update; this was resolved by moving both links from each of the routers into a single core switch and bonding them both as separate port channels. Thanks!


Why are Hornsat, 3sat and 2sat not equivalent?

Question: I have been reading a little bit about complexity theory recently, and I'm having a bit of a stumbling block. The horn satisfiability problem is solvable in linear time, but the boolean satisfiability problem in general is NP-Hard. So far so good, I understand that.
Apparently Boolean satisfiability is reducible to satisfiability of a boolean expression in Conjunctive Normal form with 3 variables per clause. This problem though is also NP-Hard. That's fine with me too, since it was proven by someone probably much smarter than me.
I am having trouble though because of the following tautology:
$$(a \vee b \vee c) \iff ((\neg a \wedge \neg b)\implies c)$$
Not exactly a Horn clause, but I am not done.
So given a 3SAT problem, apply the above tautology.
then replace each negated boolean $\neg x$ with a new variable $x_n$
This is an instance of HORNSAT, but unfortunately it isn't equivalent to the original problem. This new problem though is polynomial time equivalent to a certain instance of 2SAT(satisfiable iff the HORNSAT is). Now if for each introduced variable $x_n$, we add the following to our 2SAT problem: $$ (x \vee x_n)\wedge (\neg x \vee \neg x_n) $$
Shouldn't this 2SAT instance then be equivalent to the original 3SAT instance? The number of variables doubled and it has a linear factor more clauses.
I must be overlooking something, right? I can't for the life of me see the flaw. Can someone explain it to me?
EDIT: and a counterexample would be nice.
Comment: Some of your clauses are Horn, but the others are 2-CNF clauses. I don't think mixing them both in a single problem is a good idea.
Comment: @Tomas No, the question is a better fit at this site. [cstheory](http://cstheory.stackexchange.com/) is for research level questions in theoretical CS. SO is for programming questions and this one is mathematical, it's not about programming.
Comment: I'm thinking it has to be something to do with the reduction from hornsat to 2sat. Does such a reduction introduce new variables for example?
Comment: isn't this better asked at SO or Computational theory at SE?
Answer: What you would need is a translation between HORNSAT and 2SAT that let's you translate a witness for the satisfiability of the Horn formula into a witness for the 2SAT (or the other way around?  But this doesn't really matter.).
In any case, a cheap way to reduce HORNSAT to 2SAT is to solve your instance of HORNSAT in polynomial time, i.e., to check satisfiability, and then return a trivially satisfiable instance of 2SAT or a trivially not satisfiable instance of 2SAT.  In other words, you throw away all information about the Horn formula, other than whether it is satisfiable or not.
In particular, the terms that describe the role of the new variables that you add have no meaning relative to the 2SAT instance you get from the Horn formula.
Comment: Ok, then as long as such a witness preserving reduction doesn't exist or can't be found, it won't work. That makes sense. Further reading showed me some sort of hint: Satisfying an instance of hornsat simultaneously with an instance of 2sat is np-complete. If I alter my method slightly, I get exactly a reduction from 3sat to hornsat+2sat.
Comment: Yes, that sounds about right.  I think you basically proved that an satisfiability of an instance of hornsat simultaneously with an instance of 2sat is np-complete.


Prediction interval

Question: I calculated an 80% prediction interval of the outcome of interest (proportion of patients, average temperature etc.) based on my previous study. Is it true that in the future study I will receive the outcome within the calculated prediction interval with 80% probability? Which means that if I do a billion studies the outcome will be within the prediction interval in about 80% of them?
Answer: The answer is no: no such (nearly) free lunch can exist, even if the
model is perfect.
Consider for instance a linear regression using $n$ observations
$[x_i,\,Y_i]$. Given a "new" design point $x^\star$ you can compute a
$80\%$ prediction interval; It contains one new $Y^\star$
corresponding to $x^\star$ with probability of $80\%$. But it does not
contain $80\%$ of a large number of new values $Y^\star_j$ made at
$x^\star$, even if the model is perfectly adequate. As suggested by
the formulation of your question, you can not guess exactly the
distribution of an infinite number of new values from a finite number
of observations.
To reach the wanted probability, you have to draw a new dataset with
observations $[x_i, \, Y_i]$ for each prediction that you make. This is
well explained by G.W. Senedecor and W.G. Cochran in the regression
chapter of their famous Statistical Methods book.
An alternative where the expected coverage rate holds is when the
prediction is updated sequentially, thus modifying the prediction
interval: the first new couple $[x^\star_j, \,Y^\star_j]$ is included in
the data, then the model estimates and the prediction interval are updated
before a new prediction is made. Again, this must be repeated for each
prediction, and the coverage will be reached only in the long
run. This context is classical in time-series analysis.
Answer: There are already several answers to this question but on my reading, they are all incorrect (or easily misinterpreted).
A frequentist prediction interval works like a frequentist confidence interval. The "promise" of a frequentist confidence interval holds on repeated samples,e.g. if I construct a 95 percent confidence interval then on repeated samples 95 percent of the intervals will contain the parameter value.
Any particular interval will either contain the parameter value or not though. So once you've constructed the interval, there is no guarantee, for example, that the parameter falls in the interval with a certain probability.
This is also how a prediction interval works. You 1) sample a distribution, 2) construct an 80 percent prediction interval and then 3) sample the distribution again. Now if your repeat steps 1 - 3, thousands of times, the outcome from step 3) will fall in prediction interval from step 2) 80 percent of the time.
However, if you follow step 1) and 2) only once and then repeat step 3) thousands of times, the prediction interval from step 2) will almost certainly not cover the outcome from step 3) 80 percent of the time.
So to the question,

I calculated an 80% prediction interval of the outcome of interest
(proportion of patients, average temperature etc.) based on my
previous study. Is it true that in the future study I will receive the
outcome within the calculated prediction interval with 80%
probability?"

the answer is no.
Answer: It is probably not true. In an ideal world, where observations are truely i.i.d. and your first study had a truely representative sample and all the other assupmtions (distributions etc.) were true, than yes. However, in real life all those assumptions fail to be true and thus you will probably face larger variances then expected.
All of this is of different importance in different fields. It may be possible, to do the same experiement twice in physics - but then again, probably in fields that use statistics only rarely. In fields like medicine, psychology, sociology, the idea of a second sample that is identically distributed as the first sample, most of the time remains a dream.
Comment: Thanks for your answer. I am just interested in statistical point of view of this problem, not representativeness and so on.
Comment: "In an ideal world, where observations are truely i.i.d. and your first study had a truely representative sample and all the other assupmtions (distributions etc.) were true, than yes." This is not how a prediction interval works. You would instead need to sample one billion times and predict based on this sample one billion times.
Answer: Thanks for your answers. According to the citation below (book: Statistical Intervals A Guide for Practitioners and Researchers) the answer is Yes. Suppose that, based on the x = 20 nonconforming integrated circuits from n = 1,000 randomly selected units, the manufacturer desires a 95% prediction interval to contain the number of nonconforming units in a future sample of m = 1,000 randomly sampled units from the same production process. The conservative method given by (6.9) gives [Y,Y] = [9, 35] for a conservative 95% prediction interval and Y = 32 for an upper conservative 95% prediction bound for Y . Thus, based on x = 20 nonconforming units from the n = 1,000 sample units, one can, for example, assert, with (at least) 95% confidence, that the number of nonconforming units in the future sample of m = 1,000 will not exceed 32 units.
Comment: The answer does not correspond to the question. If you take $N^\star:= $ a
billion of randomly samples of $n=1000$ selected units and evaluate the
number of nonconforming unit $Y_i^\star$ for each sample $i$, it will
not be true that $95\%$ of the $N^\star$ values $Y_i^\star$ fall in
your prediction interval. The fact that $n=1000$ may seem large is of
no importance here. You can try this by simulating a binomial
distribution.
Comment: I thought that "confidence" for the future sample is equivalent to the proportion of future infinite samples in which the outcome is within the prediction interval.
Comment: The expression "with 95% confidence" is somewhat misleading here
because a confidence interval is for an unknown *non-random*
quantity. Yet 'in *the* future sample' does not mean 'across a large
number of future samples'.

Prediction interval


What area of statistics deals with such kind of problems?

Question: Consider $2$ samples from the starting normal distribution with parameters $\mu=0, \sigma = 1$ with size $N$. Find the variance of the random variable $\xi$ equal to average sum of $1$st sample - average sum of $2$nd sample.
My course of mathematical statistics did not include topics related to such problems, so can you point out what area of statistics deals with such kind of problems?
Comment: @probablyme  My statistics textbook doesn't have problems with sampling, and my studies was long time ago, so I tried nothing, I look for book/paper which contains such problems, but have no idea how formulate query for search. By `mean of 1st/2nd sample` I mean average (sum of N / N). About `independent` it is not defined in task, so I can not assume that for this samples.
Comment: @probablyme So I am not interesting in solution of this task by itself, but in paper/book where such task described/solved.
Comment: @probablyme Any examples of such book, what you have on your book shelf? I pick my book for mathematical statistic and it not contains similar problems. But my native language is not English, I heard that USA/GB books are more practical then in my country. So can you give name of such textbook?
Comment: Sorry, I have no recommendation. I did not learn probability from a textbook, and my mathematical statistics book was very bad. I'm sure someone will have a good suggestion.
Comment: In general, try searching the site first. You're not the first person [to ask this](http://math.stackexchange.com/search?tab=votes&q=[statistics]%20[reference-request]%20book%20recommendation).
Answer: I think the problem you state isn't fundamentally a problem in
sampling, but based on principles of elementary probability.
So I wonder if it may be in the books you have, but that the
connections are not immediately obvious to you.
As a generalization of your problem consider one sample of
size $n$ from $N(\mu_1, \sigma_1^2)$ and an independent sample of
size $m$ from $N(\mu_2, \sigma_2^2).$ Then the difference
in sample means is distributed as follows:
$$\bar X_1 - \bar X_2 \sim N\left(\mu_1 - \mu_2,
\frac{\sigma_1^2}{n} + \frac{\sigma_2^2}{m}\right).$$
So in your particular case,
$\bar X_1 - \bar X_2 \sim N(0,\, 2/N)$.
Notice that the second parameter of the normal distribution in my
notation is the $variance$ in all cases, not the standard deviation.
There are two issues here. First, sums and differences of independent  normal
random variables are normal. This theorem can be proved using moment
generating functions. but is often just stated as a fact in
very elementary texts. Second, you need to know some fundamental
facts about means and variances of sums and differences of random
variables:
For any two random variables $X$ and $Y$,
$$E(aX \pm bY) = aE(X) \pm bE(Y).$$
For two independent random variables $X$ and $Y$,
$$Var(aX \pm bY) = a^2Var(X) + b^2Var(Y).$$
In the second equation notice that the variances are always added.
In your particular problem $a = b = 1.$
These can be used to prove that for a random sample $X_1, X_2, \dots, X_n$ from a population with mean $\mu$ and variance $\sigma^2,$ we have
$E(\bar X) = \mu$ and $Var(\bar X) = \sigma^2/n.$
You should be able to find all  of the displayed relationships above in many advanced undergraduate texts on probability
theory or mathematical statistics. One such book, now available
in paperback for a relatively reasonable price, is Bain and Englehardt:
Intro. to Probability and Mathematical Statistics, (1992, 1978).
The topics above are in Chapters 4 and 5. I would not want to claim it is the very best choice for you, but I have
taught out of it several times. I have found it to be generally clearly written,
and it contains some applied examples.


read_sql and redshift giving error on unicode

Question: Query 1: Using pandas read_sql to read from MySQL. The resulting dataframe has a column whose datatype is unicode strings. This column is converted to a tuple and used in the following query.
Query 2: Using pandas read_sql to read from Redshift. The query is something like
select b.a from b where b.c in {0}

On one string, it gives me an error. The string is like u"Hello 'There" which is a valid unicode string.
The error is
syntax error at or near ""Hello 'There""

But it shouldn't take it that way. Its treating it as an empty string ("") followed by un-understandable symbol like (Hello 'There"")
Should some configuration be changed or some parameters in read_sql to be added
Answer: I suspect that that error message is being generated by someone replacing a marker (I've used {something}) a template like
'syntax error at or near "{something}"'

This means you should instead see it as a complaint about a single string whose value would appear to be
'"Hello \' There"'

In other words, it seems likely that you are dealing with a fifteen-character string starting and ending in a double-quote character, though there is always the possibility that some inappropriate conversion or quoting has added the double-quotes. No code, no traceback, so difficult to tell.
It seems as though somewhere in the processing chain there is a failure to correctly handle single apostrophes in SQL string literals. In SQL that string would be correctly represented as
'"Hello, ''There"'

You will observe that the single-quote embedded in the string had had to be doubled to represent it - the SQL syntax specifically denotes this as the correct way to embed apostrophes in SQL string constants. Since you don't actually show details of your code there is a limit to how helpful this answer can be.
I suspect you might be writing your own SQL, in which case given a query in the variable sql you might want to consider using
sql.replace("'", "''")

as the value injected into the query. But beware all the usual warnings about SQL injection if you plan to incorporate user inputs into this scheme.
Comment: The value isn't `'"Hello, ''There"'`
it's `"Hello, 'There"` or you could say `'Hello, \'There'`
Comment: And I am using pandas to read the sql not native python way of using it
Comment: in the tuple it can be seen as
`u"Hello 'There"`


Como adicionar entradas num dicionário?

Question: Como adicionar entradas fornecidas por um usuário num dicionário? Por exemplo:
Entrada:
1 abcde
2 adecd
3 aaabb

O dicionário criado seria:
dicionario = {'abcde' : 1, 'adecd' : 2, 'aaabb' : 3}

ou
dicionario = {1 : 'abcde', 2 : 'adecd', 3 : 'aaabb'}

Existe alguma função semelhante a append() para se usar em dicinarios como se usa em lista? Digo isso por que como as entradas serão fornecidas pelo usuário, não dá pra ficar adicionando entrada por entrada (dicionario['abcde'] = 1).
Answer: Pode usar algo como:
entrada1 = input("Por favor insira um numero: ")
dicionario[entrada1] = 1

Comment: Como serão várias entradas, que eu não sei quantas serão exatamente (já que quem fará isso é o usuário) posso usar um loop para ir aceitando as entradas e criando o dicionário, correto?
Comment: Sim um mecanismo de controlo de entradas funciona bem.
Comment: Irei tentar. Obrigado.
Answer: Para este exemplo que você está mostrando:
1 abcde
2 adecd
3 aaabb

Como se o usuário entrasse com os valores
 separados dessa maneira você pode fazer assim:
user_input = input('1 abcde')# simulando a entrada do usuário
user_input = user_input.split(' ')
user_notes[user_input[0]] = user_input[1];

Comment: Não entendi. Quem utilizar o programa deve fornecer as entradas da forma como mostrei, (1 abcde) e o programa deve criar um dicionário com essas entradas, utilizando cada item da entrada como chave/valor  (ou valor/chave), ou seja, as entradas devem ser inseridas num dicionário , da mesma forma como seria numa lista, onde cada entrada seria inserida na lista à medida em que fossem fornecidas, usando append(), por exemplo.
Answer: O mais prático para anexar um novo índice com um valor definido
dicionario['abcde'] = 1

Mas não entendi o que o impede de usar.
Você comentou:

Digo isso por que como as entradas serão fornecidas pelo usuário, não
  dá pra ficar adicionando entrada por entrada (dicionario['abcde'] =
  1).

Então, outra forma de fazer seria com o método update()
dicionario.update({'abcde':1})

Obtendo os dados via raw cgi
import cgi
form = cgi.FieldStorage()

for key in form:
    dicionario[key] = form[key]

Obtendo os dados via request.POST
for key in request.POST:
    dicionario[key] = request.POST[key]

Comment: Preciso utilizar raw_input ou input para que o usuário do programa (não eu, que estou escrevendo) insira as entradas. É um exercício para criar um programa que receba notas de alunos 1, 2, 3, n alunos e depois compare as suas respostas com um gabarito. O usuário (tipo um professor) deve apenas inserir o "número" do aluno e as suas respostas, no formato 1 abcde, por exemplo. Por isso não posso fazer dessa maneira.
Comment: pois basta atribuir o valor do input a variável..
Comment: Irei tentar. Obrigado.
Comment: então acho que a sua questão é como iterar dados provindos do método GET/POST.. Adicionei exemplos..
Answer: d = {}
v = raw_input('valor: ')
d.update({len(d)+1:v})

Ou coloque num laço:
d = {}
while True:
    v = raw_input('valor')
    if v == 'Q':
        break
    d.update({len(d)+1:v})
print d

Como adicionar entradas num dicionário?


here.com api key failing for calculate matrix

Question: I'm using the here.com api to calculate a matrix, using a valid apiKey but getting the error message "ApiKey invalid. ApiKey not found." However the apiKey worked until yesterday, is working for routing (as opposed to matrices) and I'm well below Freemium limits.
Using Here.coms example pages, the routing examples work and the matrix ones don't
Car route from A to B
https://developer.here.com/documentation/examples/rest/routing/route-from-a-to-b
Putting in my api key works
Many to many matrix routing
https://developer.here.com/documentation/examples/rest/routing/many-to-many-matrix-routing
Putting in my api key gives the error '{"error":"Unauthorized","error_description":"ApiKey invalid. ApiKey not found."}'
Even with the api keys that the page loads with, the matrix examples are getting no response whereas the routing examples work.
The website directs freemium users here for support so hoping you guys can help. Seems like it might be a temporary glitch?
Comment: Hi, I have similar issue, some time I get the error described above. The error is sporadic but occurs with the same valid request that gets good result or sometime error of invalid key. I made some tests with Postman and I confirm this beheivoir. This happen with calculatematrix service and also with geocoder service.
Comment: Hi, for all the day until more or less 1 hour ago the services was responding good, but now gets more 401 with the same request and the same apiKey used this morning.
Comment: Are you still having the issue? Can you share your complete code, minus the key if you want?
Comment: Hi Raymond. Its now working thanks. The easiest way to test is with the code that the here.com example pages generate. In fact when the issue is happening, the example page doesn't seem to load properly, as in the Response section stays blank, so this may be a quick way to test the service. I agree with Pasquale the error is sporadic (and fingers crossed is gone)
Answer: It looks like it may have been this status issue, https://status.here.com/status?id=status_history_details&sys_id=469f34711b264090cb5d8557cc4bcbf3, which is now marked as resolved. You can see our general status here, https://status.here.com/status. I hope this helps!
Comment: Thanks Raymond that's useful. Upvoted it but not marked as the answer as it may also have been this https://stackoverflow.com/a/59834825/11196018


Erro ao exibir array em PHP

Question: Tenho este array em PHP e devo exibir o campo nome e email dos usuarios.
Porém o php exibir uma mensagem de erro:
array(4)
    {
        [0]=> object(stdClass)#25 (5)
            {
                ["idusuario"]=> string(1) "2"
                ["nome"]=> string(5) "admin"
                ["email"]=> string(15) "email@example.com"
                ["senha"]=> string(3) "123"
                ["status"]=> string(1) "1"
            }
        [1]=> object(stdClass)#26 (5)
            {
                ["idusuario"]=> string(1) "3"
                ["nome"]=> string(5) "teste"
                ["email"]=> string(15) "email@example.com"
                ["senha"]=> string(3) "123"
                ["status"]=> string(1) "0"
            }
    }

codigo PHP
<?php

   echo $dados["0"]["nome"];
   echo $dados["1"]['email'];
?>

Mensagem de Erro:

A PHP Error was encountered
Severity: Notice
Message: Undefined index: nome
Filename: home/list.php
Line Number: 20
Backtrace

:

A PHP Error was encountered
Severity: Notice
Message: Undefined index: email
Filename: home/list.php
Line Number: 21
Comment: E se fizeres `$dados[0]->nome;`? Cada um dos subelementos é um objeto e não um array
Comment: Qual é a mensagem de erro? E como estás a tentar fazer isso?
Comment: so funcionar desta forma:  echo $dados[0]->nome;
Comment: com faco para exibir no foreach ??
Answer: É um stdClass Object, faça assim:
Suponhamos que no seu código o array esteja em $dados
// printar o campo nome dentro do loop
foreach ($dados as $dado) {
    echo $dado->nome;
}

// printar o campo nome do primeiro item da array
echo $dados[0]->nome;

Comment: Como coloco isso no  while($linha = mysql_fetch_assoc($dados)){ echo #linha[0]["nome"];
Comment: quando este codigo dá erro: Fatal error: Cannot use object of type stdClass as array in D
Comment: eu editei e coloquei um exemplo de como colocar isso dentro do while
Comment: So esta funcionado desta forma:  echo $dados[0]->nome;
Comment: editei novamente, agora tem um exemplo dentro de um foreach, substitui o while, tente e me fala.
Comment: funcionou perfeitamente, Porém existe uma linha vazia ao final..
Comment: como elimino a linha vazia do final ??
Comment: para eliminar o último item da array use a função array_pop(), no seu caso, coloque antes do foreach o seguinte: array_pop($dados);
Answer: Quando você encontrar este erro:

Undefined index: email (ou qualquer que seja)

Significa que você está tentando pegar do objeto um indexador que não existe (uma posição que não existe).
Uma boa solução é dar este comando die(vardump($minha_variavel));, ele mostrará toda a estrutura da variável ou objeto, então você chega na seguinte solução:
echo $dados[0]->nome;

Ou, ainda:
foreach($dados as $result){
    echo "O resultado é ". $result->nome;
}

Erro ao exibir array em PHP


sails helpers and machine spec

Question: I upgrade sails to the @^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
    var ob = await ails.helpers.testy('sayHello');

    res.json({ob:ob});

helper
module.exports = {
friendlyName: 'Testy',

description: 'Testy something.',

inputs: {

  bla: {
    type: 'string'
  }

},

exits: {

  success: {

  }

},

fn: async function (inputs, exits) {

  console.log({blabla:inputs.bla})

  if(!inputs.bla) return exits.error(new Error('text not found'));

  var h = "Hello "+ inputs.bla;

  // All done.
  return exits.success(h);

}

};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
  fn: async function (inputs, exits) {
            ^^^^^^^^
SyntaxError: Unexpected token function.......

and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed.  Any chance the
source code is missing an "await"?

To assist you in hunting this down, here is a stack trace:
```
    at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)

Comment: About removing the `async/await` part , you have to set the `sync` property to `true` so you can call the helper without `await`.
Comment: @HamzaFatmi in the module.exports ?
Comment: Yes in the helper definition.
Comment: not working too.. Do you maybe have some exemples of helpers use?
Answer: The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {

  friendlyName: 'Testy',

  description: 'Testy something.',

  sync: true, // Here is essential part

  inputs: {

    bla: {
      type: 'string'
    }

  },

  exits: {

    success: {

    }

  },

  fn: function (inputs, exits) {

    console.log({blabla:inputs.bla})

    if(!inputs.bla) return exits.error(new Error('text not found'));

    var h = "Hello "+ inputs.bla;

    // All done.
    return exits.success(h);

  }

};

From the another side, you have a problem with async/await. The top most reason for this are

Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing
Comment: Your sails solutions are super helpful thank you Pavlo!
Comment: I finaly beat the beast. Thank for help !

sails helpers and machine spec


Como mudar a cor de 1 string

Question: Olá, então eu to querendo fazer 1 rank de jogadores no meu site, e eu coloquei o cargo de cada jogador lá, mas tem 1 porem, cada cargo tem a sua cor, e no mysql fica apenas o nome do cargo, como eu faço para ele pegar 1 nome e mudar a cor.
Exemplo: Diretor, ele vai deixar Diretor
    public function RankSkyWars()
{
    $stmt = $this->pdo->prepare("SELECT * FROM tskywars INNER JOIN tcommons ON tskywars.id = tcommons.id INNER JOIN permusers ON tcommons.id = permusers.id ORDER BY `solowins` DESC LIMIT 100");
    $stmt->execute();
    if($stmt->rowCount() == 0) { return ""; }
    $fetch = $stmt->fetchAll(\PDO::FETCH_OBJ);
    $return = "";
    foreach ($fetch as $rs)
    {
        $deaths = "".number_format($rs->solodeaths, 0, ',', '.');
        $wins = "".number_format($rs->solowins, 0, ',', '.');
        $kills = "".number_format($rs->solokills, 0, ',', '.');
        $coins = "".number_format($rs->coins, 0, ',', '.');
        $return .= "

                        name}/32.png\"> {$rs->name}
                        {$rs->groups}
                        $wins
                        $kills
                        $deaths
                        $coins

";
    }
    return $return;
}

Answer: Você pode fazer assim (código comentado):
    $color = "color: ";

    switch($rs->groups){
        case "Diretor": $color."orange;"; break; // se for diretor
        case "Ajudante": $color."yellow;"; break; // se for ajudante
        default : $color."black;";
    }

    // insere a cor
    $return .= "

                    name}/32.png\"> {$rs->name}
                    {$rs->groups}
                    $wins
                    $kills
                    $deaths
                    $coins

";

Comment: @MatheusFerreira kkkk tranquilo

Como mudar a cor de 1 string


Change the Drupal Commerce checkout completion page

Question: How do I redirect the final checkout page of my Drupal Commerce install (from checkout/%/complete) to the actual order created (user/%/order/%)?
This seems easier than having to build and theme the line items in the completion message pane, not to mention I have inserted other information to the order display.
Answer: I used the Rules module to redirect on checkout completion event, and this seems to be working so far.


Date range picker does not show next arrow but shows previous arrow

Question: I am working with DateRangePicker and I am not shown the following arrow, I don't know what I have configured wrong.
As we see the image should have on the right side an arrow too, this time I went back to 2020 so you can see that I don't have the arrow

My input
<input type="text" id="daterange" name="daterange"/>

My script

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

Answer: you need to set the "maxDate". it cannot be "maxDate": '0',


Whether there exists a measurable function $f(t,x):[0,2]\times \mathbb R \to \mathbb R$ such that $f(t,B_t)=B_1$ for all $t∈(1,2]$?

Question: Whether there exists a measurable function $f(t, x): [0,2] \times \mathbb R \to \mathbb R$ such that $f(t, B_t)=B_1$ for all $t\in (1,2]$? Here $(B_t)_{t\geqslant 0}$ is the standard Brownian motion with natural filtration $(\mathcal F_t)_{t\geqslant 0}$. I tried by using conditional expectation w.r.t. $\mathcal F_1$ but I cannot show the deterministic function $f(t,x)$. I think that it doesnt exists but I dont know how to prove.
Answer: There is no such continuous  $f$. This follows from a result of F.B. Knight https://cms.math.ca/10.4153/CMB-1997-008-x , which asserts that if the total variation of $[0,2]\ni t\mapsto f(t,B_t)$ is integrable then $f(t,x)=f(t,0)$ for all $(t,x)$.
A more pedestrian approach dispenses with the continuity.
I suppose that if $(B_s)_{s\ge 0}$ is any standard Brownian motion and $1<t\le 2$ is fixed, then $f(t,B_t)=B_1$ a.s. Construct a second Brownian motion $\hat B$ from $B$ as follows:
$$
\hat B_s:=\cases{B_t-B_{t-s},&$0\le s\le t$;\cr B_s,&$t\le s\le 2$.\cr}
$$
Crucially, $\hat B_t=B_t$. Therefore, almost surely,
$$
B_t-B_{t-1}=\hat B_1=f(t,\hat B_t) =f(t,B_t)=B_1,
$$
which in turn implies that
$$
B_t=B_1+B_{t-1}.
$$
But the variance of $B_t$ is $t$ while that of $B_1+B_{t-1}$ is $3t-2$. These can   be equal only if $t=1$, in violation of our hypothesis. So there isn't even a measurable such $f$.
Comment: That's a hypothesis: "I suppose that if $(B_s)_{s\ge 0}$ is *any* [emphasis added] standard Brownian motion and $1<t\le 2$ is fixed, then $f(t,B_t)=B_1$ a.s."
Comment: Thank you! But I think $var(B_1+B_{t-1})=var(B_1)+var(B_{t-1})=t$ again?
Comment: The covariance of $B_1$ and $B_{t-1}$ is $t-1$ (because $1<t\le 2$).
Comment: Ahh, you're right. I'm confuse with $B_t-B_1$.
Comment: Only one thing is not clear for me, why you can conclude $\hat{B}_1=f(t,\hat{B}_t)$?


How to determine variables that make certain cluster different from others?

Question: Say clustering was performed. My concern is to understand what characterizes certain cluster. Which variables differ most for a certain cluster? Are there any methods for performing such kind of analysis?
For example, say I have 50 variables and 10 clusters. The desired result would sound like: for a cluster 1 variables 5, 16, 23, 42 and 49 contribute to the biggest difference from other clusters.
Answer: You can always assume that the clusters are classes and train a classifier on that.
A decision tree classifier comes to my mind, as it will often produce a "human readable" classification tree.
Comment: I like this approach!  Is there any literature on it I can cite?
Answer: An interesting topic to look into is Fuzzy clustering.
The idea behind fuzzy clustering is that a cluster can have elements that are more "typical" than others and therefore have a higher membership within that cluster than other members which are less "typical".
For example, a Robin would have a high value (say 0.9) for its membership in the Birds cluster, while a Penguin would have a low value (say 0.4) for its membership in the Birds cluster.
With 50 data items (and 10 clusters!) to cluster a good inference might be difficult to obtain.
A good book to read on Fuzzy Clustering and Fuzzy Logic is the following Fuzzy Sets and Fuzzy Logic: Theory and Applications by Bo and Klir, although it is a bit dated.


Código Jquery não chama Metodo no controler

Question: Não estou sabendo como usar um método jQuery. Quero obter uma lista de países. Segue o código pra ajudar em saber onde estou errando.

  < script type = "text/javascript" >
    $(document).ready(function() {
      $('#btnPais').click(function(e) {
          $('#btnPais').hide();
          $('#mensagem').html('Aguarde, carregando ..');

          $.getJSON('/Usuario/ObterPaises', function(dados) {
            if (dados.length > 0) {
              var option = '<option value="">Escolha um Pais </option>';
              $.each(data, function(i, obj) {
                option += '<option value="' + obj.PaisId + '">' + obj.Nome + "- " + obj.Sigla + '</option>';
              })
              $('#mensagem').html('Total de paises encontrados.: ' + dados.length + '');
              $('#cmbPais').html(option);
            } else {
              $('#mensagem').html('Não foi encontrado nenhum país');
            }
          })
        })
        //

      function Reset() {
        $('#cmbPais').empty().append('<option>Carregar Países</option>>');
      }
    });

  Selecione o País:
  <select id="cmbPais">
    <option>Carregar Paises</option>
  </select>
  <input type="button" value="carregar pais" id="btnPais" class="bottom" />

e no meu Controller tenho :
 [HttpGet]
 public JsonResult ObterPaises()
{
   Comandos cm = new Comandos();
   string sql = "Select Nome FROM TPais";
   List<Pais> pais = new List<Pais>();

   var dr = cm.SelectReader(sql, CommandType.Text);
   while (dr.Read())
   {
      pais.Add(new Pais
      {
          PaisId = (int)dr[0],
          Nome = dr[1].ToString(),
          Sigla = dr[2].ToString()
      });
    }
    return Json(pais, JsonRequestBehavior.AllowGet);
}

Segundo o que pesquisei, usando este código, era pra me retornar a lista certa, porem, nem entra no método ObterPaises do controller.
Aberto a sugestões que possam me levar ao entendimento de como fazer.
Comment: `$each` = [**`$.each`**](https://api.jquery.com/each/).
Comment: É porque em momento algum você insere o conteúdo da variável `option` no select. Só está concatenando as `` nela. :)
Comment: Fiz a correção, agora entra no controller. porem não devolve nenhum dado para View
Comment: Resolvido, suas dicar foram fundamentais. Obrigado !!!
Answer: Opção 1: Mudar o retorno do controller:
[HttpGet]
public JsonResult ObterPaises()
{
   Comandos cm = new Comandos();
   string sql = "Select id, nome, sigla FROM TPais";

   var dr = cm.SelectReader(sql, CommandType.Text);
   var sb = new StringBuilder();
   while (dr.Read())
   {
      sb.AppendFormat("<option value={0}>{1} - {2}", dr[0], dr[1].ToString(), dr[2].ToString())
    }
    return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
}

E na view:


Why do I get the "is not a Parquet file" error when reading a parquet file

Question: The following error occures when reading a parquet file from an hdfs
2020-06-04 14:11:23 WARN  TaskSetManager:66 - Lost task 44.0 in stage 1.0 (TID 3514, 192.168.16.41, executor 1): java.lang.RuntimeException: hdfs://data-hadoop-hdfs-nn.hadoop:8020/somedata/serviceName=someService/masterAccount=ma/siteAccount=sa/systemCode=111/part-00170-7ff5ac19-98b7-4a5a-b93d-9e988dff07eb.c000.snappy.parquet is not a Parquet file. expected magic number at tail [80, 65, 82, 49] but found [55, 49, 98, 48]

I found similar problems on the internet but most people tried to read other filetypes than parquet.
I am 100% sure that this file is written in parquet format as can be seen in the logs. Filename is part-00170-7ff5ac19-98b7-4a5a-b93d-9e988dff07eb.c000.snappy.parquet .
There is only one job writing into this somdata folder and this one is only writing parquet (spark structured streaming job)
Ending also says it is a parquet file.
Other parquet files written by the same job don't throw this error
Comment: Have you tried this- https://thatbigdata.blogspot.com/2019/09/how-to-resolve-parquet-file-issue.html
Comment: Maybe try using parquet-tools (https://github.com/apache/parquet-mr/tree/master/parquet-tools) to validate your file is in proper parquet format.
Answer: Got this same error today. For us the problem was that we were generating parquet files > 2GB, which breaks some clients.
https://issues.apache.org/jira/browse/SPARK-24296
Setting the spark option maxRecordsPerFile to limit the file sizes fixed for us.


When developing models for effect estimation, is it advisable to perform internal validation and calibration using resampling methods? #rms

Question: In predictive modelling, it is useful to perform resampling methods to assess performance e.g. validate() and calibrate() in the rms package in R. Is it useful / advisable to perform such methods when the primary purpose is estimating effects e.g. hazard ratios from a Cox model, odds ratios from logistic regression etc.?
Answer: If you sole goal is effect estimation, then Frank Harrell says in Section 4.12.2 of Regression Modeling Strategies, 2nd edition:

Model validation is not necessary unless the analyst wishes to use it to quantify the degree of overfitting.

That said, the quality of your effect estimation depends directly on the quality of your model.  For your own peace of mind and that of your audience it can be helpful to quantify the degree of overfitting by model validation. You don't want to make an effect estimate based on a severely overfit model.
Evaluating model calibration might help identify problems with model specification (e.g., missing predictors or interaction terms associated with outcome); the effect estimated from a mis-specified model might not be correct. In Cox or logistic regression models, omitting any outcome-associated predictor from a model can bias the coefficient estimates of included predictors toward 0.
There's little cost to doing that validation and calibration and potentially much to gain.
Comment: Thanks EdM. I agree, which is why I found it strange that @Frank Harrell stated, "Model validation is not necessary unless the analyst wishes to use it to quantify the degree of overfitting" since in the introduction of his great book he says "Prediction could be considered a superset of hypothesis testing and estimation". So surely it follows that it is a worthwhile exercise to validate and calibrate the model using resampling even if the goal is effect estimation.


Read Text File with stream reader

Question: I want to read a text file that has 3 lines of data one line contains "Server = ..." The next line is "Username = .. " and the last line is "Password = ... " So I want to read this file and put each line into a separate label.. (label1,label2,label3)
OFDSet is my openfiledialog
All in Visual Basic..
Some one help?
Here is the code I tried but I get an error:
Dim oReader As StreamReader

        If OFDSet.ShowDialog = Windows.Forms.DialogResult.OK Then
            oReader = New StreamReader(OFDSet.FileName, True)
            ServLabel.Text = oReader.ReadLine(1)
            UserLabel.Text = oReader.ReadLine(2)
            PassLabel.Text = oReader.ReadLine(3)

        End If

Comment: and the error would be....?
Comment: and why dont you try reading the documentation:  http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx
Comment: NullReference Exception was unhandled it circles the
Comment: ServLabel.Text = oReader.ReadLine(1)
UserLabel.Text = oReader.ReadLine(2)
PassLabel.Text = oReader.ReadLine(3)
Answer: A simpler solution is through the File.ReadAllLines method that gives back an array of strings with just one call.
If OFDSet.ShowDialog = Windows.Forms.DialogResult.OK Then
    Dim lines = File.ReadAllLines(OFDSet.FileName)
    ServLabel.Text = lines(0)
    UserLabel.Text = lines(1)
    PassLabel.Text = lines(2)
End If

See the MSDN reference here
(File class needs an imports for System.IO)
Also if your first line is something like this
Server=MyServerPC

and you want only the part MyServerPC in the ServLabel you need to split the input at the = sign
ServLabel.Text = lines(0).Split("="c)(1)

Of course this is just an example. More robust error handling is needed. You should check if you have at least 3 lines and if each line is correctly separated by the = sign.
Comment: I use it and i get error? "Index was outside the bounds of the array."
Comment: Do you have at least 3 lines in the selected file? If you set a breakpoint on the first assignement, how many lines are contained in the array `lines`?
Answer: StreamReader.ReadLine() has no overload that takes a parameter.  Intellisense will show you two overloads because the return type, String, has an indexer.

Read Text File with stream reader


Double integral from rectangular region to polar

Question: $$\int_{-1}^{1} \int_{0}^{\sqrt{3+2y-y^2}} \cos(x^2 + (y-1)^2)) dy dx $$
How do I go about solving this? I tried substituting $x$ and $y$ for $r\cos(\theta)$ and $r\sin(\theta)$ and $x^2 + y^2 = r^2$. I can't seem to figure it out. So far I believe it's a rectangular region.
Comment: It looks a bit weird... the inner integral is on $\cos(\ldots)\, dy$ but its upper limit is a function of $y$. That doesn't make sense to me.  Are you sure you've copied the expression correctly?
Comment: Yes this is an exam question, I tried for a long time, but couldn't come up with a solution. Hence I thought it is a rectangle.
Comment: If so, I'm afraid your exam question should go back to its author for correction.
Comment: @zena have you got by any chance the exam answer as a double-check for the solutions hereby?
Comment: Sorry, no. But I verified and this is a wrong question.
Answer: $$I=\int_{-1}^{1} \int_{0}^{\sqrt{3+2y-y^2}} \cos(x^2 + (y-1)^2)) dx dy $$
The change of variables in polar coordinates with center $(0,1)$ :
$\quad \begin{cases}
x=r\cos(\theta)\\
y=1+r\sin(\theta)
\end{cases}$ .
$$I=\int_{-\pi/2}^0\int_{0}^{2} \cos(r^2) rdr d\theta $$
$$I=\int_{0}^2\cos(r^2) rdr \int_{-\pi/2}^0 d\theta $$
$$I=\left(\frac12\sin(2^2)\right)\left(\frac{\pi}{2}\right)$$
$$I=\frac{\pi}{4}\sin(4)$$
Comment: The first writing of the integral with $dxdy$ was correct. Now, with $dydx$ is is not possible to integrate the inner integral with respect to $y$ because the bound is a function of $y$. In the first writing the integration versus $x$ was possible because the bound is not function of $x$. You should correct again and come back to the previous writing. In fact it doesn't matter since everybody understand what is the double integration to perform.
Comment: Sorry, I made a mistake IT IS DY DX not the other way around, I fixed the question.
Comment: This was an exam question actually, with dy dx.
Comment: Doesn't matter. Obviously $y$ cannot varies from $0$ to $\sqrt{3+2y-y^2}$ . The student must understand that this cannot be the correct boundary.  As a consequence there is no other possibility that   $-1<y<1$ and $0<x<\sqrt{3+2y-y^2}$ as in my answer.
Answer: It is clearly NOT a rectangle. y goes from -1 to 1 and, for each y, x goes from 0 to $x= \sqrt{3+ 2y- y^2}$.  Squaring both side, $x^2= 3+ 2y+ y^2$.  $x^2- y^2- 2y= 3$, $x^2- y^2- 2y- 1= 2$.  $x^2- (y+ 1)^2= 2$.  That is a hyperbola with center at (0, -1).
Comment: It is a circle $x^2+(y-1)^2=4$ .
Comment: Sorry, I made a mistake IT IS DY DX not the other way around, I fixed the question.
Answer: $$\int_0^{-\frac{3\pi}{2}}\int_0^2\cos\left(r^2\left(\cos^2\theta\right)\ +\left(r\left(\sin\theta\right)-1\right)^2\right)rdrd\theta$$
This will do it!


Comparing groups at different time points within repeated measures study using SPSS

Question: I have done a RCT (randomized control trial) of an intervention (which is of 6 week duration) versus control. The outcome measure (an exercise test) has been tested pre-intervention (Pre), immediately after (Post-1), 6 months after (Post-2), and one year after intervention (Post-3).
I have done a repeated measures ANOVA in SPSS. There is no group difference at Post-3. However, looking at the means/plots at each time point there appears to be a difference between the groups at Post-1.
How would I test to see if there is a significant group difference at Post-1?
Comment: It is very bad practice to look at the descriptive results, pick the  time point with the largest effect and then happily report the significant result. Each time point needs to be treated and reported in a similar way unless otherwise stated in the study protocol.
Comment: Welcome to this site, @neil. I considerably edited your question. Please check and re-edit if necessary. Also, what does `mixed model` tag do here? Did you mean `ANOVA`?
Comment: I edited references to time-points, hopefully it's a little easier to read now.  If you are after a fun and readable chapter on repeated-measures ANOVA, Discovering Statistics Using SPSS by Andy Field is a good start.  With multiple time points, you might also consider how you would deal with missing data, as repeated measures ANOVA does list-wise deletion.
Answer: Although the answer could be very extensive explaining all aspects of a repeated measures design I will keep it short and answer the question directly. I think, however, that it is wise to do a bit more study on your own to be able to comprehend the answer completely.

You have to look whether the interaction between the group variable (control vs. intervention) and the factor variable (the measurements over time). Although you can proceed to the next step either way it is advised that you only do so in case this step is significant.
In the SPSS repeated measures menu you click options >> select interaction term >> drag to the right column >> click continue >> click ok. You now get descriptive statistics for each group for each time interval. Using the confidence intervals you can determine whether or not the two groups differ on a certain time point.

The syntax you have to add in the second step is:
<code>/EMMEANS=TABLES(Group*factor1) << replace variable with your variable
</code>
Answer: Are you sure you want to know whether the groups are statistically different or if there is a significant time by group interaction? I also do exercise studies and I am interested if the parameter changes over times significantly different in the respective groups. This would be the line labelled time*group.
Regarding the question directly: When I am interested in the changes between Pre and Post-1 I just do a seperate repeated measures ANOVA for this two time points.


Constructing the projection of a projective module from its dual basis

Question: Let $M$ be a (left) module over a not necessarily commutative algebra $A$.
We can say that $M$ is projective if, for some $n \in \mathbb{N}$,
i)  there exists a projection $P$ (i.e. $P \in M_n(A)$ and $P^2 = P$) such that
$$
P(A^n) = M,
$$
OR EQUIVALENTLY
ii) if we have a dual basis, that is to say, a set $\{m_{i}\in M \mid i = 1, \dots,n\}$, and a set $\{f_{i} \in \mathrm {Hom}(M,A)\mid i = 1, \dots,n\}$ such that for every $x \in M$,
$$
x = \sum_{i = 1}^n f_{i}(x)m_{i}.
$$
What I would like to know is: Given the dual basis, how can one construct the projection $P$?
Answer: The definitions given in the question are for finitely generated projective modules (although they can both be adapted for arbitrary projectives).
Given the dual basis, there are module homomorphisms $f:M\to A^n$ given by
$$f(x)=(f_1(x),\dots,f_n(x)),$$
and $g:A^n\to M$ given by
$$g(a_1,\dots,a_n)=a_1m_1+\dots+a_nm_n.$$
The definition of a dual basis gives that $g\circ f=\text{id}_M$, so $f$ is a split monomorphism and $f\circ g:A^n\to A^n$ is an idempotent endomorphism of $A^n$ with image isomorphic to $M$.
So the projection you want is just $P=f\circ g$, or in other words
$$P(a_1,\dots,a_n)=(f_1(a_1m_1+\dots+a_nm_n),\dots,f_n(a_1m_1+\dots+a_nm_n)).$$
Comment: How can we see that $M$ is isomorphic to the image of $P?
Comment: @FofiKonstantopoulou Since $g\circ f=\text {id}_M$, $f$ is injective, so the image of $f\circ g $ is isomorphic to the image of $g $, and $g $ is surjective, so the image of $g $ is $M $.
Comment: great, thanks very much!


how to use composer autoloader with __autoload?

Question: my composer.json content is:
{
    "require": {
        "rlanvin/php-rrule": "1.*"
    }
}

my own autolader is:
function __autoload($class_name) {
    include __DIR__.'/classes/'.$class_name . '.php';
}

Problem is: when I want to add tha composer autoloader with
require_once 'vendor/autoload.php';

My own autoloader does not work any more. (Class not found !)
How to make noth work (the composer autolader and mine) ?
regards
I tried:
<?php
require 'vendor/autoload.php';
User::get(1);

User.php is in /classes
composer.json
{
    "require": {
        "rlanvin/php-rrule": "1.*"
    },
    "autoload": {
        "psr-0": {
            "": "classes"
        }
    }
}

and 'got Class User not found'
It works find with my autloader:
function autoload($class_name) {
    include __DIR.'/classes/'.$class_name . '.php';
}
Comment: Have as many autoload functions as you want: ... use [spl_autoload_register -  Register given function as __autoload() implementation](http://php.net/manual/en/function.spl-autoload-register.php). Also: [How to use spl_autoload_register?](http://stackoverflow.com/questions/11131238/how-to-use-spl-autoload-register). They are called in sequence until a class is loaded. very useful.
Answer: You don't need your autoloader. Composer has plenty of options: PSR-0, PSR-4, classmap and files. Try classmap.
{
    "require": {
        "rlanvin/php-rrule": "1.*"
    },
    "autoload": {
        "classmap": [
            "classes"
        ]
    }
}

UPDATED: Or even better use psr-0 in the following way
{
    "require": {
        "rlanvin/php-rrule": "1.*"
    },
    "autoload": {
        "psr-0": {
            "": "classes"
        }
    }
}

Comment: Try running `composer dump` to update `autoload.php`
Comment: did not help: Class not found. I am using: require_once 'vendor/autoload.php';
Comment: No: shoud I run that ?  I just did and did not help
Comment: Still : Class User not found: Infact it looks like composer.json is ... totally ignored ! When I delete composer.json or rename it or change its content: it has no effect at all
Comment: That composer dump did it. Thanks!


Anchor com Javascript

Question: Tenho este código:
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Que funciona como anchor, fazendo com que meu menu me leve a uma determinada parte do site, no caso selecionado pela div. Enfim, um código normal para anchor. Preciso que esse código me leve á 110px acima da div selecionada, acho que fui claro.
Answer: Nessa parte:
scrollTop: target.offset().top
Coloque:
scrollTop: target.offset().top - 110
Comment: Perefito, muito obrigado pela resposta! +1
Comment: Eu que agradeço. Copiei seu código. Estava precisando de um que funcionasse em todos os browsers.
Comment: ahhahah ótimo então!

Anchor com Javascript


Referring to another variable in the same object with jQuery

Question: Alright, so I'm completely new to jQuery, so here goes:
I have a GameCard object which accepts a div in it's "constructor" which is then assigned to a variable. Within the object, I want to perform a function when that div is clicked.
function GameCard(imageSource, div)
{
    this.cardImage = new Image();
    this.cardImage.src = imageSource;

    this.hiddenImage = new Image();
    this.hiddenImage.src = HIDDEN_SOURCE;

    this.div = div;

    $(this).WHAT_HERE_?.click(function()
    {
    });
}

pretty much how do you refer to another variable within the same object using javascript?
Thanks in advance!
Comment: `$(this.div).click(function() {});` or if you're doing the assignment inside of the constructor you can even use the `div` parameter.
Answer: You wrap the div using the jQuery function.
$(div).on('click',function(){
  //do stuff
});

Comment: So if there's multiple objects of type GameCard, this function will only apply to the object it's wrapped within?
Comment: @JohnW it will only wrap the `div`. If you want multiple objects, you can place them in an array, and wrap that array with jQuery.
Answer: What is the id of your div?
Don't use $(this) in this context.
$("#IdOfDiv").click(function(){});

But wrap the above in this;
$(function(){});

This ensures that the jQuery code is not run until the document is loaded.
So;
$(function(){   $("#IdOfDiv").click(function(){
     //Do someting
  });
});


Calculating probabilities of events of different time periods

Question: The average probability of an event occurring is 3 times in a year.  What is the probability of:
1) an event occurring in any specific month; and
2) 10 events occurring in any specific month?
Comment: Are you familiar with Poisson distribution?
Comment: BTW 'average probability' is a very vague term
Comment: Alex, Matthew and Andre, Thank you for your interest, and Amdre you have provided what I needed.  It is looking at a powerline outage where we expect 3 outages per year, and the other cases are to stress test the reliability.  Frank
Answer: We use a Poisson model: the number $X$ of events per year has Poisson distribution with parameter $\lambda=3$.
Then it turns out that if $Y$ is the number of events in time interval $t$, then $Y$ has Poisson distribution with parameter $\lambda t$.
Taking a month as $\frac{1}{12}$ of a year, we find that the number of events in a specific month is has Poisson distribution with parameter $\frac{3}{12}$.
Now to the questions. What does "an event occurring in a specific month" mean? Exactly $1$ event? At least one event? There is lack of clarity.
If it is exactly $1$, then by the usual formula for probabilities governed by the Poisson, the answer is $e^{-3/12}\frac{3/12}{1!}$.
If it is at least $1$, the probability that $Y=0$ is $e^{-3/12}$, so the probability it is $\gt 0$ is $1-e^{-3/12}$.
For the probability of $10$ events in a month, we want $\Pr(Y=10)$. This is $e^{-3/12}\frac{(3/12)^{10}}{10!}$, extremely tiny.
Remark: There are a lot of unreasonable assumptions built into our model. I eat roast turkey on average once a year, roughly as little as I can get away with. The Poisson model would give a very inaccurate result for the probability I eat roast turkey in July.


Taxonomy terms with numeric names and views filtering within range

Question: I have a very large taxonomy vocabulary with numeric taxonomy term names like: 10123,10124,10125,... etc. My node have a min value field and max value field. Both fields are taxonomy referenced fields with this vocabulary.
How I can create views filter to find a nodes, where exposed filter value is between these two fields?
Example 1.

Node field min: Taxonomy term with name "10500"
Node field max:Taxonomy term with name "11000"
Exposed filter value: 10800

This is TRUE, so this node must be in views result.
Example 1.

Node field min: Taxonomy term with name "10500"
Node field max: Taxonomy term with name "11000"
Exposed filter value: 11500

This is FALSE, so this node should not be in views result.
Exposed filter value can be as taxonomy term autocomplete widget.
Any ideas, how it can realize?
I'm looking a solution in _views_query_alter, but I still can not understand is this right way?..
Comment: I'd just add an integer field and use rules to fill it on node add or update with the node's term's field name. Then use that as the filter. (This isn't good advice.. It's more of a last resort that would work.)
Answer: I believe a numeric range can be filtered using regular expression.
The following regex can effectively filter values within the range 10500 - 11000 (both ends inclusive)
(10[5-8][0-9]{2}|109[0-8][0-9]|1099[0-9]|11000)

Here is a sample view that works as expected with the above regular expression

You can create any numeric range as a regex using this generator http://gamon.webfactional.com/regexnumericrangegenerator/
Alternativelly what you can do is to add an extra numeric field to populate with term name (as a number) and than using that field to filter the view OR create a more complex function using hook_views_query_alter as you mentioned
Comment: Thank you! Did by adding extra numeric field. It's faster solution, for this moment it's suitable for me.


Visual Studio Development Server Directory

Question: If I make a new web project and run it - it works fine.    If I then change the output directory to something like ....\build - it nicely builds to there, but when you run with the development server, it's still trying to access the  project\bin path, and doesn't work.    Anyone have any idea how to tell it to look in the output directory instead?
Comment: Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts).
Comment: Why are you trying to make it not work?
Comment: we use a lot of extra tooling - and it's much easier if you have a directory that's all source and a directory that's all output - putting the output under the source makes a lot of things much more complicated.  With everything else, there's no problem to move it out - but for some reason it doesn't work with web projects
Comment: Are you using web site "projects", or web application projects?
Answer: It is quite simple, but you have to be careful and pay attention on the location.
Your question is also not clear enough. Are you planning to have different folders of output folder and dev server folder?
If you really want to separate this, then it should be quite easy.
On your web project properties, set post BUILD event to copy the file to the output directory.
Also don't forget to publish the IIS to the IIS folder of your development server.

The best practice is not to mix the output directory of your post build event with the folder of your development server as the development server is only for publishing web app.
Comment: I like the suggestion, but want this to work without IIS, with just the built in development server.
Comment: The built in development server is not a real server. It is an IIS Express, built in web server. If you search on MSDN Library, Microsoft will not recommend using IIS Express as your development server. I think you misuse the development server term and assuming the built in web server in Visual Studio is the development server. It is not a real development server.


Possible to merge 2 summations?

Question: I'm doing a homework assignment about neural networks and it suggests that it is somehow possible to merge 2 summations. In which, one contains the other. I thought that this was not possible..
Also I tried finding an appropriate tag but there were none :(.
Here's the question:

Suppose you had a neural network with linear activation functions. That is, for each unit the output is some constant c times the weighted sum of the inputs.
Assume that the network has one hidden layer. For a given assignment to the weights w, write down equations for the value of the units in the output layer as a function of  w and the input layer x, without any explicit mention of theb output of the hidden layer. Show that there is a network with no hidden units that computes the same function.

To explain this for those who don't know neural networks. A neural network has a set if inputs and a set of hidden layers. Those layers have a number of nodes.
The first hidden layer is connect to the second and the second to the third and finally the last layer is connected to the output layer.
The input layer has a certain number of nodes. Every input is connected to each node in the first hidden layer so that each node in the hidden layer takes all the inputs as an input.
Each input to a node on a hidden layer has a weight determining how much influence an input has on a node in the hidden layer.
The node in the hidden layer then applies an activation function (in my case a linear one) to the summation of the weighted inputs.
This linear activation function would look as follows:
$$
c \sum\limits_{i=1}^n w x_{i}
$$
Where c is the constant, n is the number of nodes in the previous layer, w is the weight of the input x.
This is what the neural network would look like if there where no hidden layers but just the input and the output layer. Where x denotes an input from the input layer.
Now if we would take a neural network with one hidden layer it would look like this:
$$
c \sum\limits_{j=1}^m w_{2} (c \sum\limits_{i=1}^n w_{1} x_{i})_{j}
$$
As you can see this applies the linear activation function of a hidden layer and sets it as the input x of the output layer.
I hope this is clear so far.
Now for my question. It is suggested that these summations are some how merge-able into one summation because it is suggested that there is a neural network NO hidden units that achieves the same.
I have virtually no experience using summation (I know what they do but not how they interact with other summations).
This is what I got using my basic understanding:
$$
c^2 \sum w_{2} (\sum w_{1} x)
$$
The only constant in the equation is of course c so that is the only one I can move through the summations as far as I know.
So basically how do I rewrite equation two into the form of equation one?
Thanks in advance, Rope.
Comment: I guess the weight functions have no special properties, such as being additive, huh?
Comment: What do you mean by that? Is it a hint towards an answer or just a question? Because the weights functions indeed do not do anything special.
Answer: My knowledge of neural networks is minimal, so take this with a grain of salt. Also, I may have done it in more generality than the problem requires.
I'm assuming $n$ inputs and $m$ nodes in the hidden layer. I'm assuming that each node in the hidden layer has its own linear activation function, with its own constant and weights; the function for node $k$ is
$$y_k=c_{1k}\sum_{i=1}^nw_{1ki}x_i\;,\tag{1}$$
with constant $c_{1k}$ and weight $w_{1ki}$ for input $x_i$. Similarly, I'm assuming that each node in the output layer has its own linear activation function, with its own constant and weights; the function for node $j$ is
$$z_k=c_{2j}\sum_{k=1}^nw_{2jk}y_k\;,\tag{2}$$
with constant $c_{2j}$ and weight $w_{2jk}$ for input $y_k$. Substituting $(1)$ into $(2)$, we get
$$\begin{align*}
z_j=c_{2j}\sum_{k=1}^mw_{2jk}y_k&=c_{2j}\sum_{k=1}^mc_{1k}w_{2jk}\sum_{i=1}^nw_{1ki}x_i\\
&=c_{2j}\sum_{i=1}^n\left(\sum_{k=1}^mc_{1k}w_{2jk}w_{1ki}\right)x_i\;;
\end{align*}$$
this expresses the output $z_j$ directly as a linear activation function of the inputs $x_i$, with constant $c_{2j}$ and weight
$$\sum_{k=1}^mc_{1k}w_{2jk}w_{1ki}$$
for input $x_i$.
This can all be done more easily with matrices. If there are $r$ output nodes, let
$$W_1=\pmatrix{c_{11}w_{111}&\dots&c_{11}w_{11n}\\\vdots&\ddots&\vdots\\c_{1m}w_{1m1}&\dots&c_{1m}w_{1mn}}\text{ and }W_2=\pmatrix{c_{21}w_{211}&\dots&c_{21}w_{21m}\\\vdots&\ddots&\vdots\\c_{2r}w_{2r1}&\dots&c_{2r}w_{2rm}}\;,$$ and let $$X=\pmatrix{x_1\\\vdots\\x_n},Y=\pmatrix{y_1\\\vdots\\y_m},\text{ and }Z=\pmatrix{z_1\\\vdots\\z_r}\;.$$ The matrices $W_1$ and $W_2$ incorporate all of the information contained in the activation functions. Then $Y=W_1X$ and $Z=W_2Y$, so $Z=W_2(W_1)X=(W_2W_1)X$; i.e., the product matrix $W_2W_1$ similarly incorporates the constants and weights expressing the output $Z$ in terms of the input $X$.
Comment: I actually had something similar at one point but discarded it as I thought it might not be correct.
But I think this is as close to an answer as I'll get.

So basically I can get the form of the linear activation function but there is no way I can actually discard the inner summation? I'm guessing that's because it's an intrinsic part of the function?

Thanks for your answer :D!
Comment: @Rope: You can't discard the information contained in the inner summation, but in principle you can calculate the weights $w_{3ji}=\sum_{k=1}^mc_{1k}w_{2jk}w_{1ki}$ once and for all, and then you have directly $z_j=c_{2j}\sum_{i=1}^nw_{3ji}x_i$, just as if there were no hidden layer. I'm reasonably certain that this is what the problem is getting at.
Comment: Yeah I figured as much. Thanks for the help! I'll mark this as the answer.
Comment: I have one last question. How is it that when you create the form of a linear activation function, you swap the two summations? I get it has to be done because you want it to apply to the input layer but why is this allowed? As in, can you explain why you're allowed to do this?
Comment: @Rope: To take a simple example, $\sum_{i=1}^n\sum_{j=1}^ma_{ij}=\sum_{j=1}^m\sum_{i=1}^na_{ij}$ because both expressions give you the sum of all the $a_{ij}$ in an $n\times m$ matrix. The first double sum adds up each row and then adds the row totals; the second adds up each column and then adds the column totals. It's like a double integral over a rectangular region: the order of integration doesn't matter.
Comment: I get it. Thank you :).

Possible to merge 2 summations?


How to stop scrolling of row of UITableView inside of header UITableView

Question: When I am scrolling vertically row is going inside of headerview of table, how will change to stop going of row inside of header of UITableView. I have some important view which should show always top of UITableView and if user scroll it should hide as row hides.
Going row in top header should also go on top.
I mean it should show attaching headerview with first row.
Comment: rewrite your question properly. cant understand exactly what you want
Comment: header should also go up as user scroll?
Comment: Yes..exactly..same as row is going up..
Comment: then add 1 extra cell on top. if you put header view it wont go as row.
Comment: Do you mean section headers or the table header?
Comment: check this [http://stackoverflow.com/questions/1074006/is-it-possible-to-disable-floating-headers-in-uitableview-with-uitableviewstylep](http://stackoverflow.com/questions/1074006/is-it-possible-to-disable-floating-headers-in-uitableview-with-uitableviewstylep)
Comment: This question is already discussed here: [Change Default Scrolling Behavior of UITableView Section Header](http://stackoverflow.com/questions/664781/change-default-scrolling-behavior-of-uitableview-section-header)
Answer: keep numberOfCell
array.count+1

In cellForRow method
if(indexPath.row == 0)
{
    //create your cell as header and return
}
else
{
     //return normal cells
}

Comment: hmmm..ok.. that I was thinking to do.. but I thought if there would be any function which disabled the scrolling of rows inside of section...accepting this answer..
Comment: to make more clean code you can add two sections. in section 0 add one cell and in section 1 add others. njoy coding


UIWebView first request too slow

Question: I am using UIWebView to render web content in my application. I observed that the initial request when the app launches i.e. loadRequest, takes a long time to render the contents. However the subsequent requests which I don't track of, are much faster.
To confirm this, I created a standalone application which just has a UIWebView. This is the single line of code which I have added :
[wkBrowser loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.yahoo.com"]]];

The result is same. It takes around 15-20 seconds to load the page. However on tapping any link on web page, it takes 3-5 seconds to load the next page. I did put the UIWebView delegate function didFailLoadWithError, but there is never an error.
Question:

Why is the first web request so slow ?
How may I make it faster other than caching ?
Comment: You are working on simulator or any device?
may be there is some proxy open on your device.
Comment: @aBilal17 : I am testing this on device. Not just one. I tested this on 3 different devices.
Comment: Please add this line as well and then check.
web.scrollView.delaysContentTouches = NO;
Comment: @aBilal17 : Didn't make difference.
Comment: Does it happen only with https://www.yahoo.com? How about other websites?
Comment: @lambao : It varies. I tried with 4-5 url's. Least taken was by google.com of 4-5 seconds.
Comment: Maybe MainThread was blocked, try open urls in blank UIViewController and see what happen.
Comment: @lambao : As I mentioned, the sample project I created to confirm this, has just a UIWebView and nothing else. Can you explain how may I load url in **blank UIViewController** ?
Comment: Sorry, I'm misreading. Blank UIViewController here I mean a UIView with only UIWebView, and just load url when viewDidLoad. Aw, strange situation I thinks. Is Safari or Chrome slowly as well?
Comment: @Nitish : The issue is all about the server spending time in resolving the browser type so as to respond back with the right compatibility page. Kindly see my answer below.
Comment: Try using the Charles application to proxy and record your web server interaction. That should show you which transactions, if any, are being delayed to help you figure out if its your app, the server or a combination of both.
Answer: The main reason is because, when you invoke the first time URL request, the server on the receiving end tries to display the information as per the requested device browser, ( like mobile, desktop). This is where you see a bit of delay.

The server take some time to resolve the request origin browse type & respond according to the browser type. This value is internally send from the browser. There is a difference in mobile safari & desktop safari.
The Server upon receiving the request, responds you back with the device type compatible page, ( mostly all domain servers are implementing this internally, the responsive pages).
If you want a "no delay situation", try calling the exact mobile version of the portal in concern.
The sub-sequent requests are treated from a known type browser, hence reducing the delay in response.

Hope this solves the doubt.
Comment: I disagree. I have a static page being displayed from the app's bundle:

 `let bundlePath = Bundle.main.bundlePath.stringByAppendingPathComponent("description.html")`

`let url = URL(fileURLWithPath: bundlePath)`

`let request = URLRequest(url: requestURL)`

`webView.loadRequest(request)`

So where's network & server delay?
Comment: Does this matter when most websites use a responsive approach where the interface just adjusts to the screen size, so that there is no "other" version of the portal for mobile to call?
Answer: The answer of your first question is following:
When you're loading request for the first time, the webview downloads and caches all the files like css, images, etc... After, when you click on a url that brings you to another page of the same website, it's basically loads it from the cache instead of downloading again, and it saves a lot of time.
Comment: But the second page is also loaded for the first time when the app is first launched. There is no cache at that time for that page. It is only when the page is visited again, page is loaded from cache.
Answer: There are multiple reasons the first load might be slower than subsequent loads.
First of all, your application is linking to dynamic frameworks. Dynamic link resolution is performed lazily. So whenever you use the UIWebView for the first time, there is a very small overhead involved with resolving the symbols you have used from the dynamic library. The UIWebView itself could depend on some more internal libraries that need to be dinamically linked, adding to that overhead.
Then there is also the implementation of the UIWebView itself. The UIWebView's internal most likely involve data structures that are initialized lazily.
Then there is the memory allocation aspect. Whenever you make your first page load, the memory usage of your application rises much more than what it does upon the second page load. Allocating sufficient memory to process a page load adds to the overhead, but once that is done, iOS will entrust this memory to your application for some period of time that exceeds the point where the memory was deallocated in order to make your application faster when it hits peaks in its memory usage.
Someone suggested that there might be cached resources between your two pages. Even if both pages are different and are being loaded for the first time, they might share a common css file or a common javascript file such as jQuery. Then the browser is able to reuse those cached resources.
Overall, there are a lot of factors like these that explain why the first page load might be slower than subsequent page loads. You could get to know more about what the UIWebView is actually doing by profiling the application during both page loads.
Answer: The answer of your first question:
When you're loading request for the first time, the webview downloads and caches all the files like css, images, etc... After, when you click on a url that brings you to another page of the same website, it's basically loads it from the cache instead of downloading again, and it saves a lot of time.
Answer: One thing you can do here to see what is going on is to implement an NSURLProtocol similar to the following link: http://www.raywenderlich.com/59982/nsurlprotocol-tutorial
and intercept your requests in the canInitWithRequest method.
This will only show you what is going on with your requests at least.
Answer: Just load UIWebView with a dummy page off-screen, during your app's launch.This will work well on real devices.
In AppDelegates didFinishLaunchingWithOptions method.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.loadInitialWebView()
        return true
    }

func loadInitialWebView() {
        var dummyWebView : UIWebView? = UIWebView(frame: UIScreen.main.bounds)
        let htmlString = "<!doctype html><meta charset=utf-8><title>dummy</title>
dummy content
"
        dummyWebView?.loadHTMLString(htmlString, baseURL: nil)
        dummyWebView = nil;
    }

UIWebView first request too slow