Limit and factorization

Question: I have the following very interesting homework exercise:

Let $$f(x)=\frac{x^2-4}{2-x\cdot \sqrt {x+2}+\sqrt{x+2}}$$ Find the
  following limit, if it exists: $$\lim_{x\to 2}f(x)$$

I understand that I need to "delete" the $x-2$ factor from both nominator and denominator and then evaluate the limit. It is obvious that $x^2-4=(x-2)\cdot (x+2)$, so the nominator is done.
So, my main problem is how to factor the denominator of $f(x)$. Any help with the factorization, without the final solution, would be appreciated. Then, after I understand how to factor it, anyone can post the full solution, even I.
Comment: the answer is zero, it is simple, factorize roots expression
Comment: Well, the answer is not zero for sure: [WolframAlpha](http://www.wolframalpha.com/input/?i=lim+x-%3E2+%28x%5E2-4%29%2F%282-x*sqrt%28x%2B2%29%2Bsqrt%28x%2B2%29%29)...
Comment: correct the f(x) dominator, i mixed up with the dot multiplication
Answer: $$\begin{align}\lim_{x\to 2}\frac{x^2-4}{2-x\sqrt{x+2}+\sqrt{x+2}}&=\lim_{x\to 2}\frac{(x-2)(x+2)}{2-(x-1)\sqrt{x+2}}\\&=\lim_{x\to 2}\frac{(x-2)(x+2)}{2-(x-1)\sqrt{x+2}}\cdot\frac{2+(x-1)\sqrt{x+2}}{2+(x-1)\sqrt{x+2}}\\&=\lim_{x\to 2}\frac{(x-2)(x+2)(2+(x-1)\sqrt{x+2})}{4-(x-1)^2(x+2)}\\&=\lim_{x\to 2}\frac{(x-2)(x+2)(2+(x-1)\sqrt{x+2})}{-(x-2)(x+1)^2}\\&=\lim_{x\to 2}\frac{(x+2)(2+(x-1)\sqrt{x+2})}{-(x+1)^2}\\&=\frac{4\cdot (2+2)}{-3^2}\end{align}$$
Answer: $$f(x)=\frac{x^2-4}{2-x\cdot \sqrt {x+2}+\sqrt{x+2}}\Longrightarrow$$
$$\lim_{x\to2}f(x)=\lim_{x\to2}\left(\frac{x^2-4}{2-x\cdot \sqrt {x+2}+\sqrt{x+2}}\right)=$$
$$\lim_{x\to2}\left(\frac{\frac{d}{dx}\left(x^2-4\right)}{\frac{d}{dx}\left(2-x\cdot \sqrt {x+2}+\sqrt{x+2}\right)}\right)=$$
$$\lim_{x\to2}\left(\frac{2x}{\frac{1}{2\sqrt{x+2}}-\frac{x}{2\sqrt{x+2}}-\sqrt{x+1}}\right)=$$
$$\lim_{x\to2}\left(-\frac{4x\sqrt{x+2}}{3(x+1)}\right)=$$
$$\frac{\lim_{x\to2}\left(-4x\sqrt{x+2}\right)}{\lim_{x\to2}\left(3(x+1)\right)}=$$
($3(x+1)$ is a polynomial and thus everywhere continuous):
$$\frac{\lim_{x\to2}\left(-4x\sqrt{x+2}\right)}{3(2+1)}=$$
$$\frac{\lim_{x\to2}\left(-4x\sqrt{x+2}\right)}{3(3)}=$$
$$\frac{\lim_{x\to2}\left(-4x\sqrt{x+2}\right)}{9}=$$
$$\frac{-4\lim_{x\to2}x\sqrt{\lim_{x\to2}(x+2)}}{9}=$$
($x$ is a polynomial and thus everywhere continuous):
$$\frac{-4\cdot2\sqrt{\lim_{x\to2}(x+2)}}{9}=$$
($x+2$ is a polynomial and thus everywhere continuous):
$$\frac{-4\cdot2\sqrt{(2+2)}}{9}=\frac{-4\cdot2\sqrt{4}}{9}=\frac{-4\cdot2\cdot2}{9}=\frac{-4\cdot4}{9}=\frac{-16}{9}=-\frac{16}{9}$$
So:
$$\lim_{x\to2}f(x)=\lim_{x\to2}\left(\frac{x^2-4}{2-x\cdot \sqrt {x+2}+\sqrt{x+2}}\right)=-\frac{16}{9}$$
Answer: Let $x+2=z^2$, then clearly $z\to 2$ as $x\to2$. After transformation$$\lim\limits_{x\to2}\frac{x^2-4}{2-x\sqrt{x+2}+\sqrt{x+2}}=$$
$$ \lim\limits_{z\to2}\frac{z^2(4-z^2)}{z^3-3z-2}=\lim\limits_{z\to2}\frac{-z^2(z+2)(z-2)}{(z-2)(1+z(z+2))}=-\frac{16}{9}.$$

Limit and factorization


React Tutorial giving TypeError

Question: I decided to learn React and started with the official tutorial. All is good until I get to this state of my code. The problem seems to be about property squares of current in the render function of Game component which is defined but I'm not sure why it's flagged as an error
    function Square(props){
  return (
    <button className = "square" onClick = {() => props.onClick()}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value = {this.props.squares[i]} onClick = {() => this.props.onClick(i)} />;
  }
  render() {
    return (

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

class Game extends React.Component {
  constructor() {
    super();
    this.state = {
      history : [{
        squares : Array(9).fill(null)
      }],
      xIsNext : true
    };
  }
  handleClick(i){
    const history = this.state.history.slice(0, this.state.stepNumber);
    const current = history[this.state.stepNumber];
    const squares = current.squares.slice();
    if(calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history : history.concat([{
        squares : squares
      }]),
      xIsNext : !this.state.xIsNext,
      stepNumber : 0,
    });
  }
  jumpTo(step){
    this.setState({
      stepNumber : step,
      xIsNext : (step % 2) ? false : true,
    });
  }
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    let status;
    if(winner) {
      status = 'Winner : ' + winner;
    }
    else {
      status = 'Next Player : ' + (this.state.xIsNext ? 'X' : 'O');
    }
    const moves = history.map((step, move) => {
      const desc = move ? 'Move #' + move : 'Game start';
      return (

           this.jumpTo(move)}>{desc}

      );
    });

    return (

          <Board
            squares = {current.squares}
            onClick = {(i) => this.handleClick(i)}
          />

{status}

{moves}

    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('container')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

And this is the error I get
TypeError: Cannot read property 'squares' of undefined
    at Game.render (pen.js:208:41)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:6336:34)
    at ReactCompositeComponentWrapper._renderValidatedComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:6356:32)
    at ReactCompositeComponentWrapper.wrapper [as _renderValidatedComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at ReactCompositeComponentWrapper.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:5969:30)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at Object.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:13613:35)
    at ReactCompositeComponentWrapper.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:5974:34)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:12879:21)
    at Object.mountComponent (https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-with-addons.js:13613:35)

Comment: Did you try to add `stepNumber : 0` to the `state` inside the `constructor` of the `Game` component ?
Comment: @DavidDomain Silly me
Answer: So in your Game render function you start with these three lines of code
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);

However, in your Game constructor function, you do not set stepNumber in the state:
constructor() {
    super();
    this.state = {
        history : [{
            squares : Array(9).fill(null)
        }],
        xIsNext : true
    };
}

Therefore, when you do
const current = history[this.state.stepNumber]
what you are essentially doing is
const current = history[undefined]
which means when you do
const winner = calculateWinner(current.squares)
you are actually doing
const winner = calculateWinner(undefined.squares)
and there is your problem. You need to set stepNumber in your state in the constructor function.
Comment: Is there a way I can use a debugger along with the tutorial to figure out these errors since understanding the errors thrown seem to be hard?

React Tutorial giving TypeError


Running Time for CV.GLMNET

Question: I am running a cv.glmnet model (Poisson Model for rates) in R:
elasticnet_poisson_model <- cv.glmnet(x=design.x,y=y.,offset=log z.,family='poisson',alpha=elasticnet.alpha,standardize=FALSE,lambda=cust.lambda.series,penalty.factor=cust.pen,nfolds=5)
design.x is a sparse model matrix with around 20,000 columns and 2,80,000 rows.
*cust.lambda.series <- base_lambda * 10^seq(from=0,to=-11,length.out=15)*
base lamnbda = 1,01,827 (Computed running a glmnet earlier which makes the coeeficients 0).
The model is running for 16 hours now without completing.
Did anyone face similar issue while working with cv.glmnet ? Any help on how to do it faster will be highly appreciated.
Thanks in advance !
Comment: I have the same issue. my X matrix is 350 MB and at first I wanted to apply CV for each value of alpha running from 0.1 to 0.9 in 0.05 intervals. After I saw that it has been 16-18 hours already and it didn't finish I have decided to run CV on a specific value of Alpha. Keeping fingers crossed.
Answer: Is that 2.8M or 280,000 rows?
You might try fitting a single model without cross validation and see how long it takes, and extrapolate from there.

Running Time for CV.GLMNET


Inequality on a root

Question: Does it hold that
$$
\left|\max\left(\sqrt{\left|z\right|},\sqrt{\left|x\right|}\right)-\max\left(1,\sqrt{\left|y\right|}\right)\right|+\left|\min\left(\sqrt{\left|z\right|},\sqrt{\left|x\right|}\right)-\min\left(1,\sqrt{\left|y\right|}\right)\right|\le\sqrt{z-y+x+1}
$$
for all $x$, $y$, $z$ and $w$ with $-1<x<y<z$?
Comment: By the way, they are all real numbers.
Comment: Sorry that there was a typo, but it has been corrected in my question now.
Comment: With your stated order $x \lt y \lt z \lt w$ you don't need the max and min, nor the absolute value signs.
Comment: I solved the general question. Why did you edit it to become a special case?
Answer: Disclaimer: Lots of cases to consider, as expected when you see all the max, min and absolute values. Main idea is to smooth towards the case where $x, y, z, w$ are non-negative, then proceed to prove that case. I replace $x<y<z<w$ with the weaker condition $x \leq y \leq z \leq w$.
For real numbers $x \leq y \leq z \leq w$, define
$$f(x, y, z, w)=\sqrt{w-z+y-x}$$
\begin{align}
g(x, y, z, w)&=\left|\max\left(\sqrt{\left|w\right|},\sqrt{\left|y\right|}\right)-\max\left(\sqrt{\left|x\right|},\sqrt{\left|z\right|}\right)\right| \\
& +\left|\min\left(\sqrt{\left|w\right|},\sqrt{\left|y\right|}\right)-\min\left(\sqrt{\left|x\right|},\sqrt{\left|z\right|}\right)\right|
\end{align}
This is so that I don't have to keep writing those expressions. The inequality becomes $f(x, y, z, w) \geq g(x, y, z, w)$.
It is clear that $-w\leq -z \leq -y \leq -x$, $f(x, y, z, w)=f(-w, -z, -y, -x)$ and $g(x, y, z, w)=g(x, y, z, w)$.
Thus if $z<0$, then $-y \geq -z>0$ and it suffices to prove $f(-w, -z, -y, -x) \geq g(-w, -z, -y, -x)$.
It thus suffices to consider the case where $w \geq z \geq 0$.
This is where we start considering many cases. The idea is this:
Lemma: If $x<0$ and $w \geq z \geq 0$, then if we consider $a \leq b \leq c \leq d$ such that $\{a, b, c, d\}=\{|x|, |y|, z, w\}$, then $f(x, y, z, w) \geq f(a, b, c, d)$ and $g(x, y, z, w)=g(a, b, c, d)$
Before I prove this lemma, I will explain its applications to the problem, before we get too bogged down with the 10 cases we consider in the proof of the lemma.
Let's suppose for now we have proven the lemma. Suppose $x<0$ and $w \geq z \geq 0$. Note that to prove $f(x, y, z, w) \geq g(x, y, z, w)$, it suffices to prove $f(a, b, c, d) \geq g(a, b, c, d)$. Note that $\{a, b, c, d\}=\{|x|, |y|, z, w\}$, so $a, b, c, d$ are all non-negative. It thus suffices to prove the case where $0 \leq x \leq y \leq z \leq w$.
Let us now proceed to prove the lemma:
Case 1: $y \geq 0$. We have 4 subcases.
Case 1a) $-y \leq x<0 \leq y \leq z \leq w$.
Then $0< -x \leq y \leq z \leq w$.
$g(x, y, z, w)= (\sqrt{w}-\sqrt{z})+(\sqrt{y}-\sqrt{-x})=g(-x, y, z, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(-x, y, z, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-z+y-(-x)} \\
& \Leftrightarrow w-z+y-x \geq w-z+y+x \\
& \Leftrightarrow 0 \geq 2x
\end{align}
which is true.
Case 1b) $-z \leq x<-y \leq 0 \leq y \leq z \leq w$
Then $0 \leq y<-x \leq z \leq w$
$g(x, y, z, w)=(\sqrt{w}-\sqrt{z})+(\sqrt{-x}-\sqrt{y})=g(y, -x, z, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(y, -x, z, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-z+(-x)-y} \\
& \Leftrightarrow w-z+y-x \geq w-z-x-y \\
& \Leftrightarrow 2y \geq 0
\end{align}
which is true.
Case 1c) $-w \leq x<-z \leq 0 \leq y \leq z \leq w$
Then $0 \leq y \leq z<-x \leq w$.
$g(x, y, z, w)=(\sqrt{w}-\sqrt{-x})+(\sqrt{z}-\sqrt{y})=g(y, z, -x, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(y, z, -x, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-(-x)+z-y} \\
& \Leftrightarrow w-z+y-x \geq w+x+z-y \\
& \Leftrightarrow 2y \geq 2(x+z)
\end{align}
which is true.
Case 1d)$x<-w \leq 0 \leq y \leq z \leq w$
Then $0 \leq y \leq z \leq w<-x$.
$g(x, y, z, w)=(\sqrt{-x}-\sqrt{w})+(\sqrt{z}-\sqrt{y})=g(y, z, w, -x)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(y, z, w, -x) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{(-x)-w+z-y} \\
& \Leftrightarrow w-z+y-x \geq -x-w+z-y \\
& \Leftrightarrow 2(w+y) \geq 2z
\end{align}
which is true.
Case 2: $y<0$. We have 6 subcases.
Case 2a) $-z\leq x \leq y<0 \leq z \leq w$
Then $0<-y \leq -x \leq z \leq w$
$g(x, y, z, w)=(\sqrt{w}-\sqrt{z})+(\sqrt{-x}-\sqrt{-y})=g(-y, -x, z, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(-y, -x, z, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-z+(-x)-(-y)} \\
\end{align}
which is true.
Case 2b) $-w \leq x<-z \leq y<0 \leq z \leq w$
Then $0<-y \leq z<-x \leq w$.
$g(x, y, z, w)=(\sqrt{w}-\sqrt{-x})+(\sqrt{z}-\sqrt{-y})=g(-y, z, -x, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(-y, z, -x, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-(-x)+z-(-y)} \\
& \Leftrightarrow w-z+y-x \geq w+x+z+y \\
& \Leftrightarrow 0 \geq 2(x+z)
\end{align}
which is true.
Case 2c) $x<-w \leq -z \leq y<0 \leq z \leq w$
Then $0 \leq -y \leq z \leq w<-x$.
$g(x, y, z, w)=(\sqrt{-x}-\sqrt{w})+(\sqrt{z}-\sqrt{-y})=g(-y, z, w, -x)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(-y, z, w, -x) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{(-x)-w+z-(-y)} \\
& \Leftrightarrow w-z+y-x \geq -x-w+z+y \\
& \Leftrightarrow 2w \geq 2z
\end{align}
which is true.
Case 2d) $-w \leq x \leq y<-z \leq 0 \leq z \leq w$
Then $0 \leq z<-y \leq -x \leq w$.
$g(x, y, z, w)=(\sqrt{w}-\sqrt{-x})+(\sqrt{-y}-\sqrt{z})=g(z, -y, -x, w)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(z, -y, -x, w) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{w-(-x)+(-y)-z} \\
& \Leftrightarrow w-z+y-x \geq w+x-y-z \\
& \Leftrightarrow 2y \geq 2x
\end{align}
which is true.
Case 2e) $x<-w \leq y<-z \leq 0 \leq z \leq w$
Then $0 \leq z<-y \leq w<-x$.
$g(x, y, z, w)=(\sqrt{-x}-\sqrt{w})+(\sqrt{-y}-\sqrt{z})=g(z, -y, w, -x)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(z, -y, w, -x) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{(-x)-w+(-y)-z} \\
& \Leftrightarrow w-z+y-x \geq -x-w-y-z \\
& \Leftrightarrow 2(w+y) \geq 0
\end{align}
which is true.
Case 2f) $x \leq y<-w \leq -z \leq 0 \leq z \leq w$
Then $0 \leq z \leq w<-y \leq -x$.
$g(x, y, z, w)=(\sqrt{-x}-\sqrt{-y})+(\sqrt{w}-\sqrt{z})=g(z, w, -y, -x)=g(a, b, c, d)$
\begin{align}
f(x, y, z, w) \geq f(a, b, c, d)=f(z, w, -y, -x) & \Leftrightarrow \sqrt{w-z+y-x} \geq \sqrt{(-x)-(-y)+w-z} \\
& \Leftrightarrow w-z+y-x \geq -x+y+w-z \\
\end{align}
which is true.
Lemma proved.
Finally, we proceed to consider the case where $0 \leq x \leq y \leq z \leq w$.
The inequality becomes $\sqrt{w-z+y-x} \geq \sqrt{w} - \sqrt{z} + \sqrt{y} - \sqrt{x}$.
Note that
\begin{align}
\sqrt{w-z+y-x} + \sqrt{z} \geq \sqrt{w}+ \sqrt{y-x} & \Leftrightarrow (\sqrt{w-z+y-x} + \sqrt{z})^2 \geq (\sqrt{w}+ \sqrt{y-x})^2 \\
& \Leftrightarrow (w-z+y-x)z \geq w(y-x) \\
& \Leftrightarrow (w-z)(z+x-y) \geq 0
\end{align}
and
\begin{align}
\sqrt{y-x} + \sqrt{x} \geq \sqrt{y} & \Leftrightarrow (\sqrt{y-x} + \sqrt{x})^2 \geq y \\
& \Leftrightarrow x(y-x) \geq 0
\end{align}
Summing gives the desired inequality, so we are done. (Finally...)
That took forever to type. If anyone has an elegant proof with less cases, that would be great. The proof for the various cases are almost identical, so there might be a way to cover all cases at one go.
Answer: If $x, y, z, w = 1, 4, 9, 16$,
this becomes
$\sqrt{16-9+4-1} \le |\max(4,2)-\max(1,3)|+|\min(4,2)-\min(1,3)|$
or
$\sqrt{10} \le |4-3|+|2-1| = 1 + 1 = 2$
which seems to be false.
Note: This was the simplest example I could come up with.
Also, from the inequalities,
you can rewrite this as,
letting $x, y, z, w = a^2, b^2, c^2, d^2$
with $0 < a < b < c < d$,
$\sqrt{d^2-c^2+b^2-a^2} \le |d-c|+|b-a|$,
which looks a lot easier to analyze.
Comment: marty, sorry that I made a typo. It has been corrected in my question now.
Comment: marty, it should be $\ge$ instead of $\le$ in the question. Do you have any counterexamples? Thanks.
Comment: Letting $x,y,z,w=a^2,b^2,c^2,d^2$ assumes $x,y,z,w$ all non-negative, which is not in the hypothesis.
Comment: Dear Gerry, you may assume they are all non-negatives, but what if they are not?
Comment: marty, thank you for your answer, but your answer is incorrect (the example you gave is not a counter examples). Can you show that the inequality in the question holds?
Comment: @marty, or could you please remove your incorrect answers? Thanks.
Answer: If they are all positive, $x \lt y \lt z \lt w$ tells us what the max and min are, so you are asking whether $\sqrt {w-z+y-x} \ge \sqrt w -\sqrt z+\sqrt y - \sqrt x$.  The two element version is true:  you are asking whether $\sqrt {y-x} \ge \sqrt y - \sqrt x$  You can divide through by $\sqrt x$ to ask whether $\sqrt {\frac yx -1}-\sqrt {\frac yx}+1 \gt 0$ with $\frac yx \gt 1$.  You can prove this by taking a derivative or just by looking at the graph.  The four element version appears to be correct, but I haven't found a proof.
Comment: Ross, what if they are not all positive?

Inequality on a root


TinyMCE - Drupal 7 - Insert images not functioning

Question: I'm having trouble inserting images via TinyMCE  (I've also installed WYSIWYG). I can insert images into an article just fine and all looks as it should while I'm editing an article, but if I preview or save the article and then view it, the image doesn't show up, instead I see:
[img]/sites/default/files/myimage.png[/img]
I've tried making the content with full html, and I've installed the media module and selected an option under text formats that is supposed to convert media tags into html.
What am I missing?
Comment: Have you checked if the "Limit allowed HTML tags" checkbox is un-ticked under /admin/config/content/formats/full_html?
Comment: How are you embedding the images? If they should be stored on your drupal installation consider using this modules: http://drupal.org/project/imce, http://drupal.org/project/imce_wysiwyg
Comment: @Volker - yes, the box is unchecked
Comment: @BetaRide - Thanks for the suggestion, I've installed the Bridge module but it did not fix the issue. I've also just noticed that text formatting is not working either
Answer: Disabling the BBCode option in my TinyMCE Wysiwyg profile worked for me.
Answer: Use the Bbcode module to convert the bbcode to HTML tags. Here is a quote about it (from the module's project page):

... adds a BBCode filter to Drupal. This allows you to use HTML-like tags as an alternative to HTML itself for adding markup to your posts. BBCode is easier to use than HTML and helps to prevent malicious users from disrupting your site's formatting.
See the help screen of the module (or the code) for information on which tags and variants are supported. This implementation is not necessarily the same as the original BBCode implementation.
Note that this filter also recognizes and converts URLs and email addresses to links automatically.
The quicktags module can be used in conjunction with this module to provide a BBCode formatting bar above all text areas.
Comment: I was also looking for a solution, and after installing bbcode, everything whent smooth :)
Answer: I ended up using CKEditor instead of TinyMCE; it worked like a charm.
Answer: Disabling that BBcode was the key for me. I have been searching for some time for this problem and came across everything from permissions to .htaccess and setting.php.
Thank you localstatic for you are the hero of the day if not the week.


How can I remove javascript from everywhere but the front page?

Question: I tried using this in template.php
function MYTHEME_js_alter(&$javascript) {
  if ($!is_front) {
    unset($javascript['path/to/script.js']);
  }
}

but it doesn't work. Performance wise, would it be as good to have the javascript that's on every page in theme.info, then use drupal_add_js on the front page instead?
Answer: You need to update. Below are the update :
if (!drupal_is_front_page()) {
      unset($javascript['path/to/script.js']);
    }

function drupal_is_front_page
Reference Link : Click Here


Method that returns two classes in java

Question: I have two classes:
public class UnoLoginPageUi {
    public final Input username = new Input("id=username");
    public final Input password = new Input("id=password");
    public final Button loginButton = new Button("name=login");
}

and
public class DuoLoginPageUi {
    public final Input username = new Input("id=usernameField");
    public final Input password = new Input("id=passwordField");
    public final Button loginButton = new Button("id=submitButton");
}

and in one common class I want to make something like that:
public void loginUsingUsernameAndPassword(String username, String password, String pageType) {
    getUi(pageType).username.waitForToBeDisplayed();
    getUi(pageType).username.setValue(username);
    getUi(pageType).password.setValue(password);
    getUi(pageType).loginButton.click();
}

where getUi() is a method that gas argument pageType (which is UNO or DUO).
private Class getUi(String pageType) {
    if (pageType.equals("UNO")) {
        return new DuoLoginPageUi();
    }
    else if (pageType.equals("DUO")) {
        return new UnoLoginPageUi;
    }
    return null;
}

However it doesn't work as this method need to in type of this two pages with selectors - how to deal with that ?
Comment: Create an interface that each of those classes implement. Use that interface as return type. Also, use an enum rather than a String for the page type.
Comment: Replace the return type, currently `Class` with `Object`
Comment: add more detail how method gonna call from these two classes. ur question contains only code
Comment: What´s the error? `return new UnoLoginPageUi;` need () btw.  If you do it this way you need to check type every time. create a Wrapper for those UI-Classes and extend them from Wrapper. So u can use this type and simply null check and cast it when you need it.
Comment: You can Use Interface On Your Code
Comment: I also hope you realise that every time you call `getUi(pageType)` it is returning a new instance. by the time you call `getUi(pageType).loginButton.click();` the instance returned has no values set.
Comment: Interface as suggested by @Xing is a perfect solution .To add to your question ,instead of using pageType.equals java provides  instanceof check which will help you to check whether pageType is an instanceof DUO or UNO
Answer: You can create a interface called LoginPageUi. And let your UnoLoginPageUi and DuoLoginPageUi implement that interface.
Then your getUi method will be private LoginPageUi getUi(String pageType).
Off topic: I would recommend to implement an enum instead of String pageType.
Comment: yup thats what i m going to answer :D
Answer: create Parent class or interface for both called UI:
public abstract class Ui{
}

public interface Ui{
}

and extend it:
public class UnoLoginPageUi extends Ui{
  public final Input username = new Input("id=username");
  public final Input password = new Input("id=password");
  public final Button loginButton = new Button("name=login");
}

public class DuoLoginPageUi extends Ui {
  public final Input username = new Input("id=usernameField");
  public final Input password = new Input("id=passwordField");
  public final Button loginButton = new Button("id=submitButton");
}

or
public class UnoLoginPageUi implements Ui{
  public final Input username = new Input("id=username");
  public final Input password = new Input("id=password");
  public final Button loginButton = new Button("name=login");
}

public class DuoLoginPageUi implements Ui {
  public final Input username = new Input("id=usernameField");
  public final Input password = new Input("id=passwordField");
  public final Button loginButton = new Button("id=submitButton");
}

then return parent reference as:
private Ui getUi(String pageType) {
if (pageType.equals("UNO")) {
    return new DuoLoginPageUi();
}
else if (pageType.equals("DUO")) {
    return new UnoLoginPageUi;
}
return null;
}

Comment: Your solution is ok, but you should make `Ui` an interface or an abstract class since it's not having any behaviour or fields.
Comment: Unfortunately I can't case like that:
getUi("DUO").password.setValue(password);
Comment: Since password field is **final**, you can't change it :)
Comment: You have to remove final modifier of fields.
Comment: It's not fault of modifiers,  actuall after I try cast some selector like above I can do only .getClass or call another function on getUi().  - but not selector.
Answer: Create a common abstraction for the two classes
public abstract class LoginPageUi {
    public final Input username = new Input("id=username");
    public final Input password = new Input("id=password");
    public final Button loginButton = new Button("name=login");
}

and have UnoLoginPageUi and DuoLoginPageUi extend that
public class UnoLoginPageUi extends LoginPageUi {
    public static String getPageType() { return "UNO"; }
}

public class DuoLoginPageUi extends LoginPageUi {
    public static String getPageType() { return "DUO"; }
}

The method would return the common abstraction
private LoginPageUi getUi(String pageType) {
    if (pageType.equals(DuoLoginPageUi.getPageType())) {
        return new DuoLoginPageUi();
    }
    else if (pageType.equals(UnoLoginPageUi.getPageType())) {
        return new UnoLoginPageUi;
    }
    return null;
}

I also hope you realize that every time you call getUi(pageType) it is returning a new instance. by the time you call getUi(pageType).loginButton.click(); the instance returned has no values set.
Refactor:
public void loginUsingUsernameAndPassword(String username, String password, String pageType) {
    LoginPageUi ui = getUi(pageType);
    if (ui != null) {
        ui.username.waitForToBeDisplayed();
        ui.username.setValue(username);
        ui.password.setValue(password);
        ui.loginButton.click();
    }
}

Method that returns two classes in java


Error setting up Xdebug with Xampp (Windows 7) - server certificate does NOT include an ID which matches the server name

Question: I have been trying to setup Xdebug to work with Xampp but it gives me an error loading the file.
Error log:
<code>[Wed Mar 25 23:00:50.218514 2015] [core:warn] [pid 4144:tid 248] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?

Failed loading C:\Users\tara\workspace\php_xdebug-2.3.2-5.6-vc11-x86_64.dll.example.com:443:0 server certificate does NOT include an ID which matches the server name

[Wed Mar 25 23:00:50.438521 2015] [mpm_winnt:notice] [pid 4144:tid 248] AH00455: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3 configured -- resuming normal operations

[Wed Mar 25 23:00:50.438521 2015] [mpm_winnt:notice] [pid 4144:tid 248] AH00456: Apache Lounge VC11 Server built: Jul 17 2014 11:50:08

[Wed Mar 25 23:00:50.438521 2015] [core:notice] [pid 4144:tid 248] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'

[Wed Mar 25 23:00:50.440521 2015] [mpm_winnt:notice] [pid 4144:tid 248] AH00418: Parent: Created child process 5964

[Wed Mar 25 23:00:50.964551 2015] [ssl:warn] [pid 5964:tid 260] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
</code>
This is what I have in my php.ini file:
<code>[XDebug]
zend_extension = "C:\Users\tara\workspace\php_xdebug-2.3.2-5.6-vc11-x86_64.dll"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
</code>
Answer: I ended up finding out that I had the wrong version of XDebug installed.  I installed the newest one for my version of Windows and looked at the TS vs not TS) + PHP, but they have a custom installer that told me to go with a slightly older version and then it worked!  Here's the site:
http://xdebug.org/wizard.php
After this fix, I still had an error with the session not starting when I ran Eclipse (it would freeze at the load forever and say it was waiting for the XDebug session).  I fixed that by adding the following line to my php.ini file:
<code>xdebug.idekey=ECLIPSE_DBGP
</code>
Comment: Okay. Thats just a really easy solution. Works like a charme. Thx!


Redirect to a URL with 404 status code in Java

Question: How to redirect a http request to a specific URL with 404 status code. I am using
Response.sendRedirect("/404userfriendlypage")

The response code of requested URL is 301, instead i need that to be 404. and then redirect to this user friendly error page.
Thanks in Advance.
Answer: I have solved this  by using below code.
Response.sendError(HttpServletResponse.SC_NOT_FOUND);

which sends 404 to front end for the requested url. At application level, we have a configuration where if 404 code receives redirect to a user friendly page.
Answer: Redirect in your spring controller using this syntax
        return "redirect:/urlNotExist";

Above redirection will give 404 on to client as "/urlNotExist" route has no mapping.
Now you can either code on client-side at client side for redirecting to user friendly error page. Or Simply setup a @ControllerAdvice for server-side redirection to user friendly error page.
Solution in plain java.
Redirect using simple Response.sendRedirect("path");
Response.sendRedirect("/404Genratingpage")

And to redirect to a custom error page when staus is 404 or on some other criteria. You need to override Response.sendRedirect method.
 public class CustomResponseWrapper extends HttpServletResponseWrapper {

     @Override
    public void sendRedirect(String location) {

      //custom logic to redirect to a user friendly error page.
  super.sendRedirect(request.getContextPath()+"/404userfriendlypage.jsp");
    }

}

And for your 404 or any other status , try setting response status like below in your 404userfriendlypage.jsp.
<%response.setStatus(404);%>

Comment: Can you provide the solution in plain java. Application is not based on Spring.
Comment: Thank you @Sacin for your answer, It didn't solved my problem. I have to redirect with 404 error code as response. Using above code, it gives 301 but i need 404


Gravar registros com a máscara ou remover antes?

Question: Contextualizando minha pergunta, meio que por convenção de meu antigo ambiente de trabalho sempre gravei os registros sem a máscara na base, mas surgiu uma situação no meu novo emprego em que eles estão salvando os registros com a máscara.
Até onde eu sei o "correto" é salvar sem a máscara, mas não tenho argumentos para justificar meu ponto, o que eu gostaria são justificativas de porque os registros deveriam ser salvos desta forma no banco.
Answer: Existem argumentos para os dois lados. Particularmente acho que o correto é sem a máscara porque a máscara geralmente é só uma apresentação visual do dado, ela não faz parte do dado, a máscara é algo estranho ao dado, então conceitualmente seria errado usá-la. Sempre prefiro adotar o que é conceitualmente correto porque isso tende a dar menos problemas no futuro.
Claro que não vale se a máscara faz parte do dado, se não há uma padronização ou coisas assim. Um RG não pode ter máscara, varia para cada estado, época e outras coisas, por outro lado as pessoas provavelmente preencherão com máscara. Como ele é só descritivo não importa muito.
O principal argumento para usá-la no dado é que pode simplificar a programação em alguns casos. Dependendo da tecnologia usada pode ter que preparar o dado com a máscara antes de usá-lo ou depois de recebê-lo.
Um argumento para não usar é que a máscara pode mudar um dia e criar complicadores para adaptar o dado.
No passado existia o argumento que sem a máscara economiza espaço, hoje isso costuma ser irrelevante.
Coloquei no GitHub para referência futura.
Comment: O dígito verificador do RG não pode causar confusão? Ou ele é, sempre foi e sempre será fixo?
Comment: Sempre pode mudar. Há algum tempo sequer tinha dígito.
Comment: O correto então é colocar o dígito verificador numa outra coluna? Se não me engano o formato do RG ou do CPF é estadual, ou seja, pode ser que mudem alguns e não todos, na hora de formatar vai virar confusão certo?
Comment: Não, o dígito faz parte do código. o RG é estadual (ele vai morrer em alguns anos), como dito, é só descritivo. Por ter várias máscaras fica difícil gravar sem ela. Até dá para fazer isso já que o RG sempre precisa do órgão emissor que indica de que estado é e permite aplicar, mas complica, fora que pode acontecer de ter máscaras de acordo com a época.


Is there a rhythmic counterpart to voice leading? Is counterpoint supposed to fulfill this role?

Question: I have been studying voice leading and I feel like rhythm is unaddressed in voice leading theory.
Here's an example of the types of voice leading rules I'm referring to:

Resolve 7->1 in a V chord in the outer voices.
Keep the notes the same if you can (except in soprano).
Move mostly by step.
Avoid melodic leaps with dissonant intervals.
No parallel fifths/octaves (or unisons)
No hidden fifths/octaves between the outer voices
Don't double tendency tones!
Keep upper voices within an octave of one another (i.e. soprano is within an octave of the alto, alto is within an octave of the tenor)
No voice crossings (where one voice goes above another)
No voice overlaps
When doubling/completing chords,

you may only leave out the fifth
write complete chords whenever possible.
Double the root of the chord (except for diminished…)
Double the fifth if it makes the voice leading smoother.
Be careful with the third.

Write outer voices first – make sure they sound good together!
Contrary motion between upper voices and bass whenever possible
Start with a close position chord and work out from there.
If a pair of upper voices leap together by more than a third, rethink it

Source: https://community.wvu.edu/~mh0001/CS14.pdf
But most of these rules seem to just apply to the relationship between chords of fixed duration. These aren't really rules for making truly distinct melodic lines work together unless they happen to be just a sequence of chords. And most real melodic lines have more complex rhythmic structure than just chord sequences.
My Question:
Is there a set of "rhythmic" voice leading rules?
From what I understand, counterpoint is intended to fulfill this role. Is that correct? If so, I'm confused about how it adequately fulfills this role.
As I understand it, there are two types of counterpoint:

Species counterpoint
Other types (e.g. free, strict)

Species counterpoint is intended to be a teaching tool. Basically, each species is like a case study. You learn certain properties from each one and so each possesses it's own voice leading rules, again specific to pitch. However, you then try to combine the species in fifth species counterpoint so you can see how they work together.
I'm confused why these are sufficient however. Melodies have far more varied rhythmic divisions than a species counterpoint, even fifth species. Take this simple melody from Mozart's Piano Sonata K 545 Movement 1

This is a simple melody, but if I tried to understand it with species counterpoint, it would be incredibly difficult if not impossible. As far as I can tell, doing 5th species counterpoint would not allow me to understand how these melodies combine because the melody line doesn't fit into species 1,2, or 3.  Species 4 is irrelevant in this case because there is no syncopation. So, this melody doesn't fit into any of the species.
So, if counterpoint is supposed to be the "rhythm" version of voice leading rules, then what type of counterpoint would allow me to link melodic lines that have rhythmic variations beyond the simple ones in species?
Here's an example of some counterpoint rules that I find insufficient in that it barely addresses rhythm (otherwise, I like it a lot):
https://music.utk.edu/theorycomp/courses/murphy/documents/counterpoint.pdf
Comment: Counterpoint is not the "rhythmic version" of voice leading, and the excerpt you give isn't written according to the rules of counterpoint -- it's homophonic rather than polyphonic. Voice-leading is a set of abstract principles, which the excerpt does follow. Consider the entire first measure as a C major chord and the beginning of the second measure as a G7 chord. You'll see that each "voice" within the block chords moves according to voice-leading principles.
Answer: Your Mozart example isn't counterpoint, it's a melody and an accompaniment of broken chords. Basically this:

This is a contrapuntal approach to the piece:

Yes there are 'rules'. Melodic and/or rhythmic imitation is good. When one part is rhythmically 'busy', let the other be simple.


Determine the convergence of a series with respect to $\alpha > 0$

Question: This is a Calculus 2 exam task:
Determine the convergence of the series below with respect to $\alpha>0$.
$$\sum_{n=1}^{+\infty}\left\vert\sin\left(1\over n\right)-\frac{\cos\left(1\over n\right)} n\right\vert^\alpha$$
My TA has advised me to follow the solution of a similar task from an older exam, but I'm having problems constructing the Maclaurin series for the series in this question.
Here is the old task and its solution I was given as guidance for my original problem:
Determine the convergence of the series below with respect to $\alpha>0$.
$$\sum_{n=1}^{+\infty}\left\vert e^{\frac 2 {n^2}}-1-\frac 2 {n^2}-\frac 2{n^4}-\frac 2{n^6}\right\vert^\alpha$$
Solution. From the Maclaurin expansion of $e^x$ we know that for sufficiently small values of $x$, $$e^x\approx1+x+\frac {x^2}{2}+\frac{x^3}6$$
The series convergence depends on the size of its terms for large $n$, in which case $\cfrac 2 {n^2}$ truly is close to $0$, therefore: $$e^{\frac 2 {n^2}}\approx 1+\frac 2{n^2}+\frac 2{n^4}+\frac 4 {3n^6}$$
i.e. $$\frac{e^{\frac 2 {n^2}}-1-\frac 2{n^2}-\frac 2{n^4}-\frac 2{n^6}}{\frac 1{n^6}}\approx-\frac 2 3\qquad(1)$$
The above observation guides us to compare the given series with the series $\sum_{n=1}^{+\infty}\cfrac 1{n^{6\alpha}}$. For such comparison we evaluate the limit
$$\lim_{n\to\infty}\frac{\left\vert e^{\frac 2 {n^2}}-1-\frac 2{n^2}-\frac 2{n^4}-\frac 2{n^6}\right\vert^\alpha}{\frac 1{n^{6\alpha}}}=\left\vert\lim_{n\to\infty}\frac{e^{\frac 2 {n^2}}-1-\frac 2{n^2}-\frac 2{n^4}-\frac 2{n^6}}{\frac 1{n^{6}}}\right\vert^\alpha\qquad(2)$$
By substituting $x=\cfrac 2 {n^2}$, the limit will equal
$$\left\vert\lim_{x\to0}\frac{e^x-1-x-\frac {x^2}2 -\frac{x^3}4}{\frac{x^3}8}\right\vert^\alpha,$$
under the condition that the limit under the absolute value exists. We notice that for that limit:
$$\lim_{x\to0}\frac{e^x-1-x-\frac {x^2}2 -\frac{x^3}4}{\frac{x^3}8}\stackrel{\text{L'H}}{=}\lim_{x\to0}\frac{e^x-1-x-\frac {3x^2}4}{\frac {3x^2}8}$$$$\stackrel{\text{L'H}}{=}\lim_{x\to0}\frac{e^x-1-\frac {3x}2}{\frac{3x}4}\stackrel{\text{L'H}}{=}\lim_{x\to0}\frac{e^x-\frac 3 2}{\frac 3 4}=-\frac 2 3$$
We were expecting such result due to the approximation $(1)$. We conclude that the limit $(2)$ equals $\left(\frac 2 3\right)^\alpha\in\langle 0,+\infty\rangle$, therefore by the limit comparison test, the given series converges if and only if the series $\sum_{n=1}^{+\infty}\cfrac 1 {n^{6\alpha}}$ converges, i.e. if and only if $6\alpha>1$, i.e. $$\alpha>\frac 1 6$$
Thanks in advance for any hints on the subject.
Comment: Regarding the approximation $(1)$ - we're not allowed to use calculators on our exams; I'm not sure how we approximated this result either.
Answer: We have that by

$\sin x=x-\frac16 x^3+O(x^5)$
$\cos x=1-\frac12 x^2+O(x^4)$

we obtain
$$\sin\left(1\over n\right)-\frac{\cos\left(1\over n\right)} n = \frac 1n-\frac16\frac1{n^3}+O\left(\frac1{n^5}\right)- \frac 1n+\frac12\frac1{n^3}+O\left(\frac1{n^5}\right)=\frac13\frac1{n^3}+O\left(\frac1{n^5}\right)$$
which leads to $\alpha>\frac13$.

Edit
As an alternative, to avoid the big-O notation, it suffices to show that
$$\frac{\sin\left(1\over n\right)-\frac{\cos\left(1\over n\right)} n}{\frac13\frac1{n^3}} \to 1$$
and then conclude by limit comparison test that we need $\alpha>\frac13$ for convergence.
Comment: @Bernard Oh yes of course! Thanks I fix it.
Comment: Also, personally; I would use  Taylor-Young's formula, with $\Bigl(\dfrac1{n^3}\Bigr)$ as a complementary term.
Comment: @Bernard My idea here is refer to limit comparison to conlcude. What do you mean with "as a complementary term"?
Comment: What remains when you've subtracted the expansion at a certain order. You use $O\Bigl(\dfrac1{n^5}$, and I prefer to use` little o`, as it yields directly an asymptotic equivalent. But this depends on how you're familiar with asymptotic analysis.
Comment: @Bernard Ah ok, yes I also often use little-0 notation, there is not a particular reason for which I've adopted big-O notation here.
Comment: Thanks for the solution, however, the O notations aren't part of my Calculus 2, so I don't really understand your work. Is there any way this particular task can be solved without the use of the O notation? Or can it be explained in a fairly simple manner so that I could read your solution better?
Comment: @kyrillox Yes, I add an alternative way.


$X_1,\cdots,X_5$ is a random sample, $\sim N(0,1)$. Let $T=\sum\limits_{i=1}^5 (X_i-\bar{X})^2$. Find $E(T^2\bar{X}^2)$

Question: $X_1,\cdots,X_5$ is a random sample, $\sim N(0,1)$. Let $T=\sum\limits_{i=1}^5 (X_i-\bar{X})^2$. Find $E(T^2\bar{X}^2)$
My attempt:
$X_i$'s are independent, so $T$ and $\bar{X}$ are independent, so $T^2$ and $\bar{X}^2$ are independent.
$\therefore E(T^2\bar{X}^2)=E(T^2)E(\bar{X}^2)$
Now, $E(\bar{X}^2)=V(\bar{X})+E^2(\bar{X})=V(\bar{X})=\frac15$
How do I find $E(T^2)$?
Comment: Why are $T$ and $\bar{X}$ independent?  They don't look independent to me.
Comment: @WETutorialSchool : They are indeed independent, but the poster gives no argument to show that.
Comment: @WETutorialSchool : See my answer below.
Answer:
$X_i$'s are independent, so $T$ and $\bar{X}$ are independent

That is not a valid argument at all.
It is true that $T$ and $\overline X$ are independent, but you need to give a valid proof of that. You have
\begin{align}
& \overline X = \frac{X_1+X_2+X_3+X_4+X_5} 5 \\[10pt] \text{and } & T^2 = (X_1-\overline X)^2 + (X_2-\overline X)^2 + (X_3-\overline X)^2 \\
& {} \qquad\qquad {} + (X_4-\overline X)^2 + (X_5-\overline X)^2
\end{align}
Since $\overline X$ and $T^2$ are both defined using the same quintuple, it is hardly obvious that they are independent.
Now note that
$$
\operatorname{cov}(\,\overline X, X_1-\overline X\,) = \frac 1 n - \frac 1 n =0.
$$
That the covariance of two random variables is $0$ falls far short of proving that they are independent, but if $X_1,\ldots,X_n$ are i.i.d. normally distributed, then any two linear combinations
\begin{align}
& a_1 X_1 + \cdots + a_n X_n, \\
& b_1 X_1 + \cdots + b_n X_n,
\end{align}
are independent if their covariance is $0.$ You can use that to show that
$$
\overline X \text{ and } \big(X_1-\overline X,\ldots, X_n-\overline X\big)
$$
are independent, and consequently that $\overline X$ and $T^2$ are independent.
Next you have the question of $\operatorname E(T^2).$
Notice that
\begin{align}
& \operatorname{var}(X_1-\overline X) = \operatorname{var}(X_1) + \operatorname{var}(\,\overline X\,) - 2\operatorname{cov}(X_1,\overline X\,) \\[10pt]
= {} & 1 + \frac 1 n - \frac 2 n = 1 - \frac 1 n.
\end{align}
Since $\operatorname E(X_1-\overline X\,)=0,$ we therefore have
$$
\operatorname E\big( (X_1 - \overline X)^2 \big) = 1 - \frac 1 n = 1 - \frac 1 5.
$$
Now add that up five times.


create a user and associate with existing pem file

Question: I have an ec2 instance on which i am running ansible.I want to create a user with a playbook, but without a password and the user must be using existing pem file for authentication and must be able to login to instance that file.Tricky part here is how to write play that creates a user and associates it with existing pem file.I am completely out of ideas.
Answer: You will just need to add the public key contained in the pem file in the authorized_keys file for the user.
The public key can be extract like this:
openssl rsa -in charlie.pem -pubout > charlie.pub

The public key can than be stored in the Ansible code under files.
Than you can use the user module to create the user and the authorized_key module to add the public key like this:
- user: name=charlie state=present
- authorized_key: user=charlie key="{{ lookup('file', 'charlie.pub') }}"


SQL Server 2008 process list - Is this normal?

Question: I'm very new to SQL Server, and just wondered if anyone could tell me if this process list is normal.

Wait Time | Last Wait Type      | dbid
55372252  | ONDEMAND_TASK_QUEUE | 1
55371504  | BROKER_TRANSMITTER  | 1
55371504  | BROKER_TRANSMITTER  | 1
55352380  | BROKER_EVENTHANDLER | 1
55351938  | KSOURCE_WAKEUP      | 1
36413691  | XE_DISPATCHER_WAIT  | 0
393368    | LOGMGR_QUEUE        | 0
393367    | CHECKPOINT_QUEUE    | 2
23258     | XE_TIMER_EVENT      | 0

The server has been rebooted several times a day ago, which is what I think has caused the checkpoint restore messages to come up, db id 1 is Master and db 2 is tempdb.
As I understand it the checkpoint is when I have dirty pages which get written to the disk, but should this operation be taking as long as it is?
Answer: The CHECKPOINT_QUEUE wait is associated with SPID 19 on my system, which is a system process. Like the Service Broker processes, the wait time is probably indicative of the process just sitting around waiting for something it needs to do, rather than some work performing poorly and grinding for long periods. This is actually fairly common with system processes (SPID <= 45, from the looks of it), so I wouldn't worry too much about high wait times on any of those (especially if the thread status is "sleeping" for all of them, which they are for me).


TypeScript JQuery interface merging needs to reference module

Question: I'm having trouble finding good guidance on how to layout d.ts files for my modules.
Compiling to target ES5 and CommonJS modules.
I have a remote.ts file that exports both a class Remote and an interface IRemoteOptions.
//remote.ts
export class Remote {
 //...
}
export interface IRemoteOptions{
  ///...
}

I then extend JQuery to add a function remote(options?: IRemoteOptions).
//global.d.ts
interface JQuery{
 remote(options? IRemoteOptions);
}

How do I make sure that global.d.ts knows about IRemoteOptions without adding an import statement to that file? If I add an import statement, it becomes a module itself and ruins the scope for extending JQuery.
We have a number of other extension points to JQuery that'll need to be added, what's the correct way to do this?
Answer: I got this working using the Global Augmentation method.
https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation
I moved the JQuery interface extension back into my remote.ts file like this:
//remote.ts
export class Remote {
 //...
}
export interface IRemoteOptions{
  ///...
}
declare global{
  interface JQuery{
    remote(options? IRemoteOptions);
  }
}


onClick function is not working in reactJS input component

Question: This is my input component and when I am calling this in another component. But onClick function is not working there. Pls provide any solution.
This is input component
import React, { InputHTMLAttributes } from 'react'
import { FormControl } from 'react-bootstrap';
import './input.css';
import clsx from 'clsx';

  interface Input extends InputHTMLAttributes<HTMLInputElement>{
   half: boolean,
   lableText: string,
   typeOfInput: string,
   garyBold?:boolean
   value?:any
   placeholder?:string
}

 const InputField = ({half, lableText, typeOfInput, garyBold,value, placeholder}:
  Input) => {
    return (

        {lableText}
        <FormControl
        defaultValue={value ? value :''}
        required
        type={typeOfInput}
        className={clsx('mb-1 inputItself')}
        aria-label="Recipient's username"
        aria-describedby="basic-addon2"
        placeholder={placeholder}
        />

     )
  }

  export default InputField

And here I am calling my function( Login.tsx)
 <InputField onChange={()=> console.log('ok')} typeOfInput='text' half={false} lableText={"Email Address/ Username"}/>

But there is nothing appearing in console. Pls help if you know the answer. It will be highly appreciated.
Comment: Your component doesn't even have `onChange` prop
Comment: *"But onClick function is not working there."* - What `onClick` function?  There's no `onClick` anywhere in the code shown.  What "isn't working" about it?  Please clarify the problem.
Answer: The reason its not triggering is because you aren't giving it an onChange prop. Custom components don't have the same intrinsic hooks you can use, so you need to pass them yourself.
Take a look at this...

import React, { InputHTMLAttributes } from 'react'
import { FormControl } from 'react-bootstrap';
import './input.css';
import clsx from 'clsx';

  interface Input extends InputHTMLAttributes<HTMLInputElement>{
   half: boolean,
   lableText: string,
   typeOfInput: string,
   garyBold?:boolean
   value?:any
   placeholder?:string,
   onChange: () => void, // I added this
}

 const InputField = ({half, lableText, typeOfInput, garyBold,value, placeholder, onChange}: // And this
  Input) => {
    return (

        {lableText}
        <FormControl
        defaultValue={value ? value :''}
        required
        type={typeOfInput}
        className={clsx('mb-1 inputItself')}
        aria-label="Recipient's username"
        aria-describedby="basic-addon2"
        placeholder={placeholder}
        onChange={onChange} // And this
        />

     )
  }

  export default InputField


Continuous Bijective Map not Bicontinuous

Question: The classic example of a continuous bijective function that does not have a continuous inverse is the function $g:[0,2\pi) \rightarrow S^1$ given by
\begin{equation}
g(t)=(cos(t),sin(t)),
\end{equation}
where $S^1$ is the unit circle. I've always intuitively accepted this, because as we traverse the positive x-axis on the unit circle, the inverse function "jumps" between $0$ and $2\pi$.
But thinking about this in terms of pre-images of open sets confuses me. The characterization I am thinking of is: a function $g$ is continuous if and only if the pre-image of every open set in the codomain is an open set in the domain.
Since we want to show the inverse is not continuous, I want to show that given some open set $U$ in $[0,2\pi)$, its image $g(U)$ is not open. But I can't seem to find some open set $U$ for which this holds. Is there something I'm missing?
Thanks for the help!
Comment: do you have a typo?
"The classic example of a continuous bijective function that does not have a continuous map"
you mean (most likely)
The classic example of a continuous bijective function that does not have a continuous inverse".
Comment: Thanks @Mirko, I've corrected that.
Answer: Take $U=[0,\pi)$ for instance: it is open in $[0,2\pi)$ but its image by the inverse map is not open due to the image of $0$ having only half of a neighbourhood (see below).
What you might find confusing is that $U$ is indeed open in $[0,2\pi)$. But in $[0,2\pi)$, there is nothing to the left of $0$ that would be missing in $U$ preventing it from being open.
Comment: This is great, and I don't find it confusing. The set $U=[0,\pi)$ is open in the domain because it is the intersection of $[0,2\pi)$ and some open interval. Thanks!
Answer: Any open set in $S^1$ that contains $(1,0)$ must contain a set of the form $V=\{ (\cos t, \sin t) | |t| < \delta  \}$ for some $\delta >0$.
Then $g^{-1}(V)$ must contain a set of the form $[0,\epsilon) \cup (2 \pi -\epsilon, 2 \pi)$ for some $\epsilon>0$.
Addendum:
Let $h=g^{-1}$ to simplify notation, and let $p=(1,0) \in S^1$ to avoid confusion with an open interval. Note that $h(p) = 0$. To show that $h$
is continuous at $p$, we need to show that for any open $V \subset [0,2 \pi)$ containing $0$, there is some open $U \subset S^1$ containing $p$ such that
$h(U) \subset V$.
Now pick $V=[0,1)$, which is open in $[0,2\pi)$. Now observe that for any open $U\subset S^1$ that contains $p$, $h(U)$ contains some set of the form $(2 \pi-\epsilon , 2 \pi)$ for some $\epsilon>0$, and hence there is no open $U$
such that $h(U) \subset V$ and so $h$ is not continuous at $p$.
Note that $h$ is continuous everywhere else.
Comment: But isn't the set $[0,\varepsilon) \cup (2\pi-\varepsilon,2\pi)$ an open subset of $[0,2\pi)$? Moreover, if we're working with $g^{-1}(V)$, aren't we going to draw implications about the continuity of $g$ instead of $g^{-1}$?
Comment: @ChrisWong: I added an elaboration (and fixed a small typo. in the first line). Note that continuity is about 'controlling' the behaviour of $h$'s range as such.


Show, that $\tilde{\mathcal{R}}$ is an algebra, $\tilde{\mu}$ is a pre-measure

Question:

Let $\mathcal{R}$ be a ring on the set $\Omega$ and $\mu$ a pre-measure on $\mathcal{R}$. Show that
    $$
\tilde{\mathcal{R}}:=\left\{A\subset\Omega|\forall~R\in\mathcal{R}: R\cap A\in\mathcal{R}\right\}
$$
    is an algebra on $\Omega$ with $\mathcal{R}\subset\tilde{\mathcal{R}}$ and that
    $$
\tilde{\mu}(A):=\sup\left\{\mu(R)|R\subset A, R\in\mathcal{R}\right\}
$$
    defines a premeasure on $\tilde{\mathcal{R}}$ which continues $\mu$.

Hello, everybody! At first, I give you my proof, that $\tilde{\mathcal{R}}$ is an algebra on $\Omega$ with $\mathcal{R}\subset\tilde{\mathcal{R}}$. To show this, I have to show, that it is a ring which contains $\Omega$ (this are (1) - (4)) and of course $\mathcal{R}\subset\tilde{\mathcal{R}}$ (this is (5) below)).
ad (1): $\forall R\in\mathcal{R}$ it is $R\cap\emptyset=\emptyset$ and because $\mathcal{R}$ is a ring, it is $\emptyset\in\mathcal{R}$. So $\emptyset\in\tilde{\mathcal{R}}$.
ad (2): Let $A,B\in\tilde{\mathcal{R}}$, i.e. for all $R\in\mathcal{R}$ it is $R\cap A, R\cap B\in\mathcal{R}$. Then
$$
R\cap (A\cup B)=(R\cap A)\cup (R\cap B)\in\mathcal{R},
$$
because $\mathcal{R}$ is a ring and unions of two elements in $\mathcal{R}$ are in $\mathcal{R}$.
ad (3): Let $A,B\in\tilde{\mathcal{R}}$, i.e. for all $R\in\mathcal{R}$ it is $R\cap A, R\cap B\in\mathcal{R}$. It is $\forall R\in\mathcal{R}$:
$$
R\cap (A\setminus B)=((R\cap A)\cup (R\cap B))\setminus (R\cap B).
$$
Because of ad (2) and because of the fact, that $\mathcal{R}$ is a ring, this is in $\mathcal{R}$.
ad (4): For all $R\in\mathcal{R}$ it is $R\cap\Omega=R$. So $\Omega\in\tilde{\mathcal{R}}$.
ad (5): Let $R\in\mathcal{R}$. For all $R'\in\mathcal{R}$ it is
$$
R'\cap R=(R\cup R')\setminus (R\Delta R').
$$
This was, to my opinion, part 1 of the task.
It remains to show, that $\tilde{\mu}$ is a pre-measure ((6)-(7) below) on $\tilde{\mathcal{R}}$ and that $\tilde{\mu}$, restricted to $\mathcal{R}$, is identical with $\mu$ (point (8) below).
ad (6): $\tilde{\mu}(\emptyset)=\sup\left\{\mu(R)|R\subset\emptyset, R\in\mathcal{R}\right\}=\sup\left\{\mu(\emptyset)\right\}=\sup\left\{0\right\}=0$, because $\emptyset$ is the only subset of $\emptyset$ that is in $\mathcal{R}$.
ad (7): Consider disjoint $(A_n)\in\tilde{\mathcal{R}}^{\mathbb{N}}$ with $A:=\biguplus_{i\geq 1}A_i\in\tilde{\mathcal{R}}$. Let $R\in\mathcal{R}$ with $R\subset A$. Because the $A_i$ are disjoint, $R$ can be written as a disjoint union $R=\biguplus_{i\geq 1}R\cap A_i$. Then, because $\mu$ is $\sigma$-additive, it is
$$
\mu(R)=\mu(\biguplus_{i\geq 1}R\cap A_i)=\sum_{i\geq 1}\mu(R\cap A_i)\leq\sum_{i\geq 1}\sup\left\{\mu(R)|R\subset A_i, R\in\mathcal{R}\right\}\\=\sum_{i\geq 1}\tilde{\mu}(A_i)\\\Rightarrow \underbrace{\sup\left\{\mu(R)|R\subset A, R\in\mathcal{R}\right\}}_{=\tilde{\mu}(A)}\leq\sum_{i\geq 1}\tilde{\mu}(A_i)
$$
In order to show the other direction, consider any $R\in\mathcal{R}$ with $R\subset\biguplus_{n\geq 1}A_n$. Again one can write $R$ as $R=\biguplus_{n\geq 1}(R\cap A_n)$. It is
$$
\sum_{n\geq 1}\mu(R\cap A_n)=\mu(R)\leq\tilde{\mu}(A).
$$
Because $R$ is arbitrary, it is
$$
\sup\limits_{R\in\mathcal{R},R\subset A}\left\{\sum_{n\geq 1}\mu(R\cap A_n)\right\}\leq\tilde{\mu}(A).
$$
Because of
$$
\sum_{n\geq 1}\mu(R\cap A_n)\leq\sum_{n\geq 1}\tilde{\mu}(A_n)
$$
for any $R\in\mathcal{R}$ with $R\subset A$ it is
$$
\sup\limits_{R\in\mathcal{R},R\subset A}\left\{\sum_{n\geq 1}\mu(R\cap A_n)\right\}=\sum_{n\geq 1}\tilde{\mu}(A_n)
$$
which shows that
$$
\sum_{n\geq 1}\tilde{\mu}(A_n)\leq\tilde{\mu}(A).
$$
All in all, it is
$$
\tilde{\mu}(A)=\sum_{n\geq 1}\tilde{\mu}(A_n).
$$
ad (8): Consider any $R\in\mathcal{R}$. Consider
$$
\tilde{\mu}(R)=\sup\left\{\mu(R')|R'\subset R, R'\in\mathcal{R}\right\}.
$$
Because $\mu$ is monotonous, it is $\mu(R')\leq\mu(R)$ for all subsets $R'\in\mathcal{R}$ of $R$. If $R'\neq R$, i.e. $R'\varsubsetneq R$, it is $\mu(R')<\mu(R)$. For $R'=R$, it is $\mu(R')=\mu(R)$, so considering the supremum gives
$$
\tilde{\mu}(R)=\sup\left\{\mu(R')| R'\subset R, R'\in\mathcal{R}\right\}=\mu(R)
$$
I think, that's it!
Would be great if you gave me a feedback!
By the way: Does the finit additvity of $\tilde{\mu}$ follow from the shown $\sigma$-additivity?
Answer: The only step in your proof I do not understand is the claim
$$
\sup\limits_{R\in\mathcal{R},R\subset A}\left\{\sum_{n\geq 1}\mu(R\cap A_n)\right\}=\sum_{n\geq 1}\tilde{\mu}(A_n)
$$
from which your derive that
$$
\sum\limits_{n\geq 1}\tilde{\mu}(A_n)\leq\tilde{\mu}(A)\tag{*}
$$
So I'll give my own proof of $(*)$.
Fix $\varepsilon>0$. From definition of $\tilde{\mu}$ for each $n\in\mathbb{N}$ we have $R_n\in\mathcal{R}$ such $\tilde{\mu}(A_n)\leq\mu(R_n)+\varepsilon 2^{-n}$ and $R_n\subset A_n$. Since $(A_n)$ is a family of disjoint sets so does $(R_n)$. Denote $R=\biguplus_{n\geq 1} R_n$, then clearly $R\subset\biguplus_{n\geq 1}A_n=A$. Now we have
$$
\sum\limits_{n\geq 1}\tilde{\mu}(A_n)
\leq\sum\limits_{n\geq 1}(\mu(R_n)+\varepsilon 2^{-n})
\leq\mu\left(\biguplus\nolimits_{n\geq 1}R_n\right)+\varepsilon
=\mu(R)+\varepsilon
\leq\tilde{\mu}(A)+\varepsilon
$$
Since $\varepsilon>0$ is arbitrtary $(*)$ is proved.
P.S.
To prove finite additivity from $\sigma$-additivity just add to finite system of sets infinite family of empty sets.
Comment: To the point that you did not understand in my proof: I guess the problem is, that the supremum does not have to be $\sum_{n\in\mathbb{N}}\tilde{\mu}(A_n)$ but also can be smaller, right?
Comment: By the way: Can I show $\tilde{\mu}\left(\underbrace{\biguplus_{n\geq 1}A_n}_{=:A}\right)\leq\sum_{n\geq 1}\tilde{\mu}(A_n)$ by the following argument: Consider an arbitrary $\varepsilon > 0$. Then because of the definition of $\tilde{\mu}$ there is a $R\in\mathcal{R}, R\subset A$ with $\tilde{\mu}(A)\leq\mu(R)+\varepsilon$. Because $R=\biguplus_{n\geq 1}(R\cap A_n)$ and $R\cap A_n\subset A_n$ it is $\tilde{\mu}(A)\leq\mu(R)+\varepsilon=\mu\left(\biguplus_{n\geq 1}(R\cap A_n)\right)+\varepsilon\leq\sum_{n\geq 1}\tilde{\mu}(A_n)+\varepsilon$. So, because $\varepsilon >0$ was arbitrary thats it?
Comment: @math12 yes, there were no reason for that identity. As for your proof given in comments. You've proved that $\tilde{\mu}(A)\leq\sum\limits_{n\geq 1}\tilde{\mu}(A_n)$. But you need the inverse inequality.
Comment: I meant the proof in the comment as an alternative to the first proof in ad (7).
Comment: That proof is correct but it is not what is needed. You need to prove $(*)$ not the $\tilde{\mu}(A)\leq\sum\limits_{n\geq 1}\tilde{\mu}(A_n)$
Comment: You missunderstand me. :-) I mean: YOU have shown (*). Thanks for that! And in my first post here, I have shown the other direction, right? And now I wanted to show the direction that I had shown in an alternative way, using a similar argument as you used. So my question is: Is THIS way to show $\tilde{\mu}(A)\leq\sum\tilde{\mu}(A_n)$ right, too?
Comment: Now I understood you :-) That your brand new proof is correct!
Comment: Thanks! I find this new proof better than the old.. shorter and more compact. I would like to give you the 50 points: How can I do so? I thank you very much for your help, I learned a lot.
Comment: @math12 you are wellcome! As for the bounty you can click red button under green checkmark
Comment: One more question, concerning my proof (ad (8)): I tried to show that in an alternative way, too: Chose an arbitrary $\varepsilon >0$. Consider any $R\in\mathcal{R}$. Then because of the definition of $\tilde{\mu}$, there exists a $R'\in\mathcal{R}$ with $R'\subset R$, so that $\tilde{\mu}(R)\leq\mu(R')+\varepsilon$. Because $\varepsilon$ was arbitraty, it is $\tilde{\mu}(R)\leq\mu(R')$. On the other hand it is, because $\mu$ is monotonous, $\mu(R')\leq\mu(R)$ and because $R\subseteq R$ it is $\mu(R)\leq\tilde{\mu}(R)$. So it is $\mu(R')\leq\mu(R)\leq\tilde{\mu}(R)$. RIGHT?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11438/discussion-between-norbert-and-math12)


How to create a webform submission table with values from the form itself?

Question: I find the current webform submission table completely inadequate when forms are submitted by anonymous users - you can't tell one from another other than by its submission date which not helpful in many instances. I would like to create a new webform submission table that can display specific fields from the submission itself to help identify who the submission is from. Ideally if I could accomplish this with views that would be great, but I am not adverse to creating a module if need be. Has anyone done this before and what would be the best approach?
Thanks.
Answer: Unfortunately, the current stable release of the Webform module doesn't support getting to any of the webform submission fields through Views.
However, if you look at this issue on Drupal.org: http://drupal.org/node/680386, you'll see that integration with views is a highly desired feature!  That's why there's so much activity on it!  The good news is that (look at this comment: http://drupal.org/node/680386#comment-6480250) there's actually a patch applied to version 7.x-4.0-alpha6 of the Webform module, so you can test this new integration functionality.
Let us know if it works well!
Comment: That sounds very encouraging and I look forward to Weform 4's release but in the meantime with Webform 3, is it possible to use Webform Tokens to accomplish the same thing?
Answer: Webform 4.X is the way to go if you want to use views.
If you are only trying to change the column headers/info (or don't want to upgrade to 4) you can use the provided hooks:
theme_webform_results_table_header & theme_webform_results_table.
Webform includes 'webform.api.php' in the module that doesn't include working code, but rather documents all of the hook usage in webform.
Comment: I am trying update the contents of the table itself, not the column headers. Is it possible to use webform tokens as a possible work around with Webform 3?


Linkar recursos, como CSS, dentro da estrutura de um site

Question: Sou iniciante e estou enfrentando problemas com linkar os scripts, CSS e imagens. Tenho a seguinte estrutura em pastas do meu site, só um exemplo:
- Pasta Raiz
  --cadastro
    --- cadastro.html
  --images
    --- icon.png
  --script
    --- script.js
  --style
    --- cabecalho.css
  index.html

Supondo que todas as paginas do meu site tenham cabeçalho igual, então eu teria que importar para todas elas o CSS cabeçalho.css. Para a página inicial é fácil.
Mas para chamar esse mesmo css na pagina cadastro.html? No meu ponto de vista, para o cadastro.html o estilo cabecalho.css não existe, queria saber como linkar eles, porque é uma completa desorganização deixar todas as suas páginas na pasta raiz.
Comment: Dica: ver o código fonte de páginas alheias é essencial para aprender programação web (todo browser tem essa funcionalidade).
Answer: Uma maneira seria utilizando a tag base para definir a url padrão

<base href="http://meu-dominio/">
<link rel="stylesheet" type="text/css" href="style/cabecalho.css">

Desta forma o caminho será o mesmo tanto na página index.html quanto na cadastro.html
<link rel="stylesheet" type="text/css" href="http://meu-dominio/style/cabecalho.css">

Answer: <link rel="stylesheet" type="text/css" href="./style/cabecalho.css">
<link rel="stylesheet" type="text/css" href="../style/cabecalho.css">

O primeiro começa o caminho a partir da pasta raiz e o segundo a partir do nível anterior, mas são equivalentes no seu caso.
Comment: O "./" é uma referência à própria pasta do arquivo – é dispensável neste caso.
Answer: Como provavelmente você não trabalha com o metodo MVC você será obrigado a escrever ../style/cabecalho.css, já no index é só usar style/cabecalho.css;
Comment: Primeiro, MVC não é um método, mas sim uma arquitetura. Segundo, MVC não tem absolutamente nada a ver com o problema dele. Ele pode usar outras arquiteturas e ser obrigado a escrever da mesma forma proposta por você.
Comment: É verdade guilherme! Usei método como uma palavra mais generalizada.Mas sim o MVC é uma arquitetura.
Comment: Já li sobre MVC, mas fiquei somente na teoria, sou do 1º ano de Ciência da Computação e estou em um projeto para desenvolver um website, se puderem me ajudar com links sobre mvc aplicado a html5/php ficarei grato, eu entendi a lógica dessa arquitetura, mas não como aplicá-la de forma geral


What is memmove() alternative when I know the overlapping side?

Question: I want know what the fastest function for copy n bytes from *source to *destination, when
*destination = *source + k, and k is netural or zero.
The memcpy() function has undefind behavior for overlapping.
The memmove() function is not the best, since it has to check the overlapping side.
There is another function that is optimal to my case?
Thanks in advance!
Comment: *Why* is `memmove` "not the best"?
Comment: What does "k is neutral" mean?
Comment: You may be interested in the comment thread on this glibc bug report from a couple years ago about the merits of having memory copy functions that depend on the relative position of `dest` and `src` as a pre-condition for proper operation: https://sourceware.org/bugzilla/show_bug.cgi?id=12518  I'd suggest just using `memmove()` - what is a correct positioning of `dest` and `src` today becomes a different positioning in several months when the code is modified by someone unaware of the importance of what is nearly always a minor detail taken care of by the compiler, linker, or OS.
Comment: @user2864740 `memmove` has to correct position of the `source` and `dest` in order to prevent the overlapping problem. That's unnecessary in my case.
Comment: @MichaelBurr That's mean that I want to call the function like that: `memcpy(*source + 2, *source, 3)`
Comment: @MichaelBurr I want my code behavior well defined, and maximum performance. Using `memmove()` doesn't give the maximum performance.
Answer: memmove() is fine. It will figure out the direction of the move on its own by comparing the two pointers — an implementation might look something like:
void * memmove(void *dst, const void *src, size_t len)
{
    intptr_t dsti = dst;
    intptr_t srci = src;
    if (src > dst) {
        return _memmove_up(dst, src, len);
    } else {
        return _memmove_down(dst, src, len);
    }
 }

On most CPUs, this will compile to perhaps a half dozen extra instructions, which are only executed once when the function is called — there is no benefit to bypassing this.
(In theory, there is no reason why memcpy() should not be able to do a similar comparison itself to remove the distinction between it and memmove(). However, for some unfortunate historical reason, the authors of the C standard library did not decide to make this simplification, so we're stuck with these two functions.)
Comment: All it has to do to check is compare the pointers, though — that's a very simple operation for it to perform.
Comment: If you're calling it many times in the same situation, the check will be a correctly-predicted branch and probably consumes zero cycles.
Comment: The comparison will take a matter of a few clock cycles. It's completely insignificant.
Comment: @duskwuff Thanks. In your code, I want the `_memmove_down()` function.
The comparison is unnecessary, and may decrease the performance quality, as explained @R..
@R.. Thanks..
Answer: memmove() has to spend some time determining how and whether the source and target overlap, so it can decide the order in which to copy the data.
Hypothetically, a version of memmove() that omits this initial calculation, either because it assumes a particular direction or because it has an extra parameter that lets you tell it, might be a little faster than memmove().
But there is no such function in the standard library.
You could write your own function, but it's unlikely that it would be as fast as your system's memmove(), which is very likely to be heavily optimized. You could grab a copy of the source code for your system's memmove() function (if it's available) and modify it, but the result would likely be non-portable (memmove() can depend on the characteristics of the system it's running on).
But it's very unlikely that it would be worth the effort. The time memmove() spends doing the initial calculation is, for moves of reasonable size, likely to be a small fraction of the time spent copying the data.
Unless you know from actual measurement that the initial computation performed by memmove() carries a significant performance penalty for your program, just use memmove() itself.
Comment: I know there's no such function.
Comment: Thanks! Do you know that there is no such function in the standard library? (Or you just don't know such as)


Digital Pianos and MIDI usability

Question: I have a question following to the topic already discussed on the "Yamaha P45 Digital Piano - Can it be made MIDI compatible?"
I am soon going to get one of this digital pianos like the Yamaha or maybe a Casio and they all have MIDI at least via a USB port. Now, say I want to connect the piano to the PC to play Vst instruments, does the piano itself goes in mute automatically isolating its own generated sound or I have to turn the volume of the piano off? As I already have been using a MIDI keyboard controller I know the concept in a nutshell but as these pianos dont have a DAW button like on some modern synthesizers, I am just wondering whether PC tells Piano via MIDI to mute the sounds when connected to the Vst or if you have to turn pianos volume down or if maybe I am missing something more basic?
Comment: Since all keyboards have their own dedicated volume control, why not simply turn that down, if it's not done automatically?
Answer: No, making a MIDI connection will not automatically mute the internal sounds, in the way that attaching headphones often mutes internal speakers.
You will have to do the onerous job of turning volume down yourself!
(Maybe you were worried that turning volume down would affect the MIDI output?  It won't.)
Answer: Often, it is possible to disconnect the keyboard from the internal synthesizer.
If a device implements this, this function is called "Local Control Off" or "Local Off" (and then this can also be done with a standardized message sent from the computer).

Digital Pianos and MIDI usability


Numberpad Not Displaying Correctly

Question: I have a Java GUI project where I am creating an ATM. I have everything setup, but for some reason my number pad on the left is not displaying properly. It should appear as a 4x3 grid of numbers, but it is just displaying a 9. I have checked to make sure it is in a GridLayout and I have checked my loop, but I possibly may have looked over something. Any help is appreciated, thanks!
import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;

public class ATMProject extends JPanel implements ActionListener {
    private JPanel mainPanel = null;
    private JPanel btnPanel = null;
    private JPanel userBtns = null;
    private JTextArea textArea = null;
    private JPanel keyPanel = null;
    private JTextField numField = null;
    private JPanel numpadPanel = null;
    private JButton[] userButtons = null;
    private JButton[] keypadButtons = null;
    private String[] btnPanelbtns = { "A", "B", "C" };
    private String[] numpadPanelbtns = { "7", "4", "1", "8", "5", "2", "9", "6", "3", "0", ".", "CE" };

    public ATMProject() {
        super();
        mainPanel = new JPanel();
        this.setLayout(new BorderLayout());
        this.add(mainPanel);

        btnPanel = new JPanel();
        btnPanel.setLayout(new GridLayout(3, 1));
        this.add(btnPanel, BorderLayout.EAST);

        textArea = new JTextArea();
        this.add(textArea, BorderLayout.CENTER);

        keyPanel = new JPanel();
        keyPanel.setLayout(new BorderLayout());
        this.add(keyPanel, BorderLayout.WEST);

        numpadPanel = new JPanel();
        numpadPanel.setLayout(new GridLayout(0, 3));
        keyPanel.add(numpadPanel, BorderLayout.CENTER);

        numField = new JTextField();
        keyPanel.add(numField, BorderLayout.NORTH);

        userButtons = new JButton[btnPanelbtns.length];
        for (int i = 0; i < userButtons.length; i++) {
            userButtons[i] = new JButton(btnPanelbtns[i]);
            userButtons[i].addActionListener(this);
            btnPanel.add(userButtons[i]);
        }

        keypadButtons = new JButton[numpadPanelbtns.length];
        for (int i = 0; i < userButtons.length; i++) {
            keypadButtons[i] = new JButton(numpadPanelbtns[i]);
            keypadButtons[i].addActionListener(this);
            numpadPanel.add(keypadButtons[i]);
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }

    public static void main(String[] args) {
        MyFrame mf = new MyFrame();
    }

}

import javax.swing.JFrame;

public class MyFrame extends JFrame {
    private ATMProject atm = null;
    public MyFrame(){
        super();
        atm = new ATMProject();
        this.add(atm);
        this.setTitle("ATM");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setSize(800,300);
        this.setVisible(true);
    }
}

This is how it is supposed to appear:
Comment: Presumably the buttons should be added to `numpadPanel` whereas they are being added to `keyPanel` which has a (default) `FlowLayout` ..
Comment: That's a little better, now I get 7 8 9 vertically. Could it possibly be in this line? `keyPanel.add(numpadPanel, BorderLayout.CENTER);`
Comment: I'm stuck on the numpad part
Answer: You're adding you buttons to keyPanel...
keyPanel.add(keypadButtons[i]);

which is using a BorderLayout...
keyPanel = new JPanel();
keyPanel.setLayout(new BorderLayout());

so only the last component added to it will be laid out by the panel.
One imagines you should be adding them to numpadPanel instead...
numpadPanel.add(keypadButtons[i]);

Yeah, I have that numpadPanel.add(keypadButtons[i]); and I am getting just 7 8 9 vertically.

That's kind of how GridLayout works, you could force into a horizontal priority mode by using something more like
numpadPanel.setLayout(new GridLayout(0, 3));

Comment: BTW OP - try adding a `TitledBorder` to each panel showing the layout, as seen in [this answer](http://stackoverflow.com/a/5630271/418556). That, or setting different colors to the background of each panel, is a great way to debug a GUI that is laid out using multiple different layout managers.
Comment: Got it, posted the solution below, thanks for the input about the priority mode and TitleBorder and such!!
Comment: `keyPanel.setLayout(new BorderLayout());` Oops! missed that bit.. :-P
Comment: Welcome to the forest, watch out for the trees ;)
Comment: Yeah, I have that `numpadPanel.add(keypadButtons[i]);` and I am getting just 7 8 9 vertically.
Comment: It's kind of the way `GridLayout` works, try making your `numpadPanelbtns` in the order of `7, 4, 1, 8, 5, 2, 9, 6, 3` instead and see what happens
Comment: @Blastoize34 or you could just use `new GridLayout(0, 3)` and force into horizontal priority mode instead
Comment: I used `new GridLayout(0,3)` and I get 7 4 1 horizontally, I just updated my code above.
Comment: @Blastoize34 As I said you could change your `numpadPanelbtns` order **OR** you could use `GridLayout(0,3)`, I suggest you put your `numpadPanelbtns` back to it's original order
Comment: Okay, both ways and nothing changes. Ill look more into it later
Answer: My loop was incorrectly written. for (int i = 0; i < userButtons.length; i++) my program was only outputting 3 buttons because userButtons.length only had 3 elements. I changed userButtons.length to numpadPanelbtns.length and it fixed it because there are 12 elements in the numpadPanelbtns array.

Numberpad Not Displaying Correctly


Grouping items arbitrarily in Views

Question: I have a taxonomy vocabulary with 4 terms. One of the content types has a term reference field to tag a node with a single term from that vocabulary. Now, I want to have Views (3.5) generate a navigation block for me which would list the terms in the following way: skip item 4 and merge item 2 & 3 into a custom item labeled, say "Item 2 & 3", as in:
Item 1
Item 2 & 3  [linked accordingly: taxonomy/term/2+3]

Of course, with eventually 2 items in a block, I could do that statically, I know. However the vocabulary may grow and would like to have a scalable, dynamic solution. Hence my question: is that possible?
Comment: You might be able to do it using Panels and a Context View. So your nav block would be a panels region, and each chunk of results would be View Context > View rows panels content item with a rule to define the number of rows and offsets. I did a [write-up explaining Context Views for this unrelated question](http://drupal.stackexchange.com/questions/41247#41422), the instructions and 3rd bullet are the relevant parts. I'm not sure I understand what you're trying to do well enough to judge if it would be dynamic enough for you: you might need custom code using Views hooks.
Answer: I think the easier and simpler solution would be to create a custom block from your custom module using hook_block_info and hook_block_view.
By using these hooks, your block will be listed in the block administration page - admin/structure/block.
<?php
    /*
     * Implementation of hook_block_info()
    */
    function mymodule_block_info() {
        $blocks['yourblock'] = array(
        'info' => t('Your Module Name'),
        'cache' => DRUPAL_NO_CACHE
        );
        return $blocks;
    }
    /*
     * Implementation of hook_block_view()
    */
    function mymodule_block_view($delta = '') {
        $block = array(); # Declare array

        switch ($delta) {
            case 'yourblock' :
                // Block View
                $block['subject'] = 'Your Block Title';
                $block['content'] = _mymodule_taxonomy_content();
            }
        }
        return $block;
    }
    /*
     * Create block content as you need
    */
    function _mymodule_taxonomy_content( ) {
        $result = $query = db_select('taxonomy_term_data', 't')
                            ->join('taxonomy_vocabulary', 'v', 't.vid = v.vid')
                            ->condition('v.machine_name', 'your_tag_machine_name')
                            ->orderBy('t.tid')
                            ->execute();
        $content = '';
        foreach ($result as $term) {
            // you now have $term['vid'], $term['name'], etc. here
            // loop and build conditions here to suit your need
            // Item 1
            // Item 2 & 3  [linked accordingly: taxonomy/term/2+3]
            // For example,
            // $content .= l($term['name'], 'taxonomy/term/'.$term['vid']);
            // This is up to you.
        }

        return $content;
    }

Grouping items arbitrarily in Views


How add related nodes to content profile?

Question: In Drupal 6, I am trying to list the links to nodes created by that user and/or nodes which have her name in their tags below the profile. But I could not figure out how to do either. I appreciate your help.
Comment: I will recommend to use this service from Addthis - https://www.addthis.com/get/recommended
Answer: You can load nodes by various parameters. Just give the parameters which you want to load.
See here Here is for Drupal 6 also.
If you had a code in D6 to load a node using an array of conditions to match against in the database query like this:
<code><?php
$param = array(
    'type' => 'your_node_type',
    'title' => 'your node title',
    'status' => 1,
);
$node = node_load($param);
?>
</code>
Answer: To list content owned by a user you should ...

create a View that lists content
create a Relationship in that view to the User that owns that content
create a Block Display within that view
configure an "Argument" for that view which "Provides Default" and grabs the UID of the User from the URL
place that block using some mechanism for Block placement on each User Page.

hope that general recipe helps.
Comment: You don't need the relationship. Just add an argument for the author uid.


Solicitar preenchimento de campo na url

Question: Boa tarde...
Preciso de uma ajuda de vocês. Eu tenho uma página em html+php que basicamente é um campo que consulta um banco mysql com ajax e retorna o resultado assim que é preenchido o campo com a quantidade correta de números (10 algarismos).
Eu queria fazer uma solicitação através da URL para já carregar a página com este campo preenchido. Por ex... Quando eu digito google.com.br/?q=pergunta o Google abre com o campo escrito "pergunta"
Como eu faço isso? Eu tenho que marcar meu campo e definir esse "q"?
Answer: Creio que seja isso que procuras:
<input type="text" value="<?php echo $_GET['q'] ?>" />

Supondo que a URL seja: seusite.com/?q=string
O resultado com $_GET no exemplo acima seria:
<input type="text" value="string" />

Se o input for type="number", só irá receber números pelo $_GET (ex., q=123456).
  Se for type="text", irá receber qualquer string (tanto de números
  como de letras).

ATUALIZAÇÃO
Insira o script abaixo no seu código-fonte. Ele irá chamar a função caso o $_GET retorne algum valor:
<?php if(isset($_GET['q'])){ ?>

<?php } ?>

Solicitar preenchimento de campo na url


Pullback of a Divisor

Question: Let $f:X \rightarrow Y$ be a finite, separable morphism of curves (curve: integral scheme, of dimension 1, proper over an algebraically closed field with all local rings regular). Let $R$ be the ramification divisor on $X$.
Question 1: What is exactly $f_*(R)$? If $R = \sum_{P \in X} r_P \cdot P$ ($r_P$ is the ramification index), then i suppose that $f_*(R) = \sum_{P \in X} r_P \cdot f(P)$. Is that correct?
Now let $B$ be a boundary of $Supp(f_*(R))$, i.e. a divisor on $K_Y$ with nonzero coefficients equal to $1$ on a superset of the support of $f_*(R)$. We know that there is a homomorphism $f^* : Div(Y) \rightarrow Div(X)$ (see Hartshorne bottom of page 137) and so we can talk about $f^* B$.
Question 2: What is $f^{-1} B$?
Motivation: i saw this notation in an exercise where i am asked to prove a Hurwitz-like formula of the form $f^*(K_Y+B)=K_X+f^{-1}B$, where $K_X,K_Y$ are the canonical divisors.
Comment: If $B$ lives on $X$, then $K_Y+B$ doesn't make sense.
Comment: @QiL: You are right, i will edit.
Answer: (1) Yes, this is a standard definition. You should have read it before.
(2) This is not a canonical notation. Can you check your exercise ?
Comment: My exercise is as i have written it.
Comment: Then it means $f^*B-R$ if the desired equality holds. Strange notation anyway.
Comment: Maybe if $B=\sum_{Q \in Y} \lambda_Q \cdot Q$ then $f^{-1}B=\sum_{Q \in Y} \sum_{P:f(P)=Q} \lambda_Q \cdot P$?
Comment: This coincides with $f^*B$ if the support of $B$ is disjoint from the support of $R$. But this is not your case. What is good to know is $f^*K_Y=K_X+R$ (classical Riemann-Hurwitz) and $f^*(K_Y+B)=f^*K_Y+f^*B$. So what must be $f^{-1}B$ ?
Comment: Yea, i see this, thanks.
Comment: @Manos: sometimes, when $B$ is viewed as a closed subscheme, $f^{-1}B$ can be $B\times_Y X$. Then as Cartier divisor, it is same as $f^*B$. But definitely different from $f^*B-R$.

Pullback of a Divisor


how to create wordpress fixed nav bar with popup menu?

Question: Hi Friends,
how to create wordpress fixed nav bar with popup       menu Eg..(https://surgeryxchange.com)
Comment: Could you explain some more please? Where not there to code and style the menu you want :)
Comment: static fixed nav bar, dynamic menu should be popup .(https://surgeryxchange.com)
Answer: i used same css and javascript files.
I have created custom header and it working properly


Add compiler to java pages

Question: i would like to add a compiler to my jsp pages where the user can enter his code and compile it. Any idea whats the method to add a compiler to jsp pages?
Comment: People are not here to do your job.
Answer: Heh.  I tried to put in where I got this approach from, but the spam filter prevented it.  I can't vouch for whether the urls below are open for anyone to use, but this is one way to do it:
<code>function submitForm(){

  jQuery.support.cors = true;
  $('#wait').show();
  if ($.browser.webkit || $.browser.mozilla) {
     var url = "http://www.compileonline.com/compile_new.php";
  }else{
     var url = "col_proxy.php";
  }

  $.ajax({
    type: "POST",
    cache: false,
    crossDomain: true,
    url: url,
    target: "view",
    data: $("#ff").serialize(),
    success:function(data)
    {
        $('#view').contents().find("html").html(data);
        $('#wait').hide();
        return false;
    },
    error:function (data, status, error) {
       alert(error);
       return false;
    }
  });
  return false; // avoid to execute the actual submit of the form.
}
</code>

Add compiler to java pages


Como eu faço o programa identificar se denominador da divisão é zero usando switch-case e exibir uma mensagem de invalidez na operação?

Question: Tenho este exercício pra fazer e tudo está correndo bem, porém eu não sei como fazer o programa analisar se o denominador é zero e exibir a mensagem, podem me ajudar?

Meu código:
#include <stdio.h>
int main(){
int a, b;
char o;

printf("Digite dois valores inteiros:\n");
scanf("%d%d", &a, &b);

printf("\nDigite um caracter de soma, subtracao, divisao ou multiplicacao:\n");
scanf(" %c", &o);

switch (o){
    case '+': printf("\nO resultado da soma eh: %d\n", a + b);
              break;
    case '-': printf("\nO resultado da subtracao eh: %d\n", a - b);
              break;
    case '*': printf("\nO resultado da multiplicacao eh: %d\n", a * b);
              break;
    case '/': printf("\nO resultado da divisao eh: %d\n", a / b);
              break;

}
return 0;
}

Comment: Já pensou em utilizar um `if`? Algo como `if (b ==0) { printf("Denominador zero é proibido.\n"); }`...
Answer:
Eu posso utilizar if dentro de switch-case?

Pode. O case de um switch statement em C não é exclusivo para expressões. Você pode colocar statements (declarações) dentro deles também. Isso inclui, por exemplo, um if. O próprio break é um statement.
Portanto, bastaria verificar se o denominador é zero utilizando o if dentro do caso da divisão. Assim:
#include <stdio.h>

int main(){
    int a, b;
    char o;

    printf("Digite dois valores inteiros:\n");
    scanf("%d%d", &a, &b);

    printf("\nDigite um caracter de soma, subtracao, divisao ou multiplicacao:\n");
    scanf(" %c", &o);

    switch (o){
        case '+':
            printf("\nO resultado da soma eh: %d\n", a + b);
            break;

        case '-':
            printf("\nO resultado da subtracao eh: %d\n", a - b);
            break;

      case '*':
          printf("\nO resultado da multiplicacao eh: %d\n", a * b);
          break;

      case '/':
        if (b == 0) {
            printf("\nDenominador zero é inválido.\n");
            return 1; // Retornar 1 (código de saída padrão para erros.)
        }

        printf("\nO resultado da divisao eh: %d\n", a / b);
        break;
    }

    return 0;
}

Veja funcionando no Repl.it.
Note, no código acima, que não utilizei um else após o if. Fiz isso porque o return elimina a necessidade do else, já que encerra a função, retornando desta o valor passado. Saiba mais sobre esse padrão aqui.
Comment: Muito obrigado! s2


Can I be redirected to another route after a while in a Next.js server component?

Question: Can I do something like the following in an async server component: after ui is rendered, wait 3 seconds and redirect to another route?
By analogy, how it done in a client component:
useEffect(() => {
  function delay(ms: number): Promise<void> {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }
  delay(3000);
  router.push('/');
}, []);

But can I get the same result in the app route's server component?
Comment: You would basically keep the connection to the client open (will look like a blank page with spinner at the top) and then close it by redirecting the client.
Answer:     import { useRouter } from 'next/router';

    // Your server component
    const MyServerComponent = async () => {
      const router = useRouter();

    // Render the UI

    // Wait 3 seconds.
      await new Promise((resolve) => setTimeout(resolve, 3000));

      // Redirect to another route.
      router.push('/');
return <></>;
    }
    export default MyServerComponent;

first render the UI of the server component. Then, wait 3 seconds using the Promise.resolve() function. it will redirect to the / route using the router.push() function.
Comment: `useRouter()` hook imported from `next/router` is for **pages** router - OP mentioned **app** router - and `useRouter()` hook imported from `next/navigation` is for client component.


@email@example.com ERROR

Question: I am facing an error while installing node_modules using this command
npm install
I am having npm=9.6.7 and node=18.17.1
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @firstname.lastname@example.com
npm ERR! Found: firstname.lastname@example.com
npm ERR! node_modules/react
npm ERR!   react@"^16.13.1" from the root project
npm ERR!   peer react@">=16.3.0" from @email@example.com
npm ERR!   node_modules/@emotion/core
npm ERR!     @emotion/core@"^10.0.9" from email@example.com
npm ERR!     node_modules/react-select
npm ERR!       react-select@"^3.1.0" from email@example.com
npm ERR!       node_modules/react-timezone-select
npm ERR!         react-timezone-select@"^0.9.9" from the root project
npm ERR!     @emotion/core@"^10.0.35" from firstname.lastname@example.com
npm ERR!     node_modules/react-spinners
npm ERR!       react-spinners@"^0.10.4" from the root project
npm ERR!   30 more (@material-ui/core, @material-ui/icons, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^17.0.0" from @email@example.com
npm ERR! node_modules/@material-ui/data-grid
npm ERR!   @material-ui/data-grid@"^4.0.0-alpha.37" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: email@example.com
npm ERR! node_modules/react
npm ERR!   peer react@"^17.0.0" from @email@example.com
npm ERR!   node_modules/@material-ui/data-grid
npm ERR!     @material-ui/data-grid@"^4.0.0-alpha.37" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /Users/abhinav/.npm/_logs/2023-08-19T12_06_08_721Z-eresolve-report.txt

I am not able to install node_modules and core files of react to run my project can anyone help in resolving this error
Thank you
Answer: The error message indicates a dependency conflict. The @material-ui/data-grid package requires a peer dependency of react@^17.0.0.
You can find it here.
https://www.npmjs.com/package/@material-ui/data-grid/v/4.0.0-alpha.35

@material-ui/data-grid@4.0.0-alpha.37 ERROR


A polynomial equality problem

Question: $a_1,a_2,a_3,\ldots,a_n,a_{n+1}$ are fixed real numbers in $(-1,\infty)$.
$x_1$ and $x_2$ are fixed real numbers in $(0,1)$.
Is it possible to prove that there exists or doesn't exists a real number $x_3$ in $(0,1)$ such that
$$\prod_{i=1}^n (1 + x_3a_i) = \frac{1}{2}\prod_{i=1}^n (1 + x_1a_i) + \frac{1}{2}\prod_{i=1}^n (1 + x_2a_i)$$
and
$$\prod_{i=1}^{n+1} (1 + x_3a_i) = \frac{1}{2}\prod_{i=1}^{n+1} (1 + x_1a_i) + \frac{1}{2}\prod_{i=1}^{n+1} (1 + x_2a_i)$$
or is it possible to prove that this problem is unsolvable to begin with?
Comment: For $n=1$ the two equations imply that $x_1=x_2.$ So in general it isn't solvable... I've been looking at larger $n$ and so far it looks complicated, but unlikely that there be such $x_3$ for an arbitrary set of $a_k$ and choice of $x_1,x_2.$
Answer: If there is a simultaneous solution, then either $a_{n+1}=0$ or it must be
$$
x_3=\frac{x_1\prod_{i=1}^n (1 + x_1a_i) + x_2\prod_{i=1}^n (1 + x_2a_i)}{\prod_{i=1}^n (1 + x_1a_i) + \prod_{i=1}^n (1 + x_2a_i)}.
$$
That this is actually also a solution of the first $n$-th degree polynomial is highly unlikely.
Comment: i'll accept this if there is no formal proof after one or two months, but you're right, it's really unlikely!

A polynomial equality problem


Can we show that $1_A\text E[X\mid\mathcal F]=1_AY\Leftrightarrow\forall F\in\mathcal F:\text E[1_A1_FX]=\text E[1_A1_FY]?$

Question: Let

$(\Omega,\mathcal A,\operatorname P)$ be a probability space
$\mathcal F\subseteq\mathcal A$ be a $\sigma$-algebra on $\Omega$
$X\in\mathcal L^1(\operatorname P)$
$A\in\mathcal A$
$Y:\Omega\to\mathbb R$ be $\mathcal A$-measurable with $\operatorname E\left[1_A|Y|\right]<\infty$

Are we able to show that $$1_A\operatorname E\left[X\mid\mathcal F\right]=1_AY\text{ almost surely}\Leftrightarrow\forall F\in\mathcal F:\operatorname E\left[1_A1_FX\right]=\operatorname E\left[1_A1_FY\right]\tag1?$$

I'm especially unsure whether we need to impose any stronger measurability assumption on $Y$ and how $(1)$ is related to $$\operatorname E\left[\left.X\right|_A\mid\left.\mathcal F\right|_A\right]=\left.Y\right|_A\;\left.\operatorname P\right|_A\text{-almost surely}\Leftrightarrow\left.Y\right|_A=\left.\operatorname E\left[X\mid\mathcal F\right]\right|_A\;\left.\operatorname P\right|_A\text{-almost surely}\tag2.$$
In order to prove "$\Rightarrow$" in $(1)$ we obviously need to use that, by definition, $\forall F\in\mathcal F:\operatorname E\left[1_FX\right]=\operatorname E\left[1_A\operatorname E\left[X\mid\mathcal F\right]\right]$ (it would be clear, if $A\in\mathcal F$; do we need this?). And for "$\Leftarrow$" we somehow to argue with measure uniqueness. But I struggle to fill out the details in both directions.
Answer: In general, (1) fails: let $\mathcal F$ be the $\sigma$-algebra containing $\emptyset$ and $\Omega$. Then (1) reads
$$
1_A\operatorname E\left[X \right]=1_AY\text{ almost surely}\Leftrightarrow \operatorname E\left[1_A X\right]=\operatorname E\left[1_A Y\right],
$$
which is not true if $A=\Omega$, $X$ and $Y$ have the same expectation but $Y$ is not almost surely constant.
Comment: Thank you for your answer. Then I have no idea how we can solve this question: https://math.stackexchange.com/q/3304535/47771. Could you take a look?


error while Connecting  .mdf database

Question: I developed a small project in visual studio 2010. In my project I attach a service-based database named database1.mdf.
My connectionString is :
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True

It works fine on my developer pc but it throws an exception on a client's pc.
Exception is :

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

I don't understand what is happening.
Answer: this connection string is for your developer machine. you share your database on the network. you also must update your connection string by adding ip address of your server.
Comment: I am also copy my application.exe and database1.mdf file in the same folder.
Comment: Is sqlserver run on client pc? if so, you try to update your DataDirectory property for your client pc like AppDomain.CurrentDomain.setData("DataDirectory","C:\myDB");
Answer: Two things need to occur before you can connect to a SQL Server Express database.

SQL Server Express must be installed on the target server. Having the file present isn't sufficient. (This is what the error you're experiencing likely means).
The path to your database file should be an absolute path to rule out the possibility of a file location error.

error while Connecting  .mdf database


Uboot driver probe

Question: I am working on a project which was already built by 3 people. THey have made the Freertos port on P4080 using uboot.
Now the question is, I have very less knowledge of uboot. So, how can I find/porbe which uart driver is Uboot using to connect with minicom?
I searched in the uboot directory, there were several drivers. I am sure, in some script/folder it must be defined about which driver to use for uart on P4080 ? How and where can I find it ?
Thanks you.
Sumanth
Answer: You should consider to look the file u-boot_directory/include/configs/*yourboard*.h
You normally will find some #define used for serial configuration.
Comment: thank you Cyril :) Will check on it, after returning from Christmas, merry christmas to you too :)

Uboot driver probe