How to count elements inside list with specific condition

Question: I am making combination of six number is seems easy but i need output of specific combination
i think i need to use count function and loop?????
from itertools import combinations

comb = combinations([1, 2, 3, 4, 5, 6], 3)
for n in list(comb):
  print (n)

Actual result give me 20 combination, but i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3,
so in my case it will be
(1,2,3) (1,3,4) (1,4,5) (1,5,6) (2,3,5) (2,4,6)

Comment: not really related, but `for n in list(comb)` is unnecessary (and inefficient), just use `for n in comb:`
Answer:
i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3

Add that as an if statement inside the for loop:
for n in comb:
    if n[0] + n[1] == n[2]:
        print (n)

Answer: Another solution:
result = [(x,y,z) for (x,y,z) in combinations([1, 2, 3, 4, 5, 6], 3) if x+y==z]
print(result)

[(1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (2, 3, 5), (2, 4, 6)]

Answer: Try this oneliner:
from itertools import combinations as combs
print(list(filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3))))

Or if your want to print one combination at a time you can do:
from itertools import combinations as combs
for comb in filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3)):
    print(comb)

Comment: @Olga973 welcome to stackoverflow. U can mark my answer as accepted if it solved your problem.


Equality of dimension of $\bigwedge^2(\Bbb R^n)$ and $\text{SO}(n)$

Question: The dimension of $\bigwedge^2(\Bbb R^n)$ as a vector space is $\frac{n(n-1)}{2}$, while the dimension of $\text{SO}(n)$ as a manifold is also $\frac{n(n-1)}{2}$. Even though they don't look exactly the same ($\text{SO}(n)$ is not a vector space), I feel like $\bigwedge^2(\Bbb R^n)$ and $SO(n)$ are somehow related to each other. Is it really the case?
Here is my thought. The vectors in $\bigwedge^2(\Bbb R^n)$ somehow behave like the entries of a skew-symmetric matrix: for any entry $a_{ij}$ in a skew-symmetric matrix, we have $a_{ij}=-a_{ji}$, while for vectors in $\bigwedge^2(\Bbb R^n)$, $e_i\wedge e_j=-(e_j\wedge e_i)$. So we can identify vectors in $\bigwedge^2(\Bbb R^n)$ as skew-symmetric matrices of order $n$ by an isomorphism.
The dimensions of the vector space of skew-symmetric real matrices of order $n$ and $\text{SO}(n)$ are both $\frac{n(n-1)}{2}$. I think this is not a coincidence, as the matrix exponential of a skew-symmetric matrix is an orthogonal matrix. However, I have never seen anyone claiming that the equality of dimensions is due to the exponential relation.
So, do $\bigwedge^2(\Bbb R^n)$ and $\text{SO}(n)$ actually have some subtle relations? Or am I just imagining things, and the equality of dimensions is purely a coincidence?
Edit: What I want to know is if we could actually relate the vectors in $\bigwedge^2(\Bbb R^n)$ and matrices in $\text{SO}(n)$ in a canonical way. For instance, whether we could identify a matrix in $\text{SO}(n)$ with an element in $\bigwedge^2(\Bbb R^n)$.
Edit 2: It happens that the question I have in mind may be related to physics. See this post on Physics Stack Exchange. Sorry for not including the original context.
When I consider $\bigwedge^2(\Bbb R^n)$, it is actually the vector space of all angular momenta, and $\text{SO}(n)$ is the group describing rotational symmetry. What I actually have in mind is that

the equality of the dimensions may be due to that angular momentum is the conserved quantity corresponding to rotational symmetry.

For more details, see the post in Physics Stack Exchange.
Comment: @Omnomnomnom Yes, I know. I just wanted to show you that I think ahead.
Comment: You should be using $\wedge$ `\wedge` or $\bigwedge$ `\bigwedge`, not $\Lambda$ `\Lambda`
Comment: @Omnomnomnom All right, I replaced it in my answer!
Comment: @DietrichBurde moreso directed at the asker, but go for it
Comment: Related: http://math.stackexchange.com/questions/1887082/exterior-product-generates-the-infinitesimal-rotations-what-is-the-geometric
Answer: Geometric algebra routinely maps $\bigwedge^2 \mathbb{R}^n\to \mathrm{Spin}(n)\to\mathrm{SO}(n)$ via the exponential map (defined via the usual infinite sum within a Clifford algebra) and then via a quotient by $\mathrm{Z}_2$, the latter as the double cover.  Bivectors are a useful way of expressing rotations through this map.  So the connection is well-understood, and is used all the time.  This works for the indefinite orthogonal groups too.
To answer your final "edit" question: yes, the map is canonical.  Given an orthonormal basis, the elements of $\bigwedge^2\mathbb{R}^n$ is interpreted in the canonical way as the exterior square of ${R}^n$.  The matrix representation of the final rotation of any vector can be determined in terms of the original basis.  Intuitively, the bivector space specifies the rotation unambiguously (in 3-d, the plane and the oriented angle of rotation), and the final rotation is unambiguous, and thus also its matrix in terms of the original basis.
Comment: Is there any known expression for $\exp(x\wedge y)$, for $x\wedge y\in\bigwedge^2\mathbb{R}^n$? Or do we have to work with the series?
Comment: @AndreGomes - A simple bivector $x\wedge y$ squared according to the wedge product is just $x\wedge y\wedge x\wedge y=-x\wedge x\wedge y\wedge y=0$, since $x\wedge x=0$ for any vector $x$. But using the geometric product it's $(x\wedge y)^2=(x\cdot y)^2-(x\cdot x)(y\cdot y)<0$ (Cauchy-Schwarz); this negative number can be called $-\lVert x\wedge y\rVert^2$, thus defining a magnitude of the bivector. We define a corresponding unit bivector $i=(x\wedge y)/\lVert x\wedge y\rVert$ so that $i^2=-1$ (...)
Comment: (...) and then Euler's formula gives $$\exp(x\wedge y)=\cos\lVert x\wedge y\rVert+\frac{x\wedge y}{\lVert x\wedge y\rVert}\sin\lVert x\wedge y\rVert.$$ The situation is more complicated for non-simple bivectors; the general approach is to decompose it into a sum of commuting (or orthogonal) simple bivectors.
Comment: (I forgot to add after the first sentence: The exponential would then be $$1+x\wedge y+\frac{(x\wedge y)\wedge(x\wedge y)}{2!}+\frac{(x\wedge y)\wedge(x\wedge y)\wedge(x\wedge y)}{3!}+\cdots$$ $$=1+x\wedge y.$$ But this is not used.)
Comment: Yes, indeed.  The exponentiation is in terms of the geometric product, not the exterior product.  That was what I meant by "within a Clifford algebra", since the exterior product is not one of the Clifford algebra operations, even though it can be used (after defining the exterior product in terms of the geometric product).  There are non-canonical ways to define it, but there is a canonical way when 2 is invertible in the algebra.
Answer: We can attach a vector space of dimension $\binom{n}{2}$ to $SO(n)$, namely its Lie algebra $\mathfrak{so}(n)$, which consists of skew-symmetric matrices of order $n$. Since we have dimension equality, i.e., $\dim SO(n)=\dim \mathfrak{so}(n)=\dim \wedge^2(\mathbb{R}^n)=\binom{n}{2}$, as for all connected Lie groups $G$ with Lie algebra $\mathfrak{g}$ holds $\dim G=\dim \mathfrak{g}$, your claim on the equality of dimensions is correct. For more information on Lie group-Lie algebra correspondence see here.
Answer: Hint. The tangent space of $SO(n)$ is exactly the space of skew-symmetric matrices. The same holds of $SU(n)$, whose tangent space is the space of Hermitian matrices. Check it!
Answer: You are right saying that $\text{SO}(n)$ is a group, not a vector space. But is has an associated vector space - the tangent space at any point, which is also $\frac{n(n-1)}{2}$-dimensional. Furthemore, the tangent space at identity can be enriched with some algebraic structure - anticommutative multiplication, aka Lie bracket $[x,y]$ - that makes it into the Lie algebra $\mathfrak{so}(n)$. This algebra is isomorphic to the Lie algebra of $n\times n$ skew-symmetric matrices, if the commutator is taken as the Lie bracket: $[x,y]=xy-yx$.
The trick is how to relate $\Lambda^2\left(\mathbb{R}^n\right)$ and $\mathfrak{so}(n)$. We can embed $\Lambda^2\left(\mathbb{R}^n\right)$ into  $(\mathbb{R}^n)^{\otimes 2}$, say, via $x \wedge y \mapsto x\otimes y - y\otimes x$, and use the scalar product to identify vectors with forms and identify tensors with linear transformations. This way, $\Lambda^2\left(\mathbb{R}^n\right)$ will get mapped to skew-symmetric linear transformations.
Answer: Given any Lie group $G$ (say a matrix Lie group for simplicity), any differentiable path through the identity will have a velocity vector. The collection of all of these form the tangent space for $G$ at the point $\mathrm{Id}\in G$, called the lie algebra $\mathfrak{g}$ (it has a binary operation coming from conjugation in $G$), which will be a vector space having the same dimension as $G$.
In 3D all rotations are rotations $R$ around an axis $\ell$. However, this description doesn't generalize to higher dimensions. Instead, think of the plane $\Pi$ perpendicular to the axis: then $R$ acts as a 2D rotation when restricted to $\Pi$ and acts as the identity map restricted to $\ell$. This generalizes: in any real inner product space $V$, given any 2D oriented subspace $\Pi$ and angle $\theta$ we can form a plane rotation $R(\Pi,\theta)$ which acts as a 2D rotation by the angle $\theta$ along the orientation when restricted to a function of $\Pi$, and acts as the identity map on $\Pi$'s orthogonal complement.
In fact, every rotation $R\in\mathrm{SO}(V)$ is expressible as a product
$$R=\prod_i R(\Pi_i,\theta_i) $$
of plane rotations $R(\Pi_i,\theta_i)$, where $\{\Pi_i\}$ is a collection of pairwise orthogonal oriented 2D subspaces of $V$, and $\{\theta_i\}$ is a collection of angles. In fact if the angles are distinct the collection of planes in the decomposition is unique. Since the planes are all orthogonal, all of the plane rotations appearing as factors in the product will commute, so there's no reason to specify order.
This is equivalent to saying $R$'s Jordan block decomposition (using some coordinates) is a bunch of $2\times 2$ rotation matrices (plus maybe a $1\times 1$ block with the entry $1$).
If we view $R(\Pi,t)$ as a function of $t$ for some fixed plane $\Pi$, then it is a one-parameter subgroup, i.e. a group homomorphism $R(\Pi,-):\mathbb{R}\to\mathrm{SO}(V)$, and differentiating at $t=0$ gives
$$ \left.\frac{d}{dt}R(\Pi,t)\right|_{t=0}=E(\Pi)$$
where $E(\Pi)$ acts as a right-angle rotation when restricted to $\Pi$ and acts as the zero map on $\Pi$'s orthogonal complement. (To see this, differentiate the definition of $R(\Pi,t)$ "componentwise.") Compare this with the situation for complex numbers: $R(\mathbb{C},t)$ is multiplication by $e^{it}$, whose derivative at $t=0$ is $i$, and multiplication by $i$ is a right angle rotation.
The corresponding representation of "infinitessimal rotations" $E\in\mathfrak{so}(V)$ is
$$ E=\sum_i c_iE(\Pi_i) $$
where again $\{\Pi_i\}$ is are oriented, pairwise orthogonal, and now $c_i$ are scalars.
Note that $R$ being an orthogonal transformation of $V$ means $\langle Ru,Rv\rangle=\langle u,v\rangle$ for all $u,v\in V$. If we view $R$ as a differentiable function of $t$ with $R(0)=I$ and $R'(0)=E\in\mathfrak{so}(V)$, then differentiating this property gives $\langle Eu,v\rangle+\langle u,Ev\rangle=0$. Using $\langle u,Ev\rangle=\langle E^Tu,v\rangle$, we may write this as $\langle (E+E^T)u,v\rangle=0$ for all $u,v$, which implies $E+E^T=0$, i.e. $E$ is a skew-adjoint transformation. (With matrices, this means $R$ is an orthogonal matrix and $E$ is a skew-symmetric matrix.)
Let's switch gears for a moment. Every element of $\bigwedge^2 V$ is a linear combination of wedges $a\wedge b$, and given any particular wedge $a\wedge b$ we may write decompose $b$ into parallel/perpendicular components with respect to $a$ via $b=b_{\|}+b_\perp$, in which case
$$ a\wedge b=a\wedge (b_{\|}+b_\perp)=a\wedge b_{\|}+a\wedge b_\perp=a\wedge b_\perp $$
since $a\wedge b_{\|}=0$ (we may write $b_{\|}=\lambda a$ so this is $a\wedge \lambda a=\lambda(a\wedge a)=0$), and thus without loss of generality all wedges $a\wedge b$ are with $a,b$ orthogonal. Next, we may write $a=r\hat{a}$ and $b=s\hat{b}$, in which case $a\wedge b=(r\hat{a})\wedge(s\hat{b})=(rs)(\hat{a}\wedge\hat{b})$, so every element of $\bigwedge^2 V$ is a linear combination of $a\wedge b$ with $a,b$ orthonormal, (The same procedure can be done to any element of $\bigwedge^r V$ more generally, which is essentially the Gram-Schmidt process.)
Next, if we depict $a,b$ as directed axes in some 2D plane $\mathrm{span}\{a,b\}$, we may wonder what happens to the element $a\wedge b$ if we rotate it within this plane by an angle of $\theta$ say:
$$(\cos(\theta)a+\sin(\theta)b)\wedge(-\sin(\theta)a+\cos(\theta)b). $$
Distributing, using $a\wedge a,b\wedge b=0$ and $b\wedge a=-a\wedge b$ gives
$$ \cos^2(\theta)(a\wedge b)-\sin^2(\theta)(b\wedge a)=a\wedge b.$$
In other words, the element $a\wedge b\in\bigwedge^2 V$ is unaffected by rotating $\{a,b\}$ within their span. Therefore, given any 2D oriented subspace $\Pi$ of $V$, we may pick an ordered orthonormal basis $\{a,b\}$ for it, and then represent $\Pi$ by $a\wedge b$.
(In this way, the oriented Grassmanian $\widetilde{\mathrm{Gr}}(2,V)$, the manifold whose points are 2D oriented subspaces of $V$, may be embedded as a submanifold of $\bigwedge^2V$. This generalizes to $\bigwedge^r V$ too.)
Putting it all together, we now have a way to describe a canonical vector space isomorphism $\bigwedge^2 V\to\mathfrak{so}(V)$ by sending $a\wedge b\mapsto\mathrm{span}\{a,b\}$ (oriented span) whenever $\{a,b\}$ is an ordered orthonormal set and then extending linearly.


Getting 404 with locall IIS 7 served page

Question: My setup:
Vista 64-bit PC (my local PC)
IIS 7 obviously
VS 2008
I setup a new "Application" manually under the IIS default site.  It's running.
The application is pointing to the correct directory (where my default.aspx exists)
I've setup this same exact setup on our dev server running Server 2008 and it runs fine
But for me, when I go to http://localhost/MyAppName I get a 404 not found.
I have no clue why.
So since that did not work and still got a 404, then I tried instead changing from using the VS web server to using IIS in my web project properties in the "Web" tab in VS 2008.  Then clicked the "Create Virtual Directory" button and it created a new Application in IIS for me.  Same thing though.  If I go to that address, I get a 404 on my local machine where it's running.
Comment: What happens if you create a new site instead of an app/virtual directory?
Comment: Going to uninstall / Reinstall IIS...
Answer: Ok, I had not installed the IIS 6 functionality of IIS in Vista.  I did not know it still used legacy features in IIS 7 to run sites locally....I guess.  Not sure why but I guess it uses these IIS6 features.  Will have to research why it's dependent on this stuff.
Comment: would be nice if there was a decent book out there on IIS 7.  Any sites I see don't really give you any specific information either...the resources kinda suck.
Answer: Do you have the home directory to look for "default.aspx" as the default page?
Comment: well, when I look at the default document area, default.aspx is in there, it's there by default after installing IIS and enabling asp.net and always is there....if that's what you mean.
Answer: A couple things to check:
First, look at your access logs to see exactly what request is getting logged.
Check your IIS config - you may have a default.aspx page, but is IIS configured to use that as one of the default pages?  If you go to http://localhost/AppName/default.aspx do you still get a 404?
If you put a static test.html file in the same directory, can you access it?
These should all help determine the cause.
Comment: (If you go to http://localhost/AppName/default.aspx do you still get a 404?)  Yes
Comment: (If you put a static test.html file in the same directory, can you access it?) No


Swift json deserialize

Question: Olá, tenho o seguinte código para deserializar um json:
let urlFinal = URLSERVIDOR+"/Geral/consulta?idcliente=\(id)"
        let jsonUrl = urlFinal
        let session = NSURLSession.sharedSession()
        let shotsUrl = NSURL(string: jsonUrl)

        let task = session.dataTaskWithURL(shotsUrl!) {data, response, error in
            guard data != nil else {
                falha()
                return
            }

            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]
                let J = jsonData as! NSDictionary
                let us = J["ServicoCliente"]
                var mstemp = [servicocliente]()
                mstemp <-- us
                dispatch_async(dispatch_get_main_queue(),{
                    sucesso(servs: mstemp)
                });
            } catch _ {
                print("##")
                falha()
            }
        }
        task.resume()

Ele funciona muito bem, mas em alguns jsons específicos ele vem apresentando erro, falhando na linha
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]

Eu uso a biblioteca jsonHelper, mas ele falha antes mesmo na parte que utiliza ela (var mstemp = servicocliente; mstemp <-- us).
Não consigo encontrar o motivo da falha, o json que estão baixando é o seguinte:
{"ServicoCliente":[{"id":"190","cliente":"229","enderecoFavoritos":"41","servicoProfissional":"191","ind_estado_cliente":"A","ind_estado_profissional":"","profissional_id":"230","profissional_nome":"Athila Zuma","servicotipo_nome":"Clínica / Hospital","servicosubtipo_nome":"Consulta","dta_inc_alt":"2016-10-24 20:59:43.473","ind_finalizado":"N"},{"id":"192","cliente":"229","enderecoFavoritos":"46","servicoProfissional":"194","ind_estado_cliente":"A","ind_estado_profissional":"","profissional_id":"240","profissional_nome":"Max","servicotipo_nome":"shop","servicosubtipo_nome":"Tosa ","dta_inc_alt":"2016-11-03 00:54:58.682","ind_finalizado":"N"},{"id":"193","cliente":"229","enderecoFavoritos":"47","servicoProfissional":"195","ind_estado_cliente":"O","ind_estado_profissional":"O","profissional_id":"243","profissional_nome":"Ultra","servicotipo_nome":"Clínica / Hospital","servicosubtipo_nome":"Emergência 24H","dta_inc_alt":"2016-11-05 11:12:34.536","ind_finalizado":"Y"}]}

Como poderia obter essas informações sem causar esse erro?
Comment: Talvez seja pq esse json não está usando o unicode correto para escapar alguns caracteres, já tentou enviar o json sem esses chars especiais?
Comment: Eu não tenho acesso ao server, sera que tem como tratar isso no swift? @JanCássio
Comment: Athila, tem um repositório no GitHub demonstrando o funcionamento de um app todo em JSON. Acho que pode ser bastante útil para você. Veja: [https://github.com/ethanwang/Artistry](https://github.com/ethanwang/Artistry) Espero ter ajudado. Abraços!
Answer: Tente usar:
    public class func serializeJSON(dictionary: NSDictionary) -> NSData? {
        var data: NSData? = nil
        do {
        data = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
        } catch let error as NSError {
            print("SMCore ->  Error JSON Serialization: \(error) --<<<", terminator: "")
        }
        return data
    }

Swift json deserialize


React rendering with different content based on api response

Question: const LinkList = () => {
    const [links, setLinks] = useState([]);
    const url = 'http://localhost:5000/xyz';

    const hook = () => {
        console.log('effect');
        axios
            .get(url)
            .then(response => {
                setLinks(response.data.links);
            })
            .catch(err => console.log("couldn't fetch data", err))
    }

    useEffect(hook, []);

    return(

 link list page

                {
                    links.map((link, index) =>
 {link.link}
)
                }

    )
}

I want the above component to render a different message, based on the response from the api being called. For example, if the api returns: {'message': 'No links found'}, then I don't want to render the ul tag with links but want to render a p tag with a message saying that no links were found.
How can I make this happen?
Comment: Somehow no one linked to this yet: [React Documentation on Conditional Rendering](https://reactjs.org/docs/conditional-rendering.html)
Answer: Perhaps it would be better to check the links array length instead? If it's empty - no links were returned by API.
{links.length > 0 ? (

      {links.map((link, index) =>
 {link.link}
)}

) : (

No links found!

)}

Answer: In this particular case, wouldn't checking for the length of your "links" state be enough? you could render your message if the length is equals to 0


How do I make second div move down and up with the w and s keys on the keyboard?

Question: The Problem I'm having is that the everytime i trigger the event key for w and s characters, it logs on the console showing the w event key being triggered, but nothing happens to the div as i want it to move up and down. I tried to use the code structure as the first div but could only get a console.log(e). How do i make it move up or down?
I'm building pong on basically div elements, and some js. I got the first paddle to work. When i tried to the run the same code but using keydown funtion and use e.key to equal w. It for some reason is shown console logging the w key being press down, but it never moves the second div.

var playerOne = document.getElementById("playerOnePaddle");
var playerTwo = document.getElementById("playerTwoPaddle");

console.log(playerOne);
console.log(playerTwo);

 window.addEventListener('keydown', function (e) {
   var y = parseInt(getComputedStyle(playerOne).top);
   e.preventDefault();

   if (e.key === "ArrowUp") {
      y -= 1;
      playerOne.style.top = y + "px";
      console.log(e);
    } else if (e.key === "ArrowDown") {
      y += 1;
      playerOne.style.top = y + "px";
      console.log(e);
    }
});

window.addEventListener('keydown', function (e){
  var x = parseInt(getComputedStyle(playerTwo).top);
  e.preventDefault();

  if (e.key === 'w') {
    x -= 1;
    playerOne.style.top = x + "px";
    console.log(e);
  } else if (e.key === 's') {
    x = x + 1;
    playerOne.style.top = x + "px";
    console.log(e);
  }
});
#backBoard {
  border: 1px solid black;
  height: 200px;
  position: relative;
  width: 400px;
}

#playerOnePaddle {
  background: black;
  border: 1px solid black;
  height: 50px;
  position: absolute;
  top: 0;
  left: 4px;
  width: 4px;
}

#playerTwoPaddle {
  background: red;
  border: 1px solid red;
  height: 50px;
  position: absolute;
  top: 0;
  left: 390px;
  width: 4px;
}

#ball {
  background-color: green;
  border: 1px solid black;
  border-radius: 50%;
  height: 15px;
  position: absolute;
  top: 0;
  left: 50px;
  width: 15px;
}

Comment: You event listeners both reference `playerOne`
Answer: in the second keydown callback you're changing the style of playerOne where you would need to add it to playerTwo.
Answer: This should be what you are expecting (run the snippet) :

you don't have to make two exact event listeners just add all your code into one and use conditions.
your x and y were being reset each time the event function is executed so i moved them out of the callback function .
you were using on both events the same player playerOne.

var playerOne = document.getElementById("playerOnePaddle");
var playerTwo = document.getElementById("playerTwoPaddle");
var y = parseInt(getComputedStyle(playerOne).top);
var x = parseInt(getComputedStyle(playerTwo).top)

 window.addEventListener('keydown', function (e) {
   e.preventDefault();
   if (e.key === "ArrowUp") {
      y -= 1;
      playerOne.style.top = y+"px";

    } else if (e.key === "ArrowDown") {
      y += 1;
      playerOne.style.top = y+"px";

    } else if (e.key === 'w') {
     x -= 1;
     playerTwo.style.top = x+"px";

    } else if (e.key === 's') {
     x = x + 1;
     playerTwo.style.top = x+"px";

    }
});

#backBoard {
  border: 1px solid black;
  height: 200px;
  position: relative;
  width: 400px;
}

#playerOnePaddle {
  background: black;
  border: 1px solid black;
  height: 50px;
  position: absolute;
  top: 0;
  left: 4px;
  width: 4px;
}

#playerTwoPaddle {
  background: red;
  border: 1px solid red;
  height: 50px;
  position: absolute;
  top: 0;
  left: 390px;
  width: 4px;
}

#ball {
  background-color: green;
  border: 1px solid black;
  border-radius: 50%;
  height: 15px;
  position: absolute;
  top: 0;
  left: 50px;
  width: 15px;
}


Experience with MQ File Transfer Edition?

Question: We've got several processes that move files across servers - SFTP, FTP, SCP; Windows, Linux, AIX; there is a workflow component (usually require a control file with filenames and hash values to move a batch of related files). The action is often initiated on our servers to get the files, so we need to make sure they're done being written.
We have some homegrown scripts to do this, but they don't always work properly, and troubleshooting, maintenance, and log review is not easy this way. There's a lot of servers, and our scripts don't have central logging or a dashboard/console/etc.
We're looking into commercial products to do this. Has anyone used MQ File Transfer Edition? Another team in our company is using Aspera, does anyone have any thoughts on that, or other favored products?
I have no idea what our budget is for this, yet. Just trying to get a handle on the product space from the perspective of other admins.

/edit - In my situation, we're moving 2-file payloads (one binary, one metadata) of scanned images from different sources to different destinations. We wait until a 3rd control file is written with the checksums - when the move is complete, the control file is deleted.
The sources are primarily a handful of Windows file servers, or Windows SFTP servers, that receive these files from scanning processes. We also have sources that are FTP or SFTP servers that receive the same payloads from external parties. The destination is a set of AIX servers that ingest the images into an archive, so the files don't remain in the destination either. Robustness is definitely our major concern.
We move a few GB every day, I guess. (Without centralized logging, I can't give a better number.) The binary files probably average around 100 MB, the metadata quite a bit smaller.
Answer: I have implemented WMQ FTE for several customers and it would definitely meet the requirements that you described.  You can configure it to watch for the control file and then move the data files and delete the control file.  It can also be driven by an MQ message that the thing creating the files sends.  FTE agents can connect to WMQ as clients so you need only one WMQ server in a small deployment and the FTE agents can be on all the platforms you mentioned.  The only exception is that a z/OS FTE agent must have a local queue manager (due to there's no WMQ client for the z/OS platform).  Of course, it is set up for ad-hoc, user driven transfers as well.
FTE uses all non-persistent messages and a light control flow between the two agents (over WMQ, of course) that acks the data stream.  Assuming that both sides are up, the entire transfer happens in memory with nothing being written to disk on the queue manager so it's screaming fast.  If one side goes down, the transfer picks up where it left off as soon as service is restored.  Both agents checksum the data and files so that if either the source or target file changes during the outage or during transmission, the transfer aborts with an appropriate error message.
Any sort of automation you might like to script can be done with Ant or any executable that you want to call, either on the sender or receiver side, either before or after the transfer.  For example, I have one client who encrypts files outbound to their customers' SFTP servers and then decrypts the files on arrival.  This is done by calling Ant to run GPG before outbound transfers and after inbound transfers.
Answer: I have not used MQ File transfer edition so I cannot comment on this.  I have done a lot of file transfers including EDI, FTP, AS2, FTPS, SFTP, rsync, SCP, aspera, svn, etc.  Ultimately my answer would depend on your exact requirements.  From what it sounds like the most important thing you are after is reliability of file transfers.
Firstly I would recommend on some sort of standardization of platforms, maintenance and management, which is what it sounds like you are looking at doing.  Make every server regardless of OS/config use the same process to get files to and from nodes.  Multiplying the troubleshooting across different configurations can make simple tasks very frustrating.  When i think of reliability I do not think of windows, but a lot of the time there just simply isn't a way to avoid it.
While I do not know your exact requirements I will provide some possible solutions for you, if you can clarify on exactly your needs (WAN, LAN, file size, number of transfers daily, importance of transfers, etc) I can provide you with a more accurate answer.  The transfers I have setup in the past are anywhere from small <1kb files to hundreds of GBs of data, from people don't get paid if the transfer doesn't happen to data that may never even be used, from open internet transfers to encrypted data, across encrypted transfers across encrypted VPNs.
What you are really after is a semi new term in the industry called Managed File Transfer.  http://en.wikipedia.org/wiki/Managed_file_transfer
At the end of the day, get the Gartner Magic Quadrant Report for this, review it and choose a vendor that meets your needs.  You'll notice Aspera in the list, but consider CFI for your needs.  Considering you are specifically looking for a commercial product this is your best bet.  Private message me or comment if you want any more input on my research in this sector.
Here is my personalized input.
Centralized FTP:
This is good because FTP is universal, it's used in so many places and has so much support across systems.  A lot of popular FTP servers will provide support for a lot of authentication methods as well as protocols.  If you are able to centralize the server for all the nodes then troubleshooting becomes a lot easier, when something goes wrong you check the server log, or ideally have logs auto report to you via email, and if there isn't anything wrong its pretty clear its a client or network issue.  The problem is FTP isn't perfect, it can easily fail, and is particularly slow when dealing with large amounts of small files.  Across OS you may find file naming issues and more.  If you are going to consider this solution use clients and a server that can support simple file verification.  http://en.wikipedia.org/wiki/Simple_file_verification.  The mechanism used to check the files is as it says, simple, and could be checked across multiple platforms.  There are a number of servers that support checking files as they are uploading and can report automatically if a file fails checking, along with checking full file sets rather than individual files, also providing some percentage for the full structure to be uploaded.  gltfpd is a popular one, but keep in mind it is a bear for configuring, but once you have it setup you may never need to touch it again.  http://www.glftpd.com/.  Gene6 is pretty popular as well
Rsync the files
I've used rsync with scripts a fair amount and I found this to be very reliable and pretty robust when accounting for error checking.  You'll find rsync popular among backup scripts because of this.  I do not know of many off the shelf programs for rsync, so you are looking at coding up a solution for this and once again you will be without centralized logging and you may run in to a lot of the same issues, but honestly I found rsync reliable enough, and with the delta transmissions with large file sets and integrity checking is a pretty quick and dirty way to get things done.
Aspera
Aspera is great technology at it's core for high latency, high bandwidth transfers.  If you are not transferring across a WAN, and not transferring large data sets I would not recommend it.  I run a large Aspera deployment and it is littered with transfer problems and software bugs.  If you are looking for very basic functionality it is a pretty good solution but when it comes down to more advanced processing be prepared to write your own scripts to transfer the data.  The software seems to be more focused at a small niche business and they seem to struggle across enterprise deployments.  The centralized logging they have with one of their products would solve the centralized logging needs, and their pre and post processing would work for your needs as well but just keep in mind you may end up spending a fair amount of money for a half working solution.  I mentioned CFI above, their product is much more enterprise but they struggle to deliver on a single experience.  Depending on your needs don't take my word for it, get trials of their products for yourself.
Version Control System
I'll first say that this doesn't seem like it would fit the requirements but is another option.  If the files you are transferring are not transactional, consider storing these files in a version control system.  In this scenario when a file is needed to be transferred it is checked in to the version repository, and when needed it is synced at the remote end.  In an instance where you need version control and files possibly to interact with each other, as well as a centralized server this may be a good option.
As a final side note check out what twitter uses to pass config files across their many, many nodes: http://engineering.twitter.com/2010/07/murder-fast-datacenter-code-deploys.html
Once again I cannot stress enough that the correct answer is based on your exact requirements.
Hope this helps you.
Comment: Excellent write-up. I edited my question.
Comment: Very good writing. Just saying that usually storing files to Version Control such as GIT is considered really bad practice. The size of repository grows really fast as it keeps every version (new and old ones) of the file. Some services such as GitHub provides BLOB api as well to handle binary objects. https://developer.github.com/v3/git/blobs/
Answer: When I was working for a large insurance company, we used Connect:Direct, to automate and manage file transfers (most via SSL/TLS) between various windows/linux/AIX/mainframe servers.
Comment: OK - did you like it? Have you used anything else in that space, for comparison?


Find $F$ which interpolates $f$ at all points $x_0,x_1,\cdots ,x_n$

Question:
Suppose the function $u(x)$ interpolates $f(x)$ at $x_0,x_1,\cdots ,x_{n-1}$ and the function $v(x)$ interpolates $f(x)$ at $x_1,x_2,\cdots ,x_n$. Then find a function $F(x)$ which interpolates $f(x)$ at all the points $x_0,x_1,\cdots ,x_{n-1},x_n$.

Here , $f(x)=u(x_0)+(x-x_0)u(x_0,x_1)+(x-x_0)(x-x_1)u(x_0,x_1,x_2)+\cdots+(x-x_0)\cdots(x-x_{n-2})u(x_0,x_1,\cdots x_{n-1})$.
Again , $f(x)=v(x_1)+(x-x_1)v(x_1,x_2)+(x-x_1)(x-x_2)v(x_1,x_2,x_3)+\cdots+(x-x_1)\cdots(x-x_{n-1})v(x_1,x_2,\cdots ,x_{n})$.
But from here how I can find such a function ?
Update :
From given data , $u(x_i)=f(x_i)$ for $0\le i\le n-1$. Also , $v(x_i)=f(x_i)$ for $1\le i\le n$. Then , $(x-x_n)u(x_i)=(x-x_n)f(x_i)$ and $(x-x_0)v(x_i)=(x-x_0)f(x_i)$ for all $0\le i\le n.$Then subtracting , $$(x-x_n)u(x_i)+(x-x_0)v(x_i)=(x_0-x_n)f(x_i).$$So , $$\frac{x-x_n}{x_0-x_n}u(x)+\frac{x-x_0}{x_0-x_n}v(x)$$interpolates all the points $x_0,x_1,\cdots ,x_n$. Is it correct now ?
Comment: You do not know _anything_ about $f(x)=\cdots$. What you do know is that $f(x_i)=u(x_i)$ and $f(x_j)=v(x_j)$ for fitting $i,j$. You are asked to find a combination of $u$ and $v$ that works for all $x_i$. It might look something like this: (not a correct solution) $$(x-x_0)v(x)+(x-x_n)u(x)$$
Answer: $u(x)+{(v(x)-u(x))}{(x-x_0)(x-x_1)...(x-x_{n-1})\over(x_n-x_0)(x_n-x_1)...(x_n-x_{n-1})}$
is the function you want.
The above is a long one, amd I have come up with a short one as well:
$v(x){x-x_0\over x_n-x_0}+u(x){x_n-x\over x_n-x_0}$
Comment: How...........?
Comment: For the long one, sub in any $x=x_0,x_1,...,x_{n-1}$ will give you $u(x)$ since right part is $0$ and sub in $x=x_n$ will give you $u(x)+v(x)-u(x)=v(x)$. For the short one, sub in anything other than $x_0, x_n$, since $u(x)=v(x)$ it will give you $v(x){x_n-x+x-x_0\over x_n-x_0}=v(x)$, sub in $x_n$ it will give $v(x)$ since right part is $0$ and sub in $x_0$ will give you $u(x)$ since the left part is $0$.
Comment: Assuming that $u,v$ are polynomials of degree $n-1$, this solution has a rather high degree. Esp. since $u(x)-v(x)$ already has roots at $x_1,…,x_{n-1}$.
Comment: The short solution has degree $n$ which is definitely required for interpolating $n$ roots. The long one has high degree and yes it is not that good but it still work.
Comment: @@cr001) See my update please and comment whether am I correct or wrong ?
Comment: You are almost correct except the second term need to be the negative of itself. Try to sub in $x=x_n$ and see what you get, in your current formula you will get $-v(x)$ instead of $v(x)$.


Selecionar opção select

Question: Caros,
estou tentando selecionar uma opção em um select com o seguinte código e não estou conseguindo encontrar uma solução.
Consigo localizar o elemento, mas não informar para ele selecionar X opção.
Estou localizando com o seguinte código:
driver.findElementByXPath("//*[@data-ng-model='passoUmCtrl.model.protocoloAtivo.relacionamento']")

Como posso selecionar uma opção?
Answer: Caros,
Resolvido com o seguinte código:
driver.findElementByXPath("//*[@data-ng-model='passoUmCtrl.model.protocoloAtivo.relacionamento']").AsSelect.selectByValue (1)

Selecionar opção select


Import Linked in profile by using LinkedIn email and password with my website page without redirecting LinkedIn website page?

Question: My requirement is as below,
I have web page own login page when i enter email and password and click on Connect to LinkedIN button then  request goes to linkedin and import LinkedIn profile (same as fetching google contact list) and display my web page without redirecting to linkedin authorization page or without embed Linkedin Import profile button in my application.
Answer: If I understand you correctly, what you want to do is against the LinkedIn API terms of service:
https://developer.linkedin.com/documents/linkedin-apis-terms-use
In order to access member specific Content through the APIs, your users must sign-in with their LinkedIn credentials and grant your Application access to their Content.
Your users can't sign in through your own site and then be automatically logged into LinkedIn without first authorizing your access.


Blank Command window upon running C# in Visual Studio using CTRL + F5

Question: This is a problem in two parts - one before and one after reinstalling Visual Studio 2019.
To set the scene, I am trying to lean programming C# following a course on Udemy, in other words I am a complete beginner.
Part One:
Regardless of what program I attempt to run, using CTRL + F5, from Visual Studio (Microsoft Visual Studio Community 2019 - Version 16.5.5) - I just get at black Console window with no text the first three to four times I press CTRL + F5, then it works on the next try. Once it works it continues to work every time, even if I makes changes to the program.
Press CTRL + F5 -> Black Console, I close console;
Press CTRL + F5 -> Black Console, I close console;
Press CTRL + F5 -> Black Console, I close console;
Press CTRL + F5 -> Black Console, I close console;
Press CTRL + F5 -> works.
After that it works every time.
Write a new program, and I have to go through this again.
What is causing this?
Part Two:
To this someone suggested uninstalling VS, and reinstalling it.

All new projects now are a "Hello World" program and include this line of code Console.WriteLine("Hello World!");  they didn't before
Here is an example of a program that took a few tries to get to run (See part one):
using System;

namespace Exercise4
{
    class Program
    {
        static void Main(string[] args)
        {
            const int demeritPrKm = 5;
            Console.WriteLine("Enter speed limit:");
            var speedLimit = Convert.ToInt32(Console.ReadLine());
        {
            int demeritPoints;
            int speedExceedance;

            Console.WriteLine("Enter actual speed:");
            var actualSpeed = Convert.ToInt32(Console.ReadLine());

            if (actualSpeed <= speedLimit && actualSpeed>0)

            {
                Console.WriteLine("Speed within limits");

            }
            else
            {
                demeritPoints = ((actualSpeed - speedLimit) / demeritPrKm);
                speedExceedance = (actualSpeed - speedLimit);
                Console.WriteLine("Speed limit exceeded by " + speedExceedance + "km/h, Demerit points: " + demeritPoints);

                if (demeritPoints > 12)
                {
                    Console.WriteLine("***** LICENSE SUSPENDED *****");

                }
                else
                {
                    Console.WriteLine("** License OK **");

                }

            }

        }

    }
}

}
Comment: I tested the example in `Microsoft Visual Studio Community 2019 - Version 16.5.5`, but could not reproduce the issue. Maybe you can try to report a problem on [Developer Community](https://developercommunity.visualstudio.com/content/problem/post.html?space=8&inRegister=true).
Answer: You Don't have the Console.Readkey() In your codes
try inserting it in the last line of your codes and try building and running again.
Comment: If you test the OP code, you will find it has nothing to do with `Console.Readkey ()`.


How to change a previous Inlinekeyboard message from a normal message

Question: In my bot, the user is supposed to interact mostly through Inlinekeyboard messages.
So, if the user writes some 'regular' message or sends something, I must somehow change the last Inlinekeyboard message to continue the process or give him some message.
See the picture below:

The user wrote some message but I had to create a new Inlinekeyboard button with the new message because I couldn't find a way to get the  message_id of the previous 'Welcome' button and change it.
My code:
HELP = range(1)

def start(bot, update):
    keyboard = [
                 [InlineKeyboardButton('Help', callback_data='help')]
               ]

    # Create initial message:
    message = 'Welcome.'

    update.message.reply_text(message, reply_markup=InlineKeyboardMarkup(keyboard))

def help(bot, update):

    keyboard = [
                 [InlineKeyboardButton('Help', callback_data='help')]
               ]

    bot.edit_message_text(
        text='Help ... help..',
        chat_id=update.callback_query.message.chat_id,
        message_id=update.callback_query.message.message_id,
        reply_markup=InlineKeyboardMarkup(keyboard)
    )
    bot.answer_callback_query(update.callback_query.id, text='')

def unknown(bot, update):

    message = 'Please press the Help button for more instructions.'

    keyboard = [
                 [InlineKeyboardButton('Help', callback_data='help')]
               ]

    update.message.reply_text(message, reply_markup=InlineKeyboardMarkup(keyboard))

# Create the EventHandler and pass it your bot's token.
updater = Updater(token=config.TELEGRAM_API_TOKEN)

# Get the dispatcher to register handlers:
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CallbackQueryHandler(help, pattern='help'))
dispatcher.add_handler(MessageHandler(Filters.all, unknown))

updater.start_polling()

updater.idle()

Best Regards.
Kleyson Rios.
Comment: Well, I came out with a 'workaround' but I believe that might have a better solution. My dispatcher is basically a ConversationHandler. Then I activated in all the handlers the option 'pass_user_data=True' and now I'm keeping track of the message_id inside the user_data, and based on the content of the user_data I know if I have to update the inlinebuttons message or delete the old message and add a new one (to stay at the bottom) saving the new message_id. May I have a better solution than this ?
Answer: If you want to edit the previous messages that the bot has sent, you need to store their message_id (which you already know).
So you can simply do this:
sent_message = update.message.reply_text(
    message,
    reply_markup=InlineKeyboardMarkup(keyboard)
)

And then you can access it like sent_message.message_id
Now for the variable sent_message, you can make it global or create a separate file to handle these variables, or at larger scale, you can store it in a database.
Comment: Thanks again Amir.
Comment: @KleysonRios Any time ^_^


How to embed measurement uncertainty in a two-proportion z-test?

Question: Online marketers often need to choose a "winning" variation among, say, 2 possible variations.
Example:

PageVariation1 had 1000 sessions with 20 conversions (2.0% response rate) and
PageVariation2 had 800 sessions with 8 conversions (1.0% response rate).

I'm using the "unpooled" Two-Proportion z-Test for estimating the P-value. In the example above it is 0.9615 - so I might conclude that there's a 96% that PageVariation1 has a higher response rate. Let's say it's good enough to declare it as "winner".
Problem is that some sessions and conversions weren't tracked to the PageVariation level - i.e. I know there were, say, additional 200 sessions and 3 conversions, but those can't be allocated to any of the above. Intuitively it means that there is higher uncertainty due to tracking/measurement issues. Consequently the P-value should be lower.
Question:

Which test should be used (and how) in order to calculate the new P-value?
Comment: Your p-value is not 0.9615: it is 0.07698.  This is because your z-statistic is -1.7685 and a standard normal variate has a 0.07698 chance of exceeding 1.7685 in absolute value.  Note that this p-value is high enough that in many applications it would not be considered significant evidence of a difference anyway.  The additional uncertainty in your situation should *raise,* not lower, this p-value.
Answer: A few quick points:

You could draw on the general literature on missing data.
If the 200 sessions with missing data are known to be completely random, then you could choose to ignore these observations and just analyse the data where you have complete data.
In general it is important to think through what mechanisms might explain the missing data.
You may find it useful to read up on strategies for dealing with missing data.
Answer: It can help to survey the scene: that is, to understand the consequences for your decision of the possible states of affairs.
The missing information can be described by two integers: $m$, the number of additional sessions for "PageVariation2", and $k$, the number of additional conversions for PageVariation2.  For each possible combination of $m$ and $k$ ($k = 0, 1, 2, 3$ and $0 \le m \le 200-k$) we can compute what the p-value would be.

In this plot the graph of the p-value versus $m$ for $k=3$ is shown in blue (the highest one), for $k=2$ in red, for $k=1$ in orange, and for $k=0$ in green.  For reference, a (two-sided) p-value of 0.05 is shown with a black line.
It is evident that the p-values can range tremendously from indicating strong significance (for $m=197$ and $k=0$) to indicating no significance at all (for small $m$ and $k = 1, 2, 3$).  This tells us that your assumptions about the missingness completely determine the significance or lack of significance of the results.
If you think it highly likely that $m$ is large--so that the majority of missing results are for PageVariation2--and that $k$ is small--so that the majority of missing conversions are for PageVariation1--then you can conclude the differences in conversion rates are not likely due to chance and proceed accordingly.  If you do not have sufficient information to justify these assumptions, then the data do not provide strong evidence for a significant difference.  That is, what you have observed could be the result of random variation rather than due to some intrinsic difference between the two variations.


Expanding an esx guest disk across multiple datastores

Question: I'm a bit new to this type of vsphere maintenance, but not so much to the concept of raids, disks, etc.
The situation is this:
A guest server named "example-FS-01"
has a disk on 'esx-datastore-02'
This disk is 1 TB in size, the datastore itself has a total size available of 1.5TB
There are 2 other unused datastores, each with 1.5TB of usable space.
Each datastore isn't a single disk but a system of disks in a redundant raid.
For example, using vmotion to shift data around is it possible, safe, or close to/far from best practice to expand this guest disk to a size of 2.5TB spanning across datastore 1 and 2?
Thanks
Comment: I don't think it's possible to expand a VMDK across two different datastores.
Answer: As @joeqwerty has said in the comments, you can't expand a single VMDK across datastores.
You pretty much have two options to get where you want to go:

Create second VMDK
You can create a second VMDK on one of the empty datastores, add it to the same VM, then use the in-guest tools (LVM for Linux, Dynamic Disks for Windows) to extend the first disk with the space from the second.
Add an extent to the esx-datastore-02 datastore
This would entail deleting one of the other two datastores, then adding its capacity as a second extent to the first. You can then extend the VMDK in question to use the space you want.

Both of these approaches have the same issue: losing either of the LUNs/extents will cause the volume in the guest to do funny things, but the errors will be reported in different ways (in the guest for option 1, in vSphere for option 2).
The ideal solution would be to combine the two datastores at the array level, and then have this VM sit on its own, appropriately sized, datastore.
Comment: You missed a third option: Increase the LUN size (which is generally quite simple if you use SAN storage) and increase the datastore.
Comment: @MarioLenz, you're absolutely right, but I assumed that had that been an option, OP would have alluded to it, or already done that. My answer attempts to address his specific question.


Understanding of Open Sets

Question: Definition. A subset of $\mathbb{R}$ is open set if it is a union of open intervals.
Example: $(0,1)\cup (2,3)\cup (4,7)$ i.e., $A=${ $0<x<7$ and $x\in\mathbb{R}$} is open.
Proposition. If $\mathcal{U}$ is set of open sets then $\bigcup\mathcal{U}$ is open.
My question is: Can you check my example? What is ''set of open sets'' mean Can you explain 'set of open sets'? Also, Can you give example ''set of open set''?
Comment: My example of set of open sets: Let $A=${ $2<x<3$ and $x\in\mathbb{R}$}, $B=${ $4<y<5$ and $y\in\mathbb{R}$}. So, $X=${$A,B$} is set of open sets, right?
Comment: @Arthur Must it be in the other set?
Comment: I should point that this is not the usual definition of an [open set](https://en.wikipedia.org/wiki/Open_set). In $\mathbb{R}$, or, more generally, in a metric space $(M,d)$, the "standard topology" is the one where $A\subset M$ is open if $\forall a\in A \ \exists \varepsilon \gt 0$ such that $B(a,\varepsilon ) = \{ y: d(a,y)\lt \varepsilon \} \subset A$.
Comment: Your definition isn't the standar one, even with usual topology of $\mathbb{R}$, your "definition" is actually a theorem. On the other hand, "set of open sets" means a set whose elements are open sets. You could say instead "family of open sets" to avoid confusion.
Answer: First of all, your example is indeed an open set, but you have analyzed it incorrectly: e.g. $x=1.5$ is not in $(0, 1)\cup (2, 3)\cup (4, 7)$. Do you see why?
A set of open sets is . . . a set of open sets. For example, the set of all open intervals. Or, the set $$\{(0, 1), (2, 3), (4, 7)\}.$$ The union $\bigcup \mathcal{U}$ of a set $\mathcal{U}$ of open sets is just the set of all points which are in some set in $\mathcal{U}$. So, for example,

The union of the set of all open sets is all of $\mathbb{R}$ (since every point is contained in some open set).
The union of the set $\{(1, 3), (0, 2)\}$ is $(0, 3)$ (think about how the open sets $(1, 3)$ and $(0, 2)$ "overlap").

Does this make sense?
Comment: This makes sense. Thanks.
Comment: I still have a question. Let $\mathcal{U}=${$(2,4)\cup (3,5), (5,7)\cup (7,9), (8,12)\cup (11,13)$} be set of open sets. For each $u\in\mathcal{U}$, let $I_{u}$ be set of open intervals. ,i.e., $I_{u}=${(2,4),(3,5), (5,7), (7,9), (8,12), (11,13)$}. Are my examples true?
Comment: Now, how can I write $\bigcup\mathcal{U}$?
Comment: @Kahler I don't understand what $I_u$ is. But $\bigcup\mathcal{U}$ is just the set of points in some element of $\mathcal{U}$. So $\bigcup\mathcal{U}$ is the union of the intervals $(2, 4), (3, 5), (5, 7), (7, 9), (8, 12), (11, 13)$; and this is just $(2, 5)\cup (5, 7)\cup (7, 13)$. Note that this is **not** $(2, 13)$: it doesn't contain $5$ or $7$. Does this make sense?
Comment: Note also that your $\mathcal{U}$ can be simplified: $(2, 4)\cup (3, 5)=(2, 5)$ and $(8, 12)\cup (11, 13)=(8, 13)$, so $\mathcal{U}$ can be more clearly written as $$\mathcal{U}=\{(2, 5), (5, 7)\cup (7, 9), (8, 13)\}.$$ (Do you see why $(5, 7)\cup (7, 9)\not=(5, 9)$?)

Understanding of Open Sets


Explanation of the orthogonality relation $\int_{-π}^{π}\sin(ax)\sin(bx)\,dx=\int_{-π}^{π}\cos(ax)\cos(bx)\,dx=\begin{cases}π,&a=b\\0,&a≠b\end{cases}$

Question: I stumbled opon the orthogonality relation $$\int_{-π}^{π}\sin(ax)\cos(bx) \,dx = 0$$
and
$$\int_{-π}^{π}\sin(ax)\sin(bx)\,dx = \int_{-π}^{π}\cos(ax)\cos(bx)\,dx = \begin{cases} π & \text{if } a = b \\ 0 & \text{otherwise} \end{cases}$$
where $a,b \in \mathbb{N}$.
I understand the first one, it's because $\sin(ax)\cos(bx)$ is even, so the areas cancel each other out, but what is the explanation for the second one?
Why does $a$ have to be equal to $b$ and why is the integral $0$ otherwise?
Comment: HINT: Apply the addition angle formulae.
Answer: $$I=\int_{-π}^{π}\sin(ax)\sin(bx)\,dx = \int_{-π}^{π}\cos(ax)\cos(bx)\,dx $$
$$I+I=\int_{-\pi}^\pi\cos(a-b)x\ dx=?$$
Check with $a-b=0$ and otherwise?
Comment: This doesn't show the orthogonality relationships that the OP is trying to verify.  It only shows that if the integrals are equal, then they are $0$.
Answer: Hint.
If $a= b,$ then the integrands are of the form $\sin^2\phi,\,\cos^2\phi.$ If you integrate this over the interval, you should get $π.$
If $a\ne b,$ then for the $\sin$ integral, integrate by parts to obtain $$\sin y\int \sin z+\int \cos y\cos z,$$ where $y=az$ for some appropriate rational $a.$ The first part vanishes since the integrand is odd. The second part becomes the cosine relation. Use the transformation $$2\cos a\cos b=\cos (a+b)+\cos(a-b),$$ so that your integral is now of the form $$\int \cos m+\int\cos n.$$ Thus you have the integral to be $\sin m+\sin n,$ where $m,\,n$ are integral multiples of $x.$ It follows that substituting $\pm π$ will make the integral vanish, since $\sin kπ=0$ for any integer $k.$
Comment: Why not simply use the addition angle formulae?
Comment: @MarkViola Well, I simply wanted to indulge OP's wish to see how far I could reduce the integrands to odd functions. Originally, I was just tempted to tell OP to integrate directly and see what happens.
Answer: The symmetry argument is subtler for the second one. Note
$$\int_{-π}^{π}\sin(ax)\sin(bx)\,dx = 2 \int_{0}^{π}\sin(ax)\sin(bx)\,dx
= 2 \int_{-π/2}^{π/2} \sin(\frac π2 a+ at)\sin(\frac π2 b+ bx )\,dx $$
Examine different combinations of $a$ and $b$: In the case of odd $a$ and even $b$,
$$\int_{-π}^{π}\sin(ax)\sin(bx)\,dx =\pm 2 \int_{-π/2}^{π/2} \cos( at)\sin( bx )\,dx =0$$
Other cases of $a$ and $b$ can be analyzed  similarly to obtain vanishing value of the integrals.
Comment: Why not simply use the addition angle formulae?
Comment: $$\sin(x)\sin(y)=\frac12 \cos(x-y)-\frac12 \cos(x+y)$$
Comment: The OP asks "what is the explanation for the second one?"  I don't understand how one would infer that the OP is seeking an explanation that relies on even/odd symmetry only.  And if so, then splitting the integrand suffices any way.


On commutator relations and nilpotency class of a $p$-group

Question: Suppose $G$ is a $p$-group, and $x,y\in G$ be arbitrary.
If the commutator $[x,y]$ commutes with both $x$ and $y$, then the subgroup $\langle x,y\rangle$ has nilpotency class $\leq 2$.
Question: Suppose, $G$ is a $p$-group such that $[x,y]$ commutes with both $x$ and $y$ and this is true for all $x,y\in G$. Does it follow that the whole group $G$ has nilpotency class $\leq 2$?
Answer: The answer appears to be no. A nilpotent group in which every $2$-generator subgroup has class $2$ has class at most $3$. There is an example of order $3^7$ of such a group of class $3$. However, for $n \ge 3$, if all $n$-generator subgroups of $G$ have class $n$, then so does $G$. These results are apparently due to Levi and Heineken. See here.
Comment: Thanks Derek for the helpful comments and link to answer.


Find the dual space and dual basis of basis $\beta$ in vector space $\mathbb{C^3}$

Question: Find the dual basis $\beta^*$ of basis $\beta =\{v_1,v_2,v_3\}$in vector space $\mathbb C^3$ .
where $v_1 = (1, 0, −1),v_2 = (1, 1, 1), v_3 = (2, 2, 0)$.
I know that dual basis is the set of linearly independent functionals which satisfy $f_i(c_j)=\delta_{ij}$. Where $\delta_{ij}$ is Kronecker-Delta. Also represented as,
$\beta^*=\{f_1,f_2,f_3\}$       .
We know that any linear functional can be represented as
$f(x_1,...,x_n)=c_1x_1+...+c_nx_n$.
To find the dual basis(by the method I am trying to use), what we do is consider $f_1$ and write equations $f_1(c_1)=1$
$f_1(c_2)=0$
$f_1(c_3)=0$
to find the coefficients $c_1,c_2,c_3$ for $f_1$. Similarly for $f_2\&f_3$.
Now, what is the dual basis? Is it the set of tuples of $c_i$ for each $f$ ? or the set of functions given by $f$ ie. the linear equation given by $f$?
Also what is the dual space?
Answer: The dual space $V^*$ of a $K$-vectorspace $V$ is defined as all linear maps from $V$ to $K$
$$V^*=\{\lambda \colon V \to K \mid \lambda \text{ linear}\}.$$ Since we can identify every linear map with a matrix, we denote the elements of the dual space with $1\times n$-matrices where $n$ is the dimension of $V$. Now let $\beta^* = \{f_1,f_2,f_3\}$ be the dual basis of $\beta = \{v_1,v_2,v_3\}$. By definition the dual basis must satisfy $f_i(v_j) = \delta_{ij}$. We can convert this into a linear equation system:
$$\begin{pmatrix}
f_1^1 & f_1^2 & f_1^3 \\
f_2^1 & f_2^2 & f_2^3 \\
f_3^1 & f_3^2 & f_3^3
\end{pmatrix} \cdot
\begin{pmatrix}
v_1^1 & v_2^1 & v_3^1 \\
v_1^2 & v_2^2 & v_3^2 \\
v_1^3 & v_2^3 & v_3^3
\end{pmatrix} =
\begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}.$$
The first matrix on the left-hand side is obtained by writing the dual space basis vectors (the $1\times n$-transformation matrices) row-wise. Let's call it $A$. The second matrix on the left-hand side is obtained by writing the basis vectors column-wise. We will call it $B$. If we multiply the above equation with $B^{-1}$ from right, we get
$$A= \mathbb{1}_\mathrm n \cdot B^{-1} = B^{-1}.$$ This means the rows of $B^{-1}$ are the dual basis vectors.
In summary you have to write $v_1,v_2,v_3$ column-wise in a matrix, invert it and then read the dual basis vectors from the rows.
The solution would be $$f_1=(1,-1,0), f_2=(1,-1,1), f_3=(-1/2,1,-1/2)$$
Comment: @krishna The dual space contains all linear maps from the vectorspace $V$ over a field $K$ to K. This means the dual basis is made of linear maps. But we can represent every linear map as a matrix (there exists an isomorphism). The matrix is called the transformation matrix. Let be $\phi$ a linear map and $A$ the transformation matrix to the standard basis. Then $\phi(x)=A\cdot x$. Hence it is easier to speak in terms of matrices instead of functions.
Comment: Thank you for such a simplified answer. This means the dual basis is a set of tuples right? And how do we represent the dual space?
Comment: @krishna For the linear maps in the dual space we get $1\times n$-matrices as transformation matrices (i.e. a row-vector).


Seeing if node has been changed in custom submit handler

Question: I have written a custom submit handler that gets called whenever a certain content type is edited.
I was wondering if there was a flag in $form_state that indicates whether the node was actually edited vs whether someone is just clicking the save button without actually changing anything.  I am wondering because I would like to perform an action only if the node is edited. Thank you
function hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_unpublish_new_product';
}

function _unpublish_new_product($form, &$form_state) {
   // is there a flag in $form_state that indicates if any fields were changed so I
   // could perform a conditional action??
}

Comment: do you can do your action inside `hook_node_presave($node)`? where you have `$node` and `$node->original` to compare
Answer: As far as I know, there isn't such flag, but you can use entity_load_unchanged() to get a copy of the entity before any change, and compare the field value with the one you get from the form.
The function is called, for example, from node_save(), which contain the following code.
// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

field_attach_presave('node', $node);
global $user;

// Determine if we will be inserting a new node.
if (!isset($node->is_new)) {
  $node->is_new = empty($node->nid);
}

// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

This means that the implementations of hook_field_attach_presave(), hook_node_presave(), and hook_entity_presave() will get the unchanged version of the node object in $node->original (or $entity->original); if you are writing code for one of these hooks, you don't need to call entity_load_unchanged() because node_save() already did it for you.
Similar code is present in comment_save(), taxonomy_term_save(), taxonomy_vocabulary_save(), and user_save().
if (!empty($comment->cid) && !isset($comment->original)) {
  $comment->original = entity_load_unchanged('comment', $comment->cid);
}

field_attach_presave('comment', $comment);

// Allow modules to alter the comment before saving.
module_invoke_all('comment_presave', $comment);
module_invoke_all('entity_presave', $comment, 'comment');

  if (!empty($term->tid) && !isset($term->original)) {
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  }

  field_attach_presave('taxonomy_term', $term);
  module_invoke_all('taxonomy_term_presave', $term);
  module_invoke_all('entity_presave', $term, 'taxonomy_term');

Answer: As far as I know there isn't such a flag. You will have to compare the values yourself I think. For node forms I made this first attempt to compare the node data. This is just a quick idea how a solution could be, maybe I am missing some edge cases where this isn't working, but in my tests with a simple default "page" node form it was working well. (I used the "Preview" button for reloading the form and testing.)
As Mohammad Ali Akbari says, hook_presave() might be a better place to compare the data, but the comparison of the flatted arrays should work there, too.
Attribution for the flatten function goes to Rob Peck.
/**
 * @file mymodule.module
 * Do stuff.
 */

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Proof of concept of checking for changes to a node in form submit.
 * Uses the default "page" content type.
 *
 * You need devel module to see an nice Krumo of the fields that have changed.
 */
function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  //Get uncached data of the current node from the db.
  //Cast the node object to an array so we can use the flatten function
  //and php array_diff functions.
  $node_array_db = (array) node_load($form['#node']->nid,NULL, TRUE);

  //Throw away the changed value as this is alwasy different.
  unset($node_array_db['changed']);

  //Cast the node object to an array so we can use the flatten function
  //and php aray_diff functions.
  $node_array_form = (array) $form_state['node'];

  //The $node object from the form holds some metadata. Throw away the fields
  //in the forms $node object/array that are not in the version from the db.
  $node_array_form = array_intersect_key($node_array_form,$node_array_db );

  //Flatten the nested array structure so we can use array_diff for comparing no
  //matter what the fields are structured.
  $result = array_diff(flatten($node_array_form), flatten($node_array_db));

  //Print all fields with differences in the field values.
  dpm($result);

  if (empty($result)) {
    dpm('No Changes');
    //No changes. Just "Save" was pressed.
  }
  else {
    dpm('There are different field values in this form than those in the database.');
    //Do something.
  }

}

/**
 * Function for flattening an array.
 *
 */
function flatten($arr, $base = "", $divider_char = "/") {
  $ret = array();

  if (is_array($arr)) {
    foreach ($arr as $k => $v) {
      if (is_array($v)) {
        $tmp_array = flatten($v, $base.$k.$divider_char, $divider_char);
        $ret = array_merge($ret, $tmp_array);
      }
      else {
        $ret[$base.$k] = $v;
      }
    }
  }
  return $ret;
}


Using Data Source configuration wizard vs manually configuring data source

Question: Back in the days of VB 4 / VB 5, using data bound controls and data connection wizards would add alot of overhead to the application.
I wanted to know if using the "Configure Data Source" wizard in ASP.Net 3.5 adds alot of unneeded overhead to the webpage?
Thanks
Answer: No, it doesn't.  Adding the control to the page modifies your designer class code by one line (declaring the object).  The wizard simply modifies your markup to include all the necessary properties and attributes that you specify.
This is easily verified by just viewing the changes that adding and configuring a datasource control makes to your page and your designer class.
Nothing the wizard does would be any different than what you would do by declaring the control programatically in your code.  It's just a convenient GUI way of quickly generating your declarative markup.


marix proof by induction

Question: Given the matrix $A$

\begin{pmatrix} 2 & 1 \\ 0 & 1 \end{pmatrix}

use proof by induction to show that $A^n$ for $n=1,2..$. is

\begin{pmatrix} 2^n & 2^n - 1 \\ 0 & 1 \end{pmatrix}

so assuming $n=k$ and trying to show for $n=k+1$ .I managed to get the equation below, but im not sure how to show that $LS = RS$ on this problem?(I might have done something wrong), any tips or solutions? thanks!

$A^{k+1} =\begin{pmatrix} 2^{k+1} & 2^{k+1} - 1 \\ 0 & 1 \end{pmatrix}$
Answer: hint:$$A^{n+1} = A^n\cdot A = \begin{pmatrix} 2^n & 2^n - 1 \\ 0 & 1 \end{pmatrix}\cdot \begin{pmatrix} 2 & 1\\ 0 & 1\end{pmatrix}=....$$

marix proof by induction


How to take input in java where array length is not defined?

Question: My input is in this format:
1 2 3 4 5 6
Alice

The array length is not known.
I coded it this way:
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int i=0;
        while(sc.hasNext()){
            arr.add(sc.nextInt());
        }
        String player = sc.nextLine();
    }
}

But I am getting this error.
Exception in thread "main" java.util.InputMismatchException
        at java.base/java.util.Scanner.throwFor(Scanner.java:939)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        at Main.main(Main.java:17)

Thanks in advance.
Comment: Hint: have you debugged through the code? How far does it get? When do you expect `hasNextLine()` to return false?
Comment: It's an infinte loop even after reading 6. How to come out of the `while` loop?
Comment: I would suggest just reading the first line as a whole, then splitting it on spaces and parsing each part separately. `Scanner` is remarkably hard to use "properly".
Comment: Thanks for the reply Jon Skeet. What's the most efficient way to take such kind of input?
Answer: The reason you are seeing java.util.InputMismatchException is because you provided input "Alice" to the statement sc.nextInt(), and the scanner is telling you that it doesn't know how to convert a java.lang.String input to an int (which is the return type of nextInt()).
Here's a very simple example that reproduces the same behavior:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();

If you run those two lines and enter a non-integer, like "d", it will throw an exception:
d
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at a91.main(a91.java:6)

To fix it, you need to replace nextInt() with something that is tolerant of non-numeric input, possibly nextLine(). Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you're asking about, namely: how to address InputMismatchException. As with your original program, there is no loop termination – it will run forever (until you quit the program).
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();

while (sc.hasNext()) {
    String s = sc.nextLine();
    System.out.println("got this: " + s);
}

1 2 3 4 5 6
got this:  2 3 4 5 6
Alice
got this: Alice

Comment: Thanks for the reply. I wanted to know is there a way to terminate the loop. I tried using `sc.close()` but it didn't help either. And what's the best way to take these kind of inputs?
Comment: re: _"what's the best way to take these kind of inputs?"_ – Did you read my answer? re: _"I wanted to know is there a way to terminate the loop"_ – Where is that mentioned in your posted question? If your question is "how do I exit the loop", the entire thing should be rewritten to make the question clear, and remove anything about data types, input mismatch, etc
Comment: Thanks for the detailed answer @Kaan Your approach has solved my issue. I just wanted to know further if there was a way to stop the infinite loop? Otherwise my doubt is already solved.
Comment: _"Your approach has solved my issue"_ – Ok great. When someone posts an answer that addresses your question, you should vote up and accept the answer _ this lets everyone know the question has been resolved.
Comment: To exit the loop, you can add code to check for a specific value – maybe the string "exit" – and then break out of the loop (using `break`) if that value is seen.
Answer: You should use hasNextInt to check for integer input. Once no more integers, then just use next() to read the player.
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);

while(sc.hasNextInt()){
    arr.add(sc.nextInt());
}
String player = sc.next();

arr.forEach(System.out::println);
System.out.println(player);

Example input's supported
10 20 30 40 50 60 70
Alice

10 20 30 40
50 60 70 Alice

10 20 30
40
50
60 70 Alice

10 20 30
40 50
60 70
Alice

output
10
20
30
40
50
60
70
Alice


TYPO3 v9.5 no URL Segment [slug] field visible in Page Edit

Question: After upgrading from Typo3v9 to v9.5, I still do not see the URL Segment [slug] field .
The field has been added to the "pages" table under the column/field "slug" and also been populated, but the field is not visible in the BE and the links not updated.
Is there documentation/configuration I am missing?
Comment: Documentation:
https://typo3.org/help/documentation/whats-new/
https://forge.typo3.org/attachments/download/33792/TYPO3-v9-LTS-whats-new.english.pdf
pg20.

I now know I have to first let Typo3 create the file:
typo3conf/sites/myOwnSiteName_siteconfig1/config.yaml

which I can then customise, edit and add code for extension like News.
The steps are not clearly explained sequentially.

So first do the page 20 part
and then you can have access to the Page 9 configurations
Answer: You need to add a Site Configuration for your page tree in the new Sites module of the TYPO3 backend.
Only then the new slug field becomes visible in backend forms and the URL segments get used in the frontend instead of the old default index.php?id=1 links.
Comment: fantastic - that work - could not find that step in the documentation - just the editing once activated.


Excel VBA "Out of Memory" debugging techniques

Question: I was debugging a problem mentioned in a few other* questions on SO and noticed a strange behavior during the debugging process.
The behavior:
Experienced 'out of memory' error while pasting complex formulas. Only about half of the 20,000 rows I'm iterating get formulas pasted before the error.
Commented out virtually all code, error goes away.
Uncomment code incrementally in the hopes of discovering the specific section of code that's causing it.
End up uncommenting all code and stop experiencing the bug!
This means the exact same code worked fine in the same Excel instance, and fixing it only required running various lighter versions of the code before going back to the original version. What could possibly cause this?
Comment: I suggest you try Ron Bovey's [code cleaner](http://www.appspro.com/Utilities/CodeCleaner.htm) - it overhauls code by exporting it, deleting it and then re-inserting the exported modules
Comment: + 1 I agree with brettdj. Code Cleaner is really good. I am also curious about any one such example which is giving you the error...
Comment: Thanks @brettdj but Code Cleaner didn't help. It did manage to bring the .xla file down to 151k from 159k, which is fascinating to me.
Comment: Can you post some code excerpts, specifically the pasting of the complex formula? I would also make sure that you've set `Application.Calculation = xlCalculationManual` at the start, then back to `xlCalculationAutomatic` at the end, though I'm sure you've already done that.
Answer: Assuming the data you were running on was exactly identical every time, it sounds more like your problem was with the environment - the problem might be that the operating system ran out of memory. In Excel 2007, usable memory for formulas and pivot caches was increased to 2 gigabytes (GB), so that is probably not the issue. However it is of course also limited by how much memory your operating system had available at that time.
The problem may have occurred because when you first tested it, your available operating system memory was lower (from other processes running... could even have been pushed over the limit by background programs such as Antivirus software running a scan) than when you ran the full macro later. I would try running your macro with the Task Manager open to see if you are getting anywhere close to low on physical memory. Also, (assuming you are on Excel 2007 or later) look at how much memory Excel is using and see if you are getting anywhere close to the 2GB limit. I doubt that this would be the issue, but it's at least worth double checking. Also, like Zairja said, make sure you're setting the calculation to manual at the beginning.
You said that you were using complex formulas... check out this article on Improving Performance in Excel
There is a lot of useful information in the article that will probably help you streamline your macro.
Is this helpful to you?


Rotate a line around a point in space.

Question: I'm trying to figure this equation out before I code it.
If I have a line that starts at $(x_1,y_1)$, and ends at $(x_2,y_2)$.
I have a point not on the line, $(c_1,c_2)$ that I would like to rotate this line around to a certain angle.
Is there an equation for handling this or could you please suggest an equation to use?
Thanks,
B
Answer: First shift all coordinates such that the point $(c_1, c_2)$ is located at the origin, rotate and shift back to the original coordinate system
$$
\left(\begin{array}{c} x_{\rm new} \\ y_{\rm new} \end{array}\right) =
\left(\begin{array}{c}c_1\\ c_2 \end{array}\right) +
\left(\begin{array}{cc} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{array}\right) \left(\begin{array}{c} x_{\rm old} - c_1 \\ y_{\rm old} - c_2 \end{array}\right)
$$
where $\theta$ is the angle of rotation.

Rotate a line around a point in space.


do you want ssh for your instance?

Question: as I'm using aws I'm looking into two tutorials just to make sure I do it right. and I'm at a step to do eb init, and it asks "do you want ssh for your instance?" one tutorial says I should say yes and the other says i should put no...isn't ssh the one that connects my laptop with amazon's network shouldn't I put yes for this?but why does the tutorial say I should put no
Comment: Can you update the question with which tutorials you're looking at? Would help to get a context of the tutorials.
Comment: @TristanTao one is paid one the other is https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/
Answer: The advice against using ssh comes from a well-meaning bunch that wants us all to create reproducible configurations that don't require administrators to login in order to periodically tweak the config.  It also becomes another interface that must be secured.
Ideally, everything you need is independent of ssh because you are providing some internet-accessible service like a webserver/database/etc.
If your process isn't that mature yet, it's acceptable to enable ssh, but you should strive towards not needing it.
Comment: so if my project isn't perfect and I need to twerk the project as I go, I should enable ssh? it this what you are saying?
Comment: @emfour yes, that's what he is saying. You will probably need ssh at some point when you are initially building your application just so you can login to the server and see why a deployment isn't working or to look at a log file or something.
Comment: Maintaining ssh key in multiple server definitely not a fun job.

do you want ssh for your instance?


Boa prática com seletores em css

Question: Qual é a melhor prática para trabalharmos com seletores no css?
Usar
.menu li { }
ou
.item {}
.menu .item { }
ou
.menu-item { } //aqui usamos para atribuir propriedades para as
 por exemplo

Como seria a melhor prática para isso ?
Answer: Melhor prática, seria precisar de menos código para que tudo funcione corretamente, do qual não precisaria de muitas classes, e sim de apenas uma classe pai acessando os filhos desta forma:
.menu li {
 //codigo
}

Assim você não precisa atribuir uma classe à sua
, você pode utilizar um caminho mais longo(mais detalhado) se desejar, por exemplo:
.menu > ul > li {
 //codigo
}

Ps: os > são apenas para indicar um caminho que está sendo percorrido, não são realmente necessários, apenas para entendimento.
No seu caso, remover a classe menu-item da
 e utilizar no CSS .menu li reduz código html desnecessário, se tornando uma melhor prática.
Comment: A diferença entre usar ou não `>` é que em um caso qualquer **descendente** de `.menu` que for `li` é afetado, enquanto no outro o `li` deve ser **filho** de um `ul` que por sua vez é filho do `.menu`. Só esclarecendo...
Answer: A primeira opção me parece a melhor prática, pela seguinte razão:

.menu li
Aqui você tem um elemento (ou tipo de elementos) específico no qual você quer atribuir um estilo a todos os seus sub-elementos do tipo li. Para isso, basta dar a class menu ao seu elemento e automaticamente todos os seus lis ganham o estilo desejado.
.menu .item
Isso obriga você a adicionar a classe item a cada um dos seus lis além de adicionar a classe menu. Se você se esquecer de dar essa classe a algum item na lista, esse item terá um estilo diferente. A menos que isso seja por design (por exemplo, se você quiser dar destaque a algum elemento), é uma informação reduntante.
.menu-item
Semelhante ao item acima, só te alivia de ter que criar a classe menu. Mas o problema dos múltiplos lis cada um com sua classe permanece.

P.S. Enquanto estava escrevendo isso, o @Paulo Roberto adicionou uma resposta que sumariza isso perfeitamente:

Melhor prática, seria precisar de menos código para que tudo funcione corretamente

Boa prática com seletores em css


ARMA-GARCH model selection / fit evaluation

Question: I'm trying to fit an ARMA-GARCH model to a data set of FTSE 100 log returns (which I've uploaded here). However, I'm not able to find a well-fitting model. Below are the ACF and PACF of the log return series and the ACF of the squared log return series. Looking at the ACF of the squared series, there seems to be conditional heteroscedasticity present in the data, making an ARCH or GARCH model appropriate. At the same time there seem to be significant autocorrelations, making an ARMA-type model for the conditional mean appropriate.
Fitting ARMA(p,q)-GARCH(1,1) models of various orders (p,q) and selecting by AIC, I choose p = 1, q =2. However, the model doesn't seem to provide a decent fit as indicated by the following output:
<code>Weighted Ljung-Box Test on Standardized Residuals
------------------------------------
                         statistic p-value
Lag[1]                       3.847 0.04983
Lag[2*(p+q)+(p+q)-1][8]      5.474 0.06272
Lag[4*(p+q)+(p+q)-1][14]    10.146 0.10862
d.o.f=3
H0 : No serial correlation

Weighted Ljung-Box Test on Standardized Squared Residuals
------------------------------------
                        statistic   p-value
Lag[1]                      11.11 0.0008589
Lag[2*(p+q)+(p+q)-1][5]     12.32 0.0022979
Lag[4*(p+q)+(p+q)-1][9]     12.75 0.0121929
d.o.f=2
</code>
On the other hand, the ACF of the standardised residuals and the squared standardised residuals look okay (see below). My question is whether my model selection mechanism (AIC is in this case) is appropriate for the data set at hand (despite the hypothesis test results given above).
Comment: It is very unlikely to have significant autocorrelation of returns in time series of tradable instruments in a competitive market. You are zooming the graph and the bars look big, but in reality those autocorrelations are very low (i.e. 0.02). Squared returns are a different matter, they exhibit strong autocorrelation. It is a stylized fact called volatility clustering.
Comment: Could you post your data or full output?
Comment: I've edited my post to include the log return data.
Answer: In short, you should select models using AIC and/or out-of-sample fit criteria and view the rejected hypothesis as a suggestion to consider other types of models.
When using this class of time series models researchers are usually interested in accurate prediction\forecasting.  Since AIC measures how well a model predicts the data in-sample, it operates as a fair means of model selection in this case (you may also want to test how well the models fit out-of-sample…more on that below).
However, just because a particular model has the lowest AIC does not mean that that model is correctly specified or that it approximates the true data generating process well.  It could be that all the models you proposed were poor choices, or that the true process FTSE follows is so complex that practically every reasonable model will be rejected given enough data.  AIC provides no information on this point which is where hypothesis testing can come in.
Under the assumptions of standard ARMA-GARCH, the residuals should be homoscedastic and more generally iid normal.  Your hypothesis test suggests that your residuals are not homoscedastic and, in turn, that your ARMA-GARCH model may be miss specified.  On this note you may want to consider alternative specifications for the volatility process including other variants of GARCH models, i.e. EGARCH, GJR-GARCH, TGARCH, AVGARCH, NGARCH, GARCH-M, etc.  and/or stochastic volatility models.  It is highly likely that one of these models will offer a lower AIC value and produce residuals which cannot be rejected for homoscedasticity.
One important thing to note though is that no model will be perfect, especially for something like the FTSE 100.  The true data generating process driving a large financial index like this is impossibly complex, so pretty much every model you propose will be false.  For this reason, it can be argued that any meaningful hypothesis you do not reject is a reflection of insufficient data or lack of statistical power rather than evidence supporting one model over others.
One way to partially resolve this dilemma is to use out-of-sample fit as opposed to or in conjunction with AIC.  A simple example would be to fit the model using only the first 80% or 90% of the data and using the resulting coefficient estimates to obtain a log-likelihood for the remaining 20%-10% portion of the data.  The model with the highest log-likelihood would be preferred.  If the ARMA-GARCH model is truly misspecified in a way that impairs its forecasting performance, then an out-of-sample fit will help expose it.
Comment: The formulation of *AIC measures how well a model predicts the data in-sample* is confusing. AIC estimates the model's likelihood of a new observation coming from the same distribution. It does so based on in-sample information, i.e. uses in-sample likelihood and penalizes it for overfitting. To underline, AIC does not measure in-sample fit, it estimates out-of-sample fit (expected likelihood of a new observation).


label.BackColor.Name to variable?

Question: How can i save current label color (label.BackColor.Name) into variable, for later retrieval? Convert it to string? If so, how? My code:
label.BackColor = random_Color; // Sets new color
Color previous_Color = label.BackColor.Name // Don't work

Comment: You could try [learning C#](http://www.learncs.org/) and [reading the MSDN documentation](http://msdn.microsoft.com/en-us/library/system.windows.forms.label.aspx).
Comment: "Don't work" isn't much to go on, regardless of how obvious the problem is. If there is an error message then you should let us know what the message is and where. And no, it doesn't help to tell us it's on line 42.
Answer: You should use Color previous_Color = label.BackColor.
Comment: Thanks. I was thinking that `.Name` part is required. Back to the book.
Comment: Or `string previousColorName = label.BackColor.Name;`.

label.BackColor.Name to variable?


Como capturar 'responseText' de object

Question: Como faço para capturar o responseText?
var result = $.ajax({
    type : "POST",
    data: "idTecnico=" + 1,
    url : './Procedimentos/Servicos/ObterNomeTecnico.php'});
console.log(result);
var nomeTecnico = result;

Gostaria que a variável nomeTecnico recebece o resultado em string
Comment: Relacionado: [Ajax não é uma linguagem de programação. Então o que é?](https://pt.stackoverflow.com/q/116153/3774)
Comment: Relacionado: [Requisições multiplas com $.ajax, de forma sincrona](https://pt.stackoverflow.com/a/218526/3774)
Answer: Consegui da seguinte forma:
// NOME DO TECNICO
$.ajax({
   type : "POST",
   data: "idTecnico=" + dado.idTecnico,
   url : './Procedimentos/Utilitarios/ObterNomeTecnico.php',
}).then(function(data){
    var nomeTecnico = JSON.parse(data);
    $('#tecnicoView').val(nomeTecnico);
});

Como capturar 'responseText' de object


Usar javascript para disparar modal ulkit css

Question: Segundo a documentação do Ulkit css para exibir uma janela modal temos:
    <button uk-toggle="target: #my-id" type="button"></button>

        <button class="uk-modal-close" type="button"></button>

Sendo necessário um botão para disparar a modal.
Como eu faria para exibir a modal sem a necessidade de um botao.
No caso estaria dentro de uma função javascript e dependendo do resultado de um IF, quero chamar a modal. Exemplo:
if(meuValor > 1){
    UIkit.modal("my-id").show();
}

Entretando ao fazer isso o sistema me retorna = "Cannot read property 'show' of undefined"
Qual seria a maneira de chamar essa modal?
Answer: Pode fazer assim por exemplo. Toda vez que o número no input for maior que 1 o modal abrirá.

O seu código não funcionou pq você não passou o # na chamada do modal.
Método keyup verifica cada entrada de valor no input e testa a condição no if

$(".uk-input").on("keyup", function(){
  if($(".uk-input").val() > 1)
  UIkit.modal('#my-id').show();
})

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.10/css/uikit.min.css" />

    <input class="uk-input" type="text">

Teste

        <button class="uk-modal-close" type="button">X</button>


Compute $P(Y<3X)$ using joint PDF

Question: I'm given a joint pdf
$f_{X,Y}(x,y)=2e^{-x-y}, 0<x<y, 0<y $
and asked to compute $P(Y<3X)$. To do this, I let $Y=3X$ (the boundary) and found that the region of integration is under this line.
To find $P(Y<3X)$, it seems to me that the integral for this region be written as
$P(Y<3X)=\int_0^\infty \int_0^{3x} 2e^{-x-y} dy dx
 $
However this isn't right, as the boundaries are actually
$P(Y<3X)=\int_0^\infty \int_x^{3x} 2e^{-x-y} dy dx
 $
Why is this? I'm having a hard time seeing how to construct these boundaries (especially the fact that the $y$ boundary goes from $x$ to $3x$ instead of $0$ to $3x$)
Thank you.
Comment: I suggest you draw a plot
Comment: And [here](https://math.stackexchange.com/questions/3151543/question-about-the-joint-distribution-of-exponentials/) is another way to solve this without any actual integration.
Comment: Thank you Xi'an! I drew a plot to come up with the bounds in the first equation, as it looked like the y-boundary went from $0$ to $3x$;; I'm not super sure why they started from $y=x$
Comment: Thank you StubbornAtom! I'm definitely looking that over as it looks much easier!
Answer: Before we even consider $P(Y < 3X)$, note that we have the condition $0<x<y$. Because this specifies both the upper and lower bounds for $x$, the natural way to write the the integral over the support of $f_{X,Y}$ is:
$$ P(\Omega) = \int_0^\infty \int_0^{\color{red}y} 2 e^{-x} e^{-y} dx \, dy $$
You can confirm for yourself as a preliminary exercise that this equals 1. Note that the inner integral is over $x$ with $y$ appearing as bound; therefore it will be convenient if we first solve the inequality for $x$:
$$ \begin{align}
  y & < 3x & \\[0.7em]
  3x & > y & \\[0.7em]
  x & > y/3
\end{align} $$
We can use this to restrict the inner integral by adjusting the lower bound of the inner interval. The upper bound of $y$ is retained from above, the lower bound of $y/3$ is new and comes from the inequality which defines our event.
$$ \begin{align}
P(Y < 3X) & = \int_0^\infty \int_{\color{red}{\tfrac{y}{3}}}^{\color{red}y} 2 e^{-x} e^{-y} dx \, dy \\[1em]
& = \int_0^\infty \Bigg( -2 e^{-x} e^{-y} \Bigg|_{\tfrac{y}{3}}^{y} \Bigg) dy \\[1em]
& = \int_0^\infty (-2e^{-y}e^{-y}) - (-2e^{-y/3}e^{-y}) dy \\[1em]
& = \int_0^\infty -2e^{-2y} + 2 e^{-4y/3} dy \\[1em]
& = \frac{-2 e^{-2y}}{-2} + \frac{ 2 e^{-4y/3} }{-4/3} \Bigg|_0^\infty \\[1em]
& = e^{-2y} - \frac{3}{2} e^{-4y/3} \Bigg|_0^\infty \\[1em]
& = (0 - 0) - (1 - \frac{3}{2}) \\[1em]
& = \frac{1}{2} & \square
\end{align}
$$
Comment: Thank you so much! This might be a dumb question, but how did you go from $x<3x$  to $3y>y$ (when solving the inequality for x)?
Comment: It's one of the [property of inequalities](https://www.sparknotes.com/math/algebra1/inequalities/section2/): $a < b \Leftrightarrow b > a$.
Comment: Haha, I'm so sorry. Thank you so much, this is so helpful!!
Answer: The boundary for $y$ could actually go from $-\infty$ to $3x$, not just $0$ if the inside expression was written as $f(x,y)$. Then, you'd be forced to write $x$ to $3x$ in the inner integral limits when substituting $2e^{-x-y}$ in place of the joint since it is actually $0$ when $y<x$.
Comment: on the contrary, the second one is correct because joint pdf is $0$ when $y<x$. The first one'd only be correct if you write $f(x,y)$ to the inside of the integral, in which not only $0,3x$ but also $-\infty, 3x$ would be correct.
Comment: Hi gunes, thank you! So is the first integral actually correct (not the second one?)
Answer: If the joint PDF of $X,Y$ is $$f_{X,Y}(x,y)=2e^{-x-y}, 0<x<y, 0<y $$
Then
$$ P(Y < \theta X) = \int_0^\infty \int_x^{\theta x} 2e^{-x-y} dy dx $$
The inner lower bound is $x$ because of the $0 < x < y$ constraint. A good Calc 2 exercise is to calculate that integral and see that it equals
$$\frac{\theta-1}{\theta+1}$$
So when $\theta = 3$, this equals $(3-1)/(3+1) = 1/2$

Compute $P(Y<3X)$ using joint PDF


Excel: searching for a value within multiple arrays within cells

Question: I'm trying to set up an error check between two systems and need to compare week numbers in different formats.  One system produces week numbers in a text format e.g "8-15, 18, 31-32" and the other produces discrete values. How would I see whether a value e.g 16 fell within a multiple range like the one above?
It's part of a bigger issue where I'm checking a reference number, day, time and week number (e.g XXX111 Weds 9:00 9) in one system against the output of another system (e.g XXX111 Wed 9:00 7:11, 13, 16, 52-63 or XXX111 Thu 9:00 5, 6, 11-16).  Despite lots of searching I've hit a wall with the bit above so any help would be greatly appreciated.
I'd rather not use VBA if possible.  Thanks in advance for your wisdom.
Answer: Assumed:

7:11 should be 7-11
63 should be 53
A number not part of a range (eg 18) is not a problem
Ranges are in Text format

I hope the following helps or at least is 'a step in the right direction':
A Parse the components
Eg for 8-15, 18, 31-32, paste into a cell (say A1) and Data > Data Tools - Text to Columns > Delimited > Next > check Comma, Space and Treat consecutive delimiters as one > Next > Select Columns as required > select Text for each > Finish
May be easier to deal with a single column so select data, Copy > Select A2 > Paste Special > Transpose > OK and Delete contents of Row1.
B Add your search value (16) into B1
C Copy the formula below into B2 and copy down as required:
=AND(B$1>=VALUE(LEFT($A2,SEARCH("-",$A2)-1)),B$1<=VALUE(RIGHT($A2,LEN($A2)-SEARCH("-",$A2)))))
The result should be TRUE where the search value is within or on either bound of the discrete range:

The formula uses the hyphen to 'recognise' a discrete range. SEARCH looks for where it is positioned (because there could be one or two characters either side of it). LEFT and RIGHT are for the lower and upper bounds (in the case of RIGHT used in conjunction with LEN to address whether the upper bound is one or two characters). VALUE is required to convert the Text into something that can be equated to the search value. AND is for the process to consider both bounds in determining whether 'in range'.
"I'd rather not use VBA if possible" – but might be advisable!
However, use of some fixed references ($) should make it a little easier than otherwise with standard formulae only because the given discrete ranges (which may be appended in ColumnA) can be queried for various search values by copying the formulae across to the right/down as required and entering (as Number format) further search values in Row1.