verificar tipo de usuario para acesso php

Question: Estou tentando criar um painel de administrador. Ba tabela do banco já criei o campo tipo, onde se for 1 é usuário normal e 2 administrador. Qual o melhor método para buscar o tipo de usuário no banco?
Segue o codigo que ja fiz porem qualquer tipo de usuario tem acesso ao painel de adm.

                <form action="painel.php" method="POST" >

                        E:mail
                        <input type="text" class="form-control" name="email" placeholder="email">

                        Senha:
                        <input type="password" class="form-control" name="senha" placeholder="**********">

                        <button type="submit" class="btn btn-lg btn-default">Entrar</button>

                        <input type= "hidden" name="entrar" value="login">

                </form>

<?php

    if (isset($_POST['entrar']) && $_POST['entrar'] == "login"){
        $email = $_POST['email'];
        $senha = $_POST['senha'];

            if(empty($email) || empty($senha)){
                ?>

                <?php
            }else{
                    $query = "SELECT nome, email, senha, tipo FROM usuarios WHERE email = '$email' AND senha = '$senha' ";
                    $result = mysqli_query($conn, $query);
                    $busca = mysqli_num_rows($result);
                    $linha = mysqli_fetch_assoc($result);

                while($percorrer = mysql_fetch_array($result) ){
                        $tipo = $percorrer['tipo'];

                        if($tipo == 2){

                    $_SESSION['nome'] = $linha['nome'];
                    $_SESSION['email'] = $linha['email'];
                    header('location: painel.php');
                    }

                }
            }

            }

?>

EDIT:
no caso o usuario tipo 2 (administrador) esta sendo redirecionado para o login também, estou passando certo o TIPO?
$query = "SELECT nome, email, senha, tipo FROM usuarios WHERE email = '$email' AND senha = '$senha' ";
                $result = mysqli_query($conn, $query);
                $busca = mysqli_num_rows($result);
                $linha = mysqli_fetch_assoc($result);

            if($busca > 0){
                $_SESSION['nome'] = $linha['nome'];
                $_SESSION['email'] = $linha['email'];
                header('location: painel.php');

Answer: Crie uma $_SESSION['tipo'] = $linha['tipo']; também no login e nas páginas do painel, no , por exemplo, vc verifica o tipo:
<?php
    if($_SESSION['tipo'] != 2){
       // redireciona pra fora do painel, pois não é tipo 2
    }
?>

Atualização:
Crie uma include (ex. ver_tipo.php) e insira antes do  de cada página do painel:
<?php
include_once "ver_tipo.php";
?>

...

E no arquivo ver_tipo.php o script PHP citado no início desta resposta.
Comment: no caso esse codigo fica no login para a area administrativa, eu crio essa session['tipo'] ! = 2 no inicio do painel.php?
Comment: Isso. Coloque antes até do ``, EM CADA UMA das páginas que vc quer restringir acesso. Sugiro criar uma `include` com o código e colocar antes do ``. Com `include`, caso posteriormente vc precisar alterar o código, não terá que modificar página por página do painel.
Answer: Eu faria desse modo, pois ai ele já estaria verificando se o usuário existe/é ou não administrador. Pois se não existir data em mysql_fetch_array($result) automaticamente ele vai reportar que o usuario não existe, se existir e o tipo == 2 for falso ele reporta que o usuario não existe ou não é administrador. Tem outros modos de fazer claro, mas com o seu código eu consegui pensar nisso apenas.

                 alert ('preencha todos os campos');

                         alert ('Usuário não existe/não é administrador');


Reciprocal of 9's

Question: I happened upon an interesting pattern today. If I take the reciprocal of $998$, I get $.001002004008016032064128\dots$ which has a pattern of powers of $2$. If I take the reciprocal of $997$, I get a pattern with powers of $3$, $.001003009027081\dots$ This pattern continued with $996$ having powers of $4$ and so on. I can also control how many zeros are found between the powers by adding additional nines.
My question is this: Does this pattern have a name and what is a practical application of this pattern?
Comment: You'll come across many patterns in mathetmatics that don't usually have a name because they aren't "important". I believe this is one of them
Comment: For more fun try $\frac{1}{9899},\frac{1}{998999},\dots$
Comment: You seem to have been mislead by "the pattern": the number $\frac1{998}$ is obviously (semi)periodic, and so are the others.
Comment: If you want to play with it you can note that the reciprocal of $998$ can be written $1/(1000-2)$ ...
Answer: $$\begin{align}
\frac1{998}&=\frac1{1000-2}\\
&=\frac1{1000}\frac1{1-2/1000}\\
&=\frac1{1000}\left(1+\frac{2}{1000}+\frac{2^2}{1000^2}+\frac{2^3}{1000^3}+\cdots\right)\\
&=\frac1{1000}+\frac{2}{1000^2}+\frac{2^2}{1000^3}+\frac{2^3}{1000^4}+\cdots
\end{align}
$$
It's the jolly old geometric series again!
Answer: Here is a proof of this fact, using the fact that an infinite geometric series, when convergent, has a limit that can be computed (see Remark below); for example:
$$\dfrac{1}{998}=\dfrac{1}{1000-2}=\dfrac{1}{1000}\left(\dfrac{1}{1-\tfrac{2}{1000}}\right)=$$
$$\tag{1}=\tfrac{1}{1000}\left(1+\tfrac{2}{1000}+(\tfrac{2}{1000})^2+(\tfrac{2}{1000})^3+\cdots\right)$$
$$=\tfrac{1}{1000}\left(1+\tfrac{2}{1000}+\tfrac{4}{1000000}+\tfrac{8}{1000000000}+\tfrac{16}{1000000000000}+\cdots\right)$$
$$=\tfrac{1}{1000}\left(1.0020040080160\cdots\right)$$
$$=0.0010020040080160\cdots$$
Remark: in (1) we have applied formula $1+a+a^2+a^3+\cdots = \dfrac{1}{1-a}.$

Reciprocal of 9's


Solving a first order coupled system ODE with 2 second order ODE

Question: I was trying to solve a second order PDE and inside of the Lagrange-Charpit system, a first order coupled system popped out.
You can find the problem here: http://www.math.ucla.edu/~yanovsky/handbooks/PDEs.pdf on page 86, 87 if you want to get an idea of the whole problem. Here is the part I am interested in:
$$
\left\{
\begin{array}{c}
x'=p_1 \\
p_1'=-x
\end{array}
\right.
$$
This is the coupled system, and they say it resolves to these two second-order equations:
$$x''
+
x
=0
,x
(
s,
0) =
s,
x
'
(
s,
0) =
p
(
s,
0)  =  1
,
\\p
''
+
p
=0
,p
(
s,
0) = 1
,p
'
(
s,
0) =
−
x
(
s,
0) =
−
s
$$
And also they state the solutions to be:
$$x
(
s, t
)=
s
·
cos
t
+sin
t,\\
p
(
s, t
)=cos
t
−
s
·
sin
t.$$
The method I know for solving such system in based on eigenvalues & eigenvectors to build a decoupling matrix. In the book, they use another method, as it is stated - they break the system into 2 second order equations and then solve them.
Can someone explain in more detail, how the method is applied?
EDIT:
I Tried to solve the equation with the eigenvalue & eigenvector approach, but I got to the result:
$$
\left\{
\begin{array}{c}
x(s,t)=C_1cos(t) + iC_2sin(t) \\
p_1(s,t)=iC_2cos(t) - C_1sin(t)
\end{array}
\right.
$$
Which can give me the result, which is stated there exactly if the integration constants had the values:
$$
\left\{
\begin{array}{c}
C_1= s \\
C_2= -i
\end{array}
\right.
$$
Is there anything that suggests these values?
Comment: Why don't you edit your post to include the problem so people can see it without going to another website.
Comment: @Mattos Please accept my apologies, I edited the question.
Comment: All good mate, no need to apologise. The author got those ODEs by differentiating $x$ and $p_{1}$ respectively i.e

$$x' = p_{1} \implies x'' = p_{1}' = -x \implies x'' + x = 0$$

Similarly for the ODE in $p_{1}$. Now, you already got the same general solution as the authors did. Just remember that $i$ is a constant of sorts so $iC_{2}$ is just another constant, call it $C_{3}$. So you just need to apply your conditions. You have $x(s,t) = C_{1} \cos(t) + C_{3} \sin(t) \implies x(s,0) = C_{1} = s$ and $x'(s,0) = C_{3} = 1$.
Comment: @Mattos Very clever.. Please arrange this into an answer, so I can accept it. Thank you!
Answer: You have a coupled system of first order ODEs
\begin{align}
x' &= p \quad (1) \\
p' &= -x \quad (2)
\end{align}
This can be turned into two second order ODEs by differentiating both $x'$ and $p'$ again i.e
\begin{align}
x'' &= p' \quad \text{from (1)} \\
&= -x \quad \text{from (2)} \\\\
p'' &= -x' \quad \text{from (2)} \\
&= -p \quad \text{from (1)}
\end{align}
The boundary conditions can also be derived using your ODE system and the initial conditions for the PDE problem
\begin{align}
x(s,0) &= s, \quad x'(s,0) = 1 \\
p(s,0) &= 1, \quad p'(s,0) = -s
\end{align}
They are the same ODE, so we will just solve the one in $x$ here. There are two ways to solve this apart from using the matrix formulation. First, the ODE is linear so making an ansatz $x = e^{\lambda t}$ gives us $\lambda^{2} = -1 \implies \lambda = \pm i$, hence
\begin{align}
x &= Ae^{it} + Be^{-it} \\
&= A(\cos(t) + i\sin(t)) + B(\cos(t) - i \sin(t)) \\
&= C_{1} \cos(t) + C_{2} \sin(t)
\end{align}
where $C_{1} = A + B, C_{2} = i(A - B)$. The second way is to multiply the ODE by $x'$ and integrate i.e
\begin{align}
x' x'' &= -x x' \\
\implies \frac{1}{2} x'^{2} &= - \frac{1}{2} x^{2} + k_{1} \\
\implies x' &= \pm \sqrt{k_{1} - x^{2}} \\
\implies \int \frac{dx}{\sqrt{k_{1} - x^{2}}} &= \pm \int dt \\
\implies \arcsin \left( \frac{x}{k_{1}} \right) &= \pm t + k_{2} \\
\implies x &= k_{1} \sin(k_{2} \pm t) \\
&= c_{1} \cos(t) + c_{2} \sin(t)
\end{align}
where $c_{1} = k_{1} \sin(\pm k_{2}), c_{2} = k_{1} \cos(\pm k_{2})$. Now, applying your conditions we find
\begin{align}
x(0) &= s \\
&= C_{1} \cos(0) + C_{2} \sin(0) \\
&= C_{1} \\
x'(0) &= 1 \\
&= -s \sin(0) + C_{2} \cos(0) \\
&= C_{2}
\end{align}
Hence the particular solution is given by $x(s,t) = s \cos(t) + \sin(t)$. The same approach is used to solve the ODE in $p$.
Answer: As to the added question:
You can determine the constants in the eigenvalue solution simply by evaluating the solution formula at $t=0$
$$
s=x(s,0)=C_1\cos(0)+iC_2\sin(0)=C_1\\
1=p(s,0)=iC_2\cos(0)-C_1\sin(0)=iC_2
$$
giving exactly the same result as the cited solution.


What is the spectrum of $\begin{pmatrix}0 & A \\ A^\dagger & 0\end{pmatrix}$

Question: As the title says, I am interested in the spectrum $\{\Lambda_j\}$ of the block matrix $\begin{pmatrix}0 & A \\ A^\dagger & 0\end{pmatrix}$. Assuming I know the spectrum $\{\lambda_j\}$ of $A$, is there a simple expression for the spectrum of this?
I am interested in the case when $[A,A^\dagger] \neq 0$ but if there is a simple result when $[A,A^\dagger]=0$ that is also of interest.
Attempts: I have played around with the simple $4x4$ case in Mathematica, leading me to believe in general there is no simple expression for the spectrum $\{\Lambda_j\}$ in terms of $\{\lambda_j\}$, but I'm hoping I'm wrong.
Edit: $A^\dagger = A^*$ is the conjugate transpose.
Comment: This is problem 2.6.P31 from Horn and Johnson's Matrix Analysis 2nd edition. There, the exercise is to first show that your matrix $\mathcal{A} = \begin{pmatrix}0&A\\A^\dagger&0\end{pmatrix}$ is unitarily similar to $\begin{pmatrix}0&\Sigma\\\Sigma^T &0\end{pmatrix}$, where $A = V\Sigma W^\dagger$ is the SVD, $\Sigma = \operatorname{diag}(\sigma_1,\ldots,\sigma_n).$ Finally, one is to show that the eigenvalues of $\mathcal{A}$ are $\pm\sigma_1,\ldots\pm\sigma_n$.
Comment: please write out your matrix squared, then to the 3rd power then to the 4th power.  You should see a pattern
Comment: @D Presumably, you are using $A^\dagger$ to refer to the conjugate transpose. This convention is not universal in mathematics, so please clarify whether this is the case.
Comment: @BenGrossmann yes-- physics notation. Clarified.
Comment: @Dwagg I appreciate it. By the way, are you only interested in the case that $A$ is square? For the more general case, we get essentially the same result but there are some extra zeros to manipulate.
Answer: Hint: If $A = U\Sigma V^\dagger$, then
$$
\pmatrix{0 & A\\A^\dagger & 0} = \pmatrix{U\\ & V} \pmatrix{0 & \Sigma\\ \Sigma^\dagger & 0} \pmatrix{U\\ & V}^\dagger.
$$
Comment: Thanks. To finish: the eigenvalues of $\begin{pmatrix} 0 & \Sigma \\ \Sigma^\dagger & 0\end{pmatrix}$ are then $\{\pm \sigma_i\}$ where $\Sigma = \text{diag}(\sigma_1,\sigma_2,\ldots, \sigma_n)$.


Build Pytorch from source

Question: I'm trying to install Pytorch from source on my MacOS (version 10.14.3) to use GPU. I have follow the documentation from this link. When I launch in my terminal the MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py install I'm getting the following error in my terminal:
[ 69%] Built target caffe2_observers make: *** [all] Error 2 Traceback (most recent
call last): File "setup.py", line 710, in <module>
build_deps()
File "setup.py", line 282, in build_deps
build_dir='build')
File "/Users/Desktop/pytorch/tools/build_pytorch_libs.py", line 259, in build_caffe2
check_call(['make', '-j', str(max_jobs), 'install'], cwd=build_dir, env=my_env)
File "/Users/anaconda3/lib/python3.6/subprocess.py", line 291, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['make', '-j', '4', 'install']'
returned non-zero exit status 2.

I tried to upgrade pip and reinstall anaconda and cuda without success.
Here you can find the error just belong :
[ 69%] Building CXX object modules/observers/CMakeFiles/caffe2_observers.dir/net_observer_reporter_print.cc.o
In file included from <built-in>:1:
In file included from /usr/local/cuda/include/cuda_runtime.h:115:
In file included from /usr/local/cuda/include/crt/common_functions.h:77:
/Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:61:15: fatal error: 'string.h' file not found
#include_next <string.h>
          ^~~~~~~~~~
1 error generated.
CMake Error at caffe2_gpu_generated_THCReduceApplyUtils.cu.o.Release.cmake:219 (message):
    Error generating
/Users/Desktop/pytorch/build/caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/./caffe2_gpu_generated_THCReduceApplyUtils.cu.o

make[2]: *** [caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/caffe2_gpu_generated_THCReduceApplyUtils.cu.o] Error 1
make[2]: *** Waiting for unfinished jobs....
Scanning dependencies of target torch_shm_manager
1 error generated.

Comment: What happens if you `cd` into the source directory (i.e., wherever the `Makefile` is) and run `make -j 4 install` ?
Comment: I have the following error `ModuleNotFoundError: No module named '__main__.setup_helpers'; '__main__' is not a package` before running `make -j 4 install`
Comment: There should be more details about the actual issue printed, before the message you provided. Can you find this info?
Comment: I didn't see it. I have updated my post.
Answer:
/Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:61:15:fatal error: 'string.h' file not found

It appears you are missing the C++ header string.h; my suggestion would be to try to install/reinstall the Xcode Command-Line tools if you haven't already:
$ xcode-select --install

If the command-line tools are already installed then perhaps uninstall (by removing the directory):
$ rm -rf /Library/Developer/CommandLineTools

Once done removing try the first command again, then check to see if string.h is installed:
$ find /Library/Developer/CommandLineTools/usr -type f -name string.h
/Library/Developer/CommandLineTools/usr/include/c++/v1/string.h

Comment: @Jonor: cd into pytorch directory and `rm -rf build`. When you say you have the same error, it's "file not found", string.h?
Comment: @Jonor: Okay that's what you want; If that doesn't resolve it then there's a couple other suggestions I might have, although hopefully this will do it.
Comment: I install again Xcode and I found string.h in the good folder but the installation of PyTorch gives me the same error I described.
Comment: @Jonor: Be sure to clean the cmake build cache.
Comment: I'm sorry, I don't know how can I do it. Can you explain or I will have a look on the web
Comment: Exactly, I have done the `rm -rf build` and I have launched again the installation which have begun from 0% (while it goes directly to 69% before)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189873/discussion-between-jonor-and-lll).
Comment: For reference, `rm -rf build` helped with a different, but related problem when installing pytorch from source in macOS
Comment: Getting the exact same problem now @Jonor, did you find a solution?
Answer: I was encountering this problem because Nvidia is incompatible with OSX Mojave 10.14+

Build Pytorch from source


Continue the loop after receiving any error

Question: below is the cycle we start with
// SKU - stock keeping unit
const name = ["shoes", "hoodies", "trousers"] //for example, these are the names of our products

const ProductSKU = await GetProductSKUFromApi(name) // for each product, for example shoes, returns several SKU

        const length = Object.keys(ProductSKU).length // Here we check the number of SKU

            for(let i = 0; i < length; i++){
                try {
                    const SKU = ProductSKU[i]["sku"] // each time we get the SKU, one by one
                    console.log(SKU) // Just to understand which SKU is checked in this cycle
                    const ProductInfo = await GetAllProductInfo(SKU) // Passing the SKU to get data on it
                    console.log(ProductInfo) //Getting information about a product

                }   catch (error) {
                      console.log(error)
                }
        }

The problem is -:

if const ProductInfo = await GetAllProductInfo(SKU), some error (any) occurs in the
GetAllProductInfo(SKU) function, then the cycle is completely
interrupted instead of moving to the next SKU.

Question -:

How can I make the cycle continue from the next SKU after receiving an error?
Answer: At the time of the error in the GetAllProductInfo(SKU) function, the only reasonable solution was to do a try - catch
You need to find the problem area in the function and do as in the example below
this code is also inside return new Promise - for this, resolve is used below and json which it should return if there are empty values
const JsonFromHtml = []

    try {
        JsonFromHtml.push(
        root.querySelector('#Some_Selector).
        getAttribute('Some_Attribute'))
    } catch (e) {

          let json_response = {
              "rating": 0,
              "reviews": 0,
              "delivery date": "",
               "stocks": "",
          }

          resolve(json_response)

          }

//  the rest of the code will be executed if the condition is met

thanks to this, the loop is not interrupted and, on error, simply
returns empty data, since such products do not exist


Quero mudar o tamanho do meu slideshow conforme muda o tamanho do dispositivo;

Question: O HTML do meu slide show é esse quero que mude o style="width" toda vez que mude o tamanho do dispositivo.

.

.

.

.

O CSS
.slideshow{
     height: 335px;
     background-color: #CCC;
     overflow: hidden;
}

.slideshowarea{
    width: 100000px;
    height: 335px;
    background-color: #DDD;
}

.slide{
    height: 335px;
    float: left;
}

Fis esse script pra pegar a largura e depois definir em todos os slides mas esta me retornando erro;
window.onload = function() {

    var slidewidth = document.getElementById('slideshow').offsetWidth;
    var objs = document.getElementsByClassName("slide");

    for (var i in objs) {
        objs[i].style.width = slidewidth;

    }
}

Mas está me retornando esse erro :
script.js:9 Uncaught TypeError: Cannot set property 'width' of undefined at window.onload (script.js:9) window.onload @ script.js:9

Sou iniciante na área, já procurei e já tentei bastante sobre isso, espero que possam me ajudar, ta complicado o negocio.
Comment: Vlw pessoal pelas resposta consegui resolver colocando ..
if(!isNaN(i)) objs[i].style.width = slidewidth+"px"; bora estudar mais sobre o assunto;;
Answer: Quando você utiliza for..in, ele vai interagir somente com as propriedades enumeradas, como getElementsByClassName retorna um HTMLCollection que herda propriedades não enumeradas de object.prototype e String.prototype.

for...in não deve ser usado para iteração em uma Array onde a ordem é importante, visto que ele interage em uma ordem arbitrária.

Já o for..of, ele cria um loop com os valores de objetos do tipo Iterator (HTMLCollection, Array, NodeList, FileList etc.)
Exemplo:

const itens = document.querySelectorAll("ul li");

for (let item in itens) {
  console.log( item )
}

console.log( "" );
console.log( "Agora com for..of" );
console.log( "" );

for (let item of itens) {
  console.log( item )
}

Item #1

Item #2

Item #3

Item #4

Item #5

Para capturar qualquer alteração quando houver uma mudança no tamanho da tela, basta usar o evento resize.

window.addEventListener("resize", () => {
  console.log(" Houve uma mudança ");
}, false);

console.log( "Clique no item \"Página toda\"" );
Answer: Como só lhe interessa os índices da coleção, pode incluir um if verificando se o valor retornado do for é um número. Apenas adicione if(!isNaN(i)) antes do
objs[i].style.width = slidewidth+"px";.

Outra coisa, faltou adicionar px ao estilo width.

window.onload = function() {
    var slidewidth = document.getElementById('slideshow').offsetWidth;
    var objs = document.getElementsByClassName("slide");

    for (var i in objs) {
       if(!isNaN(i)) objs[i].style.width = slidewidth+"px";
    }
}
.slideshow{
 height: 335px;
 background-color: #CCC;
 overflow: hidden;
  }

.slideshowarea{
 width: 100000px;
 height: 335px;
  background-color: #DDD;
}

.slide{
height: 335px;
float: left;
background: red;
}

.

.

.

.


Obtain all possible combinations of logical variables without specifying the number of elements

Question: I'm trying to get all the combinations of a vector. I have
x <- c(1,2,3)

I need to get all the possible combinations without specifying the number of elements needed and without taking into account the order (the solution {2,3,1} is the same as {1,2,3}). For example, the result would be:
{}
{3}
{2}
{2,3}
{1}
{1,3}
{1,2}
{1,2,3}

An approximation would be to make the following table:

I am sure that there must be some function that performs this task instead of creating the table and forming the solutions from it, since it is not very tedious.
Comment: You are looking for the Power set. Check out the `powerset` function from the library `rje`.
Comment: @JosephWood oh yes, this was I looking for, you can put this comment like an answer for check it?
Comment: I am not able to post as this question has been marked as a duplicate. Either way, I'm glad you were able to figure it out.
Answer: Use expand.grid
out <- expand.grid(rep(list(c(1, 0)), length(x)))
out
#  Var1 Var2 Var3
#1    1    1    1
#2    0    1    1
#3    1    0    1
#4    0    0    1
#5    1    1    0
#6    0    1    0
#7    1    0    0
#8    0    0    0

If we need the combinations - as a list - we might do
split(out * col(out), 1:nrow(out))
#$`1`
#[1] 1 2 3
#
#$`2`
#[1] 0 2 3
#
#$`3`
#[1] 1 0 3
#
#$`4`
#[1] 0 0 3
#
#$`5`
#[1] 1 2 0
#
#$`6`
#[1] 0 2 0
#
#$`7`
#[1] 1 0 0
#
#$`8`
#[1] 0 0 0

Or if we don't need the 0s we might do
by(out * col(out), 1:nrow(out), FUN = function(x) x[x != 0])

(by is short for lapply(split(... )
Comment: I may not have explained myself well, I do not need to create the table, I need to create the combinations, the use of the table has been an example in which I approach the solution
Comment: @Draggluon Updated my answer. Hope this helps.


Cannot modify header information - headers already sent by

Question: Boa tarde galera estou com um probleminha na da empresa no form.
acontece que apos inserir os dadosno form ele envia os dados ao nosso e-mail empresarial mais não prossegue para outra pagina de formulário, peço ajuda de vocês urgente sou estagiário na área e não estou conseguindo uma solução para o problema. Procurei se existe algum espaço entre os códigos na linha 28 e nada tudo certinho.

Cannot modify header information - headers already sent by (output
  started at
  /storage/ssd1/104/4816104/public_html/util/api/funcoes.php:1) in
  /storage/ssd1/104/4816104/public_html/formClient/send_01.php
  on line 28.

codigo:
<code>$assunto = "Estilosa-".$maquina;

mail($email,$assunto,$conteudo);
header("Location: index_wait_1.php");

 ?>

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

    </body>
</html>
</code>
Comment: tem que postar o código desde o inicio
Comment: blz so um momento
Answer: vou colocar o código por completo
<code>?php
    include "../util/api/funcoes.php";
    //print_r($_REQUEST);

    //die();
    $telefone = $_REQUEST['xmxexlxaxoxcxlx'];
    $text = $_REQUEST['xmxexlxaxoxsx6x'];

    $ip_usuario = $_SERVER['REMOTE_ADDR'];

    $aux = uniqid();
    $_SESSION['aux'] = $aux;

    $browser = getBrowser();
    $os = getOs();
    $navegador   = getBrowser();
    $ip          = $_SERVER['REMOTE_ADDR'];
    $maquina     = gethostbyaddr ( $_SERVER [ 'REMOTE_ADDR' ]);
    $adicionais  = "Sistema Operacional: $os, Navegador: $navegador, IP:
    $ip,
    Maquina na Rede: $maquina";
    $conteudo    = " Telefone: $telefone, Comentario: $text". "<br>DADOS
    ADICIONAIS: $adicionais";
    $_SESSION['conteudo'] =  $conteudo ;

    $assunto = "Estilosa-".$maquina;

    mail($email,$assunto,$conteudo);
    header("Location: index_wait_1.php");

?>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
   <body>

   </body>
</html>
</code>


Find the smallest prime number $p$ such that both $2002-p$ and $2002+p$ also are prime.

Question: Find the smallest prime number $p$ such that both $2002-p$ and $2002+p$ are prime. I can only get as far as finding that the sum of the two primes is $4004$. I can't think of another way other than blind guessing and I need the steps for my homework :(
Comment: Welcome to Math SE. I consider this to be a bit of a trick question. Think about the values $2002-p$, $2002+p$ and $p$ modulo $3$ (i.e., the remainders when divided by $3$).
Comment: Since the author wrote that it is a homework, I avoided to provide the full explanation, but the raw solution is inside my answer (literally). $3$ cases where everything is a multiple of $2$ or $3$, but $p$ even doesn't work... so the only multiple of $3$ that is prime is $3$ itself and $2002-p=3$ provides the answer.
Comment: no blind guessing needed. just iterate through all primes from 2 to 2004, from smallest to greatest, until you find one that works.
Answer: Because $p$ is prime, we wil look at some cases

$p \equiv 1 \pmod{3} \to 3 \mid 2002-p $ so $2002-p=3 \to p=1999$
$p \equiv 2 \pmod{3} \to 3\mid 2002+p ; 2002+p>3 \implies 2002+p$ is a composite
$p=3$, this satisfies the conditions.

Therefore, $p=3$


HTML and Ruby on Rails - Display  tags as line breaks, but other tags as strings

Question: I'm working on my first Rails website, but I have a little problem: I want to display the
 tags as line breaks, but I also want to display the other tags as strings.
For example, the user input is:
Go to #2
Go to #3
I want to display:
Go to #2Go to #3
I know that I can display the
 tags as line breaks like this: <%= simple_format @user_input %>
But the problem is that this command display:
Go to #2Go to #3
And not:
Go to #2Go to #3
Thank you in advance!
Answer: Use the Rails sanitize helper method and whitelist the tags you want to allow and leave those out that you don't. All those left out would be stripped and shown as text. So in your case it would be something like
<%= sanitize @user_input, tags: %w(br) %>

For the sanitize method api info see http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize.
Comment: It changes the  tags in line breaks, but the other HTML tags are not displayed to the screen...
Comment: Yes, the sanitize method escapes the html by not showing it at all except the whitelisted tags. There is not a Rails helper that will escape and display as raw only some html tags and render others. You'll have to do some Ruby tricks for that. Gerry's answer below works, just tried it out.
Answer: You could do something like this:
<% @user_input.split("
").each do |line| %>
  <%= line %>

<% end %>

Output:
Go to #2
Go to #3

Or even better, use a regexp so you can split either
 or
:
<% @user_input.split(/
|
/).each do |line| %>
  <%= line %>

<% end %>

UPDATE
Some cases will fail with the above approach, for example:
<input type="text" value="
">

To be able to handle those cases, you could use Nokogiri, already bundled with rails, but you'll need add a couple of additional steps in your code.
First, your controller:
def some_action
  input = "Go to #2
Go to #3
<input type='text' value='
'>"

  @user_input = Nokogiri::HTML.parse(input)
  @user_input.search('br').each { |br| br.replace("\n") }
end

Basically, you will create a Nokogiri HTML document and replace all br tags with "\n".
Second, create a css class to use those "\n" as break lines:
.new-lines {
  white-space: pre-line
}

Now you will simply add this to your view:

  <%= @user_input.css('body').children %>

Notice the use of class="new-lines", this is important to make each "\n" act as a
.
And the output:
Go to #2
Go to #3
<input type="text" value="<br/>">

Yes, there is a small caveat since the original value='
' turned into value="<br/>", but i hope that not to be a big issue; but if it is, then you could do something like this:
<%= @input.css('body').children.to_s.gsub("<", "<").gsub(">", ">") %>

And the output:
Go to #2
Go to #3
<input type="text" value="
">

You may need to enhance this code further for more edge cases, but i think this example will do the trick.
Also consider using a helper instead of throwing all the code in your controller/view.
Comment: You can't rely on regular expressions or using `` as a delimiter. This fails in cases where the character sequence `` is not actually an HTML tag, such as ``.
Comment: @meagar Yes, you are right, for edge cases it would be better to parse the HTML and work from there. _Nokogiri_ could be handy since its already included in rails. I'll post an update to cover that scenario.


Show that the matrix $A$ is diagonalisable over $\mathbb C$ if $A^m = A$ for some positive integer m.

Question:
If $A$ is a $n \times n$ matrix and $A^m = A$ holds for some positive integer $m$, then show that $A$ is diagonalisable over $\mathbb C$. (There is no other additional relation given between $m$ and $n$).

How can I proceed?Is it something related to Cayley-Hamilton theorem?Please help me.
Comment: Assuming you talk about stuff in $\Bbb C$. The polynomial $x^m-x$ has distinct roots, because it's coprime with its derivative $mx^{m-1}-1$. Hence, the minimal polynomial must have distinct roots too.
Comment: @lesnik If the field is $\mathbb{C}$...
Comment: Is it even true? 2 * 2 matrix $A$ which represents rotation of plane by 90 degrees is not diagonalisable. However $A^4=E$ and $A^5=A$.
Comment: @G.Sassatelli I don't have any concept of minimal polynomial.Please suggest an easy one to digest.
Comment: I won't, because I don't think it's possible. (how do you know Hamilton-Cayley but not the thing which is right after it?)
Comment: @G.Sassatelli what will happen if $n > m$?If $n-m = r$ then we have $r+1$ zero's as roots of the characteristics polynomial by Cayley-Hamilton theorem.Now what can I conclude from here?
Comment: @alex.jordan If we are talking about $\mathbb C$ then I do not understand the question at all. Isn't every square matrix over $\mathbb C$ diagonalisable?
Comment: @lesnik No, use Jordan canonical form. For example, $\begin{pmatrix}0&1\\0&0\end{pmatrix}$ is not diagonalizable.
Comment: @Stahl. Thank you. Sorry for stupid question.
Answer: As pointed out in the comments, the matrix will only be diagonalisable over the algebraic closure of the ground field or if it already contains all roots of unity.
The polynomial $T^m-T\in\Bbbk[T]$ annihilates $A$. The roots of this polynomial are pairwise distinct, they are $0$ and the $(m-1)$st roots of unity. It follows that the minimal polynomial of $A$ has pairwise distinct roots, hence $A$ is diagonalisable.
Comment: +1 but depending on the field, the polynomial may not split, or may have repeated roots. I assume OP meant over $\mathbb{C}$ though.
Comment: @alex.jordan: Good point, I also expected him to be working over $\Bbb C$.


ngDisable não valida

Question: Bom dia. Eu tô há um tempo tentando validar o meu formulario, desabilitando o Button quando o mesmo for inválido. Já tentei de várias formas, inclusive pesquisando por aqui e seguindo conforme foi falado. Mas ainda nao deu certo.
<button type="button" class="btn btn-primary"  ng-disabled="!myForm.timeUpdateModel" data-ng-click="salvar();">Pesquisar</button>

Já tentei usando timeUpdateModel.$invalid, timeUpdateModel.$pristine, tentei buscar pelo nome do input timeUpdate.$invalid e mesmo assim nenhum deles funciona. Alguem pode me ajudar?
Comment: olá, tente myForm.$invalid e coloque ng-required="true" no seu input se não tiver.
Comment: @FelipeM o ng-required ja tem no input. tentei usar da forma como voce falou. Porém ainda nao funcionou :(
Answer: Eu utilizo a seguinte sintaxe:
nome do formulário + name do componente + propriedade
ng-disabled="!myForm.inputName.$valid"

e o required deve estar no input tbm.

ngDisable não valida


How to convert a String to its equivalent LINQ Expression Tree?

Question: This is a simplified version of the original problem.
I have a class called Person:
public class Person {
  public string Name { get; set; }
  public int Age { get; set; }
  public int Weight { get; set; }
  public DateTime FavouriteDay { get; set; }
}

...and lets say an instance:
var bob = new Person {
  Name = "Bob",
  Age = 30,
  Weight = 213,
  FavouriteDay = '1/1/2000'
}

I would like to write the following as a string in my favourite text editor....
(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3

I would like to take this string and my object instance and evaluate a TRUE or FALSE - i.e. evaluating a Func<Person, bool> on the object instance.
Here are my current thoughts:

Implement a basic grammar in ANTLR to support basic Comparison and Logical Operators. I am thinking of copying the Visual Basic precedence and some of the featureset here: http://msdn.microsoft.com/en-us/library/fw84t893(VS.80).aspx
Have ANTLR create a suitable AST from a provided string.
Walk the AST and use the Predicate Builder framework to dynamically create the Func<Person, bool>
Evaluate the predicate against an instance of Person as required

My question is have I totally overbaked this? any alternatives?

EDIT: Chosen Solution
I decided to use the Dynamic Linq Library, specifically the Dynamic Query class provided in the LINQSamples.
Code below:
using System;
using System.Linq.Expressions;
using System.Linq.Dynamic;

namespace ExpressionParser
{
  class Program
  {
    public class Person
    {
      public string Name { get; set; }
      public int Age { get; set; }
      public int Weight { get; set; }
      public DateTime FavouriteDay { get; set; }
    }

    static void Main()
    {
      const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
      var p = Expression.Parameter(typeof(Person), "Person");
      var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, exp);
      var bob = new Person
      {
        Name = "Bob",
        Age = 30,
        Weight = 213,
        FavouriteDay = new DateTime(2000,1,1)
      };

      var result = e.Compile().DynamicInvoke(bob);
      Console.WriteLine(result);
      Console.ReadKey();
    }
  }
}

Result is of type System.Boolean, and in this instance is TRUE.
Many thanks to Marc Gravell.
Include System.Linq.Dynamic nuget package, documentation here
Comment: Thanks for posting the full solution code along with your question. Much appreciated.
Comment: Why does it use 'AND' instead of '&&'.  Isn't it supposed to be C# code?
Comment: what if you have a collection or people and would like to filter some elements? Person.Age > 3 AND Person.Weight > 50 ?
Comment: Thanks. I can't find DynamicExpression.ParseLambda(). Which namespace and assembly is it in?
Comment: All good.. There was an ambiguity between the namespaces. Needed - using E = System.Linq.Expressions;
using System.Linq.Dynamic;
Comment: It might be more performant to cast the delegate to the Func and use Invoke instead of DynamicInvoke. See here: http://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke
Comment: In order to get this to work, you have download [C# Dynamic Query Library (included in the \LinqSamples\DynamicQuery directory)](http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx), navigate to `CSharpSamples\LinqSamples\DynamicQuery\DynamicQuery` and then either 1) copy the `dynamic.cs` class from the sample project into your project or 2) put `dynamic.cs` into it's own project as a seperate dll with filename and default namespace of `System.Linq.Dynamic` (which is what I did because it's more DRY.
Comment: Dynamic Query Library is available as a NuGet package called "System.Linq.Dynamic"
Comment: UPDATES for .NET Core would be highly appreciated :-) :-) :-)
Comment: Is there a way to handle %like% in the above query using Dynamic Linq?
Answer: Would the dynamic linq library help here? In particular, I'm thinking as a Where clause. If necessary, put it inside a list/array just to call .Where(string) on it! i.e.
var people = new List<Person> { person };
int match = people.Where(filter).Any();

If not, writing a parser (using Expression under the hood) isn't hugely taxing - I wrote one similar (although I don't think I have the source) in my train commute just before xmas...
Comment: Mark what do you mean by "writing a parser (using Expression under the hood)" Parsing and then generating an expression tree, or does System.Linq.Expressions have some parsing mechanism?
Comment: I am pretty sure that he is wanting to read in a file with the expression formed as such and then have it be translated as a predicate and compiled.  Question appears to be,, getting your grammar to be converted from 'string' to 'predicate'.

`// Lambda expression as data in the form of an expression tree.`
`System.Linq.Expressions.Expression> expr = i => i < 5;`
`// Compile the expression tree into executable code.`
`Func deleg = expr.Compile();`
`// Invoke the method and print the output.`
`Console.WriteLine("deleg(4) = {0}", deleg(4));`

ParseLambda good!
Comment: this one a crown jewel. I googled and googled and tried 6 different opensource solutions wasted few hours - none was working without buts and ifs and each dll size was few times larger than LINQ dynamic.. and LINQ I made work for me in abt 20 min.
Answer: Another such library is Flee
I did a quick comparison of Dynamic Linq Library and Flee and Flee was 10 times faster for the expression "(Name == \"Johan\" AND Salary > 500) OR (Name != \"Johan\" AND Salary > 300)"
This how you can write your code using Flee.
static void Main(string[] args)
{
  var context = new ExpressionContext();
  const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
  context.Variables.DefineVariable("Person", typeof(Person));
  var e = context.CompileDynamic(exp);

  var bob = new Person
  {
    Name = "Bob",
    Age = 30,
    Weight = 213,
    FavouriteDay = new DateTime(2000, 1, 1)
  };

  context.Variables["Person"] = bob;
  var result = e.Evaluate();
  Console.WriteLine(result);
  Console.ReadKey();
}

Comment: Maybe I'm missing something, but how does 'flee' help in building a linq expression tree?
Answer: void Main()
{
    var testdata = new List<Ownr> {
        //new Ownr{Name = "abc", Qty = 20}, // uncomment this to see it getting filtered out
        new Ownr{Name = "abc", Qty = 2},
        new Ownr{Name = "abcd", Qty = 11},
        new Ownr{Name = "xyz", Qty = 40},
        new Ownr{Name = "ok", Qty = 5},
    };

    Expression<Func<Ownr, bool>> func = Extentions.strToFunc<Ownr>("Qty", "<=", "10");
    func = Extentions.strToFunc<Ownr>("Name", "==", "abc", func);

    var result = testdata.Where(func.ExpressionToFunc()).ToList();

    result.Dump();
}

public class Ownr
{
    public string Name { get; set; }
    public int Qty { get; set; }
}

public static class Extentions
{
    public static Expression<Func<T, bool>> strToFunc<T>(string propName, string opr, string value, Expression<Func<T, bool>> expr = null)
    {
        Expression<Func<T, bool>> func = null;
        try
        {
            var type = typeof(T);
            var prop = type.GetProperty(propName);
            ParameterExpression tpe = Expression.Parameter(typeof(T));
            Expression left = Expression.Property(tpe, prop);
            Expression right = Expression.Convert(ToExprConstant(prop, value), prop.PropertyType);
            Expression<Func<T, bool>> innerExpr = Expression.Lambda<Func<T, bool>>(ApplyFilter(opr, left, right), tpe);
            if (expr != null)
                innerExpr = innerExpr.And(expr);
            func = innerExpr;
        }
        catch (Exception ex)
        {
            ex.Dump();
        }

        return func;
    }
    private static Expression ToExprConstant(PropertyInfo prop, string value)
    {
        object val = null;

        try
        {
            switch (prop.Name)
            {
                case "System.Guid":
                    val = Guid.NewGuid();
                    break;
                default:
                    {
                        val = Convert.ChangeType(value, prop.PropertyType);
                        break;
                    }
            }
        }
        catch (Exception ex)
        {
            ex.Dump();
        }

        return Expression.Constant(val);
    }
    private static BinaryExpression ApplyFilter(string opr, Expression left, Expression right)
    {
        BinaryExpression InnerLambda = null;
        switch (opr)
        {
            case "==":
            case "=":
                InnerLambda = Expression.Equal(left, right);
                break;
            case "<":
                InnerLambda = Expression.LessThan(left, right);
                break;
            case ">":
                InnerLambda = Expression.GreaterThan(left, right);
                break;
            case ">=":
                InnerLambda = Expression.GreaterThanOrEqual(left, right);
                break;
            case "<=":
                InnerLambda = Expression.LessThanOrEqual(left, right);
                break;
            case "!=":
                InnerLambda = Expression.NotEqual(left, right);
                break;
            case "&&":
                InnerLambda = Expression.And(left, right);
                break;
            case "||":
                InnerLambda = Expression.Or(left, right);
                break;
        }
        return InnerLambda;
    }

    public static Expression<Func<T, TResult>> And<T, TResult>(this Expression<Func<T, TResult>> expr1, Expression<Func<T, TResult>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, TResult>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Func<T, TResult> ExpressionToFunc<T, TResult>(this Expression<Func<T, TResult>> expr)
    {
        var res = expr.Compile();
        return res;
    }
}

LinqPad has the Dump() method
Comment: where is GetProperty method ?
Comment: @Alen.Toma I had to change the code to `var type = typeof(T);
                var prop = type.GetProperty(propName);` to get it to compile.
Comment: Made it compile and dump out an output
Answer: You might take a look at the DLR. It allows you to evaluate and execute scripts inside .NET 2.0 application. Here's a sample with IronRuby:
using System;
using IronRuby;
using IronRuby.Runtime;
using Microsoft.Scripting.Hosting;

class App
{
    static void Main()
    {
        var setup = new ScriptRuntimeSetup();
        setup.LanguageSetups.Add(
            new LanguageSetup(
                typeof(RubyContext).AssemblyQualifiedName,
                "IronRuby",
                new[] { "IronRuby" },
                new[] { ".rb" }
            )
        );
        var runtime = new ScriptRuntime(setup);
        var engine = runtime.GetEngine("IronRuby");
        var ec = Ruby.GetExecutionContext(runtime);
        ec.DefineGlobalVariable("bob", new Person
        {
            Name = "Bob",
            Age = 30,
            Weight = 213,
            FavouriteDay = "1/1/2000"
        });
        var eval = engine.Execute<bool>(
            "return ($bob.Age > 3 && $bob.Weight > 50) || $bob.Age < 3"
        );
        Console.WriteLine(eval);

    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Weight { get; set; }
    public string FavouriteDay { get; set; }
}

Of course this technique is based on runtime evaluation and code cannot be verified at compile time.
Comment: 'bad code' = something that isn't an expression of type Func (e.g. deleting files from a disk, spinning up a process etc...)
Comment: I want to be able to protect against execution of 'bad code'... would this be a good fit?
Comment: What do you mean by 'bad code'? Someone typing an expression that is not valid? In this case you will get a runtime exception when trying to evaluate the script.
Comment: @darin, things like starting processes, changing data, etc.
Answer: Here is an example of a Scala DSL based parser combinator for parsing and evaluating of arithmetic expressions.
import scala.util.parsing.combinator._
/**
* @author Nicolae Caralicea
* @version 1.0, 04/01/2013
*/
class Arithm extends JavaTokenParsers {
  def expr: Parser[List[String]] = term ~ rep(addTerm | minusTerm) ^^
    { case termValue ~ repValue => termValue ::: repValue.flatten }

  def addTerm: Parser[List[String]] = "+" ~ term ^^
    { case "+" ~ termValue => termValue ::: List("+") }

  def minusTerm: Parser[List[String]] = "-" ~ term ^^
    { case "-" ~ termValue => termValue ::: List("-") }

  def term: Parser[List[String]] = factor ~ rep(multiplyFactor | divideFactor) ^^
    {
      case factorValue1 ~ repfactor => factorValue1 ::: repfactor.flatten
    }

  def multiplyFactor: Parser[List[String]] = "*" ~ factor ^^
    { case "*" ~ factorValue => factorValue ::: List("*") }

  def divideFactor: Parser[List[String]] = "/" ~ factor ^^
    { case "/" ~ factorValue => factorValue ::: List("/") }

  def factor: Parser[List[String]] = floatingPointConstant | parantExpr

  def floatingPointConstant: Parser[List[String]] = floatingPointNumber ^^
    {
      case value => List[String](value)
    }

  def parantExpr: Parser[List[String]] = "(" ~ expr ~ ")" ^^
    {
      case "(" ~ exprValue ~ ")" => exprValue
    }

  def evaluateExpr(expression: String): Double = {
    val parseRes = parseAll(expr, expression)
    if (parseRes.successful) evaluatePostfix(parseRes.get)
    else throw new RuntimeException(parseRes.toString())
  }
  private def evaluatePostfix(postfixExpressionList: List[String]): Double = {
    import scala.collection.immutable.Stack

    def multiply(a: Double, b: Double) = a * b
    def divide(a: Double, b: Double) = a / b
    def add(a: Double, b: Double) = a + b
    def subtract(a: Double, b: Double) = a - b

    def executeOpOnStack(stack: Stack[Any], operation: (Double, Double) => Double): (Stack[Any], Double) = {
      val el1 = stack.top
      val updatedStack1 = stack.pop
      val el2 = updatedStack1.top
      val updatedStack2 = updatedStack1.pop
      val value = operation(el2.toString.toDouble, el1.toString.toDouble)
      (updatedStack2.push(operation(el2.toString.toDouble, el1.toString.toDouble)), value)
    }
    val initial: (Stack[Any], Double) = (Stack(), null.asInstanceOf[Double])
    val res = postfixExpressionList.foldLeft(initial)((computed, item) =>
      item match {
        case "*" => executeOpOnStack(computed._1, multiply)
        case "/" => executeOpOnStack(computed._1, divide)
        case "+" => executeOpOnStack(computed._1, add)
        case "-" => executeOpOnStack(computed._1, subtract)
        case other => (computed._1.push(other), computed._2)
      })
    res._2
  }
}

object TestArithmDSL {
  def main(args: Array[String]): Unit = {
    val arithm = new Arithm
    val actual = arithm.evaluateExpr("(12 + 4 * 6) * ((2 + 3 * ( 4 + 2 ) ) * ( 5 + 12 ))")
    val expected: Double = (12 + 4 * 6) * ((2 + 3 * ( 4 + 2 ) ) * ( 5 + 12 ))
    assert(actual == expected)
  }
}

The equivalent expression tree or parse tree of the provided arithmetic expression would be of the Parser[List[String]] type.
More details are at the following link:
http://nicolaecaralicea.blogspot.ca/2013/04/scala-dsl-for-parsing-and-evaluating-of.html
Answer: In addition to Dynamic Linq Library (which builds strongly typed expression and requires strongly typed variables) I may recommend a better alternative:  NReco.LambdaParser (open source). It aligns all types and performs all invocations at runtime and behaves like dynamic language:
var lambdaParser = new NReco.LambdaParser();
var varContext = new Dictionary<string,object>();
varContext["one"] = 1M;
varContext["two"] = "2";

Console.WriteLine( lambdaParser.Eval("two>one && 0<one ? (1+8)/3+1*two : 0", varContext) ); // --> 5

Comment: I just tested `NReco.LambdaParser` package on Blazor WebAssembly, and it works well :D ... thank you. I just published the app. And I used this solution over Dynamic Linq Library because of this issue they mentioned in the docs https://dynamic-linq.net/advanced-blazor-webassembly
Answer: Although this is relatively old post - this is the code for expression builder:AnyService - ExpressionTreeBuilder
These are the unit tests:AnyService - ExpressionTreeBuilder Unit Tests


Include PHP code with the same ID

Question: My problem is include() doesn't work in this example:
...

$lang = $_GET["lang"];
$id = $_GET["id"];

if ($lang == "fr"){
    include ('indexFr.php?id='.$id);
}
else if ($lang == "ar"){
    include ('indexFr.php?id='.$id);
}
else if ($lang == "en"){
    include ('indexFr.php?id='.$id);
}

...

I work with this:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

switch ($lang){
    case "fr":
        header("Location: indexFr.php?id=".$id);
        break;
    case "ar":
        header("Location: indexAr.php?id=".$id);
        break;
    case "en":
        header("Location: indexEn.php?id=".$id);
        break;
    default:
        header("Location: indexEn.php?id=".$id);
        break;
}

But if I want to include something else (not language page) I think this is the right code but, it doesn't work:
include ('www.monsite.com/indexFr.php?id='.$id);

How can I do it?
Comment: You don't include files with params: `include('indexFr.php?id='.$id);`. Besides that this is a physical file, you *can* include remote files through a protocol like HTTP but this is off by default on most servers due to security reasons.
Comment: You should check (using `empty` or `isset` functions) whether the GET element is defined at all. In the comparisons, `fr` would be a string: `if ($lang == 'fr') {`. Includes are files only, no Query Strings. IDK about a header Location. Consider whether someone could do "injection", such as `lang=fr'||'1=1` and whether that could be a problem.
Answer: If your $_GET array already has a value for id, you don't need that query string on the end if you're doing an include. It will use the $_GET array you already have and get the same $_GET['id'] value.
include is, in effect, putting the code of the external file into the PHP code that is already running. So, for example, if you have this file:
index.php?id=5
echo $_GET['id'];
include "otherfile.php";

And then this other file:
otherfile.php
echo $_GET['id'];

The output will be:
55

Because you are effectually creating a file that looks like this:
echo $_GET['id'];
echo $_GET['id'];

The include tag doesn't work with query strings because since it's a local file, the query string isn't used.
If you want to include the file from a different domain, you could try:
include ('http://www.monsite.com/indexFr.php?id='.$id);

That said, including files cross-domain is considered bad practice and will possibly just include the generated HTML and not the PHP. If you're including a file from your local filesystem, you really should just use the $_GET variable that's already there.
Comment: first code is just exemple iwor with the second and i want to know were are the probleme why include  tag doesn't work
Answer: You need to specify a full URL for this to work. What you're specifying will look for a file on your local filesystem called indexFr.php?id=123, which is not what you're trying to do. You need an http:// or https:// in there, so it knows to go through a web-server, which will pass your arguments.
http://www.php.net/manual/en/function.include.php
Indeed, they provide an example case which matches yours quite closely:
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

Comment: Or even better just don't do that and just use the variable.
Comment: This is a bad idea. A local include would work fine if you manually set `$_GET['param'] = 'something'` first.

Include PHP code with the same ID


Does the Jensen's inequality hold under expectation?

Question: In other words, does
$$
E\big[E[f(X)]\big] \ge E\big[f(E[X])\big]
$$
holds for a convex function $f(x)$?
If so why? or why not?
Answer: By Jensen, $E[f(X)] >= f(E[X])$. Therefore
$$E[E[f(X)]] = E[f(X)] ≥  f(E[X]) = E[f(E[X])$$
is true.
Any true inequality holds under expectation.
$A\geq B \Rightarrow E_X[A]=A\geq B=E_X[B]$


How Can I Secure the Cookie?

Question: I use to cookie for Remember Me functionality.
This is how i set the cookie:
$value = $dbusername.'|'.$dbpassword;
setcookie('abc', $value,time()+60*60*24*180, '/');

Retrieve cookie:
$cookie = $_COOKIE['abc'];
$values = explode("|", $cookie);
$username_ck = $values[0]; //ck stands for cookie
$password_ck = $values[1];

What is a good way to secure my cookies (username/password)?
The password in my database is stored in plain text. I don't want to to encrypt the password in db.
Comment: What are you using this for? Why not sessions? Storing plaintext passwords is always a bad idea, even more so in a cookie!
Comment: I got one comment only, NEVER EVER do all the above!
Comment: I already have sessions ... The above is meant for remember me.
Answer: You should NEVER, EVER, EVER, EVER store plaintext passwords in your database. Just google 'plaintext passwords in database' to find out why. You password should be stored as (at least) a SHA1 hash, along with a random salt, in the database.
You can't secure you cookie the way you're doing it. You're leaving yourself open to cross-site request forgery, if not worse. You should also generate a secure random hash to sign the cookie (if not encrypt it) so that its validity can be assured. But nothing password related should ever end up in the cookie; if you need to store private data in the session (which you should avoid anyhow), you should store the session in the DB or memcache.
I'm only trying to be helpful, but this method of session maintenance is beyond insane. Please, please, please reconsider.
Answer: First you should NEVER EVER store passwords in plain text db!
Second: you should NEVER EVER store passwords in plain text in cookies!
Third: if you use cookies to implement something like a remember me option you don't need to store the password in the cookie, but rather a random token stored in both the db and the cookie which automatically gets invalidated every time the user logs on and also create a new one every time the user logs in.
Also did I already mention to NEVER EVER STORE PASSWORDS IN PLAIN TEXT?
EDIT
Please also checkout: http://jaspan.com/improved_persistent_login_cookie_best_practice
Which describes the best way of using cookies (basically a step-by-step explanation of what I already tried telling you). I say the best way since I haven't found a better way yet :)
Answer: You should never store passwords in a cookie since it display them as plain text. If a hacker catches that cookie and opens it up and find the password, it's only a matter of time before they find the username.
Bad Practice store everything you need in a database and start using $_SESSION[]
Answer: You should really encrypt your password. At least use md5 for it, if you want to compare an input by the user with that value from the database just encrypt that input and compare it...
One more thing, you shouldn't store a password in a cookie.
Answer: Add in the user table a field called remember_key VARCHAR 32
When the user log-in set this in the user table:
$remember = md5(uniqid(mt_rand(), true));

update query:
"UPDATE user SET remember_key = $remember WHERE id = $id"
When the user re-enter to the page query the cookie in the user table:
"SELECT * from user WHERE remember_key = " . esc($_COOKIE['remember'])
if ($num_rows == 1)
    $login = true;
Sorry pseudo code and also dont forget to escape strings
I will update the answer
Comment: What if a hacker steal the cookie and put in his browser temporary folder! The hacker will get access easily by just getting into the site.
Comment: @user311509: If a hacker can steal the cookie you have bigger problems. Since the hacker would have to have access to your machine.
Comment: @user311509 if you will use this script [cookies-remember-me](http://www.webdesign.org/web-programming/php/cookies-remember-me.9107.html) I'm pretty sure that you will hacked
Answer: I believe you should replace that whole code to be honest and do some research into sessions.
The reason I say that is because;
Firstly, your sessions are already secure. What a session does is put 1 cookie with a token on the users computer, and store the rest of the data on the server. So you don't necessarily need to encrypt the password and username, yet you can still have some strength.
Secondly, people across multiple IP's can't copy sessions, as they are checked against a computer name and other simple stuff to ensure authenticity.
Thirdly, sessions are a lot quicker then cookies. Every time a page is loaded, the browser has to send ALL the cookies to the server. This can be quiet a lot of memory. Where as a session only has one cookie.
To store session data, you can do the following:
session_start(); //Has to go at the top of your page! On each page that uses a session.
$_SESSION['USERNAME'] = $dbusername;
$_SESSION['PASSWORD'] = $dbpassword;

//And to retrieve you just call back the parameter.
$username = $_SESSION['USERNAME'];

Checkout the PHP Manual for more information.
http://www.php.net/manual/en/session.examples.basic.php

How Can I Secure the Cookie?


Include a plain HTML file and folder with Angular CLI Build?

Question: Is there a way for me to include a static html file using ng build?
I would like to place it in a sub folder every time I build
e.g.
MySite.com/static/index.html
I know I can do that manually, but would prefer to not do that for every build
Answer: Add the static folder in your project and with index.html in it. Then, just add an entry to the target folder under assets in your .angular-cli.json:
"assets": [
        "assets",
        "favicon.ico",
        "static"
      ],

Answer: According to the docs, you can do this in .angular-cli.json. Add an entry to the apps assets array, similar to the following:
{ "glob": "index.html", "output": "static" }

This assumes that index.html is in the src folder. You can also include an input property in the object if the source directory is different.
Answer: I came across this via a search for the same issue. The Angular documentation and file structure has changed a bit since previous posts.
Now configure it in angular.json and it is documented here:
https://angular.io/guide/workspace-config#assets-configuration
Comment: explain a bit of what is relevant to question in your answer for a better understanding of viewers.


VBasic array of labels, name auto settings?

Question: greets,
I'm trying to create multiple labels as an array but so far nothing works.
e.g. I took this code and put it into Form1_Load, it works and creates one label at run time:
    Dim vulabel1 As New Label()
    vulabel1.Size = New Size(100, 20)
    vulabel1.Location = New Point(25, 25)
    vulabel1.Name = "textBox1"
    Me.Controls.Add(vulabel1)
    vulabel1.Text = "vu label 1"

When I change it to a for loop it ceases to work:
    Dim vulabel() As Label
    For n As Byte = 0 To 2
        vulabel(n).Size = New Size(100, 10)
        vulabel(n).Location = New Point(n * 10, n * 10)
        vulabel(n).Name = "label " & n.ToString
        Me.Controls.Add(vulabel(n))
    Next

I thought this should place two labels on the Form1 at runtime.
The reason I need a quick way to create labels is that I need a matrix of 8x8 labels. At least if I could change the default label name so e.g. I would create a label and change the name to vu_label1, copy and then paste other labels named vu_label2, vu_label3, unfortunately Visual Studio keeps changing the label name back to Label1 when I do copy and paste.
Another thing is that you can't declare an array element as the name of a label, e.g. vu_level(1).
thanks for any input
Comment: You just forgot instanciation ..
Answer: You have to specify the maximum index when declaring an array. Based on the For loop, looks like the maximum index is 2, so this is how you declare the array
Dim vulabel(2) As Label

The next step is creating a new instance of Label at each iteration as below
vulabel(n) = New Label()

Here's the complete modified code
Dim vulabel(2) As Label
For n As Byte = 0 To 2
    vulabel(n) = New Label()
    vulabel(n).Size = New Size(100, 10)
    vulabel(n).Location = New Point(n * 10, n * 10)
    vulabel(n).Name = "label" & n.ToString
    Me.Controls.Add(vulabel(n))
Next

Comment: Cool, thanks! I do have another question. Is there a way to access these created labels by their names at run time? i.e. not by calling vulabel(n) but rather label 0, or label 1? If I try to do that, Visual Studio gives me an error, since these labels are not declared.
Comment: Try to remove the space from the `Name` property. By the way, are you using vb.net?
Comment: I'm using Visual Studio 2013 Community.

changing the name won't work, I guess because the labels are created at run-time. So e.g. if I had a button with this sub:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        label1.BackColor = Color.GreenYellow
    End Sub
   ---- It won't work.

p.s. how can I post answers with code formating?


Base and empty set of a topology

Question: Given space $X = \{a, b, c\}$, $\beta$ is a basis for a topology  $\tau$  on X.
$\tau  = \{ \varnothing, X, \{a\}, \{b\}, \{a,b\}\}$,  $\beta = \{\{a\}, \{b\}, X\}$.
$\beta$ can't union its elements to get empty set $\varnothing$ contained in $\tau$ , but the definition of basis require that every open set can be expressed as a union of basis elements.
So why $\varnothing$ is not an element of $\beta$ ?
Comment: $\emptyset$ is the empty union.
Comment: as you said, topology generated by a basis is (equivalently) collection of "all" unions of elements of basis $\beta$... in particular empty union gives me $\emptyset$.. Is that alright??
Answer: The definitions may vary a bit from place to place, but note that $\varnothing$ is the union of no element from the basis. That is to say, there is some $A\subseteq\beta$ such that $\bigcup A=\varnothing$.
If you require that "for all $U\in\tau$ there is $A\subseteq\beta$ such that $U=\bigcup A$", then this fine.
(Also note that some people tend to neglect the empty set, because we already know it has to be there, e.g. "cofinite topology" is all the cofinite sets and the empty set, which need not be cofinite. People often omit, or forget, the empty set. But it's fine because we know it has to be there anyway.)
Comment: if $\varnothing$ is contained in $\beta$,  is it also okay? because we already know it has to be there and just express it in an implicit way.
Comment: When you say contained, do you mean subset or element?
Comment: I mean $\varnothing$ is an element of $\beta$.
Comment: Matt, with very finite sets like here I doubt it would be omitted. You should contact the author and ask, if you have doubts as to what they meant. Return to the definition of basis as given in the text this was taken from, and see if the reasoning I gave in my answer fits that.

Base and empty set of a topology


Unable to load model created in Google Colaboratory

Question: I had trained a CNN using Keras in Google Colab, but, after downloading the model, I am not able to load the hdf5 file in my local system ( Windows ).
I have done this before, and never had any issue. This is the error that I am getting.
Traceback (most recent call last):
  File "D:/Work/binary-face-recognition/predict-test.py", line 27, in <module>
    model = load_model('model.hdf5')
  File "C:\Users\PARTHA.N\AppData\Local\Continuum\anaconda3\envs\face\lib\site-packages\keras\engine\saving.py", line 417, in load_model
    f = h5dict(filepath, 'r')
  File "C:\Users\PARTHA.N\AppData\Local\Continuum\anaconda3\envs\face\lib\site-packages\keras\utils\io_utils.py", line 186, in __init__
    self.data = h5py.File(path, mode=mode)
  File "C:\Users\PARTHA.N\AppData\Local\Continuum\anaconda3\envs\face\lib\site-packages\h5py\_hl\files.py", line 312, in __init__
    fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr)
  File "C:\Users\PARTHA.N\AppData\Local\Continuum\anaconda3\envs\face\lib\site-packages\h5py\_hl\files.py", line 142, in make_fid
    fid = h5f.open(name, flags, fapl=fapl)
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py\h5f.pyx", line 78, in h5py.h5f.open
OSError: Unable to open file (truncated file: eof = 38486016, sblock->base_addr = 0, stored_eof = 72708080)

For loading the model, I'm doing a base load_model call
from keras.models import load_model
model = load_model('model.hdf5')

To save & download the model from Google Colab I'm using the following snippet.
# save model
model.save('model.hdf5')

# download model
from google.colab import files
files.download('model.hdf5')

I get the following error in Google colb at the line files.download() after the file is downloaded.
----------------------------------------
Exception happened during processing of request from ('::ffff:172.28.0.1', 47132, 0, 0)
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 317, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 348, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 721, in __init__
    self.handle()
  File "/usr/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "/usr/lib/python3.6/http/server.py", line 639, in do_GET
    self.copyfile(f, self.wfile)
  File "/usr/lib/python3.6/http/server.py", line 800, in copyfile
    shutil.copyfileobj(source, outputfile)
  File "/usr/lib/python3.6/shutil.py", line 82, in copyfileobj
    fdst.write(buf)
  File "/usr/lib/python3.6/socketserver.py", line 800, in write
    self._sock.sendall(b)
ConnectionResetError: [Errno 104] Connection reset by peer
----------------------------------------

Answer: I did face the same issue, what I did differently was to download the files from the files manager instead and the same worked just fine.
Click on the little arrow on the top left corner of the screen just below the colab sign looks something like

Then you will need to click on the files and navigate to the required file right click and download the required file. This worked better for me and there was no connection error, which was the case in files.download method
Comment: I didn't know we could do that. Thanks.
Answer: Coming from the description here

"Connection reset by peer" is the TCP/IP equivalent of slamming the
  phone back on the hook. It's more polite than merely not replying,
  leaving one hanging. But it's not the FIN-ACK expected of the truly
  polite TCP/IP converseur
Answer: Looks like there was some issue with the internet connection. I switched to another WiFi, and it worked fine.
The question sounds silly now, but keeping it, and answering this in hopes that it helps someone who comes across the same problem.


convert column to varchar in oracle which is mysql longtext

Question: i have a insert statement pulling data from db link.
<code>insert into table (a,b,c)
    select a,b,c from table@mysqldb;
</code>
here column c is long type in mysql and in oracle its varchar
i tried to cast as  varchar, substr(c, 1,2400), UTL_RAW.CAST_TO_VARCHAR2,dbms_lob.substr
 none of them are working on oracle side.
tried cast on mysql read part no use.
Can someone tell me how to do this. Here Iam trying to convert long to varchar. we cannot load as clob as this table is used in many places and we cannot change things at so many places
Thanks.
Comment: What error do you get? (I'm guessing that the command is executed within Oracle, right?)
Comment: Yes iam running it on oracle , when tried with substr
ORA-01461: can bind a LONG value only for insert into a LONG column
Comment: What do you get if you execute `select a,b,c from table@mysqldb;`?
Comment: well this is run inside a proc, we cannot directly query the mysql db we dont have access to it.
Comment: I was thinking about running the query from within Oracle (e.g. using SQL-Developer or the like), not MySQL.
Comment: yes i was trying to run through sql develoer it throws error"connection description for remote database not found", my user doesn't have access to run
Comment: Your SQL-Developer will not be able to access a connection unless you OPEN it. (_New Connection_).
Comment: I dont have any details about source system its not in our visibility
Answer: i had to convert the target column to clob to handle this scenario


What are some tips for battling forearm fatigue for performing long passages of fast notes (keyboard)?

Question: I am unable to play, for example Chopin etudes (most of them) and Fantaisie-Impromptu because less than 30 seconds in, my forearms fatigue. I slow down a lot and it is physically painful to proceed even at slower speeds.
I can play any short passage at full speed, as long as I start from full physical rest. I don't have a problem with accuracy in general - but I do lose accuracy once I become sore.
Many say that it takes getting used to over time, or I'll just get physically stronger, as in working out everyday. I have pushed hard on these kinds of pieces, for weeks at a time, and I never improved physically - just as sore as always. So I finally ditched them, and resorted to slower pieces or those with fast passages but give the performer "breathing room".
What do you suggest? Is there anything I can do in the gym for this, if anything?
(As an aside, I also suffer from forearm fatigue (left arm) when playing guitar when there are enough bar chords.)

Thank you very much for all of your responses. I will try the suggestions you provided. I hope that I do not have a medical condition that needs dire attention.
Comment: Not an anwser per se, but technique has very little to do with actual _strength_, so please don't approach this as if it were a "sport". Weight training will not help you acquire the requisite technique. The ability to play fast for extended periods of time comes from using _less_ force/muscular strength, not more.
Comment: I didn't mean for it to come across that way, so now, I'm interested in how to use less force/muscle to be able to play fast for extended periods.
Comment: Yes, I wouldn't think of strength when describing Chopin's Fantasie-Impromptu - that's all about delicacy.  Now, some of the Etudes (I'm looking at you, Op.25#10) are much more physically demanding.  I was warned by one of my early teachers not to even attempt playing that one at full tempo - one of her promising former students tore a ligament in his wrist doing that and basically ended his career.  I don't doubt it - even playing slowly that piece is painful on the arms.
Comment: I knew an organist once who swore by the [Alexander Technique](https://en.wikipedia.org/wiki/Alexander_technique), but mileage varies.
Answer: You don't want to "push hard", that's more likely to result in injury than in more endurance. As soon as your muscles start to feel tired, you should take a break.
Here are some tips on managing your endurance:

Take care of your general health. Eat right, stay hydrated, get some cardiovascular excercise, and get plenty of sleep.
Use proper technique. Make sure your ergonomics are correct, make sure you have correct posture, make sure you have the correct finger, hand, and arm positioning, use the minimum pressure necessary, don't over-exert yourself. If you are not sure what the correct technique is, you should discuss with your teacher, find a teacher, or at least research extensively.
Stay relaxed. Make sure your shoulders are low and relaxed, make sure your face isn't tight. Breathe slowly and deeply.
Build up slowly. None of your muscles can change instantly. You have to give your body plenty of time. Physically, the intensity and/or length of your playing should not increase more than 10% per week if you want to avoid injury. You can push that a bit if you are young and in shape, but it sounds like in your case you need to back off first and then ramp back up more slowly than you would like. This will probably require mental fortitude and self-discipline.
Warm up and cool down. Find some simple excercises and learn to play them solidly so you can ignore what your fingers are doing and focus on the rest of your body while you play them. You want to pay attention to your ergonomics, technique, breathing, and relaxation while you play your warmup exercises. This way you can program your body to be relaxed while you are playing.
Listen to your body and be aware. Fine motor skills and endurance are not about muscle strength. It's about muscle efficiency, which involves minimum effort and ideal motion. Muscle tone and strength are involved, but building raw strength is actually counter-productive for speed. Speed comes from relaxation, not from effort.
Adjust your playing to suit your body and your needs. For example, consider not playing barre chords at all. I keep my wrist high and my thumb over the top on guitar to facilitate bending, and that means I either change my wrist position dramatically for barre chords, or I don't play them. I don't play them. I fret with my thumb and emphasize the middle four strings. Another thing I do is I play at a speed that is comfortable for me and don't worry about speeding up. It's my personal "interpretation" of what I'm playing. Brainstorm on what you can change to make things work for you.
Look at other things you do with your hands. If you are typing on a computer keyboard most of the day, try to reduce how much you have to type and pay attention to your typing ergonomics. The same goes for using a smart phone or tablet. Consider any other areas where you are using your fine motor muscles.

Keep in mind that an injury can put you out of commision for months, years, or who knows how long. My brother was a brilliant keyboard player, but between being in a band, playing extensively on his own, and typing all day as a software analyst, he injured himself. He worked with doctors for a while but they all said he had to stop. He sold me all his instruments, quit his job, and became a chef (no typing). He's a brilliant chef, but I sure miss his keyboard playing. If you don't want to quit music for good and change careers, take note.
Answer: This part sounds very familiar to me:

(As an aside, I also suffer from forearm fatigue (left arm) when playing guitar when there are enough bar chords.)

Fatigue (assuming we're no longer beginners) doesn't always occur because the muscles are weak; it can be caused by different sets of muscles opposing each other. (If so, strength exercises won't help.)
If your hand is already tense then moving one of the fingers becomes harder, because the muscle responsible is being opposed by the other muscle that acts on the opposite side of the joint.
This hand tension isn't deliberate; it can be something you're not aware of. It might not happen at all on easy passages but crops up when you launch into a fast passage or when you're tense because you're trying too hard in general.
The only thing I can recommend (because it seemed to work for me) is think about movement, practice something slowly, all the while thinking about the "strings and pulleys" which move the fingers. Think about which muscle is doing what, and whether any part of the hand is more tense than it needs to be. Gradually speed up a troublesome passage or exercise and see what speed you're playing at where the trouble starts, see if there's any awkwardness at this stage causing the trouble.
By the way your mention of forearms is a dead giveaway. This is where the flexor and extensor muscles for the fingers are - tendons run right through the wrist and palm to the fingers. (The ones that spread and narrow the fingers are different, they're in the hand itself. They can suffer from similar troubles of course.)
(The above is based on my guitar playing. My piano playing is to a much lower technical level but I believe the same arguments of economy apply.)
Answer: You've given a clear hint in your question that it's more likely technique than raw strength. You say it happens very quickly (30 seconds). I bet that if you are playing at a comfortable, slow place, you can play for much, much longer, and play many more keystrokes overall.
Instead focusing on building up strength, focus on relaxing your muscles when you play fast.
Before you start playing, take a couple of deep breathes and make sure your hands, arms, and shoulders are relaxed. Then start playing at a pace you know you can play at (ideally with a metronome or drum track). Then take a few more deep breathes, and play it slightly faster. Repeat until you can't keep the tension away, then stop before you get fatigued.
Doing exercises like that (and there are many other options) will help you build up your speed. If you don't enjoy this method, look up other ways to build speed up slowly. But the key will be learning to play as relaxed in a fast passage as you are in a slow passage. Good luck!
Answer: I'll take a guess: did you learn your "technique" by using Hanon every day, then Czerny? Or did you start by assuming it was "obvious" that you play the piano by pressing the keys with your fingers? That will only get you so far, and pieces like the Chopin etudes will stay out of reach till you back-track and learn a better way. If your shoulders were aching, then you are "doing it right", but you need more practice. If your forearms are aching, that strongly suggests you are "doing it wrong," and practicing harder in the same way will either achieve little, or in the worst case lead to long-term injury.
See the videos in this thread:
Please explain hand rotation in playing the piano
playing-the-piano
And the "how to play brilliantly fast" video in
Fingering for some arpeggios on piano (Final Fantasy prelude)
Answer: Barring any physical/medical issues, you should simply relax. It's the hardest thing to do, but will yield the most benefits. Agility, speed, power, and longevity all require relaxation more than any amount of physical strength or finger dexterity. Your spine should be your tree trunk, and try to feel the weight of your forearm at the tips of your fingers as you play. Imagine a fishing hook – the hook is firm, but the fishing line is virtually weightless. The hook is your finger tip, and the line is everything between your finger tip and shoulder. Pretend that you have no muscles between those two points. Keep your shoulders relaxed, and your wrists supple. A good exercise is to play something chordal (like Bach chorales or basic cadences) so that you have multiple "fish hooks" to allow you to relax more. And practice everything slowly, very slowly. Velocity is a by-product of slow practicing.
Try this: In as relaxed a manner as you can, play a forte chord with both hands, any chord, and hold it. Take note of the tension and stiffness at any points between your fingertips and shoulders. Now lift your hands off of the keyboard. Is there much difference in the tension and stiffness? If you don't feel a noticeable reduction in tension while you were holding down the keys, then it means you're too tense, and you're not transferring the weight to your fingertips. It means you're playing "on the surface" of the keys, and using your forearm/hand/finger muscles to hold up your arm even while the keys are depressed. Obviously, you can't maintain this kind of tension for long, and it will dramatically limit your flexibility and endurance, among other things. Play that chord again, and methodically eliminate the tension at each point until the fish hooks are the only things that are firm, and everything else as limp as possible. Do you feel the weight of your arms on your fingertips? If it weren't for your fingertips, your whole arm should fall off the keyboard. Now lift your arms up again. Notice the difference now? This principle applies to even fast playing, and is absolutely crucial for advancement.
Having said all that, I wonder if there is a medical explanation for why you're feeling the level of physical pain and fatigue that you're experiencing. You mentioned that this also happened with your left hand on guitar. Although stiffness, discomfort, and fatigue are not uncommon at certain stages, the kind of pain you're describing leads me to believe something may be wrong. If the above musical prescription doesn't help, then I would suggest seeing a doctor. Best of luck.
Answer: Are you sure you don't have any physical conditions, such as tendonitis?  If you're describing pain, even once you slow down, and the inability to progress, that might be a sign that you should at least visit your primary doctor, if not a hand surgeon.


How to convert np array to StringIO

Question: I ran into a problem while trying to stream images over a local network. On the system with the camera I can see the images perfectly fine and I can establish a socket between the two computers. I want to send the data as a StringIO to attach the size of the current image in the String.
However my computer tells me, it cannot convert a np array  to a str .
Instead I sent it as a BytesIO , but the client cannot reconvert this data.
Is there a way to send the iages as a StringIO or to reconvert the BytesIO?
Comment: you have to send image as string or bytes, and use `StringIO` or `BytesIO` only in client to receive it and use it to display (without saving on disk). If you need help then show code. BTW: if you really want to use StringIO then you have to get string from it - using `read()` - and send this string, not StringIO.
Comment: BTW. numpy array has `tostring()` and `tobytes()` which you have to use it create string and send it. And client can use `numpy.fromstring()` to convert this string to array again. And later you may need `StringIO` only when functions need file-like object to display image.
Comment: BTW: on GitHub I have examples which get image from camera using `cv2` and use socket to send it to client. I don't need `StringIO` for this but only `pickle` - this way client know how many data it has to receive and I don't have to send this information before image. https://github.com/furas/python-examples/tree/master/cv2/socket-send-image
Comment: BTW: sockets sends only bytes and usually server has to `encode()` string to bytes before sending, and client has to `decode()` bytes to string after receiving. And you don't have to send size and image in one string in one `send()`. You can first `send()` only size, and later `send()` data because socket doesn't care how you send it. Socket can send it partially even if you create one string.
Answer: I forgot to encode correctly, as furas pointed out. I had to add the size as a header via header = '{0}:'.format(packet_size) ,  header = bytes(header.encode()) and out += header.
I modeled my approach after this project: https://github.com/sabjorn/NumpySocket
furas's way should work as well, but my approach was closer to the previously mentioned project.

How to convert np array to StringIO


Sampling in discrete distribution

Question: At the moment I'm working with an algorithm that calculates probabilities $Z$ for a finite sequence of data points $X= \left\{ x_1,x_2,...,x_n \right\}$ using an expression like:
$p(Z_i| X_i,\theta) = \frac{1}{\phi}f(X_i,\theta)$,
where $\phi$ is a normalising constant such that $\sum_n p(Z_n|X_n) = 1$. (i.e. $f(X_i,\theta)$ gives us a number, we have a sequence of numbers and we normalise over all of them by summing and dividing). The next part of the algorithm chooses one of the $x$'s with weighted probability.
At the moment, it is possible to enumerate the sample space and calculate $\phi$, but is it possible to have some kind of MCMC approach, to avoid having to do this? So sampling a few positions, and evaluating $p(Z_i|X_i)$ only at those positions? I can see how MCMC works in the continuous case, but not sure if it's applicable here.
If it makes any difference, the values of $f(X_i,\theta)$ can have a lot of variation (e.g. 0.08, 0.70, 0.26, 64.00, 0.79, 7.11, 0.01, etc.) so areas of high probability can be separated by regions of low probability.
Thanks in advance.
Comment: I don't see how this problem is solvable without making additional assumptions about $f$. For instance, suppose the sample space has $10^{100}$ elements, the values of $f$ just happen to sum to unity, but exactly one value of $f$ equals $1 - 10^{-100}$. In other words, most of the probability is concentrated at an extremely small subset. Even a long MCMC run has little chance of encountering such a subset and so its results will be grievously wrong.
Comment: Is your end objective to generate a random sample of the $x_i$ from the distribution $f$ without having to calculate the normalizing constant?  Or is calculating the normalizing constant itself your end objective?
Comment: Thanks for your replies.
@whuber I was coming to a similar conclusion, but your example clarifies that. In early iterations of the algorithm $f$ might be expected to have less variation - would MCMC be viable in that sort of situation? And if so, what sort of method could be used, as I'm having trouble finding eg Metropolis-Hastings over a discrete distribution?
jbowman - Yes, the end objective is to choose an $x_i$ with weighted probability/sample from $f$, preferably without calculating the normalisation constant by evaluating $f$ at each $x_i$.
Answer: Yes, you can generate random samples from $\{x_i\}_{i=1}^n$ where the associated probabilities $f(x_i)$ are known up to a multiplicative constant (the constant of integration (COI) using MCMC.  However, you do have to be able to calculate $f(x_i)$ (without the COI) for all $i$ should $x_i$ be proposed.  If your sample is large enough relative to $n$, you won't be saving yourself anything by not just calculating the COI by summing $f$ over all $i$.
Here's an example in R that does this for $n = 10$, using an independence sampler for the proposal (which simplifies the calculation of the acceptance probability $\alpha$).  The proposal is for an index $j \in \{1, \dots, n\}$, although what is stored as the sampled value is the value of $x$ associated with the current index $i$ (if the proposal is rejected) or the accepted proposal $j$.
<code># Example x, fx
x <- c("a","b","c","d","e","f","g","h","i","j")
fx <- 0.01*(2^(0:9))   # Note this is unnormalized!

# i is the "current" index
# j is the "proposal" index
# y is the output stream of samples from x

# Initialization / allocation
y <- rep(0, 10000)
i <- sample(1:10,1)

# MCMC (Metropolis-Hastings)
u01 <- runif(length(y))
for (k in 1:length(y)) {
   j <- sample(1:10,1)  # Independence sampler
   alpha <- fx[j] / fx[i]
   if (u01[k] <= alpha) {
      y[k] <- x[j]
      i <- j
   } else {
      y[k] <- x[i]
   }
}

# Compare sample frequencies to true probabilities
SampleFreq <- table(y)/length(y)
df <- data.frame(Value=names(SampleFreq),
                 Sample.Freq=as.numeric(SampleFreq),
                 True.Prob=fx/sum(fx))
> df
   Value Sample.Freq True.Prob
1      a      0.0009 0.0009775
2      b      0.0022 0.0019550
3      c      0.0040 0.0039101
4      d      0.0093 0.0078201
5      e      0.0166 0.0156403
6      f      0.0345 0.0312805
7      g      0.0678 0.0625611
8      h      0.1282 0.1251222
9      i      0.2443 0.2502444
10     j      0.4922 0.5004888
</code>

Sampling in discrete distribution


Firefox policy set "page blocked" text

Question: Friends,
i have restricted access to web pages with a policy.json file with WebsiteFilter block/exception.
How can I change the text shown when surfing to blocked pages? The default message has no option to go back to the homepage, which basically locks the browser forever when in kiosk mode (no navigation buttons).
TIA!
Answer: To customize the blocked page message, locate the policy.json or relevant configuration file, create a custom error page with a homepage link, update the configuration to point to your custom error page, test your changes, and seek assistance if needed.
Comment: "update the configuration to point to your custom error page" - what would the policy.json entry for that be?

Firefox policy set "page blocked" text


Using nested if statements vs logical operator && in c++

Question: Let us say I have an integer array representing the chess pieces on a board;
int board[8][8];

In my chess game, I am currently coding a generator function that will return an integer vector of all legal moves.
Naturally, I will be using if statements
I am at a point where I need to check a certain element in the board relative to a piece on the board
For example, If I have a pawn piece;
board[row][col] == 'p';

I need to generate [row+1][col], [row+2][col] and in some cases if it can attack a piece, a change in column too.
But if a piece is on any edge of the board, board[row+1][col] will return be index out of range
For that reason I need an extra if statement.
My question is, shall i use:
if (pieceisnotonedge && board[row+1][col] == 0)

or
if (pieceisnotonedge)
{
    if (board[row+1][col] == 0)
}

For the first example, if pieceisnotonedge returns false, will it also check the next condition? Because if it does, then I am in trouble.
Comment: This doesn't address the question, but for pawn moves you don't have to check `row + 1`. A pawn can never be on the 8th rank; `row + 1` is always valid.
Comment: The answer to this question depends on the AND operator. Is it a built-in operator or a user-defined overload? The behavior is different.
Comment: Yes, you are absolutely right. Number one: Starting stages of the game so i did not add pawn promotion. number two was it also applies to a column. That is if a pawn is on the horizontal edge i dont need to check if board[row+1][col+1] if a piece is present. And the same rule applies for all the pieces.
Answer:
For the first example, if pieceisnotonedge returns false, will it also
check the next condition?

No, it will not. Because the build-in logical operators do short-circuiting. From cppreference.com:

Builtin operators && and || perform short-circuit evaluation (do not
evaluate the second operand if the result is known after evaluating
the first), but overloaded operators behave like a regular function
calls and always evaluate both operands

Therefore, in
if (pieceisnotonedge && board[row+1][col] == 0)

if the pieceisnotonedge is false, the second will not be evaluated. Therefore, having a nested ifs is redundant, and you can go with the first version.
Comment: Noting that this question is tagged C++, the short-circuiting by operators `&&` and `||` does not occur for user-defined overloads of `operator&&()` and `operator||()`.    If such overloads are provided and called,  then an expression of the form `a && b` or of `a || b` WILL evaluate both `a` and `b`, rather than short-circuiting if `a` is true.
Comment: @AryanParekh Of course, you can. In C++ one can also [overload `operator&&`](https://stackoverflow.com/questions/25913237/is-there-actually-a-reason-why-overloaded-and-dont-short-circuit).  Peter was mentioning that in case you [have overloaded the `operator&&`](https://en.cppreference.com/w/cpp/language/operators), in the code, the behaviour is different/ order of evaluation is not guaranteed, since it behaves like a normal function call, and will be evaluating both conditions (This is same for `operator||` overloading). I hope, you have not overloaded the `operator&&` in your code.
Comment: @Peter Of course, it will. I have only emphasized the sentence, which is relevant to the question (Assuming that the OP is not overloading them). However, it is there in the citation, what I have added. One should read it completely.
Comment: I am confused as I am new to the language, should I use it, in c++
Answer:
For the first example, if pieceisnotonedge returns false, will it also check the next condition?

No. It will "short-circuit" because if the first condition is false, checking the conditions after it is unnecessary. Read more here and here.
This is guranteed by the C++ standard:

7.6.14
... && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

Note that, for || this is opposite, that is, if the first condition is "true", then checking the conditions afterwards is unnecessary

Shall i use; or...

Both are same, if you have a short if statement (with only two conditions), I would suggest using the first approach. In terms of efficiency there is no difference and you can verify this by looking at the generated assembly for both cases on godbolt
Comment: No. There will be no difference at all. The efficiency will be exactly the same
Comment: Thank you for this! is there any difference in its effeciency, that means, is there any difference in the time taken for both the examples, because it can perform the generator function well more than 50,000 times in my chess engine!
Comment: @AryanParekh If you are in doubt, you can try both on [Compiler Explorer](https://godbolt.org/) and compare the generated assembly. Even if you do not read assembly naturally a "pessimization" will usually be quite obvious simply based on the amount of code generated.
Answer: For the shown code there is no difference, both board[row+1][col] == 0 are only evaluated if pieceisnotonedge is true.
If you should use one or the other, cannot be said be in general, as it depends on other factors (like semantic, readability, …) too.
If you e.g. want to have an action that it done if either pieceisnotonedge or board[row+1][col] == 0 is false, then you probably would use &&, because then you can write:
if (pieceisnotonedge && board[row+1][col] == 0) {
} else {
  // do something else
}

with your other style you would need to write:
if (pieceisnotonedge){
    if (board[row+1][col] == 0) {
      // do something else
    }
} else {
   // do something else
}

In general, your first aim should be to have readable code. While pieceisnotonedge && board[row+1][col] == 0 easy to read, more complex expressions might not be. So you would decide that on a case by case basis, if you want to use one expression or multiple if.
Answer:
For the first example, if pieceisnotonedge returns false, will it also check the next condition?

No. It will stop immediately after pieceisnotonedge is evaluated to false. There is no subsequent check for the remainder condition board[row+1][col] == 0
You can use nested if as the second code as well - no difference. It's just a matter of what code would look clearer.
Comment: @Spektre source please?
Comment: not really in this case it does not matter but if you do `if (a && b && c)` then there is no guarantee it will be evaluated in order `a,b,c` and also no guarantee the execution will stop on first false ... so if conditions are not "order" safe (like array range checks) it should be nested `if`s and if the conditions are safe it can be both versions....
Comment: experience in past (like 10 years ago)... on MCU: GCC U-Keil and x86 BCC32  (BCB 4,5)... However newer versions might behave differently


TypoScript Menu with manual columns

Question: I have a typical grid-based dropdown menu with predefined columns, as you find them in foundation, bootstrap etc.
Now I'd like to manually let the editor control which items go in which column – without having to hardwire too many pids or creating additional pagetree nodes (Pages like "Group for column 1") in the BE.
How do I do that with TypoScript?
Answer: The page type "Spacer" or "Separator" (doktype 199) is perfect for this:

It can be rendered as html content, using the SPC state. Editors can place it in their pagetree where they want to split up columns.
lib.main_nav_1 = HMENU
lib.main_nav_1 {
  special = directory
  special.value = {$pidEntryPoint}
  wrap =

|

  1 = TMENU
  1 {
    expAll = 1
    NO {
      text = nav_title // title
      wrapItemAndSub=
|

    }
    ACT < .NO
    ACT {
      wrapItemAndSub =
|

    }
    ACT = 1
    CUR < .NO
    CUR {
      wrapItemAndSub =
|

    }
    CUR = 1
    SPC = 1
    SPC {
      doNotLinkIt = 1
      doNotShowLink = 1
      allWrap =

|

    }
  }
  2 < .1
  2 {
    wrap =
|

    SPC = 0
  }
}
}

TypoScript Menu with manual columns