DropDownButton não funciona ao buscar do Db async Future usando o Widget: Future Builder Flutter

Question: Exceção que aparece:

════════ Exception caught by widgets library ══════════
The following was thrown building FutureBuilder(dirty, state:
  _FutureBuilderState#74679): type '(Cidade) => DropdownMenuItem' is not a subtype of type '(Map) => DropdownMenuItem' of 'f'

Uso a Classe  Stateful:
class Sincronismo extends StatefulWidget {
  @override
  _SincronismoState createState() => _SincronismoState();
}

class _SincronismoState extends State<Sincronismo> {
 // return Users.fromJson(jsonresponse[0]);

**Aqui pego os dados da Classe DB:**

  getCidade( ) async {
    DBAvaliacoes db = new DBAvaliacoes();
    List city = await db.getCitys();
    return city;

  }

  Cidade selectedCountry;

  Future _future;

  @override
  void initState() {
    _future = getCidade();
    super.initState();

 }
  @override
  Widget build(BuildContext context) {

    return  FutureBuilder (
        future: _future ,
        builder: (context, snapshot){
          if(snapshot.hasError)
            return Text(snapshot.error);

          if (snapshot.hasData) {
            return  DropdownButtonFormField(
              decoration: new InputDecoration(icon: Icon(Icons.language)), //, color: Colors.white10
              value: selectedCountry,

Estoura a exceção quando chega aqui:
items: snapshot.data.map<DropdownMenuItem<Cidade>>((Cidade city) {

                return  DropdownMenuItem<Cidade>(

                  value: city,
                  child: Text(city.descricao_cidade, style: TextStyle(color: Color.fromRGBO(58, 66, 46, .9))),

                );
              })
                  .toList(),

              onChanged: (Cidade newValue) {
                setState(() => selectedCountry = newValue);
                // selectedCountry = newValue;
                print(newValue.id);
                print(newValue.descricao_cidade);
              },
            );

          }

          else{
            return CircularProgressIndicator();
          }
        }

      /**********************/
    );

  }}

Comment: Dentro do `db. getCitys()` vc faz algum tratamento para trazer o Objeto Cidade? Se vc não faz esse tratamento, ele está voltando um Map e não o model
Answer: Consegui, era pq o Future manda um MAP, converti o getCidades pra um Map do Objeto Cidade:
getCidadess() async{

    DBAvaliacoes db = new DBAvaliacoes();
    List cidades = await db.getCitys();
    List<Cidade> listaTemporaria = List<Cidade>();
    for(int i = 0; i< cidades.length; i++){
      Cidade c = Cidade.fromMap(cidades[i]);
      listaTemporaria.add(c);
    }
    setState(() {
      _listaCidades = listaTemporaria;
      _dropdownMenuItems = buildDropdownMenuItems(_listaCidades);
      _selectedCidade = _dropdownMenuItems[0].value;
    });
    listaTemporaria = null;
    print(_listaCidades.toString());

  }

Obrigado Matheus Ribeiro


Show that T is compact if $T^*T$ is compact

Question:
Let $H$ be a Hilbert space and $T: H\to H$ be a bounded linear operator. $T^*$ is the Hilbert adjoint operator. Show that $T$ is compact if $T^*T$ is compact.

I am stuck with this proof. Any help would be appreciated.
Comment: $\lVert T(x) - T(y)\rVert^2 = \langle x-y, T^\ast T (x-y)\rangle$
Answer: Let $\{ x_n \}_n $ be a sequence, bounded say by $M>0$. If $T^*T$ is compact, there exist a subsequence $\{ T^*T(x_{n_k})\}_k$ that converges and hence is Cauchy. Let $k<k' \in \mathbb{N}$, then
\begin{align*}
\|T(x_{n_k}) - T(x_{n_{k'}}) \|^2 & =\| T(x_{n_k}-x_{n_{k'}}) \|^2 \\
& = \langle T(x_{n_k}-x_{n_{k'}}), T(x_{n_k}-x_{n_{k'}}) \rangle \\
& =\langle x_{n_k}-x_{n_{k'}}, T^*T(x_{n_k}-x_{n_{k'}}) \rangle \\
& \leq \| x_{n_k}-x_{n_{k'}}\| \|T^*T(x_{n_k}-x_{n_{k'}}) \| \\
& \leq 2M \| T^*T(x_{n_k})-T^*T(x_{n_{k'}}) \| \underset{k,k'\to \infty }{\longrightarrow} 0,
\end{align*}
Therefore the sequence $\{ T(x_{n_k})\}_k$ is Cauchy and thus convergent. Since the image under $T$ of any bounded sequence admits a convergent subsequence, indeed $T$ is a compact operator.


Como vincular um back em node para um front em react recharts?

Question: Preciso fazer um CRUD que é vinculada em um react recharts usando gráficos, procurei no youtube e não consegui achar de jeito nenhum como posso vincular o back em node com o front em react recharts com os dados em um gráfico, se alguém tiver uma dica de conteúdo ficarei muito agradecido.
Aqui está o CRUD que é uma tela de cadastro para as seleções da copa:
<code>const express = require('express');

const server = express();

server.use(express.json());

const times = ['Brasil', 'Alemanha', 'Dinamarca', 'Australia'];

// Retorna um time
server.get('/times/:index', (req,res) => {
    const { index } = req.params

    return res.json(times[index]);
});

// Retorna todos os times
server.get('/times', (req, res) => {
    return res.json(times);

});

// Criar um novo time
server.post('/times', (req,res) => {
    const { name } = req.body;
    times.push(name);

    return res.json(times);
});

// Atualizar um novo time
server.put('/times/:index', (req, res) => {
    const { index } = req.params;
    const { name } = req.body;

    times[index] = name;

    return res.json(times);

});

// Deletar um time
server.delete('/times/:index', (req,res) => {
    const { index } = req.params;

    times.splice(index, 1);
    return res.json({ message: "O time foi deletado" });

});

server.listen(3000);
</code>
Ela já está vinculada ao banco de dados, agora como posso colocar os dados no gráfico em React?
Answer: Você vai precisar criar uma apliação em reactjs, para fazer as requisições no seu back pode utilizar o axios ou até mesmo o fetch.
O que vier de response do seu back você colocar no recharts, tem até exemplos de como fazer isso no próprio site eles.
A direção é essa, pelo que entendi da sua pergunta.


How to find the expected distance between two uniformly distributed points?

Question: If I were to define the coordinates $(X_{1},Y_{1})$ and $(X_{2},Y_{2})$ where
$$X_{1},X_{2} \sim \text{Unif}(0,30)\text{ and }Y_{1},Y_{2} \sim \text{Unif}(0,40).$$
How would I find the expected value of the distance between them?
I was thinking, since the distance is calculated by $\sqrt{(X_{1}-X_{2})^{2} + (Y_{1}-Y_{2})^{2}})$ would the expected value just be $(1/30 + 1/30)^2 + (1/40+1/40)^2$?
Comment: Equivalent question on the math site: [Average Distance Between Random Points in a Rectangle](http://math.stackexchange.com/q/208666/7003). A related question: [Probability that uniformly random points in a rectangle have Euclidean distance less than a given threshold](http://stats.stackexchange.com/q/22488/2970). (Unfortunately, I never got around to taking up @whuber on his suggestions there. I'll try to find some time to do that.)
Comment: Thanks for those links, @cardinal. Although the math version does not explain the answer--it just presents it--it contains links to one derivation, which is worth reviewing.
Comment: Your LaTeX code was not rendering correctly. I hope my fix is what you intended
Comment: Almost, but it helped get me there in the end, many thanks.
Answer: It is plain, from looking at the question geometrically, that the expected distance between two independent, uniform, random points within a convex set is going to be a little less than half its diameter.  (It should be less because it's relatively rare for the two points to be located within extreme areas like corners and more often the case they will be near the center, where they are close.)  Since the diameter of this rectangle is $50$, by this reasoning alone we would anticipate the answer to be a little less than $25$.
An exact answer is obtained from the definition of expectation as the probability-weighted value of the distance.  In general, consider a rectangle of sides $1$ and $\lambda$; we will scale it up to the correct size afterwards (by setting $\lambda = 40/30$ and multiplying the expectation by $30$).  For this rectangle, using coordinates $(x,y)$, the uniform probability density is $\frac{1}{\lambda}dx dy$. The mean distance within this rectangle then is given by
$$\int_0^\lambda\int_0^1\int_0^\lambda\int_0^1 \sqrt{(x_1-x_2)^2+(y_1-y_2)^2} \frac{1}{\lambda}dx_1  dy_1 \frac{1}{\lambda} dx_2 dy_2.$$
Using elementary integration methods this is straightforward but painful to do; I employed a computer algebra system (Mathematica) to obtain the answer
$$[2+2 \lambda ^5-2 \sqrt{1+\lambda ^2}+6 \lambda ^2 \sqrt{1+\lambda ^2}-2 \lambda ^4 \sqrt{1+\lambda ^2} +5 \lambda  \text{ArcSinh}(\lambda)+5 \lambda ^4 \log\left(\frac{1+\sqrt{1+\lambda ^2}}{\lambda }\right)]/(30\lambda^2).$$
The presence of $\sqrt{1+\lambda^2}$ in many of these terms is no surprise: it is the diameter of the rectangle (the maximum possible distance between any two points within it).  The appearance of logarithms (which includes the arcsinh) is also unsurprising if you have ever investigated average distances within simple plane figures: somehow it always shows up (a hint of this appears in integral of the secant function).  Incidentally, the presence of $30$ in the denominator has nothing to do with the specifics of the problem involving a rectangle of sides $30$ and $40$: it's a universal constant.)
With $\lambda=4/3$ and scaling up by a factor of $30$, this evaluates to $\frac{1}{108} (871+960 \log(2)+405 \log(3)) \approx 18.345919\ldots$.

One way to understand the situation more deeply is to plot the mean distance relative to the diameter of $\sqrt{1+\lambda^2}$ for varying values of $\lambda$. For extreme values (near $0$ or much greater than $1$), the rectangle becomes essentially one-dimensional and a more elementary integration indicates the mean distance should reduce to one-third the diameter.  Also, because the shapes of rectangles with $\lambda$ and $1/\lambda$ are the same, it is natural to plot the result on a logarithmic scale of $\lambda$, where it must be symmetric about $\lambda=1$ (the square).  Here it is:

With this we learn a rule of thumb: the mean distance within a rectangle is between $1/3 \approx 0.33$ and (approximately) $0.37$ of its diameter, with the larger values associated with squarish rectangles and the smaller values associated with long skinny (linear) rectangles.  The midpoint between these extremes is achieved roughly for rectangles with aspect ratios of $3:1$.  With this rule in mind, you can just glance at a rectangle and estimate its mean distance to two significant figures.
Comment: In the spirit of [this](http://stats.stackexchange.com/questions/29121/intuitive-explanation-of-unit-root/29129#comment55107_29129), I wish you would have started this answer with "It is *plane* ..." (+1)
Comment: @curious_cat You don't need software for that: this is the limiting mean distance as the rectangle maintains a width of $1$ and its height shrinks to $0$; the value is $1/3$.
Comment: Should that be "diagonal" instead of "diameter"? Sorry if I am nitpicking.
Comment: @curious_cat By definition, the diameter of a set of points (in any metric space) is the supremum of the distances between any two points in it. For a rectangle it is (obviously) the length of a diagonal.
Comment: Thanks! I did not realize that. I was using a naive concept of diameter.
Comment: As an aside: For all rectangles of given area would the mean distance be minimized for a square?
Comment: @curious_cat No, because among these rectangles are some that are arbitrarily long. *E.g.*, if we restrict to unit areas, then the rectangle of dimensions $\sqrt{\lambda}$ and $1/\sqrt{\lambda}$ has unit area and aspect ratio $\lambda$.  As we see here, for very large $\lambda$ the mean distance is close to $\lambda/3$, which is unbounded.
Comment: Sorry if I am again confused. But what you just described is the maximization case, isn't it? I was asking about the minimum of the mean distance.
Comment: @curious_cat My apologies--I read your question completely backwards.  Yes, you are correct, and that result can be obtained using the formulas derived here.
Comment: @whuber: It'd be fun to paste your $[2+2 \lambda ^5-2 \sqrt{1+\lambda ^2}+6 \lambda ^2 \sqrt{1+\lambda ^2}-2 \lambda ^4 \sqrt{1+\lambda ^2} +5 \lambda  \text{ArcSinh}(\lambda)+5 \lambda ^4 \log\left(\frac{1+\sqrt{1+\lambda ^2}}{\lambda }\right)]/(30\lambda^2).$
 into Mathematica and ask it to minimize for $\lambda$ :) Wonder if it'd get 1.
Answer: <code>##problem
x <- runif(1000000,0,30)
y <- runif(1000000,0,40)
Uniform <- as.data.frame(cbind(x,y))
n <- nrow(Uniform)
catch <- rep(NA,n)
for (i in 2:n) {
      catch[i] <-((x[i+1]-x[i])^2 + (y[i+1]-y[i])^2)^.5
}
mean(catch, na.rm=TRUE)
18.35855
</code>
If I understand correctly what you're looking for, maybe this helps.  You're trying to figure out the distance between to random points, who's X values are generated from unif(0,30) and Y values are generated from a unif (0,40).  I just created a million RV's from each of those to distributions and then bound the x and the y to create a point for each of them.  Then I calculated the distance between point 2 and 1 all the way to the distance between points 1,000,000 and 999,999.  The average distance was 18.35855.  Let me know if this isn't what you were looking for.
Comment: You came fairly close--perhaps by chance. The true answer is $\frac{1}{108} (871+960 \log(2)+405 \log(3))$ = $18.345919\ldots$. Your code has two problems: (1) the iterations are not mutually independent; and (2) to obtain reasonable precision, it ought to be coded to be faster. Why not do the simulation directly, as in `n <- 10^7;
distance <- sqrt((runif(n,0,30)-runif(n,0,30))^2 + (runif(n,0,40)-runif(n,0,40))^2)`. That will get you about four significant figures (in less time), as you can check by computing the standard error `sd(distance) / sqrt(n)`.
Comment: @curious_cat No, the averages would be about the same: but the calculation of the *standard error* would be different. We need that calculation in order to estimate how close the mean is likely to come to the true value. Rather than work out the more complicated SE calculation, it's simpler just to generate pairs of points completely independently of one another, exactly as stipulated in the question. (There are so many ways a simulation can go wrong--I know from experience!--that it's wise to make the simulation mimic the reality as closely as possible.)
Comment: @whuber: Can you explain your #1? e.g. say (Case-I) I drew pairs of random  numbers from any given distribution and calculated differences and took a mean. Versus (Case-II) I kept drawing one number at a time and kept calculating running differences with respect to the last number draw and then averaged. Would the average reported by Case-I and Case-II be systematically different?
Comment: @whuber: Thanks for clarifying. So, if Clark had run his code  longer he might have gotten more decimal places right?
Comment: @curious_cat Yes, but--as usual--with quadratically diminishing returns, which limit the precision of any such simulation. Running it ten times longer (about 20 seconds on my machine) would have achieved four significant figures. The next s.f. would require a run $100$ times longer, or about half an hour. The next one would need two days, etc. A good use for such simulations is to check theoretical calculations; occasionally, when only low precision is needed and no analytical insight into the nature of the solution is desired, a simulation alone will suffice to answer a question.
Comment: @whuber I did wonder after I gave my answer if I had actually been wrong to considier each x and y as independent draws. I probably answered the question too quickly.  And I definitely wrote the loop in an awkward fashion.  I should have done better there too.
Comment: Nevertheless, I think it is an interesting and worthwhile contribution (+1).
Comment: @whuber could you please explain why std error would be different between these two methods? I have a similar issue posted here: http://stats.stackexchange.com/questions/222878/difference-between-two-methods-of-random-point-generation
Comment: @swair Consider the simplest case where one method draws three independent variates $x,y,z$ from a distribution and uses the distances $d(y,x)$ and $d(z,y)$ as a sample of distances. The alternative draws *four* variates $x,y,z,w$ and uses the distances $d(y,x)$ and $d(w,z)$ as a sample of distances. In the second case the two distances are independent. In the first case the two distances are not independent--and likely correlated--because they both are distances from a common point $y$. If $y$ happens to be extreme, then likely both distances will be large: that's positive correlation.


URL Encoding with Volley

Question: Does Android Volley do URL Encoding?
I am trying to do a Get Request and on server side, it seems the URL being sent through is not encoded correctly.
I have been fiddling with my CustomRequest class but am not able to get it working, if it does encoding.
CustomRequest.java:
package com.bidorbuy.app.network;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class CustomRequest extends Request<JSONObject> {

private Response.Listener<JSONObject> listener;
private Map<String, String> params;
private Map<String, String> headers;
Priority priority;

public CustomRequest(String url,
                     Map<String, String> params,
                     Map<String, String> headers,
                     Response.Listener<JSONObject> reponseListener,
                     Response.ErrorListener errorListener,
                     Priority priority)
{
    super(Method.GET, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    this.headers = headers;
    this.priority = priority;
}

public CustomRequest(int method,
                     String url,
                     Map<String, String> params,
                     Map<String, String> headers,
                     Response.Listener<JSONObject> reponseListener,
                     Response.ErrorListener errorListener,
                     Priority priority) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    this.headers = headers;
    this.priority = priority;
}

protected Map<String, String> getParams()
        throws com.android.volley.AuthFailureError {
    return params;
};

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers;
}

@Override
public byte[] getBody() throws AuthFailureError {
    Map<String, String> params = getParams();
    if(params!=null && params.size() > 0){
        return encodeParameters(params, getParamsEncoding());
    }
    return null;
}

private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
    StringBuilder encodedParams = new StringBuilder();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
            encodedParams.append('=');
            encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            encodedParams.append('&');
        }
        return encodedParams.toString().getBytes(paramsEncoding);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
    }
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

}

and then I use the request elsewhere in the app as seen below:
    public void getRequest(String url, Map<String, String> params, final String source) {

    getHeaders(headers);

    CustomRequest jsObjRequest = new CustomRequest(Request.Method.GET, url, params, headers, getReponse(source), createMyReqErrorListener(), Constants.PRIORITY_HIGH);
    queue.add(jsObjRequest);

}

and this is the code i am passing the params through to be used in the network call:
    private void forgotPasswordExecute() {
    forgotPasswordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Map<String, String> params = new HashMap<String, String>();
            LocalBroadcastManager.getInstance(ForgotPasswordActivity.this).registerReceiver(forgotPasswordReceiver, new IntentFilter(Constants.WS_FORGOT_PASSWORD));
            params.put("emailAddress", "firstname.lastname@example.com");

            String url = Constants.FORGOT_PASSWORD_URL;
            request.getRequest(url, params, "ForgotPassword");
            System.out.println("URL is: " + url);
        }
    });
}

I just need some assistance with the encoding of the URL in volley. If volley does not do it, is there another way i could encode the URL and still use Volley?
Thanks
Comment: IMO, you can find a solution at [Volley - POST/GET parameters](http://stackoverflow.com/questions/16626032/volley-post-get-parameters). Pay attention to @Ogre_BGR's and LOG_TAG's answers. Hope this helps!
Answer: Try this , (may be not the best approach)  Direct code which I used in my project. Late answer after 1 year , may be usefull for future visitors..
public void yourMethodName() {

    StringRequest request = new StringRequest(Request.Method.GET, link , new Response.Listener<String>() {
        @Override
        public void onResponse(String result) {
            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONArray jsonArray = jsonObj.getJSONArray("data");

                // Do something here

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(),"check connection , or try again later",Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    }){
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            try {
//                    String utf8String = new String(response.data, "UTF-8");
                String data = URLEncoder.encode("param", "UTF-8") +     "=" + URLEncoder.encode("param", "UTF-8");
                URL url = new URL(link);
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line;
                while ((line = br.readLine()) != null)
                    sb.append(line);
                br.close();
                return Response.success(new String(sb.toString()), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (Exception e) {
                return Response.error(new ParseError(e));
            }
        }
    };

    queue.add(request);

}

URL Encoding with Volley


OnClick JavaScript não funcionando com "quebra de linha"

Question: Estou um problema, eu pego uma informações inseridas pelo usuário no banco de dados e coloco ele em um button com onclick para ao usuário clicar coloca-lo em um modal para que ele posso editar, não posso colocar direto no modal pois são varias informações então e elas tem que ir mudando dependendo de onde o usuário clica, o problema surge quando vem informações com quebra de linha, (o usuário utilizou um enter durante a inserção da informação), o onclick simplismente não funciona e da um alerta: "Uncaught SyntaxError: Invalid or unexpected token". O que me deixou intrigado que com caracteres especiais funciona normalmente, apenas com a quebra de linha que não. Segue abaixo o código do button:
<button class="btnEdit btn btn-primary btn-xs" onclick="editar(\'' + value.nome + '\' , \'' + value.modulo + '\' , \'' + value.roteiro + '\' ,' + value.id + ')"  ></button>';

Comment: então, esse enter vai gerar uma "constante de cadeia não finalizada" no javascript. Tem que tratar essa entrada retirando as quebras de linhas. Mostra como é que esses dados são passados para o botão.
Answer: Então, você tem que tratar de retirar essas quebras de linhas para não gerar erro de "constante de cadeia não finalizada" no javascript.
Para evitar esse erro você pode eliminar as quebras de linhas quando "pegar as informações inseridas pelo usuário no banco de dados", ou seja no select, da seguinte forma:
SELECT REPLACE(
REPLACE(NOME-COLUNA, '\r', '\\r'),
'\n',
'\\n'
) FROM NOME_TABELA;

Exemplo: tabela utilizada

Resultado:

No Javascript é uma linha unica sem quebra e portanto sem gerar erros.

console.log("Essa coluna tem\r\nquebra de linha\r\nduas veazes\r\nponto final");

No entanto com quebra de linha ...

 console.log("Essa coluna tem\r\nquebra de linha\r\nduas

        veazes\r\nponto final");
Answer: Quando você for escrever no HTML as quebras de linha devem ser representadas por "\n", portanto você deve Substituir os caracteres de quebra de linha por "\n".
Exemplo:

  <input type="button" onclick="alert('Oi, \nTudo bem com você? \n Espero que sim.');" value="Botão" />

Exemplo de Replace se você gerar o código HTML a partir do Javascript:
variavel.replace("\n","\\n")

Comment: Rafael implementei sua solução, infelizmente não funcionou, pode ser o formato que vem do mysql?
Comment: Copia o código gerado e coloca como exemplo na pergunta. Você substituiu a quebra de linha como fiz no exemplo? Qual linguagem você usa ?
Comment: peguei como ficou no debug, ficou assim:

****


configuring resolver to show my site as provider

Question: Hey i want to show my website as a hosting provider. When we search for a domain it says who is hosting that domain . so i want to setup my domain as a provider. when users search for websites that use my nameservers.
here's the site:
http://www.whoishostingthis.com
so how do i configure my server to show as a provider?
Answer: That is a simple web front-end to the WHOIS database and you'll need to be registered there as the actual owner of the ip-address your servers use, or rather the owner of the block of ip-adresses.  For most people and small companies that will be their Internet Service Provider as they won't have their own provider-independent ip address space.


How to forward AngularJS $http response to the browser?

Question: I have a backend with header-based authentication and I want to download a file from it. With cookie-based authentication it is simple: you render a link to a file into  and let browser to handle the rest.
I have this code:
    $http.get(url).then(function (response) {
      // do something
    }, function (response) {
      alert("ERROR");
    });

I have injection of HTTP headers, so in this case $http.get will populate   them for us. What I want to do is to feed this response to $window, so from user perspective it will looks like usual file download.
Is there any way of doing this? Any other options are welcomed.
Comment: If you set the headers properly, you can just set `window.location` (if using a GET) or use a plain form to POST, instead of using ajax.
Comment: @Brocco well that's a good point.
Comment: @Pointy makes a `very` good argument, I would just like to add/remind you to utilize `$location` or at least `$window.location` instead of just `window.location`
Comment: @Brocco I don't see how/why that would matter; once the HTTP request is initiated, and assuming that the `Content-Disposition` header is set, then none of the client-side software will have any idea that it's even happening.
Comment: @Pointy if he is doing the redirect via angular by doing it via an injected module/component it can be unit tested.
Comment: I've added support of access tokens in query strings, so now I can format an appropriate `href`, but I'm still interested if this "integration" is possible.
Answer: I assume what you want is to push the file to the client without them needing to click anything else on the page. You can cause this to occur without needing to mess with $window at all.
Here is an example of how I pushed a zip file created in the browser that contained multiple selected regions of a canvas:
var downloader = angular.element('download');
downloader.attr('href', "data:application/zip;base64," + content);
downloader.attr('download', 'my.zip')

var ev = $document[0].createEvent("MouseEvent");
ev.initMouseEvent(
    "click",
    true /* bubble */, true /* cancelable */,
    window, null,
    0, 0, 0, 0, /* coordinates */
    false, false, false, false, /* modifier keys */
    0 /*left*/, null
);
downloader[0].dispatchEvent(ev);

Comment: will, this solution looks like a dirty hack. I was looking for something more elegant.
Comment: Perhaps I missed something but if you are trying to push data to the user you have already downloaded in the app then this is your best bet. This is hackish because what you are doing is hackish. The only way to download a file on the client is to request it, via a click action. If you do not want to user to click something then you need to click it for them.


Css centering - It randomly jumps into place

Question: I'm creating a new website for my webshop - And I have this css problem ...
The system is made on the prestashop platform, but this is basic CSS so that doesn't matter.
On the CMS pages, I'm having a problem centering the page, i've tryed using the -tag, margin: 0 auto, margin-Left/right auto, 100% width and so on.
The problem isn't that the text isn't centered, it's that the browser doesn't realises it untill you change something with the inspector or change the browser width.
So if you update the site, the content jumps into place.
(if you don't see the problem, try pressing the same menu item again - sometimes it works sometimes it doesn't. The sites with most problems are: /betingelser-3, /udtalelser-6 and /om-os-4.)
The problem is only in Safari and Chrome (webkit) Everything is fine on IE, firefox, Opera.
http://forsejt.dk/mackabler.dk/content/betingelser-3
I think there is just too many div's and css-styles so the browser times out? If that can happen:) I've tryed on a Macbook pro 15", Macbook air 13" and Mac pro.
Any Css tricks for this?
Comment: Don't worry your browser does not time out because you have too many divs n stuff ;)

I'd be more inclined to think there's some JS trickery going on here since your css and js are at the top (well js at top is bad, but if it's a cms you might not have a choice) and thus fully initialized before the rest of the content comes.
Answer: Try adding:
<code>text-align: center;
</code>
to #columns in the css.
Answer: So I'm not quite sure why this is, but it seems like the overflow:hidden in .row is the culprit. Try removing that or overriding it and it seems to work.
My guess would be that it gets in the way of webkit calculating the width properly for some reason?
There's also some other suggestions on a similar question here: CSS centering not working with margin auto and overflow hidden
But it seems to me that the accepted solution there won't work for you, as it looks like all of your floats are properly cleared.


DLL problem after compile with cx_freeze when I use win32wnet importation

Question: I create a script that connect to network folder with specific username and password that I don't give to user. This script connecto to network folder for 1 or 2 secondes, do stuff and disconnect after that to be sure user can't access network folder after that.
I work fine in my developpement environment.
I user cx_Freeze to convert my .py to .exe ( I use it for other little program many times )
Problem is that the .exe file works fine only on the same PC where I develop my app. On all other PC it give me error : File " network.py" line 1, in  ImportError: DLL load failed: Le module spécifié est introuvable ( in english, it can't find the specified module )
I try to add DLL of win32wnet. but not working.
What I do wrong.
See my code and my import code
'''
import win32wnet
import os
import re

# configure initial parameter
shareFolder = "\\\\ultra\\circuit-bgo"
usager = "foo"
motPasse = "foo"

# use win32wnet to create resorce to connect or disconnect
net_resource = win32wnet.NETRESOURCE()
net_resource.lpRemoteName = shareFolder

# try to disconnect to be sure no connection steel exist
try:
    win32wnet.WNetCancelConnection2(net_resource.lpRemoteName,0,0)
except:
    pass

# create connection to network folder
laConnection = win32wnet.WNetAddConnection2(net_resource, motPasse, usager, 0)

if os.path.exists(net_resource.lpRemoteName):
    print("connection réussi")
    # do some stuff, like read write and modify some files ( 1 or 2 secondes )
else:
    print("connection ÉCHOUÉ")
    # opps, connection failed

# disconnect to the network folder. I don't want user can access the folder by itself
try:
    win32wnet.WNetCancelConnection2(net_resource.lpRemoteName,0,0)
except:
    pass

'''
Import code with cx_freeze
'''
import os
import sys
from cx_Freeze import setup, Executable

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

#syspath = "c:\\Python32\\Lib\\site-packages\\win32\\perfmondata.dll"

buildOptions = dict(
    packages=['win32wnet'],
    excludes=[],
    include_files=['perfmondata.dll',]
)

executables = [Executable('network.py', base=base)]

setup(name='TestNetwork',
      version='0.1',
      options=dict(build_exe=buildOptions),
      description='NetWork',
      executables=executables
      )

'''
and I try the basic code when I normaly compile with cx_freeze
this is a batch file:
cxfreeze.bat "c:/Python32/Scripts/network.py" --base-name=Win32GUI --target-dir C:/Python32/Scripts/Dist_Network --icon c:/Python32/Scripts/Logo.ico
Comment: Please try to write more clearly.
Comment: sorry, my english is not good
Answer: After many, many, many test and reinstallation of python and module I need to find DLL that give me problem. I found that 3 DLL files have to be copy to the same folder of my new .exe file ( program ). The 3 DLL files are : pythoncom32.dll, pythoncomloader32.dll and pywintypes32.dll You can find this files on c:\Windows\syswow64 or system32 depend of your python installation (32 bit or 64 bit)
If you have bether solution, you can add it.
Thanks


How to properly add multiple form elements in a loop?

Question: I have a form where I need to loop through an array and display multiple form elements in a specific area.
Example:
$form_layout = 'Some html';
$form_layout .= '
';

foreach($something as $key => $value) {
    $form_layout .= 'some html';
    $form_layout .= 'some html';

    // I need this to be displayed in between the above and below code
    // in the layout
    $form['awesome_element'] => array(
        '#type' => 'textfield',
        '#size' => 5,
        '#value' => 0
    );

    $form_layout .= 'some html';
    $form_layout .= 'some html';
}

$form_layout .= '
';
$form_layout .= 'Some html';

$form['some-other-awesomeness'] = array(
    // ...
    '#prefix' => $form_layout,
);

Doing it like the example puts the textfields after all the other page elements. I have tried using #prefix and #suffix but that breaks the layout even worse.
Any ideas on what I should do?
Edit: For clarity...
If I had layout elements such as a div tag I need my form elements, such as textfields, to be inserted in between those div tags.
So I need it to output something like this:

FORM ELEMENT
FORM ELEMENT
FORM ELEMENT

Instead it is outputting something like this:

FORM ELEMENT
FORM ELEMENT
FORM ELEMENT

Hopefully that is more clear, sorry if the above is confusing. Looking at code for the last 20 hours.
Edit2: added some visual stuff to make it easier to understand
Comment: I'm not sure if it's just me..but this doesn't seem to make much sense?!?
Comment: How would you like me to clarify? There is a layout, there are many form elements that are populated via an array which I extract with a foreach loop. I need those elements in between the layout elements.
Comment: No they are not the same... the div tag is ABOVE the form elements. I need the form elements IN BETWEEN the tags.
Answer: Could you do something like the following:
$form['openingdiv'] = array(
  '#markup' => '
'
);

//Do all your foreach stuff here

$form['closingdiv'] = array(
  '#markup' => '
'
);

(Sorry it's a bit simple..I'm tired :-p)
Comment: Ok, this is totally my fault! Your answer is exactly what I would need for the question I asked. Unfortunately though, I have not asked the question properly. Instead of editing more and possibly becoming more confusing I will just accept this and re-ask the question after some sleep lol Thank you for the quick answer!!!
Comment: @Baysaa It doesn't, if no `#type` is provided Drupal defaults to using `markup`
Comment: Probably needs `'#type' => 'markup'` as well.
Comment: What is this 'markup'? I am going to go look this up now... I will let you know if that looks promising. Thank you! :)
Comment: `'#type' => 'markup'` is the default type in D7, so no need.


Interpreting trees of XGBoostRegressor Model

Question: I fitted a dmlc XGBoostRegressor model on a dataset with the variables ['CPI', 'Fuel_Price', 'Temperature', 'Unemployment'] and Weekly_Sales as the target column.
On calling the get_dump method of the booster, I got this as the output
['0:leaf=0.0934955776,cover=329302.531\n',
 '0:leaf=0.0934955776,cover=329747.219\n',
 '0:leaf=0.0934955776,cover=330160.312\n',
 '0:leaf=0.0934955776,cover=329053.969\n',
 '0:leaf=0.0934955776,cover=329170.312\n',
 '0:leaf=0.0934955776,cover=329982.219\n',
 '0:leaf=0.0934955776,cover=329104.156\n',
 '0:leaf=0.0934955776,cover=329137.156\n',
 '0:leaf=0.0934955776,cover=330236.156\n',
 '0:leaf=0.0934955776,cover=329294.531\n',
 '0:leaf=0.0934955776,cover=329796.875\n',
 '0:leaf=0.0934955776,cover=329830.844\n',
 '0:leaf=0.0934955776,cover=328940.344\n',
 '0:leaf=0.0934955776,cover=328961.75\n',
 '0:leaf=0.0934955776,cover=329524.781\n',
 '0:leaf=0.0934955776,cover=329217.219\n',
 '0:leaf=0.0934955776,cover=329684.75\n',
 '0:leaf=0.0934955776,cover=329125.906\n',
 '0:leaf=0.0934955776,cover=328701.625\n',
 '0:leaf=0.0934955776,cover=329561.219\n',
 '0:leaf=0.0934955776,cover=329476.312\n',
 '0:leaf=0.0934955776,cover=329461.875\n',
 '0:leaf=0.0934955776,cover=328941.406\n',
 '0:leaf=0.0934955776,cover=329862.781\n',
 '0:leaf=0.0934955776,cover=329005.875\n',
 '0:leaf=0.0934955776,cover=329438.844\n',
 '0:leaf=0.0934955776,cover=329967.562\n',
 '0:leaf=0.0934955776,cover=330012.75\n',
 '0:leaf=0.0934955776,cover=330047.875\n',
 '0:leaf=0.0934955776,cover=329203.75\n',
 '0:leaf=0.0934955776,cover=329165.875\n',
 '0:leaf=0.0934955776,cover=330092.75\n',
 '0:leaf=0.0934955776,cover=328510.906\n',
 '0:leaf=0.0934955776,cover=328970.719\n',
 '0:leaf=0.0934955776,cover=329716.188\n',
 '0:leaf=0.0934955776,cover=328921.281\n',
 '0:leaf=0.0934955776,cover=329413.281\n',
 '0:leaf=0.0934955776,cover=329069.281\n',
 '0:leaf=0.0934955776,cover=329176.219\n',
 '0:leaf=0.0934955776,cover=329788.469\n',
 '0:leaf=0.0934955776,cover=329518.75\n',
 '0:leaf=0.0934955776,cover=328390.281\n',
 '0:leaf=0.0934955776,cover=329060.156\n',
 '0:leaf=0.0934955776,cover=330460.656\n',
 '0:leaf=0.0934955776,cover=330349.062\n',
 '0:leaf=0.0934955776,cover=329767.75\n',
 '0:leaf=0.0934955776,cover=330169.594\n',
 '0:leaf=0.0934955776,cover=329695.469\n',
 '0:leaf=0.0934955776,cover=329004.219\n',
 '0:leaf=0.0934955776,cover=328929.438\n',
 '0:leaf=0.0934955776,cover=329789.75\n',
 '0:leaf=0.0934955776,cover=329472.781\n',
 '0:leaf=0.0934955776,cover=329576.844\n',
 '0:leaf=0.0934955776,cover=329171.969\n',
 '0:leaf=0.0934955776,cover=328871.031\n',
 '0:leaf=0.0934955776,cover=328978.312\n',
 '0:leaf=0.0934955776,cover=330081.219\n',
 '0:leaf=0.0934955776,cover=328753.75\n',
 '0:leaf=0.0934955776,cover=329748.219\n',
 '0:leaf=0.0934955776,cover=330605.406\n',
 '0:leaf=0.0934955776,cover=329190.75\n',
 '0:leaf=0.0934955776,cover=329480.219\n',
 '0:leaf=0.0934955776,cover=328893.281\n',
 '0:leaf=0.0934955776,cover=329485.781\n',
 '0:leaf=0.0934955776,cover=329667.406\n',
 '0:leaf=0.0934955776,cover=330021.719\n',
 '0:leaf=0.0934955776,cover=328994.281\n',
 '0:leaf=0.0934955776,cover=329750.188\n',
 '0:leaf=0.0934955776,cover=329118.188\n',
 '0:leaf=0.0934955776,cover=329745.719\n',
 '0:leaf=0.0934955776,cover=329729.75\n',
 '0:leaf=0.0934955776,cover=329411.312\n',
 '0:leaf=0.0934955776,cover=328842.312\n',
 '0:leaf=0.0934955776,cover=329581\n',
 '0:leaf=0.0934955776,cover=329224.719\n',
 '0:leaf=0.0934955776,cover=329223.719\n',
 '0:leaf=0.0934955776,cover=329711.344\n',
 '0:leaf=0.0934955776,cover=330098.219\n',
 '0:leaf=0.0934955776,cover=328747.219\n',
 '0:leaf=0.0934955776,cover=329718.844\n',
 '0:leaf=0.0934955776,cover=328533.312\n',
 '0:leaf=0.0934955776,cover=329316.719\n',
 '0:leaf=0.0934955776,cover=329097.781\n',
 '0:leaf=0.0934955776,cover=329237.656\n',
 '0:leaf=0.0934955776,cover=329210.312\n']

None of the variables I used in training comes up in any of these trees and they are all leaf nodes.
How do I interpret this result?
Also, in the first tree, what does leaf=0.0934955776 and cover=329302.531 indicate?
These are the hyperparameters I used
{'alpha': 0.09609812947036414, 'colsampleBytree': 0.3905334806558341, 'eta': 0.05993483819906295, 'gamma': 2.984254821230856, 'maxBin': 27, 'maxDeltaStep': 1.5599536434168235, 'maxDepth': 8, 'minChildWeight': 6458.3654299043665, 'numRound': 85, 'rateDrop': 0.08000474078175099, 'regLambda': 0.017965626423790668, 'scalePosWeight': 0.47964508064705125, 'skipDrop': 0.3637793984107442, 'subsample': 0.7815658127047251}

Answer: For the "leaf" value, you might find an explanation here or here and "cover" according to the documentation (see here) is the average coverage of splits which use the feature where coverage is defined as the number of samples affected by the split.


Finding equivalence over a matrix

Question: <code> X  11 22 33 44 55 66

 11 1  0  0  0  1  0

 22 0  1  0  1  0  1

 33 0  0  1  0  0  0

 44 0  1  0  1  0  1

 55 1  0  0  0  1  0

 66 0  1  0  1  0  1

|A| = 6,

A = {11, 22, 33, 44, 55, 66}

B = { (22,22), (22,44), (44,22), (44,44), (44,66), (66,66), (66,22), (22,66), (66,44), (33,33),
    (11,55), (55,11), (11,11), (55,55) }
</code>
this is my matrix i know that in order to find equivalence i need to make sure first that i have a reflexive,symmetric and transitive ratios, i cant figure out how to connect the 3 of them to find the equivalence in the matrix.
i believe that the right naming for that will be the "Departments of equality"
any pointers will be great.
Answer: Let's rewrite this in a better way:
\begin{array}{c|cccccc}
& 11 & 22 & 33 & 44 & 55 & 66 \\
\hline
11 & 1 & 0 & 0 & 0 & 1 & 0 \\
22 & 0 & 1 & 0 & 1 & 0 & 1 \\
33 & 0 & 0 & 1 & 0 & 0 & 0 \\
44 & 0 & 1 & 0 & 1 & 0 & 1 \\
55 & 1 & 0 & 0 & 0 & 1 & 0 \\
66 & 0 & 1 & 0 & 1 & 0 & 1
\end{array}
where a $1$ means that the pair (row index,column index) belongs to the relation, $0$ otherwise.
The relation is clearly reflexive and symmetric. In order to be an equivalence relation, consider, for each element, the set
$$
[x]=\{y:(x,y)\in B\}
$$
Then
\begin{align}
[11]&=\{11,55\}\\
[22]&=\{22,44,66\}\\
[33]&=\{33\}\\
[44]&=\{22,44,66\}=[22]\\
[55]&=\{11,55\}=[11]\\
[66]&=\{22,44,66\}=[22]
\end{align}
So the relation partitions $A=\{11,22,33,44,55,66\}$ into disjoint sets. So…
Comment: Thank you for the answer now i need to translate this in to code :)

Finding equivalence over a matrix


DHCP conflicts on two Ubuntu 18.04 servers

Question: I have two machines running Ubuntu 18.04 server edition. Networking go through netplan. They get their IPv4 from a DHCP server v6.3 running on Windows Server 2012 R2. For some reason, they don't provide their MAC address but a very long hardware-type. And for some reason, both machines provide the same Client-ID, then the DHCP replies with the same IP address, leading to IP conflicts on my network. I tcpdump'ed DHCP requests when both machines boot:
https://pastebin.com/AFZzNqd5
We can see that machines e0:d5:5e:b0:ed:49 and e0:d5:5e:8f:a6:b0 both advertises the same Client-ID. What's wrong with my Ubuntu server configuration?
Answer: Ubuntu server default networking goes through cloud-init which by default sends /etc/machine-id in the DHCP request. I have not made these ID unique and my two machines send the same, thus DHCP server replied with the same IP address to both machines, leading to conflict. So using the MAC address as DHCP-identifier as mentioned in this solution worked for me:
https://superuser.com/a/1369369/131772
I also make /etc/machine-id unique for each machine.


Existe algum risco ao desconectar o dispositivo android durante a depuração?

Question: Não sei porque mas fiquei com um pouco de receio ao pensar que uma vez que meu ADT está em contato constante com meu Dispositivo(Nexus 5) ao desconectar durante uma troca de informações pode haver danos. Será que assim como um pendrive ao desconectar abruptamente durante a passagem ou troca de informações há riscos? Alguém já fritou parte de um dispostivo assim? Obrigado.
Answer: TL;DR - Nada que você deva se preocupar.
Resposta longa:
Os riscos envolvidos em uma desconexão da porta USB durante a depuração são exatamente os mesmos ao que o dispositivo está sujeito durante uso quotidiano.
Em algumas implementações USB antigas era possível remover um dispositivo enquanto o host ainda esta fornecendo energia para o dispositivo. Hoje isso é bem raro.
O problema principal com a remoção sem ejeção é o fato que alguns sistemas operacionais fazem cache em memória de arquivos sendo manipulados em mídia removível. Como na prática você não está manipulando arquivos (ADB se encarrega de 'serializar' e enviar seus APKs utilizando seu próprio protocolo), este risco é inexistente.
Do lado do dispositivo, o ambiente operacional se assegura que seu novo pacote APK só será instalado caso a transferência ocorra com sucesso.
Comment: Muito bom, retirou minha duvida, sem sombra para questionamentos. Obrigado!
Answer: Eu já tive a experiência de desconectar um dispositivo Android enquanto fazia uma transferência de arquivos e a fonte do PC queimou na hora. Isso aconteceu comigo apenas uma vez, hoje faço isso meio que seguido e nunca tive esse problema novamente. Porém, foi o simples ato de eu desconectar o USB e a fonte queimou.
Comment: Eu lembro de um caso onde um desenvolvedor fez o mesmo - retirou um dispositivo da porta USB - e a vítima foi a placa mãe. Isso aconteceu por que não a porta USB não tinha nenhum tipo de segurança contra curto-circuito (que ele provocou ao tirar o dispositivo inclinando lateralmente).


Tangential component of vector field

Question: I'd like to know the definition of "tangential component" in this case, it is question 3 of page 57 of Do Carmo's book Riemannian Geometry:
It says:

Define $\nabla_XY(p) = $ tangential component of $\overline\nabla_{\overline X}\overline Y(p) $, where $\overline\nabla$ is the Riemannian connection of $\overline M$.
Comment: I see there's a discussion of something with that name around pages 125–126 in that book.  Does that help at all?
Comment: I don't think, but thanks anyway
Answer: You have a submanifold $M$ of a bigger manifold $\overline{M}$.  Tangential means "tangent to $M$".
Specifically, at each point $p\in M$, you have a map $\pi:T_p\overline{M}\rightarrow T_p M$ defined as follows.
The metric $g$ gives us an orthogonal complement $\nu$ to $T_ p M$ so that $T_p \overline{M} = T_p M\oplus \nu$.  Then $\pi(X_{T_p M} + X_{\nu}) = X_{T_p M}$.  The tangential componenet of $X$ is then, by defintion, $\pi(X)$.
Answer: The problem is about an immersed submanifold $M^n$ of a Riemannian manifold $\overline{M}^{n+k}$. This immersion induces an injection
$$T_*f: T_p M \rightarrow T_{f(p)}\overline{M}$$
($f$ denoting the injection) which allows you to identify the tangent space of $M$ with a subspace of $T\overline{M}$. If now $q = f(p)\in T_{q}\overline{M}$ and $\overline{Z}\in T_{q}\overline{M}$ the tangential component of $\overline{Z}$ is just the orthogonal projection of $\overline{Z}$ with respect to the metric on $T_q\overline{M}$ onto the tangent space of (the image of) $M$.
Comment: Can you define a projection over the tangent bundle? Your projection depends on the point. Is this dependence differentiable?

Tangential component of vector field


cant get PHP_SELF to post checkbox

Question: i was trying to get my check box to output "Korting is ... %" at the bottom of the page depending on which check box is checked e.g. 2th and 3th boxes are checked it would output "Korting is 15%" but i cant seem to get it to work. can someone please help me
thank you in advance
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>XXL Computer winkel</title>

php lab 04

<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

Korting:

<input type="checkbox" name="korting" value="15" /> Student 15%

<input type="checkbox" name="korting" value= "10"  /> Senior 10%

<input type="checkbox" name="korting" value= "5" /> klant 5%

Toshiba Satellite A100-510 basisprijs 999.99

<input type="hidden" name="toshibaproduct" value="001"/>
<input type="hidden" name="toshibamerk" value="Toshiba"/>
<input type="hidden" name="toshibamodel" value="Sattelite A100-510"/>
Aantaal: <input type="text" size=2 maxlenght=3 name="toshibaaantal" value="0"/>
<input type="hidden" name="toshibaprijs" value="999.99"/>

<input type="image" src="images/Lab4/2.jpg" border=0 value="bestellen"/>

</form>

Comment: Don't use PHP_SELF. Without proper escaping it open a XSS hole. Just use `action=""` instead.
Comment: Your HTML is invalid in a way that will break your form in some browsers. [Use a validator](http://validator.w3.org).
Comment: @Hanky Panky ㇱ
this is all i have
Answer: You need to use a name ending in [] such as name="korting[]". Then you can use $_POST['korting'] which will be an array containig the values of the checked checkboxes.
Note that $_POST['korting'] will  not be set at all if no checkbox is checked!
Comment: its working but the 1st time the page loads it gives an error how can i get rid of that ?
Answer:
Use radio instead of checkbox if you want one option to be selected
Do not use PHP_SELF, it is a security hole. Instead: <form action="">
Access the value with $_POST['korting']

To sum up all values, make your form like this:
<input type="checkbox" name="korting[]" value="15" /> Student 15%

<input type="checkbox" name="korting[]" value= "10"  /> Senior 10%

<input type="checkbox" name="korting[]" value= "5" /> klant 5%

and the processing like that:
<?php
$korting = 0;
if (isset($_POST['korting']) && is_array($_POST['korting'])) {
  $korting = array_sum($_POST['korting']);
}
echo 'Korting is ' . $korting . '%';
?>

Comment: I have to be able to calculate the total sum of the korting at the bottom of the page under the 2th
like Korting is: 15% if you checked senior box and klant box
Comment: Ah, I missed that, sorry. In that case see ThiefMasters answer and use `array_sum`. My second point still remains valid.
Comment: i don't know why but his solution is not working either or i must be doing something wrong.
Comment: seems like you did something wrong ;) Look at my edited answer.

cant get PHP_SELF to post checkbox


How to auto click button when video is available in android?

Question: I have Integrated some rewarded video ads in my app an activity which contain a Button named as Show Video when I click on that I navigated to video activity which show video adds ,but problem is that Video takes time to view,I want to show a progress dialog and when Videovisibilty becomes "true" then hide progress dialog and auto click button to show video.
How can I do that ?
mainActivity code:-
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        _button = (Button) findViewById(R.id.show_button);
        _button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, Video.class);
                startActivity(i);
            }
        });

    }

Video activity code:-
 String TAG = MainActivity.class.getSimpleName();
    private Supersonic mMediationAgent;
    private Placement mPlacement;
    ProgressDialog progress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        progress = new ProgressDialog(this);
        progress.setMessage("Loading video :) ");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);
        progress.show();

        mMediationAgent = SupersonicFactory.getInstance();
        // Supersonic Advertiser SDK call
        SupersonicAdsAdvertiserAgent.getInstance().reportAppStarted(Video.this);
        mMediationAgent.setRewardedVideoListener(Video.this);
        final String userId = "9555515291";
        final String appKey = "50427d";
        mMediationAgent.initRewardedVideo(Video.this, appKey, userId);
        IntegrationHelper.validateIntegration(Video.this);
        if (mMediationAgent.isRewardedVideoAvailable()) {
            mMediationAgent.showRewardedVideo("DefaultRewardedVideo");
        }

    }

    @Override
    public void onRewardedVideoInitSuccess() {
        Log.d(TAG, "onRewardedVideoInitSuccess");
    }

    @Override
    public void onRewardedVideoInitFail(SupersonicError supersonicError) {

    }

    @Override
    public void onRewardedVideoAdOpened() {
        Log.d(TAG, "onRewardedVideoAdOpened");
    }

    @Override
    public void onRewardedVideoAdClosed() {
        // called when the video is closed
        Log.d(TAG, "onRewardedVideoAdClosed");

        // here we show a dialog to the user if he was rewarded
        if (mPlacement != null) {
            // if the user was rewarded
            showRewardDialog(mPlacement);
            mPlacement = null;
        }

    }

    @Override
    public void onVideoAvailabilityChanged(boolean b) {
        // called when the video availbility has changed
        Log.d(TAG, "onVideoAvailabilityChanged" + " " + b);

    }

    @Override
    public void onVideoStart() {
        // called when the video has started
        Log.d(TAG, "onVideoStart");
    }

    @Override
    public void onVideoEnd() {
        // called when the video has ended
        Log.d(TAG, "onVideoEnd");
    }

    @Override
    public void onRewardedVideoAdRewarded(Placement placement) {
        // called when the video has been rewarded and a reward can be given to the user
        Log.d(TAG, "onRewardedVideoAdRewarded" + " " + placement);
        mPlacement = placement;
    }

    @Override
    public void onRewardedVideoShowFail(SupersonicError supersonicError) {
        // called when the video has failed to show
        // you can get the error data by accessing the supersonicError object
        // supersonicError.getErrorCode();
        // supersonicError.getErrorMessage();
        Log.d(TAG, "onRewardedVideoShowFail" + " " + supersonicError);
    }

    public void showRewardDialog(Placement placement) {
        AlertDialog.Builder builder = new AlertDialog.Builder(Video.this);
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.setTitle(getResources().getString(R.string.rewarded_dialog_header));
        builder.setMessage(getResources().getString(R.string.rewarded_dialog_message) + " " + placement.getRewardAmount() + " " + placement.getRewardName());
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

Comment: If my answer helps then kindly accept it, so other users can get benefit of this.
Answer: Just call performClick() like
 btnViewVideo.performClick();

When you use this at that point any action write in the onclick listner will be fired automatically.
For more info:
fire button's click event programmatically
Comment: If this helps then kindly accept it, so other users can get benefit of this.


How to change all hihats to ride cymbal in GuitarPro

Question: I'm not sure if this qn belongs here, but it is related to music, so here it goes.
I've been modifying some drum tabs on Guitar Pro. The problem is, for a specific section all the HiHat notes need to be changed to Ride cymbal.
Now of course, I can do it one note at a time. I can select the note, remove the hihat and add a ride cymbal on the same note. But I'll have to do this for one at a time for a loooong time.
Is there a mass copy and replace method in guitar pro.
Again, I can copy and paste notes too, but on the same note there'll be different snare/kick being played.

I JUST want to replace the hihat with ride while keeping other things
  same for the same note
Comment: http://www.nooooooooooooooo.com/
Comment: As far as I know, there isn't any 'find and replace' method in GP. You might have to  do it on every single note
Answer: You can do it, I just figured out how and also tested it.

Export the current GP file as an XML file from: File > Export > MusicXML,
Open the exported XML file with Notepad and using "replace all" (using ctrl + H) replace the number corresponding to HiHat (probably 42, 44 or 46) with a number corresponding to Ride cymbal (probably 59).
Import this file into GuitarPro  from: File > Import > MusicXML and you're done.

Hopefully nothing else will change. If it does,then you'll have to investigate the XML file more thoroughly but I don't think it's gonna be too hard. Anyway, keep the backup file safe before doing this, good luck.
Comment: Great, and since you're trying it, it's better to consider @david strachan's advice and search for 42 (or 44, or 46, whichever you want to change) instead of just number 42 and replace it with 51 (or 59) just to be sure that nothing else will be changed.
Comment: this is why i love stack exchange! thank you for the answer. I'll try it out and let you know!
Answer:
Copy drum track to new file as precussion track
Export as MusicXML

Open file in Text Editor
Look for <fret>42</fret> OR <fret>44</fret> OR <fret>46</fret>
Find and Replace with <fret>51</fret> OR  <fret>59</fret>
Import as MusicXML into drum file
Add track to origonal file


I'm failing to create a pagedown::chrome_print pdf output from a shiny app which takes parameter inputs and renders the Rmarkdown

Question: I have a rmarkdown file which is built around the {pagedreport} package (an add-on to pagedown). This creates a html and them uses pagedown::chrome_print to convert the html to pdf.
The rmarkdown file i have works as planned when I have the parameters manually entered on the rmarkdown file, but I want to be able to pick my parameters from a shiny app.
I currently have tried this approach
    output$report <- downloadHandler(
    # For PDF output, change this to "report.pdf"
    filename =  "new_report.pdf",
    content = function(file) {
    # Copy the report file to a temporary directory before processing it, in
    # case we don't have write permissions to the current working dir (which
    # can happen when deployed).
    tempReport <- file.path("../temp/", "myRmarkdown.Rmd")
    file.copy("myRmarkdown.Rmd", tempReport, overwrite = TRUE)

    # Set up parameters to pass to Rmd document
    params <- list(A = input$A, B = input$B)

    # Knit the document, passing in the `params` list, and eval it in a
    # child of the global environment (this isolates the code in the document
    # from the code in this app).

     library(rmarkdown)
     render(tempReport,  params = params,
                   envir = new.env(parent = globalenv()))

          }

and I get the result:
    Output created: MyRmarkdown.html

but there is no pdf created. Pagedown uses chrome_print to convert - and this is in the yaml of the Rmarkdown.
This is the YAML of my Rmarkdown file
    output:
    pagedreport::paged_windmill:
    img_to_dark: TRUE
    logo_to_white: TRUE
    knit: pagedown::chrome_print
    #toc: TRUE
    toc-title: "Table of Contents"
    #toc_depth: 1
    main-color: "#264653"
    secondary-color: "#2a9d8f"
    google-font: TRUE
    main-font: "Raleway"
    header-font: "Roboto"
    params:
        A: NA
        B: NA
    editor_options:
    markdown:
        wrap: 72

I know there is an issue between shiny and chrome_print() where you need to add chrome_print(..., async = TRUE), but I don't know where to put this argument in my shiny app?
Comment: I have written a demo Shiny app to show how to use `pagedown::chrome_print()` in Shiny, see https://github.com/RLesur/chrome_print_shiny.
Answer: I am pretty sure you have to make sure that your render function creates a file at the location given by the argument file. In  your current appraoch render uses defaults, which won't work. Thus, it should be as simple as adding the output_file argument to render. The following code snippets works for me:
test.Rmd
---
title: "Untitled"
output: html_document
params:
   title: "Test"
   heading: "Header"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r results="asis"}
cat("## ", params$title)
```

You passed in argument `r cat(params$heading)`

app.R
library(shiny)
library(rmarkdown)

ui <- fluidPage(textInput("heading", "Heading"),
                textInput("title", "Title"),
                downloadButton("download_ok", "Works"),
                downloadButton("download_nok", "Does not Work"))

server <- function(input, output) {
   output$download_ok <- downloadHandler(
      filename = function() {
         paste("data-", Sys.Date(), ".html", sep="")
      },
      content = function(file) {
         p <- list(title = input$title,
                        heading = input$heading)
         render("test.Rmd", output_file = file, params = p)
      }
   )

   output$download_nok <- downloadHandler(
      filename = function() {
         paste("data-", Sys.Date(), ".html", sep="")
      },
      content = function(file) {
         p <- list(title = input$title,
                        heading = input$heading)
         render("test.Rmd", params = p)
      }
   )
}

shinyApp(ui, server)

This snippet shows how this works now in principle, I do not know pagedreport. If there is an option in the YAML to produce pdfs right away (without the manual call to whatever function) this should work in the same way.
If you absolutely need to call the function, you can do that in the downloadHandler after the render assuming that the function can deal with input file names and create output files at the given location (again you need to create the file at the given location [as per argument file])

After reading the docs of pagedown::chrome_print you can adapt your downloadHandler as follows:
output$report <- downloadHandler(
      filename =  "new_report.pdf",
      content = function(file) {
         tempReport <- file.path("../temp/", "myRmarkdown.Rmd")
         file.copy("myRmarkdown.Rmd", tempReport, overwrite = TRUE)
         params <- list(A = input$A, B = input$B)
         html_fn <- rmarkdown::render(tempReport,  params = params,
                envir = new.env(parent = globalenv()))

         pagedown::chrome_print(html_fn, file)
      }


Apache ErrorDocument doesn't work if it is a PHP file

Question: We are hosting several sites on our server. We have set a custom not_found.php file in the apache config and it works fine.
For a few of our virtual hosts, we need a custom not_found.php file. In the <VirtualHost> section we have set a custom 404 file. When we try to access a non-existing url in that virtual host, we get a "File not found" error (not the typical Firefox 404 Not Found).
If we rename the file to .html and change it to .html in the config, it loads the custom 404 just fine (the PHP scripting doesn't work of course). So I know it is reading the custom ErrorDocument statement in the VirtualHost. And I know the path is fine. It just doesn't work with an extension of .php.
Here is the relevant config:
<VirtualHost>
    Alias "/error_docs" "/var/www/vhosts/domain.com/error_docs"
    ErrorDocument 404 /error_docs/not_found.php
</VirtualHost>

PS. PHP scripts work throughout the sites (so we know PHP is working fine).
Any ideas?
Answer: I figured this out. Someone had specifically turned off PHP for the error_docs folder using
php_admin_flag engine off

It was hidden away and I just happened to find it today.


Node.js and mongoDB serving concurrent requests

Question: I am having trouble serving concurrent requests from my simple node.js server using a mongoDB.
What i am doing is sending querys in mongo shell format, parsing them and sending back data from mongoDB.
But it seems that it cannot serve multiple requests in the same time for some reason..
(BTW i am using it locally)
EDIT:
I sometimes get this error in my client app :
"Stream Error. URL: http://localhostlink:1337"
which i also get when the server is not running...
EDIT2:
I removed the db.close statements.
Is cluster really the right solution here because i will be just upgrading the app to serve 4 concurrent requests which will still not be enough.
Should i completely refactor the server in some other way? I just want to be able to serve multiple requests for data from mongoDB.
EDIT3:
Is it ok that i am first creating the server and then connection to mongo, or should i create the server inside the MongoClient.connect(...) function?
This is the code of my (unoptimised) server:
  var http = require('http');
var qs = require('querystring');
var mongo =require('mongodb');
var MongoClient = mongo.MongoClient;
var result;
var response;
var ObjectId = require('mongodb').ObjectID;
var myDb;

http.createServer(function (request, res) {
    console.log("creating server...");
    MongoClient.connect("mongodb://127.0.0.1:27017/lalal", function(err, db) {
        if(err) { return console.dir(err); }
if (request.method == 'POST') {
        var body = '';
        response = res;
        request.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
            //     FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                request.connection.destroy();
            }
        });
        request.on('end', function () {

            var clientData = qs.parse(body);
            var parts = clientData.data.split(".");
            var collectionName = parts.shift();
            var queryBig = parts.join(".");
            var queryParts = queryBig.split("(");
            var method = queryParts[0];
            var query = queryParts.join("(");

            console.log("query:"+query);
            console.log("method:"+method);
            console.log("collection:"+collectionName);

          var callback;
          switch(method){

                case 'find':
                callback = '.toArray(findCallback);';
                break;
                case 'insert':
                query = query.substring(0, query.length - 1);
                callback = ',insertCallback);';
                break;
                case 'remove':
                query = query.substring(0, query.length - 1);
                callback = ',removeCallback);'
                break;
                case 'save':
                query = query.substring(0, query.length - 1);
                callback = ',saveCallback);'
                break;
                case 'update':
                query = query.substring(0, query.length - 1);
                callback = ',updateCallback);'
                break;

            }
         if(query.indexOf('"_id"') != -1)
         {

         var indexHelper = query.indexOf('"_id"')+7;
         var s = query.substring(indexHelper, query.length);

         var indexOfQuote = s.indexOf('"')
         var restOfQuery = s.substring(indexOfQuote+1,s.length);

         var key = s.substring(0,indexOfQuote);

         query = query.substring(0,indexHelper-1) + 'new ObjectId("'+key +'")'+restOfQuery;

         }
//      Connect to the db

//      myDb = db;
        var collection = db.collection(collectionName);

        var command = 'collection.'+query+callback;
        console.log("command:"+command);
        eval(command);

            function findCallback(err, items){

                console.log(items);

                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.end(JSON.stringify(items));

            }

            function insertCallback(err, objects) {

                console.log(objects);

                if (err) console.warn(err.message);
                if (err && err.message.indexOf('E11000 ') !== -1) {
                    response.writeHead(200, {'Content-Type': 'text/plain'});
                    response.end('"error":"_id already exists"');
                }
                else{
                    response.writeHead(200, {'Content-Type': 'text/plain'});
                    response.end(JSON.stringify(objects));
                }

            }

            function removeCallback(err, numberOfRemovedDocs) {

                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.end(JSON.stringify(numberOfRemovedDocs));

            }

            function saveCallback(err, result) {

                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.end(JSON.stringify(result));

            }

            function updateCallback(err, numberOfUpdatedDocs) {

                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.end(JSON.stringify(numberOfUpdatedDocs));

            }

        });
    }
});
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

Comment: While there's a lot of code there and I certainly haven't reviewed it all, you should only open the DB connection once and leave it open for the lifetime of the Node process.
Comment: Could it be that this part "myDb = db;" in MongoClient.connect is where the problem is coming from? because it is no longer async right? Because i am passing the reference to a globally accessible variable, so when the new request comes it takes over
Comment: `db.close()` why are you closing the connection?
Answer: The problem you are seeing is because node.js is single threaded. That is, it will dispatch one request at a time (this is actually good, since it helps avoiding bugs caused by global variable handling). If you sent the response before executing your queries you would see parallel query execution. However, given the way you structured your program, you might be better off using the 'cluster' module. The code below will start four concurrent processes.
var cluster = require('cluster');

if (cluster.isMaster) {
    for (var i = 0; i < 4; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
        cluster.fork();
    });
}
else {
    // run your node.js + MongoDB code here
}

PS. You don't need to close the db connection when using MongoClient.connect, as this API uses the connection pool, which manages your connections.
Comment: @deloki Each cluster instance has its own connection pool so there can be up to 4*(pool size) MongoDB queries in progress at a given time.  Pool size defaults to 5 but you can make it however big you want.
Comment: Is the cluster really the right solution here? wont i just be upgrading my server to serve 4 concurrent requests? That is still not enough for me.
Comment: @JohnnyHK Ok, thank you. So this is the best practice way of achieving concurrent DB requests with sending response data as payload? If not what would be the best practice way?
Comment: I would say is it a good practice. BTW, you can start more processes if you want. 2 to 4 times the number of cores in your system is a good rule (I have seen this concurrency number working fine in thread pool implementations based on I\O completion ports, which normally do intensive I\O).
Comment: @ruiz can we use forky instead of cluster if yes can u please give me an example.


Get a matrix of polynomial coefficients from the roots

Question: I've got the polynomial $P(z) = \Phi_0 - \Phi_1z $ defined by the following matrices of coefficients:
$$
\begin{eqnarray}
\Phi_0 = \left[
\begin{array}{rrrr}
1 & 0 & 0 & 0 \\
0.2 & 1 & 0 & 0 \\
-0.6 & -0.4 & 1 & 0 \\
0 & 0.2 & 0.6 & 1
\end{array}
\right]
\quad
\Phi_1 = \left[
\begin{array}{rrrr}
0 & 0 & 0.4 & 0.6 \\
0 & 0 & 0 & 0.2 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0
\end{array}
\right] \,.
\end{eqnarray}
$$
I would like to know if there is some way to get the coefficients $\phi_{ij}$ knowing the roots of the polynomial.
The characteristic equation of the polynomial is given by:
$$
\begin{eqnarray}
|\Phi_0 - \Phi_1 z| =
\left|
\begin{array}{rrrr}
1 & 0 & -0.4z & -0.6z \\
0.2 & 1 & 0 & -0.2z \\
-0.6 & -0.4 & 1 & 0 \\
0 & 0.2 & 0.6 & 1
\end{array}
\right| = 0 \,,
\end{eqnarray}
$$
which yields the following second order equation:
$$
-0.0096 z^2 + 0.0432 z + 1 = 0 \,.
$$
Solving this equation, the roots of the polynomial are found to be $-8.20$ and $12.70$. This shows how to get the roots when the coefficients are known. But what about the other way around? is it possible to get the coefficients $\phi_{ij}$ from the roots?
With a polynomial consisting of scalars rather than matrices, the coefficients can be obtained from the roots of the polynomial. It is discussed here. In that setting, it is relatively easy to implement the idea. For example, the roots of the polynomial $P(z) = 1 -0.5z + 0.2z^2$ are $1.25 \pm 1.85i$; then, upon the values of the roots, the coefficients can be obtained as follows:
<code># R code
roots <- polyroot(c(1, -0.5, 0.2))
coefs <- 1
for (z in roots)
  coefs <- c(coefs, 0) - c(0, coefs) / z
coefs[-1]
#[1] -0.5+0i  0.2+0i
</code>
Is there a similar procedure that returns the coefficients of the matrices $\Phi_0$ and $\Phi_1$ from the roots obtained above?
Answer: With a scalar polynomial of degree $n$, one has $n$ roots and $n$ coefficients. Hence it's not so shocking that one can obtain one from the other and vice versa. But in your 4-by-4 matrix setting, you've got 2 roots and 16 coefficients for each of your two matrices. Hence you cannot hope to obtain all information in the latter from the former. (The situation may improve somewhat depending on what assumptions you can make on the form of your matrices, but getting a unique answer will require that these constraints be quite strong.)
Comment: Actually I have fewer coefficients (the zeros and ones are fixed) but still it seems I am trapped by the issue that you mention. I don't think I could afford setting as many restrictions as necessary, so I will have to reconsider the whole thing.
Comment: I figured your matrices were more specialized than I assumed in my answer, but didn't want to jump to conclusions about what they 'should be.' But yes, you'd probably still end up with too many parameters free to get a unique solution.


Non zero centered activation functions

Question: I read the following section from cs231n course notes:

Sigmoid outputs are not zero-centered. This is undesirable since neurons in later layers of processing in a Neural Network (more on
  this soon) would be receiving data that is not zero-centered. This has
  implications on the dynamics during gradient descent, because if the
  data coming into a neuron is always positive (e.g. $x > 0$
  elementwise in $f = w^Tx + b$)), then the gradient on the weights
  $w$ will during backpropagation become either all be positive, or
  all negative (depending on the gradient of the whole expression
  $f$). This could introduce undesirable zig-zagging dynamics in the
  gradient updates for the weights. However, notice that once these
  gradients are added up across a batch of data the final update for the
  weights can have variable signs, somewhat mitigating this issue.
  Therefore, this is an inconvenience but it has less severe
  consequences compared to the saturated activation problem above.

I have understood why the gradients with respect to weights $w$ become all positive or negative during backpropagation since
$$\dfrac{\partial f}{\partial w_j}=x_j \text{ , and } \dfrac{\partial L}{\partial w_j}=\dfrac{\partial L}{\partial f}\dfrac{\partial f}{\partial w_j}=\dfrac{\partial L}{\partial f}x_j$$
Thus the gradient of $L$ with respect to weights are all positive or negative depending on the sign of $\frac{\partial L}{\partial f}$.
But I do not understand why it has implications on the dynamics during gradient descent. More precisely, why do we get 'zig-zag' gradient updates if the derivatives with respect to weights are all positive or all negative? Can you provide some intuitions and mathematical arguments to justify this?
Answer: If the gradients are all the same sign, all the weights will either have to increase, or decrease over one iteration. So based on the step length, if you overshoot in the + direction, all weights will have to adjust in the - direction in the next time step. I think the idea he is getting at is similar to what you see in steepest descent (see slide 9 of http://www.robots.ox.ac.uk/~az/lectures/opt/lect1.pdf).
Comment: nice answer and very nice link - better explanation of the zig-zag issue of gradient descent and of similarities & differences between Gauss-Newton & Levenberg-Marquard than I've seen in a lot of time.
Comment: @Sid why dont we scale sigmoid to make it zero-centered? Just subtract 0.5
Comment: @Ritwik you are trying to get to tanh? But again it has vanishing gradient problem/gets saturated besides calculating exp() is expensive. Relu seems to work fine.
Comment: @Sid relu works fine, no doubt. But I am not able to understand why sigmoid is considered non-zero-centered function, and tanh is considered as zero-centered whereas sigmoid can easily be transformed into tanh

Non zero centered activation functions


View should show related articles from shared reference field - relation from a relation

Question: I have two content types: Article and Magazine. in Article there's an entity reference field to Magazine, field_related_magazines.
On my website, when an article is shown, I would like to show a list of related articles that share the same magazine.
When I make a new article, I can choose the magazine edition in which the article appeared.
Then, on the bottom of the node page, all other articles should be listed.
The thing I tried:
Make a views block 'Magazine related items' that lists Article titles and place the block on the Article pages.
Set the context for the block to work: Advanced>Contextual Filters>Content ID>Provide default value>Content ID from URL
Set the relation: relationships>Content using field_related_magazines (relate each Content with a field_related_magazines set to the content item.)
However, this only shows the current articles' title, not the titles of all other articles that share the same magazine.
How would I get all the others?
Answer: In order to fetch resources under specific Megazine, you need to have the Magazine ID on your contextual filter instead of the Article ID. Here is my suggestion:
Play with your URL pattern to add the magazine ID to it (You can do this using Pathauto and Token Module). Once you install those two modules define a URL Pattern for your articles (/[node: field_related_magazines:entity]/[node:title])
Now you each article page will have a URL with Magazine ID to it so, you can change your contextual filter to get Magazin ID from the URL using "Raw Value From URL". This will give you the result you are looking for.
Comment: Thank you, could you explain this somewhat further? I already use Pathauto and Token so that's nice. I tried to define a pattern with the ID of the related magazine, but the token [node: field_related_magazines:entity] you proposed is not available. Just [node: field_related_magazines] which gives the title of the magazine (I think). Then I tried to use that in the view pulling it with 'raw value from url', but with no luck.


Tremolo strokes above stems with flags

Question: Is it okay to draw tremolo strokes above/below stems with flags for more readability? Otherwise, it looks a bit tight when tremolo strokes are positioned right on a stem with a flag:

Also, I just don't want to increase the stem height, because it would look even worse in some cases.
Answer: If you feel that it is necessary you can do anything, as long as you make sure it is clear what you want. When you introduce non standard notation you need to be sure to explain it well, and usually in places where there is a standard notation, you should think at least thrice before going for a custom notation. You need to consider carefully if in your particular case (that is the notated material as well as the intended audience and performance situation) whether the benefit you assume from you notation is worth abandoning standard notation for.
Now if we compare these examples:

I cannot think of many examples where the latter would really outperform the first. But, some cases where this could make sense would be:

Scores for visually impaired people.
Scores for small children (but these tend not to feature tremolo).
Scores that are so complex that they require you to shorten the stems so much you do not have space for tremolo. But here the solution would probably not be adding them on top, because then you could simply use longer stems.
Scores where equal stem length between tremolo notes and non tremolo notes are important for optical reasons.
Really really small study scores. If you do a score at rastral height 10pt for example, this might just be too small to read the tremolo if notated conventionally:

In most cases though, I do not see the need to do so. If you really feel convinced that your reason is good enough, feel free to do it, but make sure to clarify the meaning. Notation is always flexible, there are not so much "rules" than conventions and good practices. Many challenging scores have led to creative solutions in notating them. But try to adhere to conventions as much as possible, unless there is a really convincing reason to do otherwise.
Musicians are trained to read conventions. If you do your own thing you'll confuse them. This will mean more time is needed to be spent rehearsing (because the musicians will need not only to learn the piece but also the notation) and will as a direct consequence reduce the chance that anyone will even consider performing the score (unless you are a really big name composer, at this point you will be able to throw anything at musicians and it will be performed. But if a normal composer hands in a score to an orchestra or an ensemble and tells them that they need to learn special notation — chances are high they are not even going to look at the score and will play something else).
Comment: @GuseynIsmayylov Yes, Lilypond shortens stem tremolo beams on flagged notes with stem going up to avoid collision between tremolo beams and the flag.
Comment: Thanks for such detailed answer. I can notice that in first image tremolo strokes are bit shorter horizontally, is it default behaviour of the software you're using?
Answer: No, this is not standard notation.  If it takes a longer stem, write a longer stem.
Comment: It's hard to prove a negative.  I think YOU'VE got to find a reference claiming that it IS :-)
Comment: do you have any reference where it's claimed that it's the only way to place tremolo strokes?
Comment: I guess, you're right

Tremolo strokes above stems with flags


Get kubernetes image from container registry

Question: Is it possible to get a list of available images from Kubernetes container registry? Preferably by REST API.
Comment: As far as I know, Kubernetes doesn't have a docker registry. You can install a local docker registry as a Kubernetes pod or on a separate environment or machine. After installing the docker registry, you can get the list of available repositories using this api endpoint: https://docs.docker.com/registry/spec/api/#listing-repositories
Comment: can you be more precise? do you have a registry running on k8s or do you want to get the list of images that are used in your k8s cluster? (not in the registry)
Answer: The "standard" k8s.gcr.io registry used honors docker's Registry API
curl -H 'accept: application/vnd.docker.distribution.manifest.v2+json' \
  https://k8s.gcr.io/v2/kube-apiserver/tags/list \
  | jq .tags


Why are the diameters I've made perpendicular?

Question: In the following picture, point A was found by drawing a line from point C through point B.  As it happens, point A is ninety degrees from point E.  Can someone explain why this is true?
A gif of the process used to make this image can be found here.
Comment: You haven't told us how points $B,C$ are defined.
Comment: @user10354138 I don't have the vocabulary to define them.  I've added a link to an image that shows how the points were found.
Answer: I've added some additional lines in my copy of your diagram below. I won't provide a formal proof but just point out some geometric properties which you may find useful. I'm switching the question but it remains equivalent to your original question. Without line ABC, the construction is possible with the diameter of the largest circle parallel to the chord from point $C$. Due to symmetry, $DE$ will be perpendicular to $AD$. The question therefore is, will a line through $CB$ pass through $A$? This is equivalent to your question.
The sketch below can be used to prove this via the congruency of triangles $FDG$ and $HDG$, and angles subtended by the same arcs ($GB$ and $AF$) at the center $H$ and $D (2x)$ being double the angle at the circumference $C (x)$. What this does is show the line AC is colinear with line BC, both being at angle x to the chord FC, hence the extension of CB passes through A.
It then follows that point A will determine the diameter of the larger circle through AD which will be perpendicular to DE.
Comment: I've followed your approach,  but tried to add proof that $D$ is the center of the  circle.
Comment: @Edward Porcello that's kind of a complimentary proof which has many relationships supporting it. Alternate angles, angles subtended by an arc, symmetry etc.
Answer: I've renamed points for no good reason ...

A little angle chasing gives that $\angle OQP \cong \angle OTP$ and $\angle POQ\cong\angle ROQ$. Also, in $\bigcirc Q$,
(central) $\angle PQU$ and (inscribed) $\angle PTU$ subtend $\stackrel{\frown}{PU}$, so that $\angle UTP = \frac12\angle OQP = \frac12\angle OTP$.
Thus, $\overline{OU}$ and $\overline{TU}$ are bisectors of respective angles in $\triangle OTP$, so that $U$ is the incenter of that triangle. This implies that $\overline{PV}$ bisects $\angle OPS$. Finally $\triangle OPV$ is isosceles,
$\overline{OVP} \cong \angle OPV \cong \angle VPS$, whence $\overline{OV}\parallel\overline{PS}$, and the result follows. $\square$
Answer: According to the link, the construction seems to be as follows: On the circumference of a given circle, taking points $F$, $G$ at random, draw a circle with center $F$ and radius $FG$ meeting the given circle again at $H$, and with center $H$ and radius $HF$ draw another circle meeting the given circle again at $C$. Join $GC$, intersecting the two equal circles at $K$, $L$, and join $FK$ and $HL$, extended to meet at $D$. Through the intersection of the two smaller circles at $J$ draw $DJ$ meeting the given circle at $E$. Let $HD$ intersect the circle about $H$ at $B$, and (changing here the order of construction) join $CB$.  Through $D$ draw $AM$ parallel to $GC$, and join $AC$. Prove that $B$ lies on $AC$ (cf. @Phil H), i.e. that $CB$ extended crosses the given circle at $A$, making $AD$ perpendicular to $DE$.
But first it must be shown that $D$ is the center of the given circle.
Joining $GF$, $FH$, $HC$, and $KH$, then since $FG=HC$, $FGCH$ is an isosceles trapezoid with$$FH\parallel GC$$and by symmetry $DE$ perpendicularly bisects $GC$ and $FH$.

Again, since $GF=FH=HK$, then $GFHK$ is a rhombus, with $KG$, $KH$ making equal angles with diagonal $FK$, whence the center of the given circle lies on $FK$ extended.
It follows by a like argument that the center of the circle lies on $HL$. Therefore $D$ is the center.
Now since $AM\parallel GC$, then$$\angle GCA=\angle MAC$$But (again cf. @Phil H)$$\angle KCB=\frac12\angle KHB=\frac12\angle ADG=\frac12\angle MDC=\angle MAC$$Therefore$$\angle GCA=\angle KCB$$$CB$ extended to the given circle at $A$ meets the line draw through center $D$ parallel to $GC$, and consequently$$AD\perp DE$$