como fazer item selecionado da tabela dinâmica mudar de cor

Question: Olá! estou com um projeto básico de JavaScript e HTML, do qual a pessoa irá adicionar dados à a tabela(ela será feita pelo próprio usuário e até ai tudo bem(Consegui implementar até o botão de excluir). Porém, quando a pessoa seleciona, um dos itens da lista para excluir, simplesmente não dá para saber justamente porque a cor do mesmo não muda.

let pessoas, index;

function inserir(item,descricao,quantidade,valor) {
    pessoas = document.getElementById("tabela");
    var qtdlLinhas = pessoas.rows.length;
    var linha = pessoas.insertRow(qtdlLinhas);
    var linhaParam;

    var cellItem = linha.insertCell(0);
    var cellDesc = linha.insertCell(1);
    var cellQuantidade = linha.insertCell(2);
    var cellValor = linha.insertCell(3);

    cellItem.innerHTML = item;
    cellDesc.innerHTML = descricao;
    cellQuantidade.innerHTML = quantidade;
    cellValor.innerHTML = valor;

    preencheCamposForm();

}

function preencheCamposForm() {

    for (var i = 0; i < pessoas.rows.length; i++) {
        pessoas.rows[i].onclick = function () {
            index = this.rowIndex;
            document.getElementById("txtItem").value = pessoas.rows[index].cells[0].innerText;
            document.getElementById("txtDesc").value = pessoas.rows[index].cells[1].innerText;
            document.getElementById("txtQuantidade").value = pessoas.rows[index].cells[2].innerText;
            document.getElementById("txtValor").value = pessoas.rows[index].cells[3].innerText;
        }
    }
}

function delRegistro() {

    for (var i = 0; i < pessoas.rows.length; i++) {
        if (index == i) {
            pessoas.deleteRow(index);
            return;
        }
    }
}
body {
  background-color: rgba(128, 128, 128, 0.459);
  margin: 0;
  padding: 0;
}
h1 {
  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
    "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
  color: rgba(0, 0, 0, 0.5);
  text-align: center;
}
select {
  width: 120px;
  height: 50px;
  font-size: 20px;
}

main {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: ;
}

form {
  background-color: #0000005e;
}

.form-group {
  padding: 0px 10px 0px 10px;
}
.form-control {
  width: 70px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}
.form-control1 {
  width: 400px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}
textarea {
  width: 250px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}

label {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: 700;
}

.btn {
  background-color: blue;
  color: white;
  border: none;
  padding: 10px 20px 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 10px;
}

.table {
  font-family: Arial, Helvetica, sans-serif;
  background-color: rgb(255, 255, 255);
  margin: 10px;
  cursor: pointer;
  width: 300px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modelador de orçamentos</title>

    <link rel="stylesheet" href="visual.css">

Modelador de orçamentos

         <form>

                 Item
                    <input type="text" class="form-control1" id="txtItem" placeholder="Item">

             Descrição:
             <input type="text" class="form-control" id="txtDesc" placeholder="Descrição">

              Quantidade:
              <input type="number" class="form-control" id="txtQuantidade" placeholder="Quantidade">

              Valor
             <input type="number" class="form-control" id="txtValor" placeholder="Valor">

        <button type="button" class="btn btn-primary btn-lg"
            onclick="inserir(txtItem.value, txtDesc.value, txtQuantidade.value, txtValor.value)">
            Inserir
        </button>
        <button type="button" class="btn btn-primary btn-lg" onclick="delRegistro()">
            Excluir
        </button>

    </form>

            Item
            Descrição
            Quantidade
            Valor

    </form>

Comment: 1) cria uma classe css com a cor alterada, por exemplo `.selecionado { background-color: cyan }` 2) adiciona um evento "click" na nova linha da tabela, 3) na função do evento click use o método `toggle` para adicionar/remover a classe, por exemplo `.... function(tr) { tr.classList.toggle('selecionado'); }`
Comment: Infelizmente também não funcionou essa solução
Answer: Uma outra forma que consegui alterando o seu código seria:

let tabela, index;

function inserir(item, descricao, quantidade, valor) {
    tabela = document.getElementById("tabela");
    var qtdlLinhas = tabela.rows.length;
    var linha = tabela.insertRow(qtdlLinhas);
    var linhaParam;

    var cellItem = linha.insertCell(0);
    var cellDesc = linha.insertCell(1);
    var cellQuantidade = linha.insertCell(2);
    var cellValor = linha.insertCell(3);

    cellItem.innerHTML = item;
    cellDesc.innerHTML = descricao;
    cellQuantidade.innerHTML = quantidade;
    cellValor.innerHTML = valor;

    preencheCamposForm();

}

function preencheCamposForm() {

    for (var i = 0; i < tabela.rows.length; i++) {
        tabela.rows[i].onclick = function () {
            index = this.rowIndex;
            document.getElementById("txtItem").value = tabela.rows[index].cells[0].innerText;
            document.getElementById("txtDesc").value = tabela.rows[index].cells[1].innerText;
            document.getElementById("txtQuantidade").value = tabela.rows[index].cells[2].innerText;
            document.getElementById("txtValor").value = tabela.rows[index].cells[3].innerText;
        }
        //Início do código alterado
        tabela.rows[i].onclick = function (){this.classList.toggle("mystyle")}
        //Fim do código alterado
    }
}

function delRegistro() {

    for (var i = 0; i < tabela.rows.length; i++) {
        if (index == i) {
            tabela.deleteRow(index);
            return;
        }
    }
}

/* // DAQUI PRA BAIXO É CÓDIGO TESTE
function myFunction(element) {
    element.classList.toggle("mystyle");
 } */
body {
  background-color: rgba(128, 128, 128, 0.459);
  margin: 0;
  padding: 0;
}
h1 {
  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
    "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
  color: rgba(0, 0, 0, 0.5);
  text-align: center;
}
select {
  width: 120px;
  height: 50px;
  font-size: 20px;
}

main {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: ;
}

form {
  background-color: #0000005e;
}

.form-group {
  padding: 0px 10px 0px 10px;
}
.form-control {
  width: 70px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}
.form-control1 {
  width: 400px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}
textarea {
  width: 250px;
  border-radius: 5px;
  border: 1px solid #ced4da;
  padding: 10px;
}

label {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: 700;
}

.btn {
  background-color: blue;
  color: white;
  border: none;
  padding: 10px 20px 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 10px;
}

/*.table {
  font-family: Arial, Helvetica, sans-serif;
  background-color: rgb(255, 255, 255);
  margin: 10px;
  cursor: pointer;
  width: 300px;
}

#tabela thead th {
  font-weight: bold;
  background-color: black;
  color: white;

  padding: 5px 10px;
}*/

/*DAQUI PRA BAIXO É TESTE*/

.mystyle {
  background-color: coral;
  color: white;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modelador de orçamentos</title>

    <link rel="stylesheet" href="visual.css">

Modelador de orçamentos

        <form>

                Item
                <input type="text" class="form-control1" id="txtItem" placeholder="Item">

            Descrição:
            <input type="text" class="form-control" id="txtDesc" placeholder="Descrição">

                    Quantidade:
                    <input type="number" class="form-control" id="txtQuantidade" placeholder="Quantidade">

                    Valor
                    <input type="number" class="form-control" id="txtValor" placeholder="Valor">

                <button type="button" class="btn btn-primary btn-lg"
                    onclick="inserir(txtItem.value, txtDesc.value, txtQuantidade.value, txtValor.value)">
                    Inserir
                </button>
                <button type="button" class="btn btn-primary btn-lg" onclick="delRegistro()">
                    Excluir
                </button>

W3C

        </form>

                Item
                Descrição
                Quantidade
                Valor

    </form>

Fiz uma alteração para a função rodar após a renderização dentro da função preencheCamposForm()
Após renderizar, é referenciado o próprio elemento dentro da função onde é atribuído o evento toggle referente a classe "mystyle".
tabela.rows[i].onclick = function (){this.classList.toggle("mystyle")}

Comment: Desculpa a demora para dar um retorno, é porque eu estava tentando corrigir um bug que apareceu com isso kkkk, o excluir parou de funcionar.
Comment: Conseguiu solucionar a questão da marcação e o bug?
Answer: No exemplo abaixo existe a classe:
.mystyle {
  background-color: coral;
  color: white;
}

E você ativa e desativa através evento toggle
function myFunction(element) {
   element.classList.toggle("mystyle");
}

É importante que na tag tr passe a função com o parâmetro this para a função referenciar o próprio elemento que está sendo clicado

Conteúdo

function myFunction(element) {
   element.classList.toggle("mystyle");
}
.mystyle {
  background-color: coral;
  color: white;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
<!DOCTYPE html>

HTML Table

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

Comment: O ponto é que na tela HTML assim realmente funciona, porém no tipo do código que mandei, infelizmente, não.
Mesmo adicionando os parametros que você sugeriu e removendo os meus, esse click responsivo não acontece.
link: https://jsfiddle.net/brunorafael_l/96nhecd4/
Comment: Aqui está o link com a alteração para ficar mais fácil de ver o código pela jsfiddle:
https://jsfiddle.net/gutobr9/so42wgt0/1/


Intuition of regular SVM vs kernel SVM

Question: I have been trying to understand the difference between a regular Support Vector Machine, and a kernel Support Vector Machine. I have my own intuition, but I'm not sure if it is quite right. Below is my understanding in my own words; is this correct?
So my understanding is that with a regular SVM, you are trying to find a hyperplane which separates the data into classes, based on their ground-truth labels. The problem involves optimising the parameters of the separating hyperplane, such that the distance between the hyperplane and the closest data point for each class, is maximum. In this context, the "distance" is calculated in the original space of the data.
However, if the data is not linearly-separable, then we need to find a new space in which the data is linearly-separable, so that the "distance" from before can be calculated in this new space. You could just introduce some arbitrary new dimensions, e.g. (x1 * x2), (x1 * x1), etc., but there is no guarantee that this new space is appropriate. So instead, you use a kernel to compute the new space, which takes into account the actual locations of the datapoints, rather than just the space as a whole.
A kernel takes in two datapoints, and computes a scalar value which effectively describes the "similarity" of the two datapoints. Then, for each datapoint, the kernel is applied between this datapoint and every single other datapoint in the dataset. This datapoint can now be described by a vector of "similarities", one element for each of the other datapoints. In this new space, it may now be easier to separate out the data, because the new space actually represents similarities between datapoints, whereas in the original space, it just represented the real-world data.
And the reason why this new space is considered to have potentially infinite dimensions, is that you can have one dimension of the new space for each datapoint in your data; so as your dataset approaches infinite size, the dimensionality of the new dataset also approaches infinity.
Am I thinking about this in the right way?
Specifically, I'm not sure about the following:
1) My understanding of why the kernel SVM space is better than just introducing arbitrary new dimensions (because the kernel method actually considers the relationships between datapoints).
2) My understanding of how the optimal separating hyperplane is calculated in the new space correct (by taking a datapoint and computing its similarity to every other datapoint, and then creating a vector with one similarity value for each of these other datapoints).
3) My understanding of why the new space can be thought of as having virtually infinite dimensions (because the dataset can have a virtually infinite number datapoints, and therefore a virtually infinite number of "similarities" in the vector which describes new space).
Answer: Your understanding of linear SVMs sounds correct, but there may be some misconceptions about kernelized SVMs.
A kernelized SVM is equivalent to a linear SVM that operates in feature space rather than input space. Conceptually, you can think of this as mapping the data (possibly nonlinearly) into feature space, then using a linear SVM. However, the actual steps taken when using a kernelized SVM don't look like this because the kernel trick is used. Rather than explicitly mapping the data into feature space, the mapping is defined implicitly by the kernel function, which returns the dot product between feature space representations of two data points. Say $x$ and $x'$ are points in input space and $K$ is the kernel function. Then $K(x, x') = \Phi(x) \cdot \Phi(x')$, where $\Phi$ is a mapping from input space to feature space. Because a linear SVM can be formulated in terms of dot products, one can replace these dot products with kernel function evaluations to obtain a linear SVM that operates in feature space, without ever having to compute (or even know) $\Phi$.

You could just introduce some arbitrary new dimensions...but there is no guarantee that this new space is appropriate. So instead, you use a kernel to compute the new space, which takes into account the actual locations of the datapoints, rather than just the space as a whole.

Feature space isn't defined by the data points, but by the kernel function itself. There's no guarantee that any particular kernel function will give linear separability. So, the choice of kernel is an important model selection problem.

In this new space, it may now be easier to separate out the data, because the new space actually represents similarities between datapoints, whereas in the original space, it just represented the real-world data.

Consider the linear kernel $K(x, x') = x \cdot x'$ which simply computes the dot product in input space. This gives a feature space that's equivalent to input space (up to rotation and reflection, which preserve the dot product). So, an SVM with this kernel would be equivalent to a regular linear SVM, and the above statement can't be true--just framing things in terms of similarities between data points doesn't necessarily increase separability.

And the reason why this new space is considered to have potentially infinite dimensions, is that you can have one dimension of the new space for each datapoint in your data; so as your dataset approaches infinite size, the dimensionality of the new dataset also approaches infinity.

Feature space does not have one dimension per datapoint. For example, consider the linear kernel again. Feature space is equivalent to the input space, and therefore has the same number of dimensions. Polynomial kernels induce a finite dimensional feature space, with higher dimensionality than the input space (for degree > 1). Some kernels (such as the RBF kernel) do induce an infinite dimensional feature space. This just means that, in order for $\Phi(x) \cdot \Phi(x')$ to equal $K(x, x')$, $\Phi(x)$ must be infinite dimensional. This is a consequence of the kernel function, rather than the number of data points. However, even if feature space is infinite dimensional, the data can only span a finite-dimensional subspace. The maximum possible dimensionality of this subspace is the number of data points.

Intuition of regular SVM vs kernel SVM


drupal add class to form-item if error on form to all forms

Question: I just want to add class to .form-item if there is error on form i used the following code but its not working.
function semanticUI_form_element($variables) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $attributes['class'][] = array('error1');
  }
  if(form_get_error($element)){
    $attributes['class'][] = array('error1');
  }

  if (!empty($element['#required'])) {
    $element['#attributes']['class'][] = 'test';
  }
}

Any help would be appreciated.
Comment: Is this your actual code or have you simplified it for inclusion here?  for example, you don't appear to define `$element` which you need to grab out of `$variables['element']`...
Comment: sorry forget to mention this $element = $variables['element']; i used this.
Answer: If you copy the theme_form_element() function out of includes/form.inc and into your theme's template.php file, re-name it to match your theme, and change the initial setting of $attributes['class'] accordingly:
  if (form_get_error($variables['element'])) {
    $attributes['class'] = array('form-item', 'da-error');
  } else {
    $attributes['class'] = array('form-item');
  }

...this will put a da-error class in the overall
 wrapping this element.


Managing nested Firebase realtime DB queries with await/async

Question: I'm writing a Firebase function (Gist) which

Queries a realtime database ref (events) in the following fashion:
 await admin.database().ref('/events_geo').once('value').then(snapshots => {

Iterates through all the events
 snapshots.forEach(snapshot => {

Events are filtered by a criteria for further processing

Several queries are fired off towards realtime DB to get details related to the event
 await database().ref("/ratings").orderByChild('fk_event').equalTo(snapshot.key).once('value').then(snapshots => {

Data is prepared for SendGrid and the processing is finished

All of the data processing works perfectly fine but I can't get the outer await (point 1 in my list) to wait for the inner awaits (queries towards realtime DB) and thus when SendGrid should be called the data is empty. The data arrives a little while later. Example output from Firebase function logs can be seen below:
 10:54:12.642 AM Function execution started
 10:54:13.945 AM There are no emails to be sent in afterEventHostMailGoodRating
 10:54:14.048 AM There are no emails to be sent in afterEventHostMailBadRating
 10:54:14.052 AM Function execution took 1412 ms, finished with status: 'ok'
 10:54:14.148 AM
Super hyggelig aften :)

super oplevelse, ... long string generated
Gist showing the function in question
I'm probably mixing up my async/awaits because of the awaits inside the await. But I don't see how else the code could be written without splitting it out into many atomic pieces but that would still require stitching a bunch of awaits together and make it harder to read.
So, two questions in total. Can this code work and what would be the ideal way to handle this pattern of making further processing on top of data fetched from Realtime DB?
Best regards, Simon
Answer: I ended up refactoring the function as I realized it could be made much simpler thanks to Tarik Huber's answer.
The keypoints were:

to not use forEach and instead iterate using for(const event of events) as that is compatible with async calls
split the function into more modular parts. One part now fetches, filters and stores the data in an array. Second part iterates through the array and makes more async calls

This lead to more readable code that was also easier to debug.
The old function did both parts mentioned above in one go and wrongfully used forEach which lead to the issues with async calls not resolving properly.
An outline of the new function can be seen below. Only the important parts have been highlighted.
async function afterEventHostMail() {
 // Initialize variables
  events = [];

  await admin.database().ref('/events_geo').once('value').then(snapshots => {
    snapshots.forEach(snapshot => {
      var event = snapshot.val();
      var eventKey = snapshot.key;

      // Do some filtering
      const mergedObj = { ...event, ...{ key: eventKey } };
      events.push(mergedObj)
    });
  });

  for (const event of events) {
    // Do a ton of await calls here
  }

  // The rest of the function
}

Answer: Your problem is that you use async in a foreEach loop here:
  Object.keys(event.participants).forEach(async (value: any) => {

The forEach loops don't support async calls. You need to map the data to an normal array and use a for loop. There you can use await normaly.
Comment: That was the missing piece. The fact that `forEach` don't support async calls lead me to refactor the entire function as there was also `snapshots.forEach(snapshot => {` which also lead into issues as I was revising the function. See my answer for a complete walkthrough of the refactoring.


Perl Moose Dynamic assign the value to attribute suggestion

Question: I am trying to accomplish the following.

I have a Moose style modules A and B
A need metadata as mandatory params
B wants to create the object of A multiple time
hence wanted to set as an attribute

Is there a better way to do this (so that I can pass the metadata to package A and in package B avoid calling new multiple times) also trying to get it done 1 liner if possible.
package A {

    use Moose;
    has 'metadata' => (
        is      => 'rw',
        isa     => 'HashRef',
        default => sub {{}},
        required => 1
    );

    sub process {
        die unless keys %{shift->metadata};
        # ... process
        print "Success!\n";
    }

    __PACKAGE__->meta->make_immutable;

}
#######B#########
package B {
    use Moose;
    use A;

    has 'obj_a' => (
        is      => 'rw',
        isa     => 'A',
        writer  => 'set_meta',
    );

    sub _set_meta {
        my ( $self, $metadata) = @_;
        return $self->set_meta(A->new(metadata => $metadata));
    }

    sub obj_with_meta {
        my ( $self, $metadata) = @_;
        return A->new(metadata => $metadata);
    }

    __PACKAGE__->meta->make_immutable;

    1;
}

############
use B;
my $b = B->new();

# want to call like this but I am sure I am missing something which moose is providing
# here I am supposed to call obj_a instead of _set_meta I believe
#calling _set_meta I am bypassing the Moose attribute I guess
$b->_set_meta({id=>'id for metadata'})->process;

#works
$b->obj_with_meta({id=>'id for metadata'})->process;

Note above code is working
output is
Success!
Success!
I am trying to know if there is anything in moose that I can leverage. so that I can share data to the next class by writing to meta may be or using some trait maybe.
package A is the catalyst controller
package B is an independent module not tightly coupled with the catalyst.
Comment: Both the calls work. What's the problem?
Comment: @choroba B::_set_meta returns a B instance which does not implement process(). Looks like a delegate pattern would be a solution.
Comment: @clamp: Why doesn't it die then?
Comment: I am trying to know if there is anything in moose that I can leverage. so that I can share data to next class by writing to meta may be or using some trait may be
Comment: description updated
Comment: @choroba sorry, wrong assumption about the generated writer. Thanks for clarifying.
Comment: You're saying A is a Catalyst controller. Why does your Catalyst-independent package B instantiate new controllers? That is... unusual. An attribute on a Catalyst controller can be passed in via Catalyst config (as in the config file, or with `__PACKAGE__->config(...)` in the package itself , and instances of these controllers typically stick around for a while. Can you explain explain in more detail what you are actually trying to do please? Try to be a little less generic. Give them better names, and tell us what they are for please.
Comment: @simbabque
lets say A => Controller::User  GET|POST => localhost/user controller only takes request and validate.
B => API::User (uses DBI plain SQL query to perform the operation) where I can create object and do db operations. for db operation, session data need to pass to API::User.

Reason for keeping B separate is this way I can even switch the framework in future.
suppose to mojo or dancer as per the need.
request received by Controller::User and want to insert to hence
API::User->new('metadata' => $c->session->data)->insert;
everytime I will need something like above.
Answer: Separating business logic from your controllers in a Catalyst app is a great idea. You can encapsulate it into its own modules and use them via a thin Catalyst::Model layer.
You don't actually need to worry about passing the session in from the controller, because all Catalyst::Components provide you with a means to do this, called ACCEPT_CONTEXT. This is a method that you can implement in any component, but typically it's used in models. It is called whenever a $c->model(...) call is done, and it gets passed the context object $c, and is supposed to return an object that can be used like a model. This might or might not be a Catalyst::Component object.
I've build a sample application that I will be using for this answer. You can find the full source code in this github repository.
Let's assume there is a Catalyst::Model class called MyApp::Model::API::User, with the following code. It inherits from Catalyst::Model::DBI in order to leverage database handle caching via Catalyst.
package MyApp::Model::API::User;

use strict;
use warnings;

use API::User;

use parent 'Catalyst::Model::DBI';

sub ACCEPT_CONTEXT {
    my ( $self, $c, @args ) = @_;

    $c->log->debug( sprintf 'Creating a new API::User object for %s line %d',
        ( caller(2) )[ 0, 2 ] );

    return API::User->new(
        dbh      => $self->dbh,
        metadata => $c->session->{data},
    );
}

1;

Every time a Controller does $c->model('API::User') the ACCEPT_CONTEXT method gets called, and it instantiates a class called API::User, which is my implementation of your Catalyst-agnostic business logic. It accepts a database handle object, which the DBI Model provides for us, as well as the metadata, which we take from the user's session.
In my example I've made the user's ID part of the session so that there is actual metadata to play with (and if there is none, we create one, but that's not important here).
package API::User;

use Moose;
use DBI;

has metadata => (
    isa      => 'HashRef',
    is       => 'ro',
    required => 1,           # either it's required or it has a default
);

has dbh => (
    isa      => 'DBI::db',
    is       => 'ro',
    required => 1,
);

sub create { ... }

sub read {
    my ($self) = @_;

    my $sql = 'SELECT id, number_of_writes FROM user WHERE id=?';
    my $sth = $self->dbh->prepare($sql);

    $sth->execute( $self->metadata->{id} );

    return $sth->fetchrow_hashref;
}

sub write { ... }

__PACKAGE__->meta->make_immutable;

The API::User has three methods. It can create, read and write. This is all very much simplified as an example. We will focus on reading in this answer. Note how the metadata property is required, but has no default. You can't have both, because they contradict each other. You want this to be passed in, so you want it to blow up if it's missing, rather than set a default value of an empty hash reference.
Finally, in a Controller this is used as follows.
package MyApp::Controller::User;
use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Controller' }

__PACKAGE__->config( namespace => 'user' );

sub auto : Private {
    my ( $self, $c ) = @_;

    unless ( $c->session->{data}->{id} ) {
        # we have to initialise data first because the model depends on it
        $c->session->{data} = {};
        $c->session->{data}->{id} = $c->model('API::User')->create;
    }
    return 1;
}

sub index_get : Path('') Args(0) GET {
    my ( $self, $c ) = @_;

    $c->stash->{json_data} = $c->model('API::User')->read;

    return;
}

sub index_post : Path('') Args(0) POST {
    my ( $self, $c ) = @_;

    $c->stash->{json_data} = $c->model('API::User')->write;

    return;
}

__PACKAGE__->meta->make_immutable;

I'm setting some session data in the auto action, which gets called before any other action. For a specific session this will be done once, and then that user's ID is stored in the session for subsequent requests.
In the index_get action I am accessing our class via $c->model('API::User), which will call ACCEPT_CONTEXT on our Model class, instantiate a new API::User object that is populated with both the existing database handle as well as the session metadata that contains our user's ID.
For the sake of the example, I'm using a JSON view so we can see what's happening in the DB.
When we curl the application to GET our user, the logs look as follows.
[info] *** Request 2 (0.044/s) [31642] [Fri May  6 19:01:25 2022] ***
[debug] Path is "user"
[debug] "GET" request for "user" from "127.0.0.1"
[debug] Created session "36d509c55d60c02a7a0a9cbddfae9e50b092865a"
[debug] Creating a new API::User object for MyApp::Controller::User line 15
[debug] Creating a new API::User object for MyApp::Controller::User line 23
[debug] Response Code: 200; Content-Type: application/json; charset=utf-8; Content-Length: unknown
[info] Request took 0.018616s (53.717/s)
.------------------------------------------------------------+-----------.
| Action                                                     | Time      |
+------------------------------------------------------------+-----------+
| /user/auto                                                 | 0.013309s |
| /user/index_get                                            | 0.000640s |
| /end                                                       | 0.000994s |
|  -> MyApp::View::JSON->process                             | 0.000411s |
'------------------------------------------------------------+-----------'

As you can see, we go to auto first, and then go to index_get. In the debug statements above it creates two instances of API::User. One is in auto to create a new user because I've not supplied a session cookie, and the second is from index_get.
If we call it with an existing user by supplying a session cookie (see my test script in the repository) it will only call it once.
[info] *** Request 8 (0.037/s) [31642] [Fri May  6 19:04:16 2022] ***
[debug] Path is "user"
[debug] "GET" request for "user" from "127.0.0.1"
[debug] Found sessionid "710cb37124a7042b89f1ffa650985956949df7d0" in cookie
[debug] Restored session "710cb37124a7042b89f1ffa650985956949df7d0"
[debug] Creating a new API::User object for MyApp::Controller::User line 23
[debug] Response Code: 200; Content-Type: application/json; charset=utf-8; Content-Length: unknown
[info] Request took 0.017655s (56.641/s)
.------------------------------------------------------------+-----------.
| Action                                                     | Time      |
+------------------------------------------------------------+-----------+
| /user/auto                                                 | 0.001887s |
| /user/index_get                                            | 0.001238s |
| /end                                                       | 0.003510s |
|  -> MyApp::View::JSON->process                             | 0.001463s |
'------------------------------------------------------------+-----------'

Comment: @simplebque Sir thank you so much for all your efforts in explaining the stuff in this much detail.
I will definitely give a try and so far looks it might solve the problem I am dealing with.
once Again Tons of thanks Sir.
Comment: Sorry this took a while to compile, I hope it is useful to you. :)
Answer: Thanks @simbabque
I have created a factory method like this
package MyApp::Model::API::Factory;

use Moose::Util;
use Module::Load  qw/autoload/;

sub ACCEPT_CONTEXT {
    my ( $self, $c, $args ) = @_;

    my $module = 'MyApp::API::';

    if(!defined $args->{api_module}) {
        #eg. MyApp::Controller::API::Event::ConferenceCall::Role
        my $caller_package = ( caller(2) )[ 0 ];

        if($caller_package->can('api_module')) {
            #get from attributes
            $module .= $caller_package->new->api_module;
        } else {
            #auto detect/infer from caller name
            $caller_package =~ /MyApp::Controller::API::(.*)/;
            $module .= $1;
        }

    } else {
        #append the prefix to the module name MyApp::API::
        $module .= $args->{api_module};
    }

    $c->log->debug( sprintf "Creating a new %s object for %s line %d",$module,( caller(2) )[ 0, 2 ] );

    my $object;

    try {
        autoload  $module;
        my $meta_method;
        #auto_detect meta_method if not defined
        # here check the attributes of the class and see if it has a meta_method with suffix _metadata
        # if it does, use that
        if(!exists $args->{meta_method}) {
            my $meta = Moose::Util::find_meta($module);
            my @has    = $meta->get_attribute_list;
            foreach my $has (@has) {
                #since we have standard suffixes for the meta_methods _metadata
                if($has =~ /_metadata$/ ) {
                    $meta_method = $has;
                    last;
                }
            }
        } else {
            $meta_method = $args->{meta_method};
        }
        $object = $module->new( $meta_method => $c->{stash}{internal});
        $c->log->debug("object created by api factory for ". ref($object) . " meta attr set: $meta_method");
    } catch {
        $c->log->error( $_ );
        return;
    };

    return $object;
}

1;

In every controller
    my $user_api_obj = $c->model('API::Factory');

    my $result = $user_api_obj->register_user($valid_params);


SVG Image neither displayed by IMG nor Background Image

Question: I can't get the SVG Image to disaply correctly in Google Chrome 34
Example
As you can see object and iframes are working. IMG and Backgroudn image aren't working.
IE11 and FireFox can display all 4 examples correct.
Answer: The Chrome developers have chosen not to support the use of SVG fragments in images in order to protect user's privacy.
Because your SVG file only displays each shape if it is the target of a URL fragment (the part after <code>#</code> in the filename), nothing is displayed when Chrome strips out the fragment.
Comment: (Hope you don't mind the edits.  Nowhere in the question or original answer text was there an explanation of the key fact that this involved fragment targets.)


Commerce shipping by weight and country

Question: I'm having trouble finding a solution for combining location & weight-based shipping with drupal commerce.
I need to have three shipping zones (DK, EU, ROW) with individually priced weight steps inside each zone (0-500g, 500-1000g, 1000-2000g, 2000-5000g).
I've gone through a bunch of tutorials and looked at other forums where people have similar requests. But haven't found a solution yet - which should be possible for such a 'simple' problem, right?
To sum up I need advice on how to configure the following shipping calculation rules:

Free Shipping (no weight)
DK Shipping (1-500g)
DK Shipping (501-1000g)
DK Shipping (1001-2000g)
DK Shipping (2000-5000g)
EU Shipping (1-500g)
EU Shipping (501-1000g)
EU Shipping (1001-2000g)
EU Shipping (2000-5000g)
ROW Shipping (1-500g)
ROW Shipping (501-1000g)
ROW Shipping (1001-2000g)
ROW Shipping (2000-5000g)

I can't figure out how to check for a line item's weight in a rule?
I've got Shipping, Flat Rate, Physical Product, Physical Fields and Rules Extra enabled.
Answer: I ended up doing 12 rules as @nvahalik suggested. Here's an export of one of them. Doing the others is just a matter of cloning this rule and changing weight, territories and shipping price accordingly
<code>{ "rules_dk_shipping_1_499g" : {
    "LABEL" : "DK shipping (1-499g)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout", "Commerce Payment" ],
    "REQUIRES" : [
      "rules",
      "commerce_physical",
      "commerce_order",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-shipping-service" ],
          "value" : "by_weight"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:order" ],
          "field" : "commerce_customer_shipping"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E=",
          "value" : "1",
          "unit" : "g"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003C",
          "value" : "500",
          "unit" : "g"
        }
      },
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "operator" : "is one of",
          "value" : "DK"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "3300",
          "component_name" : "shipping",
          "round_mode" : "0"
        }
      }
    ]
  }
}
</code>
Comment: Looks good. Glad you got it figured out.
Comment: thanks Kristoffer for the export from your rules but i would like to put the same configuration for a drupal commerce website, mixing weight and location calculating shipping from a total cart.
As a newbee, could you please help me with a tutorial explaining how you have configurate your shipping total cost based on different weight and locations.
Thanks
Comment: It's actually in the rules too. Look at the amount lines. Those are the prices in Danish kroners. Makes sense?
Answer: This would be doable with 12 individual rules (3 countries x 4 sizes = 12 rules). You can also try this module: Commerce shipping Province weight.
Shipping is one of the few areas where Commerce tends towards more customized solutions. But perhaps that one will help you.
Comment: Thanks a lot @nvahalik. I'd prefer the Rules solution to avoid installing yet another module and to avoid a lot of configurations. I've elaborated my question with some specific issues with my rules-knowledge. Hope you've got time to take a look.
Comment: Wait, nailed it I think - will test and provide my solution here when it's tested

Commerce shipping by weight and country


How to install dev packages on a Red Hat server that is not connected to internet?

Question: I'm a programmer and my Linux knowledge is poor. I have to install rrdtools on a server, and i get some warnings about missing libraries. The server has been set up so that whenever I connect to it via a VPN client, I cannot access the Internet from that server or from the computer I use to access the server. The only way I can bring new files on that server is to put the files on a USB stick and then upload them to the server via pscp.
I normal circumstances, according to a forum post I've found, if I had Internet access from the server, I would use this command:
yum install cairo-devel libxml2-devel pango-devel pango libpng-devel freetype freetype-devel libart_lgpl-devel
I can't do that but I have access to another Red Hat server which has these missing libraries already installed since I was able to install rrdtools on it and I wonder if I can somehow use it to solve my problem.
My question isn't specifically targeted at rrdtools. I expect to encounter this problem further when I'll attempt to install some other software. Is there a way to list the dev packages that yum checks when I run yum install? And a way to find the download location of each package so I can download them manually and try to use something like yum localupdate as I've seen here?
Answer: You can determine the requirements/dependencies of a particular package with yum deplist packagename.
That doesn't fully solve your problem, though. Do you have access to a Red Hat DVD? Can you bring that with you?
Another option is to try yumdownloader (part of the yum-utils) package. Install yum-utils on a server with internet access and run yumdownloader packagename to download the rpms and depedency packages to your current working directory. You could then take the resulting files to the server that does not have internet access.
If your organization does not provide internet access, it is still possible to use a local repository on your network...


How to calculate the expected number of times a specific pattern appears in a set of n numbers of Bernouilli trials?

Question: Let's consider a set of n Bernouilli trials of parameter p $\text{(O1,...,On)}$. Let's name the two possible outcomes as + and -. How to calculate the expected number of times we will match a pattern of k outcomes with k < n ? For instance how many times the pattern $\text{(+,-,+)}$ will appear if we perform 20 Bernouilli trials in a row ? What's the name of probability law for this experience ?
Comment: Does $+-+-+$ count as two appearances of $+-+$?  If so, the answer to your example is $18p^2(1-p)$ and the generalisation is obvious, by [linearity of expectation](http://en.wikipedia.org/wiki/Expected_value#Linearity)
Comment: well I'm not sure if I should count it as two appearances. My final goal is to test wether a pattern occurs randomly or not in times series so maybe I will have to work out a P-value. Thanks for the formula I'll try to think of what you're saying about linearity of expectation until I get a detailed answer.
Answer: I'll use $1,0$ instead of $+,-$, with $1$ having probability $p$.
Let $\mathbf{1}_i(k)$ be the indicator on the event that pattern $k$ appears at position $i$. So for example if you see $11011$, and your pattern is $k=11$ then it appears at $i=1$ and $i=4$. Then let $X_n$ be the number of occurances of your pattern for $n$ throws, and also define $|k|$ to be the length of your pattern (if $k=11$ then $|k|=2$). We get that:
$$X_n=\sum_{i=1}^{n-|k|}\mathbf{1}_i(k).$$
By linearity of expectation, $E[X_n]=\sum_{i=1}^{n-|k|}E[\mathbf{1}_i(k)]$, and $E[\mathbf{1}_i(k)]=P(k)$, where $P(k)$ is of the form $p^{k_1}(1-p)^{k_0}$, where $k_1$ is the number of 1's in $k$ and $k_0$ is the number of $0$'s, with $k_1+k_0=|k|$,  so
$$E[X_n]=(n-|k|)p^{k_1}(1-p)^{|k|-k_1}.$$
Comment: soz for the edit $\mathbf{1}_i(k)$ equals 1 or 0 that's why you call it indicator and not index edit : ok got it very nice formalism ty


Inheritance implement

Question: I learn Java from a book. I finished already inheritance episode and I don't understand an example program in User Interfaces episode:
public class AWTApp extends Frame {
...
public AWTApp(String caption)
    {
        super(caption);
        setLayout(new GridLayout(PANELS_NO, 1));
        for(int i=0;i<PANELS_NO;i++)
        {
            panels[i]=new Panel();
            add(panels[i]);
        }
        label_test(panels[0]);
        ...
    }
}

This is the constructor in the main class(AWTApp) which inherits Frame class.
In the other example the frame is a variable in the main class(AWTApp) and to add components you write frame.add(component) ((Frame nam - frame, Component name - component)). How can they write in this code just add() or just pack() if there is no frame object?
Comment: `AWTApp` is a `Frame`. When you call `add()` in the constructor, you're calling it on `this`, which is a reference to an object of type `AWTApp`.
Answer: public class AWTApp extends Frame
This means that AWTApp is a Frame
So when you call
public AWTApp(String caption)
    {
        super(caption); // here you are calling super constructor the frame constructor and creating the frame

       this.setLayout(new GridLayout(PANELS_NO, 1)); // cause you are a frame you can call with this parents public protected (and package if they are in the same package)
       this.add(..);
    }
}

Comment: Thanks! I will try to understand it better tomorrow. It is just hard to understand. Do you know where can I find exercises for inheritance? I just always find very hard excercises that consists content I haven't learnt yet.
Answer: Here is some explanation.
First, some code:
public class Parent{

    public void doThing(){
        System.out.println("I did a thing!");
    }

}

public class Child extends Parent{

    public void doAnotherThing(){
        System.out.println("I did another thing!");
    }

}

public class MainClass{

    public static void main(String[] args){
        Parent p = new Parent();
        Child c = new Child();
        p.doThing();
        c.doThing(); // This is correct because c is a Parent!
        c.doAnotherThing(); // This is correct, because c is also a child.
     }

}

Child inherits all of Parents methods, because Child is just an extension of Parent. In the context of your program, this means that AWTApp can call all of Frame's methods because it IS a frame and therefore can do anything that a frame can do, plus its own methods.

Inheritance implement


Como exibir erros no ambiente de produção?

Question: Estou vindo do embalo desta pergunta aqui.
Existe alguma maneira de, no ambiente de produção, quando ocorrer algum erro eu avisar, que ocorreu o erro e que devo olhar o arquivo de log?
Eu queria que fosse exibido na tela algo mais ou menos assim quando acontece um erro: Ocorreu um erro, verifique o arquivo de log do sistema.
Lembrando que venho da pergunta acima, então no caso no ambiente de produção não exibo os erros, apenas guardo-os em um arquivo de log.
Comment: Qual a diferença dessa aqui para aquela? Me parece ser o mesmo problema. Lá você está pedindo meios de receber erros, e o log é só um desses meios. Acho que qualquer resposta aqui caberia lá. Não estou vendo diferença suficiente pra não votar pra fechar.
Comment: @Bacco tipo no caso ele envia o erro para o arquivo de log, porém não avisa nada na página. Eu queria poder escrever na tela algo mais ou menos assim quando acontece um erro: `Ocorreu um erro, verifique o arquivo de log do sistema`.
Comment: Isso já tem na sua pergunta, o que eu não entendi é porque abrir uma nova, se é o mesmo problema da anterior. Sua pergunta não fala nada de log. Naquela mesmo alguém poderia falar da aplicação enviar um email, por exemplo. Ou mesmo gravar a informação num DB de uma página sua de monitoramento, como outro exemplo.
Comment: Eu fiz essa pergunta no comentário, ai carinha que me respondeu falou pra eu abrir uma nova pois era muito extenso pra responder nos comentários
Comment: Me parece que o problema é que você aceitou cedo demais uma resposta que não resolve seu problema, aí diminuiu a chance de outros responderem. Cabem muitas respostas diferentes naquela pergunta sua.
Comment: Hm, desculpa não faz muito tempo que conheci o Stack overflow, acha melhor eu editar minha pergunta lá? Quanto tempo devo esperar você recomenda? E da pra desmarcar como aceito?
Comment: Vou fazer o seguinte, eu não vou votar pra fechar, pois meu voto de fechar duplicata de PHP é instantâneo. Vamos ver o que o resto da comunidade resolve. Se fecharem essa, vc desmarca a aceita daquela, e aguarda mais respostas (ou aguarda o autor da resposta complementar com mais detalhes). Se deixarem aberta, aí fica como está.
Answer: No PHP você pode usar a função set_error_handler(), e criar sua própria função de tratamento de erros tipo:
minha_funcao_trata_erros(){
  //sua lógica
}
set_error_handler("minha_funcao_trata_erros");

Neste link você pode ver a documentação da função set_error_handler() http://php.net/manual/pt_BR/function.set-error-handler.php


Practical interpretation of Precision-Recall AUC

Question: I have a classifier with an AUC (PR) of 0.06 which I will use for a practical interpretation.
My test set consists of three months of data with a total of 2,200,000 observations of which 0.03 are labelled as the positive class (1).
Can I then use the following calculation: (2,200,000*0.03/90)*0.06 = 44, where 90 represents the three months.
From the above, can I then say that my classifier correctly classifies 44 true positive observations per day? Or should/could I interpret the AUC (PR) of 0.06 in another practical way?
Answer: When the "positive class" is rare, attempting to make all-or-nothing classifications will usually be misleading and not very informative.  It is far better to predict tendencies in such cases, and measures such as sensitivity, specificity, proportion "correctly" "classified", precision, and recall are improper accuracy scores that when optimized will result in the wrong features being selected and the wrong weights being given to them.  This can most easily be seen by your case in which "classifying" every observation as negative will result in an accuracy of 0.97.  These issues are detailed here.
Estimation of tendencies by estimating the probability of positive will result in optimum decisions, which in some cases will be "no decision" when there are close calls (intermediate probabilities).  Class calls are completely lost when using classification rather than prediction.


Can't login: user/login redirects to live site

Question: I copied a live site built by a previous developer to my local MAMP environment, and discovered that trying to use /user/login redirected me to the live site. I discovered that .htaccess had numerous dreaded 301 redirects. So, I changed the .htaccess to a clean one, cleared cache, cleared history, rebooted MAMP, tried a clean browser. I think I've now cleared the 301 redirects to regular pages, but user/login still goes to the live site.
Created fresh local install with a clean .htaccess; clear cache, reboot MAMP, etc, still can't login to local.
Is there a backend way to login to drupal? Through drush?
Could that demon-spawn developer have set something else that prevents local login?
Comment: Is it using the secure pages module, is the base URL set in settings.php?
Comment: Yes, Thank you. The secure pages module: drush dis securepages
Answer: If the live site uses HTTPS, implements SSL, try to check if is using modules like secure_pages. This kind of modules sometimes causes that kind of redirections.
Another thing to check could be the settings.php to see if there are something related to this issue.
Comment: Thank you Gerzensti & Jsheffers. It was in fact the Secure Pages module. Disabled that with Drush, and I was golden. I was looking in this direction already from a suggestion on another problem to look at Securelogin module.
Answer: If you're using Domain or something like this, what I did (on Windows) was editing the "hosts" file to redirect the production site URL (http://www.production.com) to 127.0.0.1.
So all your requests to your production site will be redirected to localhost.
After that, edit your domain settings to set the domain to 127.0.0.1 (or the URL you access your development website).
Finally, delete the redirection in hosts file.
I would also suggest to check for custom modules and clear cache with drush.
Answer: Another module that can cause this problem is Ubercart SSL.  I was being redirected when attempting to login and it took me a while to figure out which module was the culprit.  drush dis uc_ssl did the trick.
Answer: If Secure page causing the issue then you can disable it with following ways
1) Drush command
drush dis -y securepages
2) Disable the status in DB
UPDATE system SET STATUS =0 WHERE name =  'securepages'


QT - Modal Window with child windows

Question: I am creating an interface where you are requested to login. If you do not have a user, you can create one with a register button. Upon pressing this button a modal registration window will pop-up. Now, this all works great, but, the registration has a pop-up calendar window for helping to select dates. How can I allow this child-calendar-widget to come above the modal window?
Comment: If anything my edits improved the readability of your question. Tags are not supposed to be part of the title. And there are minor issues with your punctuation and sentence structure which I corrected. But I won't get into an edit-war with you, so I'll let it be. You're free to disagree.
Comment: Now why did you rollback my edits? Any particular reason?
Comment: I did not feel that your edits provided much more than personal preference. I feel that the way my question is written is to the point and easily understood. For this reason, I would prefer it remain in its original form.
Answer: If you create a modal popup with the modal dialog as the parent, it should already be shown above the modal dialog.
You could, for example, put the calendar widget inside a QDialog with Qt::Popup window flag.

QT - Modal Window with child windows


How to set Rules event for "Content is viewed" from excluding Teaser view?

Question: I set up a Rule that will execute during the "Content is viewed" Event and the action was to show a system message.
It worked and was triggered when I viewed the node. However, when I went to the home page, it was triggered N times, where N is the number of nodes on the /node page.
How do I stop this from happening? The Rule should only fall through on content full view, and exclude the teaser view.
Answer: In your rule add a data comparison called "view-mode" and set it to "Full content".
Answer: This might be inefficient but this is what I did:
Added a condition - Data comparison
site:current-page:path == node/[node:nid]
This is to make sure that it is showing up on the actual full /node/nid page and not as a teaser view.
Comment: In data comparison is also "view-mode" and you can set it to "Full content"
Comment: @NigelWaters that's the right answer, you can add it as answer.
radj: you condition will fail if you enable pathauto or an other URL aliasing mechanism.
Comment: @NigelWaters Yes, please add as an answer so I can select it as the correct an answer. Thanks!
Comment: @Mathankumar It did not fail because [...:path] is the pure system path, not the URL which can be an alias.


Azure Web App for containers CI with Azure Container Registry

Question: I'm having an issue with Azure Container Registry CI with my Azure Web App for Containers. It seems that the web hook between them has broken.
I've tried turning the CI within the Docker settings on the Web App however this fails and also tried creating a web hook from the Azure Container Registry however it says my container registry isn't managed but doesn't give me the option to upgrade it to one.
Comment: What is the exact error message you receive?
You may try the steps mentioned here:
https://learn.microsoft.com/en-us/azure/container-registry/container-registry-upgrade
Answer: Webhooks are not available in the classic SKU and you need to migrate for this. For CI you need to enable a webhook with the publishing creds which can call into the App service scm endpoint which can restart and repull.


Connected spaces of $M(n,\mathbb R)$

Question: Consider $M(n,\mathbb R)$, the space of all  $ n\times n$ matrices over $\mathbb R$.Which of the following are connected?
a.$O(n)$ the set of all orthogonal matrices
b.$GL(n,\mathbb R)$ set of all non-singular matrices over $\mathbb R$
c.$SL(n,\mathbb R)$ set of all non-singular matrices over $\mathbb R$ with determinant equals one.
d.set of all nilpotent matrices.
Answer:since the determinant map is continuous and continuous image of a connected set is connceted using them I have concluded (a),(b) is not connected since image set  of (a) is $\{-1,1\}$and of (b) is $(-\infty,0) \cup (0,\infty)$. Is  it correct?But how to approach the others
Answer: Hint: for (c), you can prove the result by showing that any matrix of $SL_n$ is a product of matrices of the form $I_n+\lambda E_{ij}$ with $i\neq j$, and create a path to the identity by shrinking the $\lambda$ to $0$.
Hint: for (d), if $n$ is nilpotent, then so is $tn$, for $t\in[0,1]$: this is a continuous path of nilpotent matrices that stops at $0$, thus...
Comment: part (d) is ok but (c) I dont get that.I am reading metric spaces.Is there any book that discusses $M(n,\mathbb R)$ in detail@Olivier
Comment: part (c) is elementary matrix manipulations. It is a theorem that these types of matrices generate $SL_n$.
Comment: Ok but how are getting these so easily in fact I have been pondering over it for such a long time .Any suggestion of books
Comment: I learnt all of this in french books... Do you read french?
Comment: No sir, no English books yet
Comment: This is discussed in http://en.wikipedia.org/wiki/Special_linear_group#Generators_and_relations, but no details are given unfortunately.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18310/discussion-between-learnmore-and-olivier-begassat).

Connected spaces of $M(n,\mathbb R)$


Neo4j,How to return nodes and relations where pathes between two nodes more than one

Question: Create sample data, Actually data has 50 thousand Persons, 10 thousand Company.
CREATE(p1:Person{name:"p1"})
CREATE(p2:Person{name:"p2"})
CREATE(p3:Person{name:"p3"})
CREATE(c1:Company{name:"c1"})
CREATE(c2:Company{name:"c2"})
CREATE (p1)-[:STAFF]->(c1)
CREATE (p1)-[:STAFF]->(c2)
CREATE (p2)-[:STAFF]->(c1)
CREATE (p2)-[:STAFF]->(c2)
CREATE (p3)-[:STAFF]->(c1)

I want to find nodes and relations where paths between two person nodes more than one, in this example(p1,p2).
I try to query with example, but it is very slowly.
Answer: I would try this:
MATCH path=(p1:Person)-[:STAFF]->(c:Company)<-[:STAFF]-(p2:Person)
WHERE id(p1) > id(p2)
WITH p1,p2, COLLECT(path) AS paths
WHERE SIZE(paths) > 1
RETURN paths

Neo4j，How to return nodes and relations where pathes between two nodes more than one


Inner product space related to pythagorean theorem.

Question:
So I understand that the an inner product space basically uses pythagorean theorem because it is similar to a distance formula. I'm still having trouble with this proof. I am a bit confused about where to start. It could be notation that is throwing me off, so any breakdown would be great.
Comment: Use the fact that $\|v\|^2$ is defined as $\langle v,v\rangle$. Use also the fact that, by definition, $u$ and $v$ are orthogonal iff $\langle u,v\rangle = 0$. Start on the LHS and arrive, by a series of equalities, at the RHS.
Comment: you can select an answer as correct answer at the left side of the answer, remember do this for help the comunity.
Answer: Let be $v_1,\ldots,v_n$ an orthogonal set, then:
$$\|\displaystyle\sum_{i=1}^{n}a_iv_i\|^2=\langle \displaystyle\sum_{i=1}^{n}a_iv_i;\displaystyle\sum_{j=1}^{n}a_jv_j\ \rangle = \sum_{i,j=1}^{n}\langle a_iv_i;a_j,v_j\rangle $$ Here almost all products will be zero because $v_i$ is orthogonal to $v_j$ iff $i\neq j$ then the non-zero terms are these where $i=j$:
$$=\displaystyle\sum_{i=1}^{n}\langle a_iv_i;a_i,v_i\rangle=\displaystyle\sum_{i=1}^{n}|a_i|^2\langle v_i,v_i\rangle=\sum_{i=1}^{n}|a_i|^2\|v_i\|^2$$


como fazer um git clone sem o repositório .git?

Question: Tenho um repositório onde guardo meus arquivos de front-end. Queria saber uma forma de fazer um "git clone" desse repo para dentro de uma pasta de um projeto (ex: um tema do wordpress), de forma que só venha os arquivos, sem a pasta ".git" (que cuidaria do versionamento). E não crie uma pasta nova para o repo, mas que o arquivos venha para meu diretório raiz do projeto(vulgo meu working directory).
Na verdade estou me esforçando pra entender o git com abordagem mais "Plumbing Commands", mas na documetação oficial é muito hard/técnico de entender. Nos tutoriais da internet é tudo muito engessado e voltado para o simples. Estou em busca de um meio termo para q eu possa avançar.
Tipo, no meu repo eu tenho meu projeto sass e minhas tarefas padrões com gulp (que comportam perfeitamente minha demanda de projetos para internet) e esse repo tem a intenção de evoluir sempre. Mas a ideia é chegar num comando git onde eu possa baixar os arquivos desse repo para um projeto novo para q eu agilize "o ambiente de desenvolvimento".
Comment: Vc quer por linha de comando? Pq não vai direto no site GitHub e faz o download do zip e coloca na pasta que vc quer? Manda exibir os arquivos ocultos e apaga a pasta .git se ela estiver lá.... As vezes isso pode te ajudar https://pt.stackoverflow.com/questions/356852/visual-studio-git-5000-changes/356914#356914
Comment: Por linha de comando, pois a intenção é q eu consiga automatizar com bash. acho que fiz uma pergunta bem precisa sobre isso.
Comment: @user7069 se você for clonar, você necessitará do `.git`. O mais padrão seria você fazer um build e deixá-lo acessível para fazer o download. Isso fica mais explícito quando você está fazendo algo que precise passar por compilação antes de ir pra produção, mas também pode ser feito em PHP.
Answer: Você não consegue isso com o clone, mas é possível com o archive ou checkout-index:
git archive master | tar -x -C /somewhere/else

O git archive vai criar um pacote com o código comitado na sua branch e em seguida você pode extraí-lo com o tar.
git checkout-index -a -f --prefix=/destination/path/

O git checkout-index com a flag -a copia todos os arquivos no index e o -f forçar sobrescrever os arquivos no destino caso eles já existam.
No --prefix você define o caminho que deseja copiar seus arquivo. Atenção para a última /, se você esquece-la seu arquivo irá para um destino errado com um prefixo chamado path.
Referencia: https://stackoverflow.com/questions/160608/do-a-git-export-like-svn-export/160719


How can I access the user email associated to an object that implements the \Drupal\user\UserInterface interface?

Question: If a method of a class returns an object that implements the \Drupal\user\UserInterface interface, how can I access the user email associated to that object?
Answer: The object you have is a user entity object.
The user entity class has a getEmail() method, that you can use to get the user's email.
For more info look here, User::getEmail().
Answer: Since the \Drupal\user\UserInterface interface extends the \Drupal\Core\Session\AccountInterface interface, which makes available the getEmail() method, you can use it to get the email associated with the returned object.
For example, if you stored the returned object in $account, you can access its email address with $account->getEmail().
Do not confuse \Drupal\Core\Session\AccountInterface::getEmail() with \Drupal\user\UserInterface::getInitialEmail(). The latter returns the email address used when the account was registered, which can be later changed. To get the current email address, you need to call \Drupal\Core\Session\AccountInterface::getEmail().


How to find the max of $|e^x-1-\frac 32x|$ on $[0, 1]$ more rigorously?

Question: I have to find
$$\max_{x \in [0, 1]}\left|e^x-1-\frac 32x\right| = \max_{x \in [0, 1]} f(x) $$
To do this, I of course have to check the endpoints of the interval, the points where the derivative is zero, and the point(s) where the derivative is undefined.
From the graph, it is clear what to do.

I have to find where the derivative of $-\left( e^x-1-\dfrac{3}{2}x \right) $ is zero, and then check it against $f(1)$. But how can I do this completely rigorously?
Thank you very much.
Comment: What's mean *more rigorously*?
Comment: @Azif00 For example, I assumed that the critical point occured where the graph is below the $x$ axis, so I looked at the derivative of $-(e^x-1-\frac 32x)$, rather than the derivative of $e^x-1-\frac 32x$. But I justified this based on the graph, not on rigor. Also, it is "obvious" that where the derivative is undefined, $f$ will be zero, but I did not prove this (though I think I can prove this if I think about it, I will try it)
Answer: $$f(x)=|g(x)|, g(x)=e^x-1-3x/2, x\in [0,1] \implies g'(x)=e^x-3/2$$ $$ \implies x_0=\ln(3/2)=0.4050...<1.$$
So $f(x)$ has a maximunm at $x_0<1$ and $f(x_0)=1/2-3\ln(3/2)=0.1081$.., but the value od $f(1)=e-1-3/2=0.2182...$ So this is the global maximum  of $f(x)$. However, there is a local max. at $x=x_0$ of value 0.1081....
See  $f(x)$ in the Fig.below
Answer: If by "rigorously" you mean without using a graphing calculator to graph it then one thing you can do is prove that the function $g(x)=e^x-1-\frac{3}{2}x$ has the properties illustrated by the graph which allow you to conclude that you only need to check the endpoints and the point where the derivative is zero. To be more specific, one way you could do this would be to:

Prove that if $x<\ln(1.5)$ then $g'(x)<0$ (so g strictly decreasing) and if $x>\ln(1.5)$ then $g'(x)>0$ (so g strictly increasing).
Prove that $g(\ln(1.5)) < 0$ (might help to use fact that $e<2.72$), $g(0)=0$ and $g(1)>0$ (might help to use fact that $2.7<e$).
From $g(x)$ continuous, 1., and 2. conclude that $g(x)$ has exactly two zeros call them $x_0$ and $x_1$ such that $x_0=0$ and $\ln(1.5) < x_1 < 1$.
From the preceding you can conclude that if $x < x_0$ then $g(x) > 0$, if $x_0 < x < x_1$ then $g(x) < 0$ and if $x_1 < x$ then $g(x) > 0$. Therefore, since $f(x) = |g(x)|$,
$$f(x) = \begin{cases} g(x) & \impliedby x \in (-\infty, x_0] \cup [x_1, \infty) \\
-g(x) & \impliedby x \in [x_0, x_1] \end{cases}.$$
Furthermore, $x_0$ and $x_1$ are all of the points at which the derivative of $f$ are undefined, but you also know $f(x_0) = f(x_1) = 0$ and there is at least one $x \in [0, 1]$ such that $f(x) > 0$ and so neither of $x_0$ or $x_1$ can be points at which the maximum occurs.
From 1. and 2. you know that $g$ has a global minimum at $\ln(1.5)$ and so $-g$ has a global maximum at $\ln(1.5)$. Therefore, from 4., you know that on the interval $[x_0, x_1]$ the largest value of $f$ occurs at $\ln(1.5)$. You also know that $f(x_1)=0$ and $f$ is increasing on $[x_1, \infty]$ (since f=g on that interval), and so the maximum $f$ can achieve on $[x_1, 1]$ occurs at $1$.
Make your original conclusion that you only need to check $f(\ln(1.5))$ against $f(1)$.
Comment: Thanks! ${}{}{}$


Python Discord Bot Embed Userinformation

Question: i am currently programming a discord bot with Python and i want him to show an embed with all the user informations ( Name, since when he is using discord, since when he is on the server).
My problem is that he is only working when you use his name (!userinfo "Bot") but not when you use an actual user. Please help me.
if message.content.startswith('!userinfo'):
        args = message.content.split(' ')
        if len(args) == 2:
            member: Member = discord.utils.find(lambda m: args[1] in client.user.name, message.guild.members)
            if member:
                embed = discord.Embed(title='Userinfo for {}'.format(member.name),
                                      description='This if the Userinfo from  {}'.format(member.mention),
                                      color=0x22a7f0)
                embed.add_field(name='Joined server', value=member.joined_at.strftime('%d/%m/%Y, %H:%M:%S'),
                                inline=True)
                embed.add_field(name='Joined Discord', value=member.created_at.strftime('%d/%m/%Y, %H:%M:%S'),
                                inline=True)
                rollen = ''
                for role in member.roles:
                    if not role.is_default():
                        rollen += '{} \r\n'.format(role.mention)
                if rollen:
                    embed.add_field(name='Roles', value=rollen, inline=True)
                embed.set_thumbnail(url=member.avatar_url)
                embed.set_footer(text='I am an`enter code here` EmbedFooter.')
                mess = await message.channel.send(embed=embed)

Answer: What you are trying to accomplish can be done in a much simpler way.
If you just use discord.ext.commands you can access information directly from the context, instead of doing a lot of string processing:
from discord.ext import commands

bot = commands.Bot("!")

@bot.command()
async def userinfo(ctx):
    member = ctx.author
    # then you build your embed with the user info extracted from member


Drupal7 REST webservices API KEY vs OAUTH two-legged authentication for clientside JS consumer library

Question: I'm working on an Drupal7 API, using REST services, and consumer JS library (no server code). I'm not trying to authenticate/authorize the end-users, only to identify and allow access to the 'application' using an API KEY.
The goal is to have the 'developers' create an account, request an API KEY, register domains for this api key, and use this key to 'identify' their application to the Drupal7 API. This is pretty much the same API-KEY model that Google Maps is using in v2.
I've looked into OAUTH 2legged approach, which would have been great if my client library was running on the server side, so the secret key wouldn't be exposed, but in our case, the library is JS only (client side), and it doesn't seem a good idea to expose the secret key.
Am i missing something about OAUTH that will allow this? Any pointers will be welcome.
Thanks!
Answer: The solution came from Kyle Browning (thanks!) - the current dev version of services 7.x-3.x-dev has support for the following OAuth authentications methods:

None, OAuth authentication will be disabled by default
Unsigned with consumer key
Consumer Key, also known as 2-legged OAuth
Consumer key and access token, also known as 3-legged OAuth

With this version I ended up using the consumer key for the client libraries as identification token for applications.


Kotlin coroutines multithread dispatcher and thread-safety for local variables

Question: Let's consider this simple code with coroutines
import kotlinx.coroutines.*
import java.util.concurrent.Executors

fun main() {
    runBlocking {
        launch (Executors.newFixedThreadPool(10).asCoroutineDispatcher()) {
            var x = 0
            val threads = mutableSetOf<Thread>()
            for (i in 0 until 100000) {
                x++
                threads.add(Thread.currentThread())
                yield()
            }
            println("Result: $x")
            println("Threads: $threads")
        }
    }
}

As far as I understand this is quite legit coroutines code and it actually produces expected results:
Result: 100000
Threads: [Thread[pool-1-thread-1,5,main], Thread[pool-1-thread-2,5,main], Thread[pool-1-thread-3,5,main], Thread[pool-1-thread-4,5,main], Thread[pool-1-thread-5,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-9,5,main], Thread[pool-1-thread-10,5,main]]

The question is what makes these modifications of local variables thread-safe (or is it thread-safe?). I understand that this loop is actually executed sequentially but it can change the running thread on every iteration. The changes done from thread in first iteration still should be visible to the thread that picked up this loop on second iteration. Which code does guarantee this visibility? I tried to decompile this code to Java and dig around coroutines implementation with debugger but did not find a clue.
Comment: Yes, this code is legitimate, but only because you run a single coroutine here. `x` and `threads` variables aren't thread-safe, but they aren't accessed concurrently, so this is fine. I'm not sure what do you mean about the visibility of changes. As you noted, this code runs sequentially, so why changes would be not visible?
Comment: Ahh, you probably meant that `x` is not volatile?
Comment: By visibility I mean the fact of the writes to variable from one thread being visible to other thread, actually a concept used by Java Memory Model. Yes, in my opinion `x` being volatile would solve the problem related to `x` if the problem existed at all (I still assume that there is no problem with this code but it kinda contradicts my understanding of concurrency).
Comment: It seems to be exactly this question: https://github.com/Kotlin/kotlinx.coroutines/issues/1363

The final answer is still a bit unclear in my opinion, I don't know for sure. But it does look like within a coroutine, the state is always "up to date", regardless of which thread modified it last. So in a sense it kinda behaves like a volatile. But I'd also be interested in an actual accurate answer for this, as to how and why this works.
Comment: ^ I meant not exactly the initial question on Github (which talks about 2 coroutines), but the discussion below which mentions the single-coroutine case
Comment: https://proandroiddev.com/what-is-concurrent-access-to-mutable-state-f386e5cb8292
Comment: @IR42 This article does not really answer the question. Nobody here is saying these modifications are concurrent. They are sequential, but even then there still should be a problem with CPU caches. For some reasons such problem does not occur. Of course it makes perfect sense that Kotlin solves this automatically - otherwise it would be really hard to develop with coroutines. We just don't know how it does it exactly.
Answer: Your question is completely analogous to the realization that the OS can suspend a thread at any point in its execution and reschedule it to another CPU core.  That works not because the code in question is "multicore-safe", but because it is a guarantee of the environment that a single thread behaves according to its program-order semantics.
Kotlin's coroutine execution environment likewise guarantees the safety of your sequential code. You are supposed to program to this guarantee without any worry about how it is maintained.
If you want to descend into the details of "how" out of curiosity, the answer becomes "it depends". Every coroutine dispatcher can choose its own mechanism to achieve it.
As an instructive example, we can focus on the specific dispatcher you use in your posted code: JDK's fixedThreadPoolExecutor. You can submit arbitrary tasks to this executor, and it will execute each one of them on a single (arbitrary) thread, but many tasks submitted together will execute in parallel on different threads.
Furthermore, the executor service provides the guarantee that the code leading up to executor.execute(task) happens-before the code within the task, and the code within the task happens-before another thread's observing its completion (future.get(), future.isCompleted(), getting an event from the associated CompletionService).
Kotlin's coroutine dispatcher drives the coroutine through its lifecycle of suspension and resumption by relying on these primitives from the executor service, and thus you get the "sequential execution" guarantee for the entire coroutine. A single task submitted to the executor ends whenever the coroutine suspends, and the dispatcher submits a new task when the coroutine is ready to resume (when the user code calls continuation.resume(result)).


Prove that $IL,JK$ and angle bisector of angle $BCD$ are concurrent

Question: Given a convex quadrilateral $ABCD$. In $\Delta ABC$, $I$ is the incentre and $J$ is the excentre opposite to vertex $A$. Similarly, $K$ is the incentre and $L$ is the excentre opposite to vertex $A$ of $\Delta ACD$. Prove that the three lines $IL,JK$ and the angle bisector of angle $BCD$ are concurrent.
I tried assuming some angles in one if the triangle. Used some trigonometry, but the problem just got nasty. I don't think pure geometry would do it. The problem looks good. If possible, please solve using trigonometry and/or algebraic geometry. Thanks.
Comment: Anyway, a good general technique for solving such concurrency problems is to use trilinear coordinates: to prove a concurrency boils down to proving that a determinant is zero, and computations are not that difficult.
Comment: The claim looks all right to me.  The result holds for a cycluc quadrilateral. In a square, the concurrency point is $A$.
Comment: Also, the computation is difficult. Writing, the coordinates of the incentre and the excentre and then finding the line and the equation of the angle bisector and then substituting them in the determinant. Looks like a tough job to me. If it doesn't look to you, please post the solution.
Answer: With somewhat-altered labels, we have this figure for $\square ABOC$ with incenters $P$ and $Q$ (and inradii $p$ and $q$) and excenters $R$ and $S$ (and exradii $r$ and $s$).

We embed the figure in the coordinate plane with $O$ at the origin, and:
$$A = a\;(1,0) \qquad B = b\;(\cos 2\beta,\sin 2\beta) \qquad C = c\;(\cos 2\gamma,-\sin 2\gamma)$$
$$\begin{align}
P &= \frac{p}{\sin\beta}(\phantom{-}\cos\beta,\sin\beta) \qquad
Q = \frac{q}{\sin\gamma}(\phantom{-}\cos\gamma,-\sin\gamma) \\[4pt]
R &= \frac{r}{\cos\beta}(-\sin\beta,\cos\beta) \qquad
S = \frac{s}{\cos\gamma}(-\sin\gamma,-\cos\gamma)
\end{align}$$
In/exradius formulas are known, and we can compute, for instance,
$$\frac{p}{\sin\beta} = \frac{|\triangle OAB|}{\sin\beta\;(a+b+e)/2} = \frac{a b \sin 2\beta}{\sin\beta\;(a+b+e)} = \frac{2 a b\cos\beta}{a+b+e}$$
Likewise,
$$\frac{q}{\sin\gamma} = \frac{2 a c\cos\gamma}{a+c+f} \qquad
\frac{r}{\cos\beta} = \frac{2 a b \sin\beta}{a-b+e} \qquad
\frac{s}{\cos\gamma} = \frac{2 a c \sin\gamma}{a-c+f}$$
From here, brute-force symbol manipulation (and, very likely, a slick geometric argument that has eluded me) determines the intersection point, $K$, of lines $\overleftrightarrow{PS}$ and $\overleftrightarrow{QR}$:
$$K = \frac{a b c}{a b + a c + c e + b f }\; \left(\;\cos 2 \beta + \cos 2 \gamma\;,\;\sin 2\beta - \sin 2\gamma\;\right) = \frac{a\;( c B + b C )}{a b + a c + c e + b f}$$
Since $c B + b C$ is a direction vector for the bisector of $\angle BOC$, we have that $K$ is on this bisector and is therefore the sought-after point of concurrency. $\square$

Edit. We can reduce some symbol manipulation, and get an interesting general concurrence criterion, by deferring the radius calculations. For instance, with
$$\begin{align}
P = p^\prime\;(\phantom{-}\cos\beta,\sin\beta) &\qquad Q = q^\prime \;(\phantom{-}\cos\gamma,-\sin\gamma) \\
R = r^\prime\;(-\sin\beta,\cos\beta) &\qquad S = s^\prime\;(-\sin\gamma,-\cos\gamma)
\end{align}$$
(where $p^\prime$, etc, are distances from $O$ along various angle bisectors, although not necessarily related to any in/exradii) we find that
$$K = \frac{\cos(\beta+\gamma)}{p^\prime r^\prime + q^\prime s^\prime + (p^\prime q^\prime + r^\prime s^\prime ) \sin(\beta + \gamma)}\;\left(\;q^\prime r^\prime (P-S) + p^\prime s^\prime (Q - R) \;\right)$$
Ignoring the multiplied scalar, we force $K$ onto the bisector of $\angle BOC$ by substituting its components into the equation $y = x\,\tan(\beta-\gamma)$. The result is this relation:
$$q^\prime r^\prime s^\prime \cos\beta - p^\prime r^\prime s^\prime \cos\gamma - p^\prime q^\prime s^\prime \sin\beta + p^\prime q^\prime r^\prime \sin\gamma = 0$$
Or, better:

$$\frac{\cos\beta}{p^\prime} - \frac{\sin\beta}{r^\prime} = \frac{\cos\gamma}{q^\prime} - \frac{\sin\gamma}{s^\prime} \tag{$\star$}$$

(This seems like something that should have an elegant geometric derivation.) Substituting $p^\prime = 2 a b \cos\beta/(a+b+e)$, etc, causes each side of $(\star)$ to reduce to $1/a$.
Comment: Nice. I just didn't get the last step. From the point $K$, how did you get to your RHS. Also, what is it you have written on the RHS?(it is new to me-$cB+bC$?)
Comment: @You-know-me: I'm (ab)using some vector shorthand. If $B = (x_1,y_1)$ and $C = (x_2,y_2)$, then $$c B + b C = c(x_1,y_1) + b(x_2,y_2) = (c x_1 + b x_2, c y_1 + b y_2)$$ Likewise, the "fraction" is just the vector $(cB+bC)$ multiplied by the scalar $a/(ab+ac+ce+bf)$. The last step is a matter of "noticing" that $K$ is a convenient combination of $B$ and $C$. That $cB+bC$ is the direction vector of the angle bisector follows from the fact that vector $B$ has length $b$, and $C$ has length $c$, so $cB$ and $bC$ have equal length $bc$; consequently $cB+bC$ is the diagonal of a rhombus.


uninitialized constant Active Scaffold rails 2.3.5

Question: I update my rails application 2.0.2 to 2.3.5. I use active scaffold for the administration part.
I change nothing in my code but a problem is coming with the update.
I have a controller 'admin/user_controller' to manage users.
Here is the code of the controller:
    class Admin::UserController < ApplicationController

  layout 'admin'

  active_scaffold :user do |config|
    config.columns.exclude :content, :historique_content, :user_has_objet, :user_has_arme, :user_has_entrainement, :user_has_mission, :mp, :pvp, :user_salt, :tchat, :notoriete_by_pvp, :invitation
    config.list.columns = [:user_login, :user_niveau, :user_mail, :user_bloc, :user_valide, :group_id] #:user_description, :race, :group, :user_lastvisited, :user_nextaction, :user_combats_gagner, :user_combats_perdu, :user_combats_nul, :user_password, :user_salt, :user_combats, :user_experience, :user_mana, :user_vie
    config.create.link.page = true
    config.update.link.page = true
    config.create.columns.add :password, :password_confirmation
    config.update.columns.add :password, :password_confirmation
    config.create.columns.exclude :user_password, :user_salt
    config.update.columns.exclude :user_password, :user_salt
    config.list.sorting = {:user_login => 'ASC'}
    config.subform.columns = []
  end
end

This code hasn't change with the update, but when I go in this page, I got this error:
    uninitialized constant Users

/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:443:in `load_missing_constant'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:80:in `const_missing'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:92:in `const_missing'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:361:in `constantize'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:360:in `each'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:360:in `constantize'
/Users/Kiva/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/inflections.rb:162:in `constantize'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb:28:in `reverse_matches_for'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb:24:in `each'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb:24:in `reverse_matches_for'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb:11:in `reverse'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/column.rb:117:in `autolink?'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold.rb:107:in `links_for_associations'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/columns.rb:62:in `each'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/columns.rb:62:in `each'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold.rb:106:in `links_for_associations'
/Users/Kiva/Documents/Projet-rpg/jeu/vendor/plugins/active_scaffold/lib/active_scaffold.rb:59:in `active_scaffold'
/Users/Kiva/Documents/Projet-rpg/jeu/app/controllers/admin/user_controller.rb:11

I search since 2 days but I don't find the problem, can you help me please.
Answer: the naming convention in your application seems buggy
it should be:
class Admin::UsersController < ApplicationController

not UserController as it is. maybe it won't fix your problem, but it worth a try!
Answer: Starting with Rails 2.3.x you have to install the Render Component plugin:
./script/plugin install git://github.com/ewildgoose/render_component.git -r rails-2.3
See instructions here: https://github.com/activescaffold/active_scaffold/wiki/getting-started
Answer: It seems to be a problem with the way the Model is defined. I had the very same issue when accessing tables in the database with a rake backup task. The problem was that I had a table defined in the database through "belongs_to". I didn't think I needed a model for that table but constantize kept failing. Introducing the model fixed the problem.
Table : users_clients
Model : UsersClient


The difference $\log(2)-\sum_{n=1}^{100}\frac{1}{2^n n}$ is

Question: The difference $$\log(2)-\sum_{n=1}^{100}\frac{1}{2^n n}$$ is
(1) less than $0$
(2) greater than $1$
(3) less than  $\frac{1}{2^{100}101}$
(4) greater than $\frac{1}{2^{100}101}$
My Attempt:
I know $$\log(2)=1-1/2+1/3-1/4+\dots\tag{1}$$
Let us call $S=\sum_{n=1}^{100}\frac{1}{2^n n}$ so $S=\frac{1}{2}+\frac{1}{8}+\frac{1}{24}$
How should I move from here?
Comment: $$ \log{2}=\sum_{n=1}^{\infty}\frac{1}{2^n\,n} $$
Comment: [Related](https://math.stackexchange.com/questions/2267376/series-that-sum-to-log2)
Comment: Just looking at the choices it must be 3.  If 1 is true so is 3 and if 2 is true so is 4, so neither 1 nor 2 is the unique answer.  The fact that 3 is so small makes it the surprising choice, which must be right.
Answer: Use the fact that\begin{align}\log(2)&=-\log\left(\frac12\right)\\&=\frac12+\frac1{2\times2^2}+\frac1{3\times2^3}+\cdots\\&=\sum_{n=1}^\infty\frac1{n2^n}.\end{align}
Answer: You could also determine the value of the summa by using the polylogarithm functions:
$\sum\limits_{n=1}^{\infty}\frac{1}{2^n\,n}=\sum\limits_{n=1}^{\infty}\frac{{\big(\frac{1}{2}}\big)^n}{n}=Li_1(\frac{1}{2})=\ln2$


Selenium Crashing: Chrome automation extension has crashed

Question: I am using Selenium web drivers, and today, for no apparant reason I started getting an error with the message"Chrome Automation Extension has crashed.  Click this balloon to reload the extension".
The only thing I can think of is I added an extension for testing XPath to Chrome today.  But it was working fine for a while after I added that.
Could it be some Chrome security issue?
Comment: I'm having the same issue and I have no idea what's going on.
Comment: Add please info about which version of Selenium Webdriver you use? Also chromedrive version and chrome version.
I have the same problems.
My chromedriver is 2.23 version, selenium webdriver v 3 (beta) and chrome v.52
Answer: I had the same problem, I could resolve it as the following:
1.Don't run Chrome as Admin.
2.Don't run your selenium App as Admin.
Comment: Thanks! This has made a trick. If you run it using console command - start console without admin rights.
Comment: How to do it if I use TeamCity to run tests? I created not admin account to start teamcity agent service but it didn't solve the problem.
Comment: Thanks. Instead of using Jupiter from Chrome using Spyder. It worked..
Comment: The same applies to webdriver.io. You shouldn't be running your VS Code in admin mode.
Answer: Ok, so you are serious about the admin part as a solution to the problem?
Why not follow the advices from Google?
http://chromedriver.chromium.org/help/chrome-doesn-t-start

Passing '--no-sandbox' flag when creating your WebDriver session.
  Special test environments sometimes cause Chrome to crash when the
  sandbox is enabled.

So I ended up doing as they adviced and can run things as admin.
Guess it's a way forward for me now and hopefully it's a valid solution for others too.
var options = new ChromeOptions();
options.AddArgument("--no-sandbox");
browser = new ChromeDriver(options);

Comment: This fixed the problem for me, caused by running from a windows junction (mklink /D /J)
Answer: My problem was that my Windows temp folder was on a drive (D) that is not my primary Windows drive (C) and that I had also mapped that drive to a sub-folder of C.

I went into Disk Management
Right-clicked my secondary drive
Selected "Change drive letter and paths"
Removed the entry where I had mounted the drive as a folder
Opened my Environment Settings
Changed my TEMP and TMP entries from "C:\Temp" (the path where my 2nd drive was mounted) to "D:\"
Restarted my computer

Note that step #4 was important. The plugin would still crash if this was present.
Comment: I ran into the same problem when executing Chrome from a disk which was mapped as a whole to a directory on the C:\ volume. A situation the Chrome sandbox seems to dislike. I added the --no-sandbox argument and everything worked.
Comment: I had this problem when running from a junction in windows (mklink /D /J)
Answer: I have the same issue but my situation is I tried to open visual studio with different profile.When i am opening visual studio with default profile its working fine.So i guess its profile issue.
Comment: When you open any solution in visual studio its uses default profile (your windows username and password).But i have to open visual studio with different profile cause of vpn connectivity issue.Now i am not able to launch chrome driver. I tried using chrome default profile but it launch the browser and return null in webdriver object.
Comment: i am facing same issue @Neeraj ..did you find any solution.?
Answer: I resolve my problem when I start Git Bash without admin rights.
Answer: I had the same issue, using Python with Selenium
options = webdriver.ChromeOptions();
options.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=options,executable_path="../drivers/chromedriver.exe")

The above piece of code resolved my issue
Answer: We faced the same problem. For work around we are using Firefox now. You just need to add Selenium.Firefox.WebDriver by jbaranda NuGet package
Answer: I had the same problem. In my case it was related to the Windows account I use to log in to Windows, which is account in the Administrators group. However, it was not desirable to change the account type.
To solve this I created a new local account under the control panel (of type 'power user') and used that account to run Chrome and it worked fine.
Answer: For Python this solved my problem use:
from selenium import webdriver

# start the browser
options = webdriver.ChromeOptions()
# options.add_argument("--headless")
options.add_argument("--no-sandbox")
# options.add_argument("--disable-dev-shm-usage")
# options.add_argument("--disable-gpu")
# options.add_argument("--window-size=1920,1080")

driver = webdriver.Chrome(options=options)
driver.get("https://www.google.com")

print(driver.title)
print(driver.current_url)

#driver.quit() # Uncoment to keep chromedriver open.

Answer: In my case I have to run it under Admin, I fixed it by updating .NET framework. You can update this in Windows Update. I updated every item that is related to .NET framework, including crucial ones and optional ones.
Here are two items I updated:
2018-01 Preview of Quality Rollup for .NET framework (KB4057272)
.NET framework 4.7.1 (KB4033369)
Edit: I run Win 10 with chromedriver 2.34 and Chrome v64.0.3282.140(64-bit)
Comment: I don't think this answers the original posted question at all.


Rewrite all folder and files with htaccess

Question: I want all files and folder links change
I use below code for this problem, but not work
RewriteEngine on
RewriteRule ^([^/]+)(\.zip|\.pdf|\.jpg|\.png)$ index.php?file=$1$2 [NC,L]

I want change actual url to another url automatic
upload/1.png => index.php?file=/upload/1.png
upload/in/2.png => index.php?file=/upload/in/1.png
Comment: `index.php` I edited my question. sorry
Comment: What is not working? Provide details.
Comment: @anubhava I want if user open my directory, he see new url not actual url
Comment: You need to change the URLs in your application. Don't redirect these requests in `.htaccess` (that's only for SEO purposes, if the URLs have already been indexed / linked to).
Answer: You may use these rules in your site root .htaccess:
RewriteEngine On

RewriteCond %{THE_REQUEST} /index\.php\?file=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=301,L,NE]

RewriteRule ^[\w-]+\.(?:zip|pdf|jpe?g|png)$ index.php?file=$0 [L,QSA,NC]

Comment: I need to be offline for few hours for some work. But you've misunderstood it. Directory listing must not be displayed in browser for security reasons Just have a web page with href links as `/1.jpg`, `/image.png` etc and this rule will forward it to `/index.php?file=1.jpg`
Comment: thank you, but not work me: please check this image and url of 1.png : http://tinyimg.io/i/T2rgjGX.png ( left bottom )


UILabel in segue.destination - Unexpectedly found nil while implicitly unwrapping an Optional value

Question: I've got a ViewController class, and two IBOutlet UILablels that I created from storyboard.
Here is the code of the class:
import UIKit

class AnnouncementViewController: UIViewController {

    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var infoTV: UITextView!
    var mail: String = ""
    var url: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func set(_ announcement: [String: String]) {

        print(announcement)

        nameLabel.text = announcement["name"]    // here goes the error
        self.infoTV.text = announcement["info"]
        self.mail = announcement["email"]!
        self.url = announcement["url"]!

    }

}

And here is the code from another class (TableViewController) I've got:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        super.prepare(for: segue, sender: sender)
        guard segue.identifier == "announcementSegue" else { return }

        let indexPath = tableView.indexPathForSelectedRow!
        let announcement = tasks[indexPath.row]

        let destinationVC = segue.destination as! AnnouncementViewController

        destinationVC.set(announcement)

}

The error I get is:
Unexpectedly found nil while implicitly unwrapping an Optional value
So, nameLabel is nil. I cannot get why it is.
Comment: > Tip : Think of a model struct/class instead of using a dictionary
Answer: Solution 1 call loadViewIfNeeded()
let destinationVC = segue.destination as! AnnouncementViewController
destinationVC.view.loadViewIfNeeded()
destinationVC.set(announcement)

Solution 2
let destinationVC = segue.destination as! AnnouncementViewController
destinationVC.ann = announcement

var ann = [String: String]()

override func viewDidLoad() {
    super.viewDidLoad()
    set(ann)
}

func set(_ announcement: [String: String]) {
    print(announcement)

    nameLabel.text = announcement["name"]    // no error
    self.infoTV.text = announcement["info"]
    self.mail = announcement["email"]!
    self.url = announcement["url"]!

}

Comment: @ВладимирКовальчук it does exist inside viewDidLoad
Comment: view may doesn't exist in viewDidLoad,
call set(ann) in viewWillAppears
Comment: Thank you, I used solution 2, it works now :)


How do I mitigate memory leaks when recursively calling a function inside a Future[T]?

Question: This question is inspired by some comments in an earlier Stackoverflow article on the same topic and also motivated by some code I'm writing as well. Given the example contained therein, I'm somewhat convinced that this pattern is tail recursive. If this is the case, how do I mitigate the memory leak posed by accumulating futures whose underlying threads never join the ForkJoinPool from which they were spawned?
import com.ning.http.client.AsyncHttpClientConfig.Builder
import play.api.libs.iteratee.Iteratee
import play.api.libs.iteratee.Execution.Implicits.defaultExecutionContext
import play.api.libs.ws.ning.NingWSClient
import scala.util.{Success,Failure}

object Client {
 val client = new NingWSClient(new Builder().build())
 def print = Iteratee.foreach { chunk: Array[Byte] => println(new String(chunk)) }

 def main(args: Array[String]) {
   connect()
   def connect(): Unit = {
     val consumer = client.url("http://streaming.resource.com")
     consumer.get(_ => print).onComplete {
       case Success(s) => println("Success")
       case Failure(f) => println("Recursive retry"); connect()
     }
   }
 }
}

In the example I've shared, the get[A](...) method returns a Future[Iteratee[Array[Byte],A]]. The author of the above article I've included remarks that "scala.concurrent Futures don't get merged" once they return but that Twitter's futures some how manage this. I'm using the PlayFramework implementation, however, which uses futures provided by the standard Scala 2.1X library.
Do any of you have evidence that support or dismiss these claims? Does my code pose a memory leak?
Answer: The issue you linked (was in a comment, not the question or answer) refers to a memory leak that occurred with flatMap. Your code doesn't use flatMap, so I don't think you wouldn't run into any problems, as you're just conditionally executing another Future via a callback, and not caring at all about the previous.
Either way, it's kind of irrelevant because this issue was fixed in 2.10.3. See issue SI-7336 and the pull request that fixes it for more info.
Answer: While your call does not suffer from the stack overflow dangers of regular recursive calls, it is not tail recursive either. The exit statement of connect() is onComplete which simply lets connect() exit and release its stack. The "recursive" call to connect() actually happens as a continuation when the future completes and therefore is not an actual recursion.
Caveat: if get actually always returned a Future.successful (as it might in a unit test), chances are that get could suffer from a stack overflow, since the Success case would like trigger immediately and before onComplete exited. I haven't tested this and it might be something that may or may not happen depending on the ExecutionContext's properties.