Como focar um elemento

Question: No CSS seria algo assim:
div {
    display: none;
}
div:active {
    display: block;
}

E alguma ação do usuário daria o foco a essa div pelo javascript
Sei que posso fazer adicionando e removendo uma classe/atributo porém  quero fazer sem isso
tentei, sem sucesso:
document.getElementByTagName('div')[0].focus();

document.activeElement = document.getElementByTagName('div')[0];

Answer: Acho que você está misturando as pseudo-classes :active com :focus. A primeira ocorre quando você clica e segura o clique sobre o elemento; a segunda é quando recebe o focus — são comportamentos distintos.
Neste caso você deveria usar:
div:focus {
   display: block;
}

Mas isso também não funcionaria porque não é possível dar focus a um elemento oculto.
Geralmente os que podem receber focus são elementos de formulários (inputs, selects etc.); divs podem receber se tiverem o atributo tabindex, como mostra o exemplo abaixo:

document.querySelector("div").focus();
div {
   opacity: .2;
}
div:focus {
   opacity: 1;
}
Clique fora do texto para tirar o focus da div:

texto

Concluindo, seu intento não é possível de realizar, principalmente com elementos ocultos.
Edit a pedido do autor
Como não se pode dar focus ao elemento oculto, pode colocar opacity: 0 e position: absolute. Assim o elemento ficará transparente e não irá ocupar espaço no layout:

document.querySelector("div").focus();
div {
   opacity: 0;
   position: absolute;
}
div:focus {
   opacity: 1;
   position: static;
}
Clique fora do texto para tirar o focus:

texto
 Texto texto
Comment: Então não é possível dar foco a um elemento oculto? Mesmo que seja com o `opacity: 0` em vez de `display: none`
Comment: Isso, não é possível. O opacity não faz com que o elemento seja oculto, ele continua lá, apenas não aparece porque não tem opacidade.
Comment: Com opacity é possível, porque não é oculto, como mostrei no exemplo da resposta.
Comment: Dar focus a algo que não existe na tela vai até contra o conceito da função rs... Como vou focar algo que não faz parte do layout? :)
Comment: Então até da pra fazer algo como quero... colocar o `opacity: 0; position: absolute;` no elemento sem o foco e com o foco colocar `opacity: 1; position: initial;`
Comment: coloque um exemplo na resposta pra eu aceitar

Como focar um elemento


Migrate Jenkins jobs from Cloud Bees to another Jenkins server

Question: I have a Jenkins server at CloudBees server and it has a lot of jobs.
I have created new Jenkins server at AWS Ec2 instance.
Now, I need to migrate all Jenkins jobs from CloudBees to New Jenkins Server(AWS EC2instance)
How can I do this task? Is there any way to migrate all jobs by CLI?
Answer: Use Backup Plugin or thinBackup
Answer: You first need to ensure that you do not use proprietary CloudBees features (RBAC, Folders+ plugins). This is the only thing that's really specific to migrating from a CloudBees Jenkins.
After that, standard steps for migrating Jenkins apply:

ensure that you have same plugins installed on the new Jenkins
align credentials and credentials-IDS
API tokens need special handling

After that, you can just copy all <code>$JENKINS_HOME/jobs/*/config.xml</code> files (if using folders, copy recursively).
You can also copy job configs via CLI or REST API, but usually the fastest way is to copy directly on filesystem level.


Image Style issue

Question: I have created an Image style which I am applying in my Blog view.
But the Images are not generated in the Blog View Image folder and hence it is not showing up because of the path issue.
sites/default/files/blog/images/testing.jpg - This is the path where my images are getting stored.
sites/default/files/styles/test/public/blog/images/testing.jpg - This is the path generated from my view.
Adding "$config['image.settings']['allow_insecure_derivatives'] = TRUE;" in settings.php solves my issue. But I prefer not to use this because of security risks.
Also, there are no PHP errors that I can notice.
Please suggest to me how the issue can be resolved.
Comment: Welcome to Drupal Answers!  How did you upload/store the original images? How did you configure the image style? And how did you configure the view to display it? Please update your question and add the exact steps that need to be done to reproduce this issue. Many thanks
Comment: Verify that your folder `sites/default/files/styles` have the good owner and group (www-data) see https://www.cyberciti.biz/faq/find-the-group-name-of-the-folder-in-unix-linux. If it's not the case `cd sites/default/files/` and `sudo chown -R www-data:www-data styles` and check that the folder is writable for the group. If it's not the case `sudo chmod -R g+w styles`
Answer: Maybe you're trying to create the URL to the image style by string manipulation? There is a security check in place to ensure that image derivatives can't be used to DDoS (distributed denial of service) your site - basically spamming your server with image style requests.

Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.

SA-CORE-2013-002

For this all image style URL's now require a token in the query string in the form of sites/default/files/styles/test/public/blog/images/testing.jpg?itok={token} (note it's the itok querystring in the end).
You need to create the image style URL through various formatters or class methods provided in order to get a URL with the security token, otherwise you will get access denied on any URL without the itok. If you're using Views, then for the Image field in your view change the Formatter to "Image Style" and choose the style in the view's config.
To do this from code, you should use the ImageStyle entity to generate the URL's, which give you the URL with token as well. If you have a $file file entity or just a file URI string you can generate it like this:
$style_name = 'test';
$style = ImageStyle::load($style_name);
$file_uri = $file->getFileUri();
$image_style_url = $style->buildUrl($file_uri);

or single line:
$image_style_url = ImageStyle::load('test')->buildUrl($file->getFileUri());

See also: Drupal 7.20 release notes where this change happened.
Comment: Here the original Image is getting created with the path sites/default/files/blog/images/testing.jpg
But the cropped Image (Image of applied Image style) is not getting generated. But the path is getting created sites/default/files/styles/test/public/blog/images/testing.jpg

Please provide more clarity on the above Answer
Comment: @lakshmiHS added more info

Image Style issue


Computing this limit: $ \lim_{y\to0} \frac{f(x,y) - f(x-y,y)}{y} = g(x)$

Question: If $f(x,y) \in \mathbb{R^2}$ and $g(x) \in \mathbb{R}$. Assuming
$\frac{f(x,y) - f(x-y,y)}{y} = g(x); \forall y \in \mathbb{R}$
$$$$
Can we do the following:
$$ \lim_{y\to0} \frac{f(x,y) - f(x-y,y)}{y} = g(x)$$
$$ \lim_{y\to0} \frac{\partial{f(x,y)}}{{\partial x}}= g(x) $$
Comment: What are the properties of $f$?  Differentiable?
Answer: No, that's not quite valid, though it's getting you to the right answer. The difference quotient inside the limit is not equal to the partial $\frac{\partial f}{\partial x}$, because it's just a difference quotient; it doesn't become a derivative until you take a limit. And even after you do, that quotient is not simply a partial in the $x$ direction, because both terms are changing.
$\begin{align*}
\lim_{y \to 0} \frac{f(x,y) - f(x-y,y)}{y} &= \lim_{y \to 0} \frac{f(x,y) - f(x,0)}{y} - \lim_{y \to 0} \frac{f(x-y,y) - f(x,0)}{y} \\
&= \frac{\partial f}{\partial y}(x,0) - \left(-\frac{\partial f}{\partial x}(x,0) + \frac{\partial f}{\partial y}(x,0)\right) \\
&= \frac{\partial f}{\partial x}(x,0)
\end{align*}$
For the second equality above I recognized those difference quotients as directional derivatives.
Comment: To use the chain rule in the second line, you need some kind of regularity condition on $f$ (e.g., differentiable).
Comment: Yes, I was assuming the function was differentiable. This looked to be an intro multivariable calc problem about manipulating directional derivatives, so I figured that was safe.
Comment: I'm just a little confused by the chain rule part. How did that work?
Comment: What are your working definitions of (directional) derivatives of functions of 2 variables?
Comment: never mind, I got it.
Answer: Why not to use Taylor expansion around $y=0$ ?
$$f(x,y)=f(x,0)+y f^{(0,1)}(x,0)+O\left(y^2\right)$$
$$f(x-y,y)=f(x,0)+y \left(f^{(0,1)}(x,0)-f^{(1,0)}(x,0)\right)+O\left(y^2\right)$$
$$f(x,y)-f(x-y,y)=y f^{(1,0)}(x,0)+O\left(y^2\right)$$
$$\frac{f(x,y)-f(x-y,y) }y=f^{(1,0)}(x,0)+O\left(y^1\right)$$


In finding boundary of the product of two half-lines, shall homeomorphism be global?

Question: Lets $ \mathbb{R_{+}^{n}} = \mathbb{R^{n-1}} \times [0;+\infty[ $
Basically in my course I have this statement within the definition of a manifold with boundary:

$ \forall x \in M, \exists U_x $ an open neighborhood of $x$ in $M$ and a homeomorphism $\phi: U_x \rightarrow A \subseteq \mathbb{R_{+}^{n}}$, where $A$ is an open in  $ \mathbb{R_{+}^{n}} $

Later it is written that:

a point $x$ is said to be a boundary point if for one (and hence for all) homeomorphism $\phi: U_x \rightarrow A \subseteq \mathbb{R_{+}^{n}}  $, with $U_x \in V(x)$ and $A$ is an open in  $ \mathbb{R_{+}^{n}}$ we have  $\phi(x) \in \mathbb{R^{n-1}} \times \{0\} $

The above became problematic to me once I tried to prove:

let M be $[0;+\infty[ \times [0;+\infty[ $, then its boundary $\partial M = ([0;+\infty[ \times {0})  \cup ( {0} \times [0;+\infty[) $

It seems to me that for any boundary points in $M$, the only open neighborhood available is $M$ itself (as it is the whole space it is open by the very definition of a topology). Indeed, no other open set can contain one of these boundary points, for example $(0,0)$.
Accepting that I have to exhibit a homeomorphism between $\mathbb{R_{+}^2}$ and $M$. Basically between the upper half of the plane and the upper right quarter of the plane. And then I'll have to prove $\partial M $ to be the set of point ending up on the $x$-axis.

I guess the mapping $z \rightarrow z^2$ in the complex plane will do the job. It will double angles, mapping the boundaries of the right set on the  boundaries of the left one.

My question:

Is the above correct?
If so, since boundary points will never be contained in an open set other than $\mathbb{R_{+}^{n}}$ itself, the above local homeomorphisms will always have to be global as far as boundary points are concerned ?
Answer:
for any boundary points in $M$, the only open neighborhood available is $M$ itself

This is not true. Recall that by the definition of induced topology, the intersection $U\cap M$ is open in $M$ for every open set $U\subset\mathbb{R}^2$. In particular, the set
$$
\{(x,y)\in M: x<1, y<1\}
$$
is an open subset of $M$ containing $(0,0)$.
But you correctly observed that the map $z\mapsto z^2$ gives a global homeomorphism between $M$ and the upper half-plane, which suffices to prove that $M$ is a (topological) manifold with boundary. You did not have to find a global homeomorphism, but since one is easily found, may as well use it.
More generally, the product of topological manifolds $M,N$ with boundary is itself a topological manifold with boundary, and $\partial (M\times N) = \partial M\times N\cup M\times \partial N$. (This fails for smooth manifolds.)
Comment: Thanks, I was indeed confused because I was not using induced topology...


Azure Scheduler to remove old azure-sql-database-entries, possible?

Question: As the title is stating my question. i am wondering if this is possible and in that case what should i read on? Anyone done this before?
Ok so to be clear - what i want to do is:

Clear old entires in a database, preiodically. That is for example
clear all  entries in a database table that are 1 month old.
Possible to use Azure Scheduler to automate this for azure sql
Database?

Thanks! :)
Comment: Hi John - Need to know a little bit more about what you're trying to do, do you mind update your questions to be more precise?
Comment: Thank you for your responce. I hope that made the picture a bit clearer.
Comment: How are you doing this today? Is there an HTTP endpoint that you call, or maybe a stored procedure?
Comment: We managed to do the work with the help of the "job" being written in an API having the correct functionality. And using the scheduler to trigger the API as a Delete function wich in turn will do what we where looking for.

I dont know if there is a better way of doing it.
Answer: Per your description, I see a two options for you using Azure services to do this with ease -

Maintain your current API, and set up Azure Scheduler to call the API on a defined schedule. This is how most Scheduler users use the service for and will fit your need.
Rewrite the clean up logic as a stored procedure, and use Azure Logic Apps to trigger the stored procedure on a defined schedule. The benefit for this is that there's no more code to maintain/host besides the stored procedure.
Comment: Both suggestions where great, It works Perfectly, Thank you!
Comment: Great to hear @John, please feel free to reach out to me anytime for any questions and suggestions regarding both Logic Apps and Scheduler service at Derek.Li (at) microsoft dot com.


Automatic updating of data in TableView and traceing all changes in QSqlTableModel

Question: I have TableView and QSqlTableModel as a model for this TableView. They connected as written here (the second method).
I'd like that TableView would refresh its view (data) automatically (when something inserted/updated/removed in the model). How should I do this?
Can I trace somehow all changes in QSqlTableModel (insertion/updating/removing) by one signal? Yes, probably, I can look after rowsInserted, rowsModed and rowsRemoved signals, but may there is one signal for any type of change?
Comment: in your QsqlTableModel class you should emit a **SIGNAL** for ex **dataChanged()** in the **method** where you think changes happened and connect it to a **SLOT** to do what you want to do
Answer: There doesn't seem to be a single signal in QSqlTableModel or its base classes. But I suppose if you don't want to implement a different slot for each signal, you can connect those signals to a custom signal. So every time one of the signals rowsInserted, rowsMoved... are emitted, it will automatically emit your custom signal.
UPDATE:
side note:
The rowsInserted etc. signals are from the base class QAbstractItemModel. It might be easier to work with QSqlTableModel's signals such as: beforeDelete, beforeInsert etc.


JSON em Laravel

Question: Queria saber como faço pra mandar os dados da query em json através do controller e como a view deveria receber eles.
Controller:
$dados = $req->all();

$query = "";

if($dados['filter'] == 1)
{

  $query = User::where('id','LIKE','%'.$dados['search'].'%');
}
else if($dados['filter'] == 2)
{

  $query = User::where('name','LIKE','%'.$dados['search'].'%');
}
else if($dados['filter'] == 3)
{

  $query = User::where('email','LIKE','%'.$dados['search'].'%');
}

return view('users.index')->with([$users->$query]);

View:
  @foreach($users as $user)

        {{$user->id}}
        {{$user->name}}
        {{$user->email}}

      @endforeach

Comment: Como você colocou o return da sua função no controller? Você só precisa colocar o view/('view')->with([$var_para_chamar_no_blade -> $query]);
Comment: entendi, vou estar tentanto
Comment: Luiz, olhe como estava o return eu editei na publicação
Comment: Luiz, eu coloquei, porém esta dando erro de Object
Comment: Não é necessário usar saudacoes aqui, se quiser saber mais o porquê, leia: https://pt.meta.stackoverflow.com/q/846/28595
Comment: Obrigado! Sou novo aqui
Comment: faltou a atribuição da variável p chamar no blade, tenta assim:
return view('users.index')->with(['users' -> $query]);
Comment: ele da esse erro: Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
Comment: boa.. acho q faltou ai o ->get() no final. atualiza o retorno para: ->with(['users' -> $query->get()]);
Comment: é isso mesmo: https://laravel.com/docs/5.5/queries#json-where-clauses
Comment: Cara, mesmo erro
Comment: cara tem algum bo na query ai, troca o LIKE por like, se não rolar tenta ver aqui q é o mesmo BO.
https://pt.stackoverflow.com/questions/165859/object-of-class-illuminate-database-eloquent-builder-could-not-be-converted-to-s
Answer: Faça da seguinte maneira:
$dados = $req->all();

$query = "";

if($dados['filter'] == 1)
{

  $users = User::where('id','LIKE','"%'.$dados['search'].'%"')->get();
}
else if($dados['filter'] == 2)
{

  $users = User::where('name','LIKE','"%'.$dados['search'].'%"')->get();
}
else if($dados['filter'] == 3)
{

  $users= User::where('email','LIKE','"%'.$dados['search'].'%"')->get();
}

return view('users.index', compact('users'));

Sua view pode deixar da mesma maneira.
Aconselho você tirar isso da Controller e separar em uma outra camada, uma Service por exemplo.

JSON em Laravel


Fredholm integral operator

Question: Let $T(f)(x):=\int_{\mathbb{R}^d} k(x,y)f(y) dy$ where $k_1(x)= \int_{\mathbb{R}^d} |k(x,y)|dy$ and $k_2(y)= \int_{\mathbb{R}^d} |k(x,y)|dx$ are two $L^{\infty}$ functions. Then I want to show that $T: L^2 \rightarrow L^2$ has $||T||\le \sqrt{||k_1||_{L^{\infty}}||k_2||_{L^{\infty}}}.$
I was able to show this inequality without the square-root, i.e.
$$||T||_{L^2} = \sup_{||\phi||_2=||\psi||_2=1} \langle T \psi, \phi \rangle$$
$$\le  \sup_{||\phi||_2=||\psi||_2=1} \int_{\mathbb{R}^{2d}} |k(x,y)| |\phi(x)| |\psi(y)| dx dy$$
and now by Cauchy schwartz
$$\le  \sup_{||\phi||_2=||\psi||_2=1} \int_{\mathbb{R}^{2d}} |k(x,y)| |\phi(x)|^2 dx dy\int_{\mathbb{R}^{2d}}|k(x,y)||\psi(y)| dx dy$$
$$\le  \sup_{||\phi||_2=||\psi||_2=1} \int_{\mathbb{R}^{d}}|k_1(y)| |\phi(y)|^2 dy \int_{\mathbb{R}^{d}}|k_2(x)| |\phi(x)|^2 dx$$
$$\le ||k_1||_{\infty} ||k_2||_{\infty}$$
Now, I was wondering whether the more inequality stated on the exercise sheet is still correct or whether there has to be some error?
Answer: You forgot a square root in the Cauchy-Schwarz inequality. To be more precise: Choose $\phi, \psi \in L^{2}(\mathbb{R}^d)$ with $\lvert \lvert \phi \rvert \rvert_2 = \lvert \lvert \psi \rvert \rvert_2 = 1$. Then
\begin{align}
\lvert \langle T \psi, \phi \rangle \rvert = \Bigg| \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} k(x,y) \psi(x) \phi(y) \, \textrm{d}y  \, \textrm{d}x \Bigg|
\leq \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} \big( \lvert k(x,y) \rvert^{1/2} \lvert \phi(x) \rvert \big) \big( \lvert k(x,y) \rvert^{1/2} \lvert \psi(y) \rvert \big) \, \textrm{d}y \, \textrm{d}x.
\end{align}
Now, we can apply Cauchy-Schwarz' inequality (or Hölder inequality) and Tonelli's theorem, and we obtain that
\begin{align}
\lvert \langle T \psi, \phi \rangle \rvert
&\leq \Bigg( \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} \lvert k(x,y) \rvert \lvert \phi(x) \rvert^{2} \, \textrm{d}y \, \textrm{d}x \Bigg)^{1/2}\Bigg( \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} \lvert k(x,y) \rvert \lvert \psi(y) \rvert^{2} \, \textrm{d}x \, \textrm{d}y \Bigg)^{1/2}\\
& = \Bigg( \int_{\mathbb{R}^d} k_1(x) \lvert \phi(x) \rvert^{2} \, \textrm{d}x \Bigg)^{1/2}\Bigg( \int_{\mathbb{R}^d} k_2(y) \lvert \psi(y) \rvert^{2} \, \textrm{d}x \Bigg)^{1/2}\\
& \leq \Big( \lvert \lvert k_1 \rvert \rvert_{L^{\infty}(\mathbb{R}^d)} \lvert \lvert k_2 \rvert \rvert_{L^{\infty}(\mathbb{R}^d) } \lvert \lvert \phi \rvert \rvert_2 \lvert \lvert \psi \rvert \rvert_2 \Big)^{1/2}
= \sqrt{ \lvert \lvert k_1 \rvert \rvert_{L^{\infty}(\mathbb{R}^d)} \lvert \lvert k_2 \rvert \rvert_{L^{\infty}(\mathbb{R}^d) } }.
\end{align}
As this is true for all $\phi, \psi \in L^{2}(\mathbb{R}^d)$ with $\lvert \lvert \phi \rvert \rvert_2 = \lvert \lvert \psi \rvert \rvert_2 = 1$ the claim follows.

Fredholm integral operator


Testing correlation between multiscaled rank-ordered variables

Question: I aim to test correlation for the following rank ordered ordinal variables :

1st set of variables - Total 4 ( These are reduced variables using PCA from original 10 variables to 4, ranked on a scale of 1 to 10)
2nd set of variables - Total 2 ( These are reduced variables using PCA from original 6 variables to 2, ranked on a scale of 1 to 6)
3rd set of variables - Total 9 , ranked on a scale of 1 to 9

I believe Spearman Rank Correlation (SRC) would be the right technique to test correlation. However, the tricky part is all the above variables are ranked at different scales. All the SRC examples show that the variables tested for correlation are measured at same scale.
Is there any way to standardise the rank-ordered ordinal variables on the same scale to be eligible for Spearman Rank Correlation test though they are measured on different scales?
I would be grateful if you could advise on it.
Many Thanks.
Regards,
- Tanuja
Answer: It is not necessary to have the same scales if you use Spearman's Rank Correlation.
The benefit of rank techniques is that the results do not change if you do monotonous transformations on the original data. Such transformations would take care of different scales.
Rank techniques basically replace the original values by their ranks, i.e. the number if the values were ordered. So if you transform monotonically the original data, their ranks do not change: E.g. the largest value will still be the largest value after the transformation. Consequently, statistics defined on the ranks (like Spearman's Rank Correlation or the Wilcoxon-Mann-Whitney-test) will be the same irrespective of the monotonous transformation.
Comment: Is there any reference article or weblink which explains that SRC test need not have same scale variables? Secondly, what techniques are used to achieve transformation or does SRC take care of it?


Why does the integral of $x^x$ not have a non-elementary solution.

Question: If a function like $\frac{\sin x}{x}$ can have a solution to its integral in the form of a non-elementary function $Si(x)=\int_0^x{\frac{\sin t}{t}}dt$ , then why can't the function $x^x$ have a non-elementary solution to its integral in the form of $\int_0^x{t^t}dt$
Comment: It *does* have a non-elementary solution.  Whether or not this has been *named* is a different question.  If it doesn't have a name, it's probably because it hasn't been useful to a lot of people.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @johnnyb Thanks for the answer and clarifying that for me. It seems that the integral probably hasn't been named as i couldn't find anything online that references that integrals non-elementary solution.
Comment: Check this: https://math.stackexchange.com/a/1068896/42969
Comment: Maybe the question should be: Some non-elementary functions have standard names, like Si.  But why does $\int_0^x{t^t}dt$ not have a standard name?
Answer: It does have one, see Sophomores dream function. The notation isn't as commonly used as $Si(x)$ but you'll see the following notation:
$$Sphd(\alpha ; x) = \int_{0}^{x} {t^{\alpha t}dt}$$
So you'd write the integral of $t^t$ as
$$Sphd(1 ; x) = \int_{0}^{x} {t^{t}dt}$$
or sometimes simply
$$Sphd(x) = \int_{0}^{x} {t^tdt}$$


read file in form with js codeigniter

Question: i need to create a form with two textarea and 1 file input that uploads a txt/csv file where there are 2 numbers in two row (1 row - 1 number) and popolate the 2 textarea with the two numbers using codeigniter and Javascript. thanks for the help
file:

     59.8
     42.8
     55.8
     51.1

html
<input type="file" id="id">

<textarea id="result1" cols="50"></textarea>
<textarea id="result2" cols="50"></textarea>
<textarea id="result3" cols="50"></textarea>
<textarea id="result4" cols="50"></textarea>

this is the js if there is 1 textarea where print the result but every row need to be print in a single textarea and doens't work
  $("#id").on('change', function(event){
        event.preventDefault();

        var selectedFile = event.target.files[0];
        var reader = new FileReader();

        var result = document.getElementById("param3");

        reader.onload = function(event) {
          result.innerHTML = event.target.result;
        };

        reader.readAsText(selectedFile);
    });

Comment:
Answer: To achieve this you can use split() to convert the value read from the text file in to an array, with one element per line of text.
Then you can loop through that array and set the values within each textarea. Try this:
<input type="file" id="id">

<textarea class="result" id="result1" cols="50"></textarea>
<textarea class="result" id="result2" cols="50"></textarea>
<textarea class="result" id="result3" cols="50"></textarea>
<textarea class="result" id="result4" cols="50"></textarea>

let $results = $('.result');

$("#id").on('change', e => {
  e.preventDefault();

  var reader = new FileReader();
  reader.onload = e => {
    e.target.result.split(/\r\n/).forEach((text, i) => {
      $results.eq(i).val(text);
    });
  };
  reader.readAsText(e.target.files[0]);
});

Note that I applied the same class attribute to the textarea elements to make the logic much simpler. Generally speaking, incremental id attributes are an anti-pattern and should be avoided where possible.
Here's a working example in a jsFiddle (as SO snippets are sandboxed and cannot use FileReader). You'll need to create a text file yourself to see it in action.

read file in form with js codeigniter


Copy multi gitlab variable to file .env in server

Question: this is the script that I copy Gitlab variable to file .env:
 - ssh server "echo CI_REGISTRY_IMAGE=$CI_REGISTRY_IMAGE >> ./shopping-cart-nestjs/.env"
 - ssh server "echo CI_COMMIT_REF_SLUG=$CI_COMMIT_REF_SLUG >> ./shopping-cart-nestjs/.env"
 - // more script if I have more variable

it work well but now if I have multiple gitlab variable I need to write multiple script line. How do I solve this.I search on the Internet and it suggest to use for.
This is my script using for but when read .env it is empty:
 - for var in CI_REGISTRY_IMAGE CI_COMMIT_REF_SLUG; do
        ssh server "echo $var=\$$var >> ./shopping-cart-nestjs/.env";
      done
 - ssh server "cat ./shopping-cart-nestjs/.env"
 CI_REGISTRY_IMAGE=
 CI_COMMIT_REF_SLUG=

Any help is appriciated.
Comment: Consider `CI_COMMIT_REF_SLUG=';echo rm /some/dir;'; ssh server "echo CI_COMMIT_REF_SLUG=$CI_COMMIT_REF_SLUG >> ./shopping-cart-nestjs/.env"`. You shouldn't pass unchecked variables to your server to be later re-evaled, this can end bad! Consider researching `eval` security issues, use `printf "%q"` or use  `${var@Q}` bash expansion to quote variables. check scripts with shellcheck. If this is getting complicated, add `.sh` script to the repo, checked with shellcheck and call it.
Comment: I don't know gitlab, but bash has no idea of a "multiple" variable. Do you  perhaps mean a bash array?
Comment: why do you echo on remote side?
Comment: @KamilCuk, so do not need to echo, right ?
Answer: Just run ssh once, why echo something already expanded to a file for every var.
- for var in CI_REGISTRY_IMAGE CI_COMMIT_REF_SLUG; do
     echo "$var=${!var}";
  done | ssh server 'cat > ./shopping-cart-nestjs/.env'

Overall, I would rather do:
- for var in CI_REGISTRY_IMAGE CI_COMMIT_REF_SLUG; do
     echo "$var=${!var}";
  done >tempenv
- scp tempenv server:./shopping-cart-nestjs/.env

${!var} is bash indirect expansion. On POSIX shell you have to use eval. Research how to expand a variable by using a name.


How do I execute my custom submission handler before any other submission handler?

Question: I want to execute my custom submission handler for a button before any other submission handler associated with that button. How could I do this?
Answer: You should add it at the first position in handlers array.
<code>$form['actions']['submit']['#submit'] = array_merge( array('your_form_submit'), $form['actions']['submit']['#submit']);
</code>
Answer: array_unshift() the name of the function onto the "#submit" array of the button.
Comment: This is valid also for `$form['#submit']` for which the code is similar to `array_unshift($form['#submit'], 'mymodule_form_submit')`.
Comment: @kiamlaluno Me thinks this would affect all buttons on the form.
Comment: I know; I was pointing out to who reads that the same code can be used with `$form['#submit']`, not that in this case the code should alter both the buttons' submission handler and the form submission handler.


Proving/disproving an identity on a Hessian.

Question: Let $A=(a_{i,j})$ be a $n$ x $n$ matrix $(n\geq 2)$, where $a_{i,i} = |x|^2-2x_i ^2$ and $a_{i,j} = -2x_i x_j$ for $i\neq j$. Here $|x|^2 = x_1^2+x_2^2+ \cdots + x_n^2$. I'd like to compute the determinant of $A$.
Calculations suggest that $\det A = -|x|^{2n}$ and it is true for $n=2,3,4$. But I have no idea how to prove/disprove that identity for general $n$.
This matrix came up when computing the Hessian of the function $\phi(\xi) = \log |\xi| + \frac{1}{\tau}x\cdot \xi$ at its critical point $\displaystyle \xi_0 = -\frac{\tau}{|x|^2}x$. I was estimating an oscillatory integral by using the stationary phase method.
Answer: Notice that we can write your matrix as
$$A(x) = |\underline{x}|^2 I - 2\underline{x}\underline{x}^t = |\underline{x}|^2(I-2\underline{v}\underline{v}^t)$$
where $\underline{v} = \frac{\underline{x}}{|\underline{x}|}$. So your matrix is basically an Householder matrix, scaled by $|\underline{x}|^2$. In other words, your transformation is a reflection about the vector $\underline{v}$ plus a dilatation of a factor $|\underline{x}|^2$. Now, since an Householder matrix has has one eigenvalue equal to $-1$ and all the others equal to $1$ (easy to prove), it follows that for your matrix
$$\lambda_1(A) = -|\underline{x}|^2\qquad \lambda_{2,\ldots,n}=|\underline{x}|^2$$
and hence,
$$det(A)=-|\underline{x}|^{2n}$$
Comment: Interesting. I just got to know Householder matrix from this answer. Interesting. Thank you very much.
Answer: Because $A$ is symmetric, by the spectral theorem, there is a real orthogonal matrix $Q$ such that $Q^{−1}AQ$ is a diagonal matrix D. The determinant of $A$ will then be the product of the diagonal entries of $D$. It should be possible to find a general formula for $Q$ and $D$ (as $n$ varies...)
Comment: Thanks for your interest and answer. Bartgol gave a simple proof for the problem.


Como armazenar o resultado de uma iteração em uma nova variável usando python?

Question: Bom dia pessoal!
Estou analisando um conjunto de dados de compartilhamento de bicicletas. Nesse dataset existe uma coluna chamada 'birthyear', que indica o ano de nascimento do usuário.
Estou tentando transformar essa coluna em uma coluna de série temporal. Para fazer isso, criei a seguinte iteração:
salvei essa coluna em uma variavel chamada yr
for i in yr:
    x = datetime(yr[i],1,1)
    print(x)'

A saída é:
1964-01-01 00:00:00
1986-01-01 00:00:00
1967-01-01 00:00:00
1976-01-01 00:00:00
1991-01-01 00:00:00
1975-01-01 00:00:00
1975-01-01 00:00:00

Mas quando armazeno a saída na variável 'x', ela não armazena essa lista, mas apenas a primeira linha.
Saída: datetime.datetime(1975, 1, 1, 0, 0)

Como posso resolver esse problema ?
Comment: teria como postar o código de yr aqui?
Comment: `yr = dataframe.birthyear`
Answer: Se eu entendi direito, você pode adicionar elementos em uma lista python usando append
x=[]
for i in yr:
    x.append(datetime(yr[i],1,1))

print(x)

Isso vai adicionar todas as iterações do loop na lista x, da maneira que você demonstrou no seu código, a cada iteração a variável x é sobrescrita, no final do loop a variável x só terá armazenado o valor da ultima iteração.
Comment: Muito obrigado !


What does conditioning on a random variable mean?

Question: What does conditioning on a random variable mean?
For example: in p(X|Y), X and Y are the random variables, so does the conditioning on Y mean Y is fixed (or non-random)?
Comment: wondering what a conditional random variable means, normally a conditioned random variable means known value, such as P(X|Y=1), but I also noticed sometimes Y is unspecified as P(X|Y=y), so in this case, what does a condition really mean?
Comment: It can also be interpreted as filtering query before computing the probabilty, as in WHERE in sql.
Answer: Conditioning on a random variable is much more subtle than conditioning on an event.
Conditioning on an Event
Recall that for an event $B$ with $P(B) > 0$ we define the conditional probability given $B$ by
$$
P(A \mid B) = \frac{P(A \cap B)}{P(B)}
$$
for every event $A$. This defines a new probability measure $P(\ \cdot\mid B)$ on the underlying probability space, and if $X$ is a random variable which is either non-negative or $P$-integrable on $A$, then we have
$$
E[X \mid B]
= \int X \, dP(\ \cdot\mid B)
= \frac{1}{P(B)} \int X \mathbf{1}_B \, dP.
$$
The intuitive interpretation is that $E[X \mid B]$ is the "best guess" for what value $X$ takes, knowing that the event $B$ actually happens.
This intuition is justified by the last integral above: we integrate $X$ with respect to $P$, but only on the event $B$ (and dividing by $P(B)$ is due to us concentrating all our attention on $B$ and hence re-weighting $B$ to have probability $1$).
That's the easy case. To understand conditioning on a random variable, we need the more general idea of conditioning on information. A probability measure by itself gives us prior probabilities for all possible events. But probabilities that certain events happen change if we know that certain other events do or do not happen. That is, when we have information about whether certain events happen or not, we can update our probabilities for the remaining events.
Conditioning on a Collection of Events
Formally, suppose $\mathcal{G}$ is a $\sigma$-algebra of events. Assume that it is known whether each event in $\mathcal{G}$ happens or not.
We want to define the conditional probability $P(\ \cdot\mid \mathcal{G})$ and the conditional expectation $E[\ \cdot\mid \mathcal{G}]$.
The conditional probability $P(A \mid \mathcal{G})$ should reflect our updated probability of an event $A$ after knowing the information contained in $\mathcal{G}$, and $E[X \mid\mathcal{G}]$ should be our "best guess" for the value of a random variable $X$ using the information contained in $\mathcal{G}$.
(NB: Why should $\mathcal{G}$ be a $\sigma$-algebra and not a more general collection of events? Because if $\mathcal{G}$ weren't a $\sigma$ algebra but we know whether each event in $\mathcal{G}$ happens or not, then we would know whether each event in the $\sigma$-algebra generated by $\mathcal{G}$ happens or not, so we might as well replace $\mathcal{G}$ with $\sigma(\mathcal{G})$.)
Conditional Probability
Here's where things get interesting. $P(A \mid\mathcal{G})$ is no longer just a number: it is a random variable!. We define $P(A \mid\mathcal{G})$ to be any $\mathcal{G}$-measurable random variable $X$ such that
$$
E[X \mathbf{1}_B] = P(A \cap B)
$$
for every event $B \in \mathcal{G}$.
Moreover, if $X$ and $X^\prime$ are two random variables satisfying this definition, then $X = X^\prime$ almost surely.
That is pretty abstract stuff, so hopefully an example can shed some light on the abstraction.
Example.
Let $(\Omega, \mathcal{F}, P)$ be a probability space, and let $B \in \mathcal{F}$ be an event with $0 < P(B) < 1$.
Suppose $\mathcal{G} = \{\emptyset, B, B^c, \Omega\}$.
That is, $\mathcal{G}$ is the $\sigma$-algebra containing all the information about whether $B$ happens or not.
Then for any event $A \in \mathcal{F}$ we have
$$
P(A \mid \mathcal{G})
= P(A \mid B) \mathbf{1}_B + P(A \mid B^c) \mathbf{1}_{B^c}.
$$
That is, for an outcome $\omega \in \Omega$, we have
$$
P(A \mid \mathcal{G})(\omega) = P(A \mid B)
$$
if $\omega \in B$ (i.e., if $B$ happens), and
$$
P(A \mid \mathcal{G})(\omega) = P(A \mid B^c)
$$
if $\omega \notin B$ (i.e., if $B$ doesn't happen).
It is easy to check that this random variable actually satisfies the definition of the conditional probability $P(A \mid \mathcal{G})$ defined above.
Conditional Expectation
I mentioned already that conditional probabilities aren't unique, but they are unique almost surely.
It turns out that if $X$ is a nonnegative or integrable random variable, $\mathcal{G}$ is a $\sigma$-algebra of events, and $Q$ is the distribution of $X$ (a Borel probability measure on $\mathbb{R}$) then it is possible to choose versions of conditional probabilities $Q(B \mid \mathcal{G})$ for all Borel subsets $B$ of $\mathbb{R}$ such that $Q(\ \cdot \mid \mathcal{G})(\omega)$ is a probability measure for each outcome $\omega$. Given this possibility, we may define
$$
E[X\mid\mathcal{G}]=\int_{\mathbb{R}} x \, Q(dx\mid\mathcal{G}),
$$
which is again a random variable.
It can be shown that this is the almost surely unique random variable $Y$ which is $\mathcal{G}$-measurable and satisfies
$$
E[Y \mathbf{1}_A] = E[X \mathbf{1}_A]
$$
for all $A \in \mathcal{G}$.
Conditioning on a Random Variable
Given the general definitions of conditional probability and conditional expectation given above, we may easily define what it means to condition on a random variable $Y$: it means conditioning on the $\sigma$-algebra generated by $Y$:
$$
\sigma(Y)
= \big\{\{Y \in B\} : \text{$B$ is a Borel subset of $\mathbb{R}$}\big\}.
$$
I said "easy to define," but I am aware that that doesn't mean "easy to understand."
But at least we can now say what an expression like $E[X \mid Y]$ means: it is a random variable that satisfies
$$
E[E[X \mid Y] \mathbf{1}_A] = E[X \mathbf{1}_A]
$$
for every event $A$ of the form $A = \{Y \in B\}$ for some Borel subset $B$ of $\mathbb{R}$.
Wow, that's abstract!
Fortunately, there are easy ways to work with $E[X \mid Y]$ if $Y$ is discrete or absolutely continuous.
$Y$ Discrete
Suppose $Y$ takes values in a countable set $S \subseteq \mathbb{R}$.
Then it can be shown that
$$
P(A \mid Y)(\omega) = P(A \mid Y = Y(\omega))
$$
for each outcome $\omega$.
The right-hand side above is shorthand for the more verbose
$$
P(A \mid \{Y = Y(\omega)\})
$$
where $\{Y = Y(\omega)\}$ is the event
$$
\{Y = Y(\omega)\}
= \{\omega^\prime : Y(\omega^\prime) = Y(\omega)\}.
$$
That is, if our outcome is $\omega$, and $Y(\omega) = k$, then
$$
P(A \mid Y)(\omega) = P(A \mid Y = k) = \frac{P(A \cap \{Y = k\})}{P(Y = k)}.
$$
Similarly, if $X$ is another random variable taking values in $S$, then we have
$$
E[X \mid Y](\omega) = E[X \mid Y = Y(\omega)] = \sum_{x \in S} x P(X = x \mid Y = Y(\omega))
$$
$Y$ Absolutely Continuous
Suppose now that $Y$ is absolutely continuous with density $f_Y$.
Let $X$ be another absolutely continuous random variable, with density $f_X$.
Let $f_{X, Y}$ be the joint density of $X$ and $Y$.
Then we define the conditional density of $X$ given $Y = y$ by
$$
f_{X\mid Y}(x \mid y) = \frac{f_{X, Y}(x, y)}{f_Y(y)}
= \frac{f_{X, Y}(x, y)}{\int_{\mathbb{R}} f_{X, Y}(x^\prime, y) \, dx^\prime}.
$$
Now we may define a function $g : \mathbb{R} \to \mathbb{R}$ given by
$$
g(y)
= E[X \mid Y = y]
= \int_{\mathbb{R}} x f_{X \mid Y}(x \mid y) \, dx.
$$
In particular, $g(y) = E[X \mid Y = y]$ is a real number for each $y$.
Using this $g$, we can show that
$$
E[X \mid Y] = g(Y),
$$
meaning that
$$
E[X \mid Y](\omega) = g(Y(\omega)) = E[X \mid Y = Y(\omega)]
$$
for each outcome $\omega$.
This is just scratching the surface of the theory of conditioning.
For a great reference, see chapters 21 and 23 of A Modern Approach to Probability by Fristedt and Gray.

Some Takeaways

Conditioning on a random variable is different from conditioning on an event.
Expressions like $P(A \mid Y)$ and $E[X \mid Y]$ are random variables
Expressions like $P(A \mid Y = y)$ and $E[X \mid Y = y]$ are real numbers.
Comment: @ProQ please see [Wikipedia](https://en.wikipedia.org/wiki/Sigma-algebra) for details. In the context of probability, a sigma-algebra is a set of events that satisfies some useful properties. One way of intuiting about them is that a sigma-algebra is a way of capturing "information" about outcomes of a statistical experiment, but a detailed discussion of that is better suited for its own question (or there might be one here or on math.SE already!)
Comment: What is a sigma-algebra?
Answer: Conditioning on an event (such as a particular specification of a random variable) means that this event is treated as being known to have occurred.  This still allows us to specify conditioning on an event $\{ Y=y \}$ where the actual value $y$ is an algebraic variable that falls within some range.$^\dagger$  For example, we might specify the conditional density:
$$p_{X|Y}(x|y) = p(X=x | Y=y) = {y \choose x} \frac{1}{2^y}
\quad \quad \quad \text{for all integers } 0 \leqslant x \leqslant y.$$
This refers to the probability density for the random variable $X$ conditional on the known event $\{ Y=y \}$, where we are free to set any $y \in \mathbb{N}$.  The use of the variable $y$ in this formulation simply means that the conditional distribution has a form that allows us to substitute a range of values for this variable, so we write it as a function of the conditioning value as well as the argument value for the random variable $X$.  Regardless of which particular value $y$ we choose, the resulting density is conditional on that event being treated as known ---i.e., no longer random.
As I have stated in another answer here, it is also worth noting that many theories of probability regard all probability to be conditional on implicit information.  This idea is most famously associated with the axiomatic approach of the mathematician Alfréd Rényi (see e.g., Kaminski 1984).  Rényi argued that every probability measure must be interpreted as being conditional on some underlying information, and that reference to marginal probabilities was merely a reference to probability where the underlying conditions are implicit, rather than explicit.

$^\dagger$ Technically, it's worth noting that if we conditioning on the value of a continuous random variable (an event with probability zero) then there is an extended definition of the conditional probability.  Essentially this is just a function that satisfies the required integral statement for the marginal probability.  In the present answer we will stick to discrete random variables to keep things simple.
Comment: The expression for the conditional pdf should depend on x in some way, like $\phi(x-y)$.
Comment: Ben, would you be able to elaborate or send resources on the extended definition of the conditional probability for conditioning on the value of a continuous random variable, that satisfies the integral statement for the marginal probability?
Comment: @aesthete: I recommend you read about conditional probability in an advanced probability book such as [Billingsley (1995)](https://www.amazon.com.au/Probability-Measure-Patrick-Billingsley/dp/0471007102).
Answer: It means that the value of the random variable Y is known. For example, suppose $E(X|Y)=10+Y^2$. Then if $Y=2, ~E(X|Y=2)=14.$
Comment: Yes, that's fair. Our different explanations our just semantics.
Comment: $E(X|Y=y)$ is just a different notation. If you are conditioning on $Y$, that means $Y$ is known. $E(X|Y=y)=10+y^2$ is a function that gives expected value of $X$ conditional on $Y=y$ for an arbitrary value of $Y$.
Comment: my understanding is that if E(X|Y=y), the Y is still not a known value, but a non-random unknown variable,  which means the condition Y=y only removed the randomness of random variable Y. In summary, the conditioning random variable is either a specific value(like Y=5) or a unspecified non-random variable(like Y=y), but in either case, the Y is not treated as random anymore in terms of expectation of X. Am I right to think this way?
Comment: Thanks for your explanation, I found that E(X|Y=y) is also possible, so here the y is still unspecified and E(X|Y=y)=10+y^2, in this case, do the condition only remove the randomness of the Y?


Why there is no alpha parameter for GaussianNB()?

Question: Why there is no alpha argument ( smoothing parameter in Laplace smoothing) for GaussianNB() in sklearn library? ? Although BernoulliNB() and MultinomialNB() have an alpha parameter but GaussianNB() doesn't have ? So how the zero probability problem is handled with GaussianNB()
Answer: Just to recall: With $y_i, i=1,\ldots,k$ being the possible classes and $x_i, i=1,\ldots,n$, the features, Naive Bayes does classification by ranking the product
$$
R(y | \mathbf x) := p(y)\prod_{i=1}^n p(x_i|y)
$$
and assigning to $\mathbf x$ the class $y$ for which $R(y|\mathbf x)$ is maximal.
Now, the expression for $R(y|\mathbf x)$ above shows, that it suffices to have just one single $x_i$ with $p(x_i|y)=0$ to set $R(y|\mathbf x)$ to zero. This is often not wanted, because the estimation of $p(x_i|y)$ is often not very accurate. So people apply Laplace or Lidstone smoothing, which consists in setting each $p(y|x_i)$ to at least a small value $\alpha$. This way, other features $x_j$ with large conditionals $p(x_j|y)$ still have a chance of bringing $R(y|\mathbf x)$ to the top.
Now let's consider GaussianNB. Since a Gaussian pdf is always positive, one could argue that $\alpha$ should not be necessary here.
However, we could still get problems with Gaussian pdfs with arbitrarily high precision which could again result in probabilities $p(x_i|y)$ with values below the resolution of doubles and numerical instability. That's why scikit-learn added another smoothing parameter, var_smoothing, which makes sure that all Gaussian pdfs $p(y|x_i)$ have a positive lower bound on variance.
Comment: Added "pdf" for clarification.
Comment: What does "a Gaussian is always positive" mean?
Comment: @dipetkov "Gaussian" is a [generic term for a bounded function on $\mathbb R^n$ given by the exponential of a quadratic](https://en.wikipedia.org/wiki/Gaussian_function)--which, being an exponential of a finite value, is defined everywhere and is always (strictly) positive.
Comment: @whuber I've also come across it as a shorthand for a Gaussian random variable. I'm wondering how helpful it is to save typing "function" after "Gaussian". Even better "probability density function".
Comment: @dipetkov The context makes the meaning clear, I think, but I agree that for novice readers it would be helpful to be a little less telegraphic.


Prevent divs from wrapping, but do not add default scroll

Question: Alright, so I'm a little puzzled about this: as you can see on the site for the Polymer Project, they have tabs that are horizontally scrollable if there are too many. I'd like to replicate this effect, but I can't figure out how to both prevent the
 elements for tabs from wrapping as well as scrolling. Obviously, JS will need to be used here. Unless it's possible to get a custom scrollbar?
How can I do the above? A non-jQuery solution would be very much preferable.
Answer: Give the divs a fixed height and dynamic length. Where the length property of the div is made by counting the number of columns you want in a div.
Why the aversion to jquery?
Comment: The reason I'd rather not use jQuery is because it's a pretty big library that I'm not going to use in this project, for the most part.
Answer: Should be able to use plain JavaScript or jQuery to compare the calculated width of the inner div to the set width of the outer div. If #inner is wider than #outer, add a class to one of the divs to change how they're displayed. If not, remove the class.
The markup:

The styling:
#outer{
  width:500px;
  overflow-x:hidden;
}
#outer .scroll-buttons{
  display:none;
}
#outer.has-scroll-buttons .scroll-button{
  display:block;
}

Comment: This didn't answer my question in itself, but it *did* help me find an answer to my question. I'll answer this question myself later. Perhaps my solution isn't the most efficient, though. Accepting yours.
Comment: What part of your question is still unanswered?


Scaling an icon tabBar loaded with require

Question: I want to scale an icon tab loaded with require, I test this code below but that doesn't work, the icon doesn't scale.
let img = require('../img/logo_lesson.png');
img.scale = 10;

return(
   <TabBarIOS>
       <TabBarIOS.Item title="React Native"  icon={img}  selected={true}>

Thank in advance !
Answer: The syntax you are using is slightly incorrect, img should just contain the image data, not the scale, to scale an icon add it to the icon JSON in the TabBarIOS.Item object like so:

<TabBarIOS.Item
    selected={this.state.selectedTab === 'thisTab'}
    icon={{uri: 'thisTab', scale: ScaleHere}}
    title='tab'
    onPress={() => {
        this.setState({selectedTab: 'thisTab'});
    }}>

</TabBarIOS.Item>

Additionally, you will usually want to multiply your scale by PixelRatio.get() as just hardcoding it to 10 will generally scale incorrectly on different pixel density devices.


Mover variáveis para fora de um vetor em PHP

Question: Eu tenho um controller que irá passar informações de exibição para uma view, essas informações serão objetos, e eles serão passados em array.
namespace app\controllers\conteudo;

class index
{
    public function get_index()
    {
        // Supondo que eu já tenha os objetos $usuario e $publicacao instanciados e populados.

        $args = array
        (
            $usuario,
            $publicacao
        );

        $view = new \app\views\view();
        $view->pagina('publicacao', $args);
    }
}

E uma função que irá carregar uma página do template e exibir essas informações.
namespace app\views;

class view
{
    private $template;

    public function pagina($arquivo, $args = null)
    {
        require(getcwd() . "/app/views/templates/{$this->template}/{$arquivo}.php");
    }

}

No arquivo do meu template, eu consigo acessar $args[0] e $args[1], porém não gostaria de ter acesso à essas variáveis dessa forma, e sim como $usuario e $publicacoes.
Eu poderia definir variáveis para pegar esses valores, porém o problema é que os parâmetros que serão passados são incertos, então se eu passar $categoria por um array, eu quero ter acesso à $categoria no arquivo do template.
Como fazer isso?
Comment: Um `extract()` em `$args` é uma opção os indices vão virar variáveis. Deve ter outras maneiras de resolver isso.
Comment: É uma pergunta parecida: [include, require dentro de funções métodos](http://pt.stackoverflow.com/q/60314/91)
Answer: Uma opção para isso é usar extract() para transformar os indices em variáveis
$arg_vars = ['categoria' => 'sapatos', 'descricao' => 'sapato de couro', 'valor' => 200];
extract($arg_vars);
echo $descricao;

Ou no seu projeto:
public function pagina($arquivo, $args = null)
{
    if(!empty($args)){
       extract($args);
    }
    require(getcwd() . "/app/views/templates/{$this->template}/{$arquivo}.php");
}


Center Div over Div with Background Size = Cover, Overflow = Hidden and Large Image

Question: I'm trying to vertically and horizontally center a div filled with text (id = rulesContent) over a background image (id = rulesBackground). The background image is 3840 x 2160 px, but I only ever want users to see the top left corner of it, adjusted to their screen size. I've got that part figured out.
If #rulesContent is longer than the page, I want it to display all and have the ability to scroll to the bottom of it, which is why I've left its position as absolute.
I need to support IE9+. I've spent all day looking for a solution.
Link to CodePen: https://codepen.io/kokeefe/pen/OxjQxa

body {
  text-align: center;
  font-size: 1.2em;
  font-family: Arial;
}

#container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

#rulesBackground {
  background: url("http://katyokeefe.com/bets/includes/images/stadium-seats.png") no-repeat top center fixed;
  background-size: cover;
  height: 100vh;
  overflow: hidden;
}

#rulesContent {
  background-color: white;
  opacity: .9;
  display: inline-block;
  vertical-align: middle;
  top: 50vh;
  overflow-y: auto;
}

#rules {
  margin: 0 10%;
  padding: 0;
  max-width: 700px;
}

li {
  text-align: left;
  margin: 15px;
}

/*only menu styling follows*/

#nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: #051C2C;
  display: block;
}

#nav>li {
  float: left;
}

#nav>li a {
  display: block;
  color: white;
  text-align: center;
  vertical-align: middle;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */

#nav li a:hover {
  background-color: #DC4405;
}

      Menu

The Rules

Pick one game winner per week straight up (no spread).

You can only pick one NFL Team per week; you cannot pick an NFL Team more than once throughout the 16 game season.

This pool only lasts for the 16 game season and does not include the playoffs.

You can pick your NFL winner at any time throughout the official NFL Week (i.e. Week 1, Week 2, etc.), but you must have your picks in before the game starts, no if's and or butts.

If you lose, you're OUT!

The player who lasts the longest wins.

In the case of a tie (let's say 2 remaining players lose in the same week), the pool is split.

Winner takes all!

In the case of an NFL game tie, you're not officially out, and may continue forward. However, your win will only counts as a ½ point in the case of multiple winners.

Comment: Can you prefer jQuery or not....?
Comment: i can use jQuery, but I'd rather stick to a CSS solution if anyone knows one.
Comment: Please check solution.
Answer: Please check this. I try my best to solve your problem. Check in full page of snippet code and responsive view.

body {
  text-align: center;
  font-size: 1.2em;
  font-family: Arial;
  margin:0;
}
#container {
  width: 100%;
  height: 100vh;
}
#rulesBackground {
  background: url("http://katyokeefe.com/bets/includes/images/stadium-seats.png") no-repeat top center;
  background-size: cover;
  height: calc(100% - 82px);
  overflow: hidden;
  position:relative;
}
#rulesContent {
  background-color: white;
  display: inline-block;
  left: 0;
  margin: 0 auto;
  max-width: 700px;
  width:100%;
  opacity: 0.9;
  overflow-y: auto;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  vertical-align: middle;
  padding:30px;
}
h2{
  margin-top:0;
}
li {
  text-align: left;
  margin: 15px;
}

/*only menu styling follows*/

#nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: #051C2C;
  display: block;
}
#nav>li {
  float: left;
}
#nav>li a {
  display: block;
  color: white;
  text-align: center;
  vertical-align: middle;
  padding: 14px 16px;
  text-decoration: none;
}
/* Change the link color to #111 (black) on hover */

#nav li a:hover {
  background-color: #DC4405;
}

/*for tablet view*/
@media screen and (max-width:1024px){
#rulesContent {
  height:500px;
  max-width: 60%;
}
}
/*for mobile view*/
@media screen and (max-width:767px){
#rulesContent {
  height:200px;
  max-width: 75%;
}
}

      Menu

The Rules

Pick one game winner per week straight up (no spread).

You can only pick one NFL Team per week; you cannot pick an NFL Team more than once throughout the 16 game season.

This pool only lasts for the 16 game season and does not include the playoffs.

You can pick your NFL winner at any time throughout the official NFL Week (i.e. Week 1, Week 2, etc.), but you must have your picks in before the game starts, no if's and or butts.

If you lose, you're OUT!

The player who lasts the longest wins.

In the case of a tie (let's say 2 remaining players lose in the same week), the pool is split.

Winner takes all!

In the case of an NFL game tie, you're not officially out, and may continue forward. However, your win will only counts as a ½ point in the case of multiple winners.

Comment: This does the trick. I can adjust the mobile sizes easily from your framework.


How does Gm → C9 → Ebm → Ebm/Gb work?

Question: I have a song in Bb major. It begins its verse in G minor like this:
Gm → C9 → Ebm → Ebm/Gb
Gm → C9 → Ebm → D7
I can relate that Gm and C9 are a ii-V, but it resolved not to F but to Ebm (bVII?). Strangely it sounds totally fine.
Is there a theory behind this? Any songs with similar structure?
Comment: There's no theory behind music, unless someone made music starting from a theoretical  description. It's the other way around: music theory is descriptions of musical practices. Musical practices were first, then someone decided to try and describe them to someone, from some perspective, for some reason. It looks like you want someone to describe your chord progression. Who, from what perspective, to whom, for what purpose?
Comment: @user94880 Hi, take a look at the site logo. :)
Comment: You didn't understand. Practice is behind theory.
Answer: Thinking in Bb major, consider a slightly different progression: Gm Gm6 Ebm (vi vi[+6] iv).

This is a relatively run-of-the-mill progression, related to the very common IV-iv progression, but with vi subbed in for IV — they share two pitches, so this is not such a leap.
Now add a stepwise bass line, D C Bb.

This is Gm/D C9 Ebm/Bb, which, voicing aside, is the original progression. Ordinarily one would expect the C9 to operate as V/V, but in this case, it's really functioning more like a chromatically altered ii chord.
So in the abstract, the original progression is akin to vi ii vi (or, if you prefer, vi II iv). Up to a point, ii, iv, and vi, being pre-dominant chords and sharing common tones, are interchangeable. Thus, this progression could be viewed, in functional — though not literal — terms as IV-iv.
The expected next chord would be Bb, but instead we have a deceptive resolution back to Gm. The second line of chords functions more clearly as G minor: i IV vi V
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/149200/discussion-on-answer-by-aaron-how-does-gm--c9--ebm--ebm-gb-work); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: It doesn't sound WRONG.   There's no requirement for a progression to be a string of 'cycle of 5ths' resolutions.  But I could criticise it for inconsistency in harmonic density.  Ebm to Ebm/Gb sounds particularly bare after Gm to C9.
Answer: Theory does come afterwards, however if you're looking for a connection to understand why stuff works and sounds good, theory is not totally unhelpful.
Here is one way to see a connection and it depends on the context:
Ab7 is the tri-tone substitution for D7 (dominant of Gm).
Then Ebm7 is the ii of that chord.
I guess you could call it the ii-V of the tritone, if you need to express it.
Gm goes naturally to EbMajor.  Maybe your Ebm is a minor sub because the melody called for it.
Although we'd really need the melody to properly analyze this, and this might not apply in your case, another way to look at it (warning: more theory coming up) is that you are trying to get from G minor (as the tonal center in the verse) to BbMajor where the song 'starts'.  They are pretty far away actually since that G minor has a sharp. F#.  Playing through Ebm7 and Ab7 adds more flats than Bb Major has so you are kind of going past Bb Major in the cycle of fifths and then coming back.  That is really what that chord motion sounds like anyway.  It sounds like you are going too far in the other direction, or like coming at Bb from below, which makes the resolution satisfying.  I'm assuming you use Ab7 to get to Bb, but if not maybe give it a try.
And please don't quote me on all that theory.
So why does Ebm work?  It's connected to Gm in all of those ways.
But ultimately, melody implies harmony.  So you just need a strong melody leading to a note (maybe not even a common tone) in a chord "outside" of the key and then you can go anywhere.   That's probably the simplest way to explain it.
Just do something that sounds good.  (quote me on that).  You can see how all that theory becomes somewhat meaningless after a simple statement like that.
Gm to Ebm directly is probably somewhat less common, but one song comes to mind: Dindi by Antonio Carlos Jobim.  On the bridge.  (But that's in Eb Major, so maybe functioning a bit differently there).  But the melody is at work there with a nice common tone.
There's a million songs that go from BbMaj to Ebm7.  "iv" minor.  It's one of my favorite chords.
Hope that was helpful.

How does Gm → C9 → Ebm → Ebm/Gb work?


CentOS - how do I check if "Development Tools" is installed?

Question: I installed "Development Tools" with yum (`yum group install "Development Tools") and wanted to check it's installed. However, if I re-run the group install command I get:
Maybe run: yum groups mark install (see man yum)
No packages in any requested group available to install or update.

so I assume the group has installed. However is there a way to check? E.g. listing the packages so I can tick a few off.
Comment: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sec-Working_with_Package_Groups.html
Comment: Yes, of course.
Answer: You can use the yum grouplist command e.g.
yum grouplist Dev* installed  ...
Installed Groups:
   Development tools
Done


Parsing HTML tags using python

Question: I am new to python. I want to store each HTML tag into item of list.
from bs4 import BeautifulSoup
text = """

orange

apple

 This is text

"""
soup = BeautifulSoup(text)

y=[]
for i in (soup.find_all("div", class_="product")):
   y.append(i.get_text().encode("utf-8").strip())

From the above code the length of y is 1 and store all text on one item of list. However,it is necessary to parse using "div product" and store each text inside html tag into different item to list.
So the y will be :
y =['orange', 'apple', 'This is text']

instead of :
 y=['orange\napple\n This is text']

Answer: Don't use text if all you wanted was the directly contained string, and ask only for elements contained in the div.product tag:
for elem in soup.select("div.product *"):
    y.append(elem.string.strip().encode('utf8'))

Demo:
>>> y = []
>>> for elem in soup.select("div.product *"):
...     y.append(elem.string.strip().encode('utf8'))
...
>>> y
['orange', 'apple', 'This is text']

Answer: soup.find_all("div",class_="product")

gives all the div tags with class product so u have a list now. So when u run the for loop it iterates only once and gives the complete text in div tag.
So to get data of every child use something like this
for child in soup.find_all("div", class_="product").findChildren():
         y.append(child.string.strip().encode('utf8'))

Parsing HTML tags using python


Basic Questions About Database Development

Question: I searched for the answers to these questions before, but couldn't find them - so I apologize if they have been answered already, or appear stupid. I am new to learning about databases, and am pretty confused.
I am helping someone who wants to build a website with a database. It is supposed to have secure html links, secure password and username inputs, and relatively low bandwidth use. It will also handle financial transactions, and should work with Paypal.

My partner is familiar with Visual Studio. Can the .net framework produce anything other than asp pages (like html or other language formats), or is every webpage produced a .asp?
How is Visual Studio for working with MySQL?
If the answer to #2 is terrible, then I was thinking of using PHPMyAdmin with MySQL. How is this for secure front-ends? Would this allow me to easily interface with a MySQL backend? Would this be my best bet considering #1? Or should I take a look at other programs/frameworks?
Are there any programs that help with back-end work, or does it all have to be coded by hand? If there are any, does anyone have recommendations considering the above? Would PHPMyAdmin, Microsoft SQL Server, or Xataface have a GUI to help do any back-end work?

Thanks a lot,
Answer:
My partner is familiar with Visual Studio. Can the .net framework
  produce anything other than asp pages (like html or other language
  formats), or is every webpage produced a .asp?

ASP.NET produces HTML. The pages may have the aspx extension as opposed to .html but they stuff rendered is regular HTML. You can use both, HTML controls and ASP.NET controls. Using ASP.NET controls offers some advantages but you don't have to if you don't want to.

How is Visual Studio for working with MySQL?
  If you are concerned about being able to connect from VS to a MySQL database without using other admin tools, then the answer is yes, you can do it; however, VS is powerful for many more reasons than just this capability: like intellisense, a huge set of libraries at your disposal, powerful controls out of the box, etc.
If the answer to #2 is terrible, then I was thinking of using
  PHPMyAdmin with MySQL. How is this for secure front-ends? Would this
  allow me to easily interface with a MySQL backend? Would this be my
  best bet considering #1? Or should I take a look at other
  programs/frameworks?

PHPMyAdmin is a tool for interfacing with MySQL; it allows you to run queries, create databases, tables, etc. but it won't help you creating "secure front-ends" per se. There are many tools available that sort of do the same PHPMyAdmin does; one of them is MySQL Workbench. As far as security, you can build secure websites pretty much using any kind of database; it really amounts more to how you design and program your application than any feature offered by any tool.

Are there any programs that help with back-end work, or does it all have to be coded by hand? If there are any, does anyone have recommendations considering the above? Would PHPMyAdmin, Microsoft SQL Server, or Xataface have a GUI to help do any back-end work?

As far as MS SQL Server is concerned, you can use SQL Server Management Studio. You can create Databases, tables, stored procs, functions, indexes, views, users, etc, etc. from there and it offers intellisense when you connect to a MS SQL Server 2008 DB or greater version.


Impacts of having unused JAR files in CLASSPATH

Question: I've read so many Q&A here about tools available to find out unused JARs, such as:

loosejar
Classpath Helper

My question here is, are there any impacts (such as loading of classes into memory, performance,  etc.) of having unused JARs in the classpath either at compile time or run time?  Question applies to both running as a Standalone program and Web Server (Apache Tomcat), though I initially thought about only Standalone programs.
NOTE: I'm running JDK 6u32 (64-bit).
Answer:
Are there any impacts (such as loading of classes into memory, performance, etc.) of having unused JARs in the classpath either at compile time or run time?

There is going to be a small impact.  When the class loader (or the compiler's equivalent) starts, it has to read the index of each JAR file to find out what classes are in each JAR.  If you've got unnecessary JARs on the classpath, the classloader has more work to do, and will (at least temporarily) use more memory to cache the indexes.
This applies to all kinds of Java application.  Other related impacts are:

the extra disk space needed to hold the unused JARs, and
for unused JARs that are part of a downloadable installer or container, the extra time and network bandwidth needed to do the download.

The question that you didn't ask ... is whether these impacts are significant.  The answer is "Generally No" ... but the more useless stuff you have on the classpath, etc, the greater the impact is going to be.

IMO, a more important problem with having unused JARs on the classpath is that it is likely to increase your maintenance overheads.  For example, if there are old unused JAR files that happen to have vulnerabilities, someone is liable to spend time checking and upgrading those JARs in response to a security scan ... not realizing that it doesn't affect actual security, and is (arguably1) a waste of time.
1 - It is certainly a waste of time in the sense that you wouldn't have needed to expended if the unused JAR had been removed in the first place!
Comment: So that *small impact* is applicable at both compile time and run time?
Comment: Yes ... in both cases.  And not usually worth worrying about in either case.
Answer: The main problem is not performance as the cost is relatively small and only on loading new classes.  The main problem is maintainability.  For example, when a library needs to be upgraded, you can waste alot of time testing the application still works ok with the new version only to find the library was not used. (Say you have a new library which needs a newer version of a library you are already "using")
Comment: Say you have log4j version 1.1, but you want to use library X which needs log4j 1.2 for some reason.  You can't just drop in version 1.2 until you determine it doesn't break your application. So you retest your application using 1.2 to see if it still works and waste alot of time because you are not even using log4j. If you only have libraries you are actually using, this would not be an issue.
Comment: I couldn't clearly understand this point -- `when a library needs to be upgraded, you can waste alot of time testing the application still works ok with the new version only to find the library was not used`.  Can you clarify on this?
Answer: Yes, it has an impact - because the JVM looks for necessary classes in the JARs of the CLASSPATH. It also makes sense to keep sealed JARs, to tell the JVM not to look for related classes in other JARs.
P.S.: javac is also a java program, for the record.
Comment: However, the caching of JAR file indexes means that the overhead of looking in extra places is minimal.


Is it possible for Extjs 4.2 CSS vars to not be applied globally?

Question: I am using Extjs 4.2 and Sencha CMD 3.1 to customize the CSS of my application.
As instructed in this guide by Sencha, I am setting the CSS vars in "/sass/vars" as follows
<code>$grid-row-cell-font-size : 16px;
$grid-row-cell-focus-border-style : solid;
$grid-row-cell-line-height : 40px;
$tree-icon-spacing : 10px;
</code>
but all these changes are global -- they apply to the treepanel that I wanted to change but also in all other gridpanels and treepanels.
The attributes above are only available as CSS vars (they aren't in the Mixin for treepanel), so I don't know how to make it such that only the tree I want to customize is affected by the vars.
Can someone please help?
Answer: Am I missing something or can't you just use the cls class of the TreePanel?
<code>cls: 'your-custom-css-class'
</code>


Convexity of a function of CDFs (cumulative distribution function)

Question: I want to examine whether the following function, $G(q)$, is concave on $q$ ($q>0$):
$G(q)=(1-\alpha )\int^{\frac{\beta .q}{1-\alpha }}_0{F(x)dx}-\int^{(1+\beta ).q}_0{F(x)dx}$
The assumptions are $0<\alpha ,\beta <1$ and $\frac{\beta }{1-\alpha}\le 1+\beta $ (so, $\frac{\beta.q}{1-\alpha }\le (1+\beta ).q$ hold). Besides, $F(x)$ is CDF for a general random variable $x$ (so, $F(x)$ is non-decreasing and also $F(x)\le 1$ hold). Would you please advise?
For specific distribution functions like uniform and exponential, it is valid. I wondered whether $G(q)$ is concave for any general distribution function. Or is there any property for the distribution function to make it concave?
Answer: The function $G$ is not necessarily concave, you need additional hypotheses.
For a continuous positive distribution with pdf $f$, we must have $$ \dfrac{f\!\left(\frac{\beta}{1-\alpha} q\right)}{f((1+\beta)q)} \le (1-\alpha)\frac{(1+\beta)^2}{\beta^2} $$
for every $q > 0$. This is shown by using the fact that a twice differentiable function is concave if and only if its second derivative is non-positive.

Indeed, $$G'(q) = \beta F\!\left(\frac{\beta}{1-\alpha}q\right) - (1+\beta) F\!\left((1+\beta)q\right)$$
and
$$G''(q) = \frac{\beta^2}{1-\alpha} f\!\left(\frac{\beta}{1-\alpha}q\right) - (1+\beta)^2 f\!\left((1+\beta)q\right).$$
Now use the hypotheses over $\alpha$ and $\beta$ along with $G''(q) \le 0$ to finish the proof.

As a counter-example, take $\alpha=\beta=1/2$ and the exponential distribution with cdf $F(x) = 1 - e^{-x}.$ Then, $G(q) = \dfrac{1}{2}-q-e^{-\frac{3 q}{2}}+\dfrac{1}{2}e^{-q}$ and $G''(q) = \dfrac{1}{2}e^{-q}-\dfrac{9}{4} e^{-\frac{3 q}{2}}$. However, $G''(q) < 0$ if $q < 2\ln(9/2)$ and $G''(q) > 0$ if $q > 2\ln(9/2)$.
Comment: Thank you so much. It was very helpful.


How do programming languages implement daylight savings?

Question: Programming languages of course offer timezone support, that I at least take for granted. But as the European Union is moving away from daylight savings, it struck me that I don't actually know how all this works under the hood.
Let's say starting 2022, many countries switch away from daylight savings. How do old programs react to this? And how is the language patched? Probably easy to answer once you know how it actually works.
This is not so much a practical problem for me, but asking out of interest. Tried to find an answer, but to my surprise there seems to be very little info available.
Comment: https://www.youtube.com/watch?v=-5wpm-gesOY
Comment: This question will be hard to answer for all existing programming languages. Please consider to rewrite your question to one specific language only. The more specific the question is, the more valuable the answers will be.
Answer: I have seen it hard coded.  Then when the rules change, all that software needs to be upgraded.  I have seen folks/software simply punt by use UTC everywhere.  I have also seen people use the well known "tz" database (aka "tzdata", "zoneinfo", "IANA timezones",the "Olson database", etc.).
Comment: An example of "all that software needs to be upgraded" (back in 2007) : https://www.cisco.com/c/en/us/support/docs/ip/network-time-protocol-ntp/81675-dst-recommendations.html
Comment: (the smartly run networks were using UTC so they saved all that work, as well as all the work/errors converting timezones while troubleshooting!)


jQuery AJAX loads twice

Question: I'm programming a site, and I've got a problem.
I have the following jQuery code:
<code>$('input[type="text"][name="appLink"]').keyup(function() {

    var iTunesURL = $(this).val();
    var iTunesAppID = $('input[name="iTunesAppID"]').val();

    $.ajax({
        type: 'POST',
        url: jsonURL,
        dataType: 'json',
        cache: false,
        timeout: 20000,
        data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
        success: function(data) {
            if (!data.error) {
                $('section.submit').fadeOut('slow');
                //Modifying Submit Page
                setTimeout(function() {
                    $('input[name="appLink"]').val(data.trackViewUrl);
                    $('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
                    $('div.title > p:nth-child(1)').html(data.trackName);
                    $('div.title > p:nth-child(2)').html('by '+data.sellerName);
                    $('span.mod-category').html(data.primaryGenreName);
                    $('span.mod-size').html(data.fileSizeBytes);
                    $('span.mod-update').html(data.lastUpdate);
                    $('select[name="version"]').html(data.verSelect);
                    $('input[name="iTunesAppID"]').attr('value', data.trackId);
                }, 600);
                //Showing Submit Page
                $('section.submit').delay('600').fadeIn('slow');
            } else {
                $('.json-response').html(data.message).fadeIn('slow');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            //$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
            $('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
        }
    });
});
</code>
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
Comment: please check with debugger in chrome
Answer: I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
<code> $('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {

 });
</code>
Comment: A short explanation would be nice.
Comment: Yes, please do if you can! Thanks!
Comment: @MCL Sorry for that, I added explanation
Comment: Hmm, I still can't understand, but never mind, it looks like it works :) Thanks for your help!
Comment: Oh no, it keeps doing that sometimes :/
Comment: It would be helpful if you can show us how you are calling this function,
or try adding
    return false;
at the bottom of the event callback function
Comment: It looks like when I delete the content of the `input` and write anything like asdasdasd exactly than I paste the link that reacts with the jSON it loads twice. Chrome inspector shows that the json is loaded twice!
Comment: And other, I think it's in connection with the "non-finished" ajax requests. Because if I'm typing a word, ajax runs every time. And if it finds the commant that'd allows the `fadeOut` it starts it's working, and I think it'll act samely with the non-finished requests

jQuery AJAX loads twice


Dica de como transformar laços em função recursiva

Question: Esse programa faz o teste de aptidão profissional baseado na logica de relações fuzzy.
Tenho que transformar esses laços em uma função recursiva, pesquisei e até entendi como como uma função recursiva deve ser implementada, porém não consegui mentalizar uma forma de usar esses laços em uma. A função recursiva invoca ela mesmo como um laço de repetição até que uma condição de parada seja satisfeita. Como eu poderia transformar esses laços em uma função recursiva?
$aptidoes = array (
array ("aptidao_id" => "3","cod" => "ap1", "aptidao" => "Nível de Raciocínio Lógico?"),
array ("aptidao_id" => "4","cod" => "ap2", "aptidao" => "Gosta de Cálculos?"),
array ("aptidao_id" => "5","cod" => "ap3", "aptidao" => "Nível de Curiosidade?")
);

$casos = array (
array ("caso_id" => "35","nome" => "KELLY", "ap1" => "0.1", "ap2" => "0.1", "ap3" => "0.1")
);

$profissoes = array (
array ("profissao_id" => "1","profissao" => "Cientista da Computação", "ap1" => "1", "ap2" => "0.9", "ap3" => "0.9"),
array ("profissao_id" => "2","profissao" => "Psicologo", "ap1" => "0.5", "ap2" => "0", "ap3" => "0.6"),
array ("profissao_id" => "3","profissao" => "Professor de Humanas", "ap1" => "0.4", "ap2" => "0", "ap3" => "0.6")
);

//Pega repete a analise somente para o caso corrente, ou seja 1.
for ($p=0; $p < 1; $p++) {
//Inicializa o arrey.
$_max = array();
//Pega todas as profissoes registradas no banco para análise.
for ($d = 0; $d < count($profissoes); $d++) {
    //Inicializa o arrey.
    $_min = array();
    //Pega todos as aptidões registrados no banco para análise.
    for ($i=1; $i < count($aptidoes)+1; $i++) {
        //Cria um array com as relações (aptidão x profissao) e (aptidão x casos), e gera o valor mínimo de cada uma.
        array_push($_min, min($profissoes[$d]['ap'.$i],$casos[$p]['ap'.$i]));
    }
//Recebe o valor mínimo da relação, para cada profissão.
$valor = max($_min);
//Gera um array com o valor máximo, da relação dos mínimos.
array_push($_max, $valor.' - '.$profissoes[$d]['profissao']);

  };
};

//Trás o resultado e a porcentagem de precisão.
echo '
'.explode ("-", max($_max))[1].' com precisão de '.(explode ("-", max($_max))[0] * 100).'%
';

Comment: `teste de aptidão profissional baseado na logica fuzzy` http://i0.kym-cdn.com/photos/images/facebook/000/852/286/9ac.jpg
Comment: Não devo estar conseguindo explicar direito. Me ajudem. Pfv
Answer: Primeiro você precisa entender a estrutura do laço em PHP. Resumidamente, você tem:
for (a; b; c)
    d;

Onde:

a: é uma expressão que é executada somente uma vez, antes do laço começar;
b: é uma condição executada antes de cada passo do laço. Se for verdadeira o laço continua, caso contrário o laço para;
c: é uma expressão que é executada ao final de cada passo;
d: é uma expressão que é executada para cada passo do laço.

Portanto, o for acima é equivalente a este while:
a;
while(b) {
    d;
    c;
}

Como transformar isso em um algoritmo recursivo? A recursão consiste em um método chamar a si próprio, logo você precisa do seguinte:
function recursiva(parametrosOriginais) {
    if (b) return;
    else {
        d;
        c;
        return recursiva(parametrosAlterados);
    }
}

a;
recursiva(parametros);

Note que tanto no laço com while quanto na recursão, as expressões c e d podem ser combinadas em uma só. Mas o mais importante: na recursão, a execução dentro do else modificará os parâmetros que serão passados para a próxima chamada. Em todos os casos, b é a condição de parada. Ao ser atingida, o algoritmo para e você tem um resultado.
Segue um exempo de fatorial, iterativo e depois recursivo, em PHP.
Iterativo com for:
$param = 4; // pode ser qualquer outro número
$resultado = 1;
for ($i = $param; $i > 0; i--) {
    $resultado *= $i;
}

Iterativo com while:
$param = 4; // pode ser qualquer outro número
$resultado = 1;
$i = $param
while ($i > 0) {
    $resultado *= $i;
    $i--;
}

E finalmente, recursivo:
function fatorial($numero) {
    if ($numero == 1) return 1;
    else {
        $proximo = $numero - 1;
        return $numero * fatorial(proximo);
    }
}

$param = 4;
$resultado = fatorial($param);

Tente perceber o padrão, e poderá transformar praticamente qualquer algoritmo iterativo em uma versão recursiva (o inverso nem sempre é verdadeiro). Note que a função recursiva pode receber mais de um parâmetro se necessário.
Isso vale para dezenas de outras linguagens, desde C até Javascript.
Comment: Renan. Muito obrigado. Me ajudou muito essa sua explicação.


Change directory of css in patternlab

Question: I want to change the directory of the style.css file in the pattern lab setup, how and where do I do this? I have a whole booststrap sass project setup already and I want patternlab to use the current files for this projects.
Answer: You can add css and javascript files in the following file:
source/_patterns/00-meta/_00-head.mustache

Change directory of css in patternlab


How to update adb to v.39 or newer on Ubuntu?

Question: I'm not very familiar with Ubuntu. Right now, I'm on adb version 1.0.32, I need adb version 39 or newer. Whatever I do I seem to be stuck at v.32 . I've tried uninstalling adb with
sudo apt-get remove android-tools-adb android-tools-fastboot

and re-installing with
sudo apt-get install android-tools-adb android-tools-fastboot

adb version is still showing 32. Help!
Update: I also tried
wget https://dl.google.com/android/repository/platform-tools-latest-linux.zip
unzip \platform-tools-latest-linux.zip
sudo cp platform-tools/adb /usr/bin/adb
sudo cp platform-tools/fastboot /usr/bin/fastboot

But after that, when I run adb version, I get -bash: /usr/bin/adb: cannot execute binary file: Exec format error
Comment: The problem turned out to be in the 32-bit OS that I had on the machine. Once we upgraded that to a 64-bit, I was able to update the adb with no problem.
Answer: You could update, upgrade, uninstall adb, then reinstall adb.
sudo apt remove android-tools-adb
sudo apt remove android-tools-fastboot
sudo apt update && sudo apt upgrade
sudo apt install android-tools-adb android-tools-fastboot

Answer: The problem turned out to be in the fact that our Raspberry Pi's were on armv71 processors. Which are 32 bit processors. And 32-bit processors are not able to run adb versions newer than 1.0.32 because those are all meant for 64-bit processors. Once we upgraded to 64-bit, I was able to update adb.
Answer: Remove adb the installed version from Ubuntu repository:
sudo apt purge adb

Create an alias:
alias adb='/usr/bin/adb'
alias fastboot='/usr/bin/fastboot'

check it:
adb --version

Then add it to your ~/.bashrc:
cat <<EOF >> ~/.bashrc
alias adb='/usr/bin/adb'
alias fastboot='/usr/bin/fastboot'
EOF

run:
source ~/.bashrc


Show that the determinant of jordan normal form wtih spatial weight matrix by its eigenvalues

Question: I try to figure out the proof of determinant of matrix by eigen decomposition,
$$det(I_n-\lambda W)=det(QQ^{-1}(I_n-\lambda W))$$
$$=det(Q(I_n-\lambda W)Q^{-1})$$
$$=(1-\lambda \upsilon_1)(1-\lambda \upsilon_2)...(1-\lambda \upsilon_n)$$
where $\lambda$ is spatial autoregressive coefficient, $W$ is normalized weight matrix, $\upsilon$ is eigenvalues of $W$, $Q$ is the matrix that trinagularizes $W$.
1.i can't figure out how changes taking place of the $Q^{-1}$ matrix in front of $(I_n-\lambda W)$ in the first equation to behind of $(I_n-\lambda W)$ in the second equation? is there any proporties for that?
2.why do need $W$ is triangularized? can it be proof without triangularized?
I would really appreciate some help.
Comment: Note that the determinant is multiplicative i.e. $\det(Q(I_n-\lambda W)Q^{-1})=\det(Q)\det(I_n-\lambda W)\det(Q^{-1})$ and the values of the determinant commute
Answer: So we know (given) that there is a $Q$ such that $QWQ^{-1}$ is triangular. The first step is to introduce $Q$
$$\det(I - \lambda W) = \det( Q^{-1}Q(I-\lambda W))$$
Second let's use the property $\det(AB) = \det(BA)$ where $A = Q^{-1}$ and $B = Q(I-\lambda W)$ hence
$$\det(I - \lambda W) = \det(Q(I-\lambda W) Q^{-1})$$
Third, expand the above
$$\det(I - \lambda W) = \det(QQ^{-1}-\lambda Q W Q^{-1} )$$
Notice that $QQ^{-1} = I$ again so
$$\det(I - \lambda W) = \det(I-\lambda Q W Q^{-1} )$$
Fifth denote our triangular matrix $QWQ^{-1} = T$ hence
$$\det(I - \lambda W) = \det(I-\lambda T )$$
Notice that $I - \lambda T$ is also triangular with diagonal elements $1 - \lambda v_1$, where $v_k$ appear on the diagonal entries of $T$. Using the fact that the determinant of a triangular matrix is nothing other than the product of it's diagonal entries, then
$$\det(I - \lambda W) =(1 - \lambda v_1)\ldots(1-\lambda v_n)$$
Comment: Thank you detailed explanation. It is cleary seen.
Comment: I'm glad it helped. If you found it useful, you could mark the answer as correct and upvote to help other viewers know that it was helpful @v.yildirim
Answer:
Just think of a theorem saying that $$\det(AB)=\det(A)\det(B)$$so we have $$\det(AB)=\det(BA)$$2. sure it can be proved in such way. Probably in your problem the matrix is particularly triangular but it doesn't require to remain so. To show that the key idea is that $$\text{the determinant of a matrix is multiplication of all its eigenvalues}$$can you finish this one?
Comment: So i can see how it can change and i think it is easy to show dererminant with eigenvalues by triangularized matrix. Thank you


Is it possible, to see hibernate`s queryPlanCache contents?

Question: I got memory leak problem with queryPlaneCache in Hibernate 5.2.10.Final. I found information about leak troubles with IN() queries and marked them with setCacheable(false). Leak decreased, but not dissapeared.
I tried decrase hibernate.query.plan_cache_max_size and turn off caching (hibernate.cache.use_query_cache). It helps, but i think this is no right solution. I want mark some problem queries as setCacheable(false) and save cache mechanism in good work, but don`t have some things about trouble queries.
By this reason i want dump a queryPlaneCache content for see concrete SQL queries and found source of problem. Is it possible?
Comment: What do you refer to when you say `memory leak` - an `OutOfMemory error`? Is it enough for you to print the content of said cache or are you looking for something else?
Comment: Yes, it's OutOfMemory. I get heap dump and see in MAT a big count of queryPlaneCache rows. Yes, i want print this cache for see which queries a get a lot of space there. For example, may be i skip one query with big volatile IN() and it's born this error.
Comment: You are using `ehcache` as a provider? I know you can configure the cache to be written to the harddisk (but I don't remember whether it was a readable format) and (at least in older hibernate versions) it was possible to get access to the cache programmaticly and print out its content from there.
Comment: If you do please also mention the version you are using and whether you have a configuration file for it or not. If not name what provider and what version you are using.
Answer: Sure you can, if you're ok with a little reflection to access private fields. This is how I did it. getQueryPlanCacheDump() returns a list of strings representing the cached queries, the other information stored in the cache is discarded (its likely not necessary for diagnosing your issue)
When I did it, I found that my cache was filling up due to the IN clause caching a new query plan each time they query was used with a different number of parameters.
  private final EntityManagerFactory entityManagerFactory;

  public List<String> getQueryPlanCacheDump() {
    try (var session = entityManagerFactory.createEntityManager().unwrap(Session.class)) {
      var sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
      return getQueryList(sessionFactory);
    }
  }

  private List<String> getQueryList(SessionFactoryImpl sessionFactory) {
    BoundedConcurrentHashMap<?, ?> queryPlanCache = getQueryPlanCache(sessionFactory);
    var queries = new ArrayList<String>();
    try {
      var hqlQueryPlanKeyClazz = Class.forName("org.hibernate.engine.query.spi.QueryPlanCache$HQLQueryPlanKey");
      var filterQueryPlanKeyClazz = Class.forName("org.hibernate.engine.query.spi.QueryPlanCache$FilterQueryPlanKey");
      queryPlanCache.forEach((key, value) -> {
        // The cache contains 3 different types of keys
        if (key instanceof NativeSQLQuerySpecification nativeSql) {
          queries.add(nativeSql.getQueryString());
        } else if (hqlQueryPlanKeyClazz.isInstance(key)) {
          queries.add(getQuery(hqlQueryPlanKeyClazz, key));
        } else if (filterQueryPlanKeyClazz.isInstance(key)) {
          queries.add(getQuery(filterQueryPlanKeyClazz, key));
        }
      });
    } catch (Exception e) {
      // If Hibernate adds more key types in the future, return all the key types instead so you can investigate adding support for them
      var keyClasses = new HashSet<String>();
      queryPlanCache.forEach((key, value) -> keyClasses.add(key.getClass().toString()));
      return keyClasses.stream().toList();
    }
    return queries;
  }

  private String getQuery(Class<?> clazz, Object key) {
    try {
      var queryField = clazz.getDeclaredField("query");
      queryField.setAccessible(true);
      return (String) queryField.get(key);
    } catch (IllegalAccessException | NoSuchFieldException e) {
      throw new IllegalStateException(e);
    }
  }

  private BoundedConcurrentHashMap<?, ?> getQueryPlanCache(SessionFactoryImpl sessionFactory) {
    try {
      var queryPlanCacheField = QueryPlanCache.class.getDeclaredField("queryPlanCache");
      queryPlanCacheField.setAccessible(true);
      return (BoundedConcurrentHashMap<?, ?>) queryPlanCacheField.get(sessionFactory.getQueryPlanCache());
    } catch (IllegalAccessException | NoSuchFieldException e) {
      throw new IllegalStateException(e);
    }
  }


Multilevel alternative to Paired t-test

Question: I have a problem where we have N patients, and we measure some property of tumoral lesions for each patient, where the number of lesions varies on each patient (patient A could have 1 lesion, and patient B could have 5).
For each lesion we measure the property using two different methods, so from this point of view we could use a paired t-Test, but, I would like to account on possible differences between patients.
Is there any alternative test to the paired t-test that could account for differences in each patient?
Thanks,
Comment: What do you mean by accounting for possible differences between patients? It's not immediately clear to me that you're wanting to do something that t-tests don't already do. Do you mean that you want to know whether there's a relationship between the number of lesions and the measurement?
Comment: I mean, in patient 1, maybe I measure 5 lesions with method A and B, and there is a decrease in the measurement, but it is due to the patient. And patient 1 counts 5 time more than patient 2, which only have one lesion and with method A and be the measurement increases.
Comment: Are the measurements using the two different measures taken at different time points? Or are the different lesions measured at different times but both with the same method? Without knowing about the design of your study it's really difficult to suggest an appropriate test.
Comment: The measures are the same measure but using two different methods.
Comment: Okay, so what do you mean in your earlier comment when you say "decrease in measurement"? In order to show a decrease in something you would need to have two measurements, one before the decrease and one after. It sounds like you have two measurements, but they're both taken at the same time, hence no way of observing a decrease. Do you mean something else? I'd stress that you're much more likely to get an answer if you edit the question to make a lot of these details (e.g., the design of the data, your hypothesis, etc.) explicit
Comment: I mean a decrease in the measurement using method A vs  method B. Fo example, in patient 1, lesions {1,2,3} measure {20, 25, 35} with method A and {19,23, 30} with method B, so there is a decrease in the measure from method A to B. Maybe, this decrease is intrinsic to the measurement method but I can not reject that the decrease is instrinsic to the patient insted of the measurement method.
Comment: So a _difference_ rather than a decrease. Decrease implies a change over time, rather than two methods "disagreeing". And is your hypothesis that there's going to be a systematic difference between the two methods?
Comment: I accept your suggestion, thanks! Sadly I can not edit the question. With the exploratory data analysis, I saw that mean values for method A is higher than method B, but that is not true for all patients. Doing the paired t-test I obtain a p < 10^-5.
Answer: Following on from discussion in the comments, my suggestion would be that, in general, for a case like this mixed-effects regression would be the appropriate approach to take.
Your model would contain two random effects (unless there's others not mentioned): patient, and lesion which would be nested under patient. There would be at least one fixed effect: the method used for measurement.
You would likely want to test both random intercepts and random slops for both patient and lesion.
Now the catch, it sounds like you may have some patients who only have one lesion. For these patients you couldn't estimate distinct random effects for both patient and lesion (because you couldn't tease apart the variance associated with each). Assuming such a model would converge, I'm not sure whether this would have a consequence for the estimates associated with the fixed effect (i.e., assessing whether there's a difference overall difference between methods). Someone else may know.
The alternatives here would be to remove the random effect for lesion (the between lesion variance within a patient would no longer be being accounted for) or to retain the random effect but remove the nesting (between lesion variance would still be accounted for, but the fact that a pair of lesions within a single person may be more similar than a pair of lesions between two people would not). I'm not sure whether either way is better than the other...
Some reading:
https://en.wikipedia.org/wiki/Mixed_model
https://cran.r-project.org/web/packages/lme4/index.html
<code>@book{gelman2007data,
  address =  {New York, NY},
  author =   {A. Gelman and J. Hill},
  publisher = {Cambridge University Press},
  title =    {Data analysis using regression and multilevel/hierarchical models},
  year =     2007
}
</code>

Multilevel alternative to Paired t-test


Series expansion of $\coth x$ using the Fourier transform

Question: Hi I have research about the series of coth but all of the solutions emerges from integral on a contour, Could you calculate the fourier transform of coth? Is that possible at all?My goal is to reach : $$\coth x = \frac{1}{x} + 2 \sum_{n=1}^\infty \frac{x}{x^2+\pi^2n^2}$$
through fourier.
Answer: The expansion can be derived from the complex Fourier series of the $2 \pi$-periodic function $f(x) = e^{ax}$ for $- \pi < x < \pi$.
By definition of the complex Fourier series, $$e^{ax} = \lim_{N \to \infty}\sum_{n=-N}^{N} c_{n} e^{inx} $$
where $$ \begin{align} c_{n} = \frac{1}{2 \pi} \int_{-\pi}^{\pi} e^{ax} e^{-inx} \ dx &= \frac{1}{2 \pi} \int_{-\pi}^{\pi} e^{(a-in)x} \ dx  \\ &= \frac{1}{2 \pi} \frac{e^{(a-in)x}}{a-in} \Big|^{\pi}_{-\pi} \\ &= \frac{1}{2 \pi} \frac{1}{a-in} \Big( e^{a \pi}e^{-in \pi} - e^{- a \pi}e^{i n \pi} \Big) \\ &= \frac{1}{\pi} \frac{(-1)^{n}}{a-in}\frac{e^{a \pi}-e^{- a \pi}}{2}  \\ &= \frac{(-1)^{n}}{\pi} \frac{a+in}{a^{2}+n^{2}} \sinh a \pi \end{align}$$
At $x= \pi$ (a point of discontinuity), $$\frac{e^{a \pi}+e^{- a \pi}}{2} = \cosh a \pi = \lim_{N \to \infty}\sum_{n=-N}^{N} c_{n} (-1)^{n} =  \frac{\sinh a \pi}{\pi} \lim_{N \to \infty} \sum_{n=-N}^{N} \frac{a+in}{a^{2}+n^{2}}$$
which implies
$$ \begin{align} \coth a \pi &=  \frac{1}{\pi} \lim_{N \to \infty}\sum_{n=-N}^{N} \frac{a+in}{a^{2}+n^{2}} \\ &= \frac{1}{\pi} \lim_{N \to \infty}\sum_{n=-N}^{N} \frac{a}{a^{2}+n^{2}} + \frac{i}{\pi} \lim_{N \to \infty} \sum_{n=-N}^{N} \frac{n}{a^{2}+n^{2}} \\ &= \frac{1}{\pi} \lim_{N \to \infty}\sum_{n=-N}^{N} \frac{a}{a^{2}+n^{2}}+ 0 \\ &= \frac{1}{\pi}\sum_{n=-\infty}^{\infty} \frac{a}{a^{2}+n^{2}}  \end{align}$$
And replacing $a$ with $ \displaystyle \frac{x}{\pi}$, we get
$$ \begin{align} \coth x &= \sum_{n=-\infty}^{\infty} \frac{x}{x^{2}+\pi^{2}n^{2}} \\ &= \frac{1}{x} + 2 \sum_{n=1}^{\infty} \frac{x}{x^{2}+\pi^{2}n^{2}} \end{align}$$
Comment: Would you please explain what happened to the term $\sum_{n=-\infty}^{n=\infty} \frac{i n}{a^2+n^2}$? Why is it zero? Thanks. (computer says it does not converge).
Comment: @Nasser I was careless with the notation.  The complex Fourier series is the limit of a symmetric sum.
Comment: Thanks. Now it is more clear.