How to use the Vanilla JS version of Drupal Once

Question: Once again i am having a problem with the JS called more than once.
the code here transform the select/options of the exposed filters to ul/li.
The problem is that the

console.log("enter init")

is called many times , when i would need it to be called only once on load :
(function($, Drupal) {
  /**
   *
   * Retourne la valeur correspondante du localstorage
   *
   * @param {string} key
   * @return {string}
   */
  function getFromLocalStorage(key) {
    if (localStorage.getItem(key) === null) {
      localStorage.setItem(key, "All");
    }
    return localStorage.getItem(key);
  }

  const variables = {
    selectElement /** @type={HTMLElement} */: document.querySelector(
      ".views-exposed-form .form-select"
    ),
    optionElements /** @type={HTMLCollection} */: document.querySelector(
      ".views-exposed-form .form-select"
    ).children,
    inputElement /** @type={HTMLElement} */: document.querySelector(
      ".views-exposed-form .form-submit"
    ),
    selectedFilter: getFromLocalStorage("data-value"),
    ul: document.createElement("ul")
  };

  /**
   * Stocke le li clické
   *
   * @param {Event } e
   * @return {void}
   */
  function setToLocalStorageOnClick(e) {
    variables.selectedFilter = e.target.dataset.value;
    localStorage.setItem("data-value", variables.selectedFilter);
  }

  /**
   * Convertit select/option to ul/li
   * Affranchit de l'usage du submit bouton
   * Mémoire des clicks
   *
   * @return {void}
   */
  function selectToUlFilter() {
    variables.inputElement.classList.add("visually-hidden");
    variables.selectElement.hidden = true;
    variables.ul.setAttribute("class", "selectlist");
    Array.from(variables.optionElements).forEach(item => {
      const li = document.createElement("li");
      li.setAttribute("class", "selectlist-option");
      li.dataset.value = item.value;
      li.innerHTML = item.innerHTML;
      variables.ul.append(li);
    });
    variables.selectElement.after(variables.ul);
  }

  /**
   * Transpose le li sélectionné au select/option avant le submit
   *
   * @return {void}
   */
  function transposeModifToSelect() {
    Array.from(variables.optionElements).forEach(item => {
      if (item.value === variables.selectedFilter) {
        item.setAttribute("selected", "selected");
      } else {
        item.removeAttribute("selected");
      }
    });
  }

  /**
   * Ajout d'un attribut à l'element sélectionné pour le css
   *
   * @return {void}
   */
  function addSelectedAttribute() {
    document.querySelector(
      `li[data-value="${variables.selectedFilter}"]`
    ).dataset.selected = "true";
  }

  /**
   * Default controller appelé au chargement de la page
   *
   * @return {void}
   */
  function init() {
    console.log(drupalSettings.amu_bef_selectors);
    console.log("enter init");

    selectToUlFilter();
    addSelectedAttribute();
    transposeModifToSelect();

    variables.inputElement.click();

    const newUl = document.querySelector(".selectlist");
    const liDefaultEN = document.querySelector(
      '.lang--en li[data-value="All"]'
    );
    if (liDefaultEN) {
      liDefaultEN.innerHTML("All");
    }
  }

  Drupal.behaviors.bef = {
    attach(newUl) {
      document.addEventListener("DOMContentLoaded", init(), { once: true });

      newUl.addEventListener(
        "click",
        e => {
          setToLocalStorageOnClick(e);
          transposeModifToSelect();
          variables.inputElement.click();
        },
        { once: true }
      );
    }
  };
})(jQuery, Drupal);

EDIT:

if (!initialised) added

what happen then is eventlistener is not working on : variables.inputElement.click() : error Form submission canceled because the form is not connected.
(function($, Drupal) {
/**
 *
 * Retourne la valeur correspondante du localstorage
 *
 * @param {string} key
 * @return {string}
 */
function getFromLocalStorage(key) {
  if (localStorage.getItem(key) === null) {
    localStorage.setItem(key, "All");
  }
  return localStorage.getItem(key);
}

const variables = {
  selectElement /** @type={HTMLElement} */: document.querySelector(
    ".views-exposed-form .form-select"
  ),
  optionElements /** @type={HTMLCollection} */: document.querySelector(
    ".views-exposed-form .form-select"
  ).children,
  inputElement /** @type={HTMLElement} */: document.querySelector(
    ".views-exposed-form .form-submit"
  ),
  selectedFilter: getFromLocalStorage("data-value"),
  ul: document.createElement("ul")
};

/**
 * Stocke le li clické
 *
 * @param {Event } e
 * @return {void}
 */
function setToLocalStorageOnClick(e) {
  variables.selectedFilter = e.target.dataset.value;
  localStorage.setItem("data-value", variables.selectedFilter);
}

/**
 * Convertit select/option to ul/li
 * Affranchit de l'usage du submit bouton
 * Mémoire des clicks
 *
 * @return {void}
 */
function selectToUlFilter() {
  console.log("enter selectToul");
  // variables.inputElement.classList.add("visually-hidden");
  // variables.selectElement.hidden = true;
  variables.ul.setAttribute("class", "selectlist");
  Array.from(variables.optionElements).forEach(item => {
    const li = document.createElement("li");
    li.setAttribute("class", "selectlist-option");
    li.dataset.value = item.value;
    li.innerHTML = item.innerHTML;
    variables.ul.append(li);
  });
  variables.selectElement.after(variables.ul);
}

/**
 * Transpose le li sélectionné au select/option avant le submit
 *
 * @return {void}
 */
function transposeModifToSelect() {
  Array.from(variables.optionElements).forEach(item => {
    if (item.value === variables.selectedFilter) {
      item.setAttribute("selected", "selected");
    } else {
      item.removeAttribute("selected");
    }
  });
}

/**
 * Ajout d'un attribut à l'element sélectionné pour le css
 *
 * @return {void}
 */
function addSelectedAttribute() {
  const selectedLi = document.querySelector(
    `li[data-value="${variables.selectedFilter}"]`
  );
  if (selectedLi !== null) {
    selectedLi.dataset.selected = "true";
  }
}

/**
 * Default controller appelé au chargement de la page
 *
 * @return {void}
 */
function init() {
  console.log(drupalSettings.amu_bef_selectors);
  console.log("enter init");

  selectToUlFilter();
  addSelectedAttribute();
  transposeModifToSelect();
  // variables.inputElement.click();

  const liDefaultEN = document.querySelector(
    '.lang--en li[data-value="All"]'
  );
  if (liDefaultEN) {
    liDefaultEN.innerHTML("All");
  }
}

const form = document.querySelector(".views-exposed-form");
form.addEventListener("click", e => {
  setToLocalStorageOnClick(e);
  transposeModifToSelect();
  // works but no ajax
  form.submit();
  // when this does not work : Form submission canceled because the form is not connected
  // variables.inputElement.click();
});

let initialised = false;
Drupal.behaviors.bef = {
  attach() {
    if (!initialised) {
      initialised = true;
      init();
    }
  }
};

})(jQuery, Drupal);
Comment: Oh, and `document.addEventListener("DOMContentLoaded", init(), { once: true });` is wrong - you shouldn't invoke `init`, just pass it. You don't even need that line, the DOM is guaranteed to be loaded when behaviors are invoked so you can replace it with `init();`
Comment: You don't put the once on every line of code. You just put it once.

Okay, so is the question actually "How can I refactor jQuery once with Vanilla JS"? Then I guess this is off-topic...
Comment: Once is applied to the context, it is not needed multiple times in a behavior. A reason to follow the official docs in this respect is so you do not get bit by ajax or bigpipe etc later. https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview#s-drupalbehaviors
Comment: Does this answer your question? [jquery once onload](https://drupal.stackexchange.com/questions/244492/jquery-once-onload)
Comment: Do you try to avoid jQuery? If not add `- core/jquery.once` to the dependency of the library and then use as outlined in the other answer, it has a snippet for D8&+ in the bottom. Also explained in more detail in the [official docs](https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview).
Comment: @leymannx no, because i would need a native js solution and also because i am hoping there's a solution not having to put a once() on every lines of code
Comment: You might be overthinking this, a simple approach will suffice, some variation of: `var initialised = false; if (!initialised) { initialised = true; // Now run your code }`
Comment: what would be the only line with once() on this code? , or where to place the initialised var?. I have tried and i don't really get it
Comment: i have edited the code, if init() is loaded once , then the clicklistener does not work anymore when triggering the input submit()
Answer: There is now a vanilla version of Drupal once (https://www.drupal.org/project/once) and I've been using it successfully on a Drupal 9 project with vanilla JS in my theme. You can look at the change log here and the original issue that was the impetus for converting to vanilla. The source file in the project from which you can build sheds some insight on its use.
In your code above, I see you are using document.querySelector and you'll want to pay attention to that as I found a bug as noted here. "Error when context.querySelector() doesn't find an element on the page".
The documentation says:
 // once methods always return an array, to simplify the use with a single
 *   // element use destructuring or the shift method.
 *   const [myElement] = once('my-once-id', document.body);
 *   const myElement = once('my-once-id', document.body).shift();

So in the end, it's probably best for a single element to use an id with the patch linked to herein rather than document.querySelector. For example, I have a single element I want to target so I do it like this:
const glossary_view_conditions = once('glossary-view-once', '#views-exposed-form-scs-conditions-block');

For multiple elements being targeted, querySelectorAll works great. You'll also need your main function to target once, beginning and end. So an example would be:
(function (Drupal, once) {
  Drupal.behaviors.customCheckboxes = {
    attach(context) {
      // Find checkboxes, add markup.
      let outer_checkboxes = once('yay-only-once', context.querySelectorAll('.js-form-type-checkbox'));
      // Loop through each matched element.
      for (let i = 0; i < outer_checkboxes.length; i++) {
        // This is similar to jquery $(this).find('input.form-checkbox).
        let inner_inputs = outer_checkboxes[i].querySelectorAll("input.form-checkbox");
        // This is similar to jquery .after().
        // Since querySelectorAll returns a collection, we target with [0].
        inner_inputs[0].insertAdjacentHTML('afterend', '');
      }
    }
  };
}(Drupal, once));


Preencher um jCombobox usando join e hibernate

Question: Estou fazendo um trabalho na faculdade que onde devo criar um sistema de agenda para vendedores de uma concessionaria  de veiculos. As tecnologias utilizadas são Java, Swing, e Hibernate.
Dividi o projeto em camadas para facilitar, criei as classes cliente, vendedor e compromisso para agendar as atividades dos vendedores com os clientes. Para cada uma dessas classes estão na camada domain, a conexão os métodos de salvar, pesquisar excluir estão na camada dao, e existe uma camada chamada control que chama os metodos de uma interface de cada classe DAO.
Fiz a tela de cliente, fiz a tela de Vendedores, mas na tela de Compromisso tem um JComboBox que era para mostrar os vendedores e outro para monstrar os clientes , mas só aparece as referencias deles e não os nomes.
Como faço para aparecer o nomes dos vendedores e clientes?
Projeto no BitBucket
Segue código do control compromisso:
package control;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import model.dao.CompromissoDao;
import model.dao.CompromissoDaoImp;
import model.domain.Cliente;
import model.domain.Compromisso;
import model.domain.Vendedor;
import model.service.ServiceLocator;
import org.jdesktop.observablecollections.ObservableCollections;

/**
 *
 * @author joao.rolim
 */
public final class CompromissoControl {
    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
    private Compromisso compromissoDigitado;
    private Compromisso compromissoSelecionado;
    private List<Vendedor> vendedorTabela;
    private List<Cliente> clienteTable;
    private List<Compromisso> compromissoTabela;
    private final CompromissoDao compromissoDao;

    public CompromissoControl() {
        compromissoDao = ServiceLocator.getCompromissoDao();
        compromissoTabela = ObservableCollections.observableList(new ArrayList<Compromisso>());

        clienteTable = ObservableCollections.observableList(
                new ArrayList<Cliente>());
        clienteTable.addAll(compromissoDao.buscarClientes());

        vendedorTabela = ObservableCollections.observableList(new ArrayList<Vendedor>());
        vendedorTabela.addAll(compromissoDao.buscarVendedores());
        novo();
        pesquisar();
    }

    public Compromisso getCompromissoDigitado() {
        return compromissoDigitado;
    }

    public void setCompromissoDigitado(Compromisso compromissoDigitado) {
        Compromisso oldcompromissoDigitado = this.compromissoDigitado;
        this.compromissoDigitado = compromissoDigitado;
        propertyChangeSupport.firePropertyChange("compromissoDigitado",oldcompromissoDigitado,compromissoDigitado);
    }

    public Compromisso getCompromissoSelecionado() {
        return compromissoSelecionado;
    }

    public void setCompromissoSelecionado(Compromisso compromissoSelecionado) {
        this.compromissoSelecionado = compromissoSelecionado;
        if (this.compromissoSelecionado != null) {
            setCompromissoDigitado(compromissoSelecionado);
        }

    }

    public List<Compromisso> getCompromissoTabela() {
        return compromissoTabela;
    }

    public void setCompromissoTabela(List<Compromisso> compromissoTabela) {
        this.compromissoTabela = compromissoTabela;
    }

    public void addPropertyChangeListener(PropertyChangeListener property){
       propertyChangeSupport.addPropertyChangeListener(property);
    }
    public void removePropertyChangeListener(PropertyChangeListener property){
        propertyChangeSupport.removePropertyChangeListener(property);
    }

    public void novo() {
        setCompromissoDigitado(new Compromisso());
    }

    public void salvar(){
        compromissoDao.salvarAtualizar(compromissoDigitado);
    }

    public void excluir(){
        compromissoDao.exluir(compromissoSelecionado);
    }

    public void pesquisar() {
        compromissoTabela.clear();
        compromissoTabela.addAll(compromissoDao.pesquisaGeral(compromissoDigitado));
    }

    public List<Vendedor> getVendedorTabela() {
        return vendedorTabela;

    }

    public void setVendedorTabela(List<Vendedor> vendedorTabela) {
        //Vendedor vendedor = this.vendedorTabela.
        this.vendedorTabela = vendedorTabela;
    }

    public List<Cliente> getClienteTable() {
        return this.clienteTable;

    }

    public void setClienteTable(List<Cliente> clienteTable) {
        this.clienteTable = clienteTable;
    }

}

Answer: A forma mais simples de se resolver o problema da exibição do JComboBox é sobrescrevendo o método toString() das suas duas classes Vendedor e Cliente, retornando o que você quer que seja exibido. Pelo que vi nos códigos, você pode fazer assim para as duas classes:
public String toString(){
    return this.nome;
}

Desta forma, os JCombobox irão exibir o nome do vendedor e o nome do Cliente. Outra forma é criando seu próprio ComboModel, mas ai você teria que criar um para cada combo.
Comment: Puxa era só isso mesmo que faltava, cara como pude esquecer do toString() valeu!


Back transforming regression results when modeling log(y)

Question: I'm fitting a regression on the $\log(y)$.  Is it valid to back transform point estimates (and confidence/prediction intervals) by exponentiation?  I don't believe so, since $E[f(X)] \ne f(E[X])$ but wanted other's opinions.
My example below shows conflicts with back transforming (.239 vs .219).
<code>set.seed(123)

a=-5
b=2

x=runif(100, 0, 1)
y=exp(a*x + b + rnorm(100, 0, .2))
# plot(x, y)

### NLS Fit
f <- function(x, a, b) {exp(a*x + b)}
fit <- nls(y ~ exp(a*x + b),  start = c(a=-10, b=15))
co=coef(fit)
# curve(f(x=x, a=co[1], b=co[2]), add = TRUE,col=2,lwd=1.2)
predict(fit, newdata=data.frame(x=.7))
[1] 0.2393773

### LM Fit
# plot(x, log(y))
# abline(lm(log(y) ~ x), col=2)
fit=lm(log(y) ~ x)
temp=predict(fit, newdata=data.frame(x=.7), interval='prediction')
exp(temp)
        fit       lwr       upr
1 0.2199471 0.1492762 0.3240752
</code>
Comment: @Glen Do a search for Duan smearing on this site.
Comment: Is this not one of the problems that is solved by log-linked gaussian GLMs?
Comment: @ARM Yes I believe so.  Thanks for pointing that out.  However using GLM it is harder to get prediction intervals but I think I can work it out.
Answer: It depends on what you want to obtain at the other end.
A confidence interval for a transformed parameter transforms just fine. If it has the nominal coverage on the log scale it will have the same coverage back on the original scale, because of the monotonicity of the transformation.
A prediction interval for a future observation also transforms just fine.
An interval for a mean on the log scale will not generally be a suitable interval for the mean on the original scale.
However, sometimes you can either exactly or approximately produce a reasonable estimate for the mean on the original scale from the model on the log scale.
However, care is required or you might end up producing estimates that have somewhat surprising properties (it's possible to produce estimates that don't themselves have a population mean for example; this isn't everyone's idea of a good thing).
So for example, in the lognormal case, when you exponentiate back, you have a nice estimate of $\exp(\mu_i)$, and you might note that the population mean is $\exp(\mu_i+\frac{1}{2}\sigma^2)$, so you may think to improve $\exp(\hat{\mu_i})$ by scaling it by some estimate of $\exp(\frac{1}{2}\sigma^2)$.
One should at least be able to get consistent estimation and indeed some distributional asymptotics via Slutsky's theorem (specifically the product-form) as long as one can consistently estimate the adjustment. The continuous mapping theorem says that you can if you can estimate $\sigma^2$ consistently... which is the case.
So as long as $\hat{\sigma}^2$ is a consistent estimator of $\sigma^2$, then
$\exp(\hat{\mu_i})\cdot \exp(\frac{1}{2}\hat{\sigma}^2)$ converges in distribution to the distribution of $\exp(\hat{\mu_i})\cdot \exp(\frac{1}{2}\sigma^2)$ (which by inspection will then be asymptotically lognormally distributed). Since $\hat{\mu_i}$ will be consistent for $\mu_i$, bu the continuous mapping theorem, $\exp(\hat{\mu_i})$ will be consistent for $\exp(\mu_i)$, and so we have a consistent estimator of the mean on the original scale.
See here.
Some related posts:
Back transformation of an MLR model
Back Transformation
Back-transformed confidence intervals
Comment: Thanks, I looked at the previous posts and, while enlightening, was still somewhat confused, hence my question.
Comment: You should be able to get it just by directly integrating: $E(Y) = \int_0^\infty y\, f(y)\, dy$ where $f$ is the density for the lognormal, but it is probably easier to do by calculating $E(e^X)$ for a normal (where $X=\log Y$), but then perhaps it is better to find the MGF for $X$  - which is no more difficult - and from which moments for $Y$ are very readily obtained (by replacing $t$ by $1,2,...$ in turn), essentially getting higher moments for free.
Comment: @usεr11852 In either of the latter cases you take the $e^x$ or $e^{tx}$ into the $e^{...}$ term in the density, then complete the square in $x$, and bring additional constants (i.e. all except the normalizing constant for the normal) out the front of the integral (which has the $\frac12$ in it), leaving a Gaussian pdf integrated on the real line (with shifted mean from the original) which integrates to 1, leaving only the constants you brought out the front. This involves nothing more than very simple algebraic manipulations, ... ctd
Comment: ctd... and from which the $t$-th raw moment of a lognormal is $e^{\mu t + \frac12 \sigma^2t^2}$.
Comment: +1 Great answer! Just a quick clarification: Where did the $\frac{1}{2}$ came from as a scaler for $\hat{\sigma^2}$? I saw it in the definition of the lognormal in Wikipedia but it is not explained there either, is it just integrating out mean from the PDF?
Comment: @Glen_b Thank you
Comment: The "$\frac12$" in that case ultimately comes from the effect of completing the square under the $\frac12$ in the exponent in the normal density. The $\mu$ term doesn't get one because it gets a $2$ that cancels with the $\frac12$.
Comment: Can you comment on why prediction intervals backtransform fine, but confidence intervals do not? I don't understand how those can both hold at the same time.


Edifact D16 XML schemas for use in BizTalk 2016

Question: This might be a longshot, but I decided to give it a go anyway. As far as I understand, BizTalk does not include Edifact Schemas after v. 2013 and as such, no schemas for the D16A and D16B formats have been created by Microsoft. The currently released schemas can be found on Github, by following this link: Microsoft/Integration/BizTalk Server/Schema/EDIFACT/
Our current solution (which is very sub-optimal) is to change the current D10 schemas to match as closely as possible the D16 specifications for the various document types. Obviously this is prone to a lot of validation errors.
Does anyone know if these schemas have been created by a third party? And if so, where can I find them? So far we managed to find one schema for a single document type created by a developer.
Answer: To be clear, what you are planning is not uncommon.
This has been the solution for odd versions in both EDIFACT and X12 for ever.
Couple things...

The specs don't really change that much so modifications aren't too chalenging.
You only have to modify what you need to support based on your trading partner agreements.  Meaning, you don't need to add segments that you will not be using.
Comment: Thank you for the explanation, I will keep that in mind. Ok, I will create the map based on the D10A schemas as we have the XSD's for those.


How to pass a array into webapi function?

Question: I want to pass an array into webapi.
Here is my function for getting checkbox selected items in albumNameArray.
$scope.Delete = function () {
        debugger
        $scope.albumNameArray = [];
        angular.forEach($scope.InboxList, function (CU) {
            if (CU.selected) $scope.albumNameArray.push(CU.InboxMailID);
        })
    }

Now I want to send the albumNameArray into webapi function. I have modified the delete function but it is not working, what is wrong in my code?
$scope.Delete = function () {
        debugger
        $scope.albumNameArray = [];
        angular.forEach($scope.InboxList, function (CU) {
            if (CU.selected) $scope.albumNameArray.push(CU.InboxMailID);
        }).$http({
        url: "MailRoute/DeleteSelecetedEmail",
        dataType: 'json',
        method: 'POST',
        data: albumNameArray,
        headers: {
            "Content-Type": "application/json"
        }

    }).success(function (response) {
        debugger
        if (response != null) {

        }

    })
      .error(function (error) {
          alert(error);
      });
}

Comment: paste your WebAPI code as well here
Comment: I think this is model. You must paste Controller code.
Comment: public HttpResponseMessage Delete(HttpRequestMessage request, [FromBody]GetAllInbox obj)
    {

        if (something!= 0)
        {

        }
        else
        {

        }

        return response;
    }
Comment: actually the array is not going to my angularjs function thats the problem
Comment: first of all you are passing array, so must have received array in WebAPI parameter. Second check that your Array is not null before passing to function
Comment: array is not null i have checked.i think the problem is on the function.some bracket problem.i have checked with debugger.but the data is not going on the webapi function.can you modify my delete function please?
Comment: if you have postman you can check WebAPI in that
Answer: Try this:
public HttpResponseMessage Delete(string data)
{
    if (something!= 0)
    {

    }
    else
    {

    }
    return response;
}

If this is not working Try with List
Answer: this is the model class i have declared
public class GetAllInbox
    {
        public string data{ get; set; }
   }

the webpai fuction is shown below
public HttpResponseMessage Delete(HttpRequestMessage request, [FromBody]GetAllInbox obj)
    {

        if (something!= 0)
        {

        }
        else
        {

        }

        return response;
    }

here is my webapi code.
Comment: public List data{ get; set; }
try with this
Comment: actually the array is not going to my angularjs function thats the problem


Do traded players get their names on the Stanley Cup if previous team wins?

Question: So, I would assume the answer to this question is "No", but I can't actually verify it anywhere.  The criteria for getting your name on the cup is to play at least 41 regular season games for the cup winning team.  But if a player is traded after that 41 games, is his name still engraved on the Cup even though he played out the season with another team?
Comment: Okay, I think I've answered my own question.  No, because Cam Barker played 51 games for Chicago in the 2009-2010 season before being traded to Minnesota.  His name does not appear on the cup.

http://1.bp.blogspot.com/_VIzeHgMtkks/TKUw4ndFl-I/AAAAAAAACOs/oXB_xRmXZeI/s1600/STanley+Cup+Engraved.jpg
Comment: Answering your own question is perfectly legitimate; feel free to move that comment into an answer.
Comment: Not only legitimate, it's even encouraged! Although I'm going to add the NHL tag as this is not necessarily the case in all Ice Hockey.
Answer: According to this article:

Prior to 1977 only players who had completed the Stanley Cup playoffs
  were eligible. Today, players appearing in 41 regular-season games or
  one Stanley Cup Final game for the championship team have their names
  engraved on the Cup. The NHL makes exceptions for players who do not
  meet the standard because of injury or other extenuating
  circumstances.

And according to the NHL:

To have one's name engraved on the Stanley Cup certain requirements
  must be met. A player must have at least 41 games played with the club
  or one game played in the Stanley Cup Finals. However, in 1994 a
  stipulation was added to allow a team to petition the Commissioner for
  permission to have players' names put on the Cup if extenuating
  circumstances prevented them from being available to play.

However, according to Wikipedia:

The Detroit Red Wings received special permission from the NHL to
  inscribe the name of Vladimir Konstantinov, whose career ended after a
  car accident on June 13, 1997, on the Stanley Cup after Detroit
  defended their title in 1998.

So it appears that player traded away could be added in theory, but probably not in practice.
Comment: `Today, players appearing in 41 regular-season games or one Stanley Cup Final game for the championship team have their names engraved on the Cup` seems to indicate the player traded away after 41 games *would* be added.  Your conclusion doesn't seem to be supported?
Comment: @matthew, from the context, the 41 games rule was in effect if the player was still with the organization when the Stanley Cup was won.
Comment: This does raise the question: if a player was so instrumental to the team that you would add them to the cup, why would you trade him?
Comment: @corsiKa, some possible reasons might include acquiring another key player at a position of need or building depth for the playoff run.


Arrangements of the word COMBINATION not containing CAN, BIN, NIB

Question: How many ways can we arrange the letters of the word COMBINATION, containing none of the patterns CAN, BIN and NIB?
Without restrictions, arranging the 11 letters with 2 O's, 2 I's and 2 N's is $\frac{11!}{2!2!2!} $ ways.
Where I'm stuck at now is how to calculate the arrangements with CAN, NIB and BIN, since there are 2 I's and 2 N's, and also each of the patterns contain letters in the other pattern.

Can anyone could help me out with this problem?
Thanks in advance.
Answer: It's an application of the inclusion exclusion principle. We use the above to write properties $P_1, P_2$ and $P_3$ respectively as
$P_1$ - Pattern CAN occurs
$P_2$ - Pattern BIN occurs
$P_3$ - Pattern NIB occurs
Let $A_1, A_2, A_3$ be the sets conforming to each property. Now using the above stated principle we know that
$$|\bar{A_1}\cap\bar{A_2}\cap\bar{A_3}| = |S| - \sum_{i=1}^3|A_i| +\sum_{i,j}|A_i \cap A_j| - |A_1\cap A_2\cap A_3|$$
$A_1$ - Treat CAN as one entity and calculate the permutations of the entities (CAN),O,M,B,I,T,I,O,N which is equal to
$$|A_1| = \frac{9!}{2!}$$
$A_2$ - Treat BIN as one entity and calculate the permutations of the entities C,O,M,(BIN),A,T,I,O,N which is equal to
$$|A_2| = \frac{9!}{2!}$$
$A_3$ - Treat NIB as one entity and calculate the permutations of the entities C,O,M,(NIB),A,T,I,O,N which is equal to
$$|A_3| = \frac{9!}{2!}$$
$A_1\cap A_2$ - Putting CAN and BIN together and calculating the permutations of the entities (CAN),(BIN),O,M,I,O,T which is equal
$$|A_1\cap A_2| = \frac{7!}{2!}$$
$A_2\cap A_3$ - We cannot have BIN and NIB together as there's only one B in COMBINATION
$$|A_1\cap A_3| = 0$$
So, also $|A_1\cap A_2\cap A_3| = 0$
EDIT - As was suggested by the commenter, there's one extra case that I forgot to account for, which is CANIB. This will be a part of $A_1\cap A_3$ and is calculated by the number of permutations of (CANIB),O,O,T,I,N,M
$$|A_1\cap A_3| = \frac{7!}{2!} + \frac{7!}{2!}$$
Hence the total number of combinations become
$$|\bar{A_1}\cap\bar{A_2}\cap\bar{A_3}| = \frac{11!}{2!2!2!} - 3\cdot\frac{9!}{2!} + 3\cdot\frac{7!}{2!}$$
Comment: You overlooked the case CANIB.
Comment: Thanks for pointing it out. I'll edit my answer to reflect that


Can PHP maintain a persistent session with a server, as a client?

Question: Say I'm on my home PC with my browser open, I visit a site that uses sessions, as long as I don't close my browser or remain idle for 24 minutes the session will be maintained as I make subsequent HTTP requests to the site.
However on my server running PHP, if I use fopen() or file_get_contents() to request a page from that same site, does that site create a session for the 'user' that is my server?  Is there a way to keep the connection open so the session is maintained for subsequent fopen() requests?
Can I do this by passing the session id in the request headers on the subsequent request?  ie I set the headers including the session id, pass the headers to a context_stream_create(), and then pass the context with the next fopen() request?  Can this be done for POST requests (which is what I really need to do)?
Answer: Any app which can speak HTTP language have the capability to save the cookie and therefore save the state in HTTP.
The answer to your questions is YES. You can do anything you want with just using the right protocol ( GET/POST ) and sending proper headers ( Host, User-Agent, ... )
But you have an alternate solution, i think this class will help : PHP Browser Class
Comment: @Joey You could also use curl. You can send any headers you want, including the session id cookie.
Comment: That looks like it could work for what I'm doing but does it include a way to send custom headers in each request?
Comment: The Browser class doesn't have a method for adding arbitrary headers, but as it uses CURL, you can do it with a few lines code.


The amount of right triangles on a finite square/rectangular lattice.

Question: To preface I am not entirely sure lattice is the correct word for this but my "research" on the question makes it seem like that is a good way to phrase the question. Just to highlight my experience I am currently taking "calculus 2" and a discrete/foundations of math course but I don't mind going outside of that zone of knowledge to figure out the problem. I am not looking for a program that iterates through points finding which triangles are right and which are not.
For simplicity I will only be talking about the square lattice. The triangles in question can only have their vertices on lattice points.
What I have done so far:

Found the number of ways to place points. If there are $n$ points its $n \choose 3$.
The amount of right triangles where the right angle is aligned with rows and columns. $n (p-1)^2$. $n$ is the amount of points that could be the vertices of the right angle and each $(p-1)$ is the amount of points left to choose from.

I am not really sure what to do from here. I have had a few thoughts though. I looked to see if finding the amount of rectangles and somehow connecting it to the amount of triangles would be easier, but to get all the triangles there would be some rectangles that were partially outside the lattice. I have also thought that maybe there is someway to find all the right triangles that could not be made by other ones(in the lattice) and maybe that could lead to a way to say how many there are. There is of course "how many are not right?" question but I do not know how I would find that. I have also tried using perpendicular lines but not really sure how to apply that idea to get the amount of right triangles.
Comment: @Gerry: OEIS also has text search :-) This is [OEIS sequence A077435](https://oeis.org/A077435). For a rectangular grid, [OEIS sequence A189814](https://oeis.org/A189814).
Comment: I do not know if it helps, but a triangle is right if and only if its hypotenuse is a diameter of the circumcircle.
Comment: The number of triangles is not right. Your $3$ points could be on the same slanty line. Counting right triangles whose right angle is not in the "obvious" places is a difficult number-theoretic problem, best one can hope for is a good estimate.
Comment: You've got $p$, and you've got $n$. In fact, $n=p^2$, right?
Comment: The distinct points $(a,b),(c,d),(e,f)$ form a right triangle with a right angle at $(c,d)$ if and only if $(a-c)(e-c)+(b-d)(f-d)=0$, so you're looking for the number of solutions to this diophantine equation with all variables between 1 and $n$. I don't know how hard the analysis would be. Another approach is to calculate the answer for, say, $n=2,3,4$ and then look up the result in the Online Encyclopedia of Integer Sequences.
Comment: @AndréNicolas I removed the incorrect statement.
Comment: @joriki, excellent! Too bad the site gives no formula, asymptotics, references, etc.
Answer: I think it was a mistake to look at the square case "for simplicity". The rectangular case is more approachable, because one can  get a meaningul result by fixing the height $k$ and considering the dependence on width $n$. The simplest case is $n\times 2$, which  yields
$$4\binom{n}{2} +2(n-2) $$ right triangles. R. H. Hardin observed empirically that for every $k$ there exists $n_0$ such that the number of right triangles is a quadratic function of $n$ when $n>n_0$. (The links to relevant OEIS data: A077435 for square grid and A189814 for rectangular, were found by joriki).
This suggests some lines of investigation (I think these three are in increasing order of difficulty):

Prove the existence of $n_0$ and give an estimate for it.
Find a formula for the $n^2$ coefficient (as a function of $k$) and prove it.
Same for the $n^1$ and $n^0$ coefficients.

In general, the problem is very hard. The $50\times 50$ case, greatly simplified by fixing one vertex of a triangle, was Euler project problem 91.


How to calculate inclusion probability under sampling without replacement

Question: I am quite new to sampling method.
The task is sampling without replacement with unequal probabilities, but I have problem in calculating inclusion probability.
I want to sample $n$ units from the population of size $N$ through the following procedure in the figure. After the procedure, I need to calculate the inclusion probability in order to get the Horvits-Tompson estimator, an unbiased estimator of the Population Total.
But I don't know how to calculate inclusion probability, because I need to traverse $n!\binom{N-1}{n-1}$ n-tuples (e.g. add the probability of $50!\binom{999}{49}$ n-tuples), it's huge and not realistic!!!
My ultimate goal is to have an unbiased estimator of the Population Total, based on $p_i(k)$ constructed by myself.
How can I do this?

The inclusion probability is also written as the following $p(u_i)$:
$p(i) = \sum_{(i_1, i_2, ..., i_n)\in S(i)}{p(i_1, i_2, ..., i_n)}$
where $S(i)$ is consisting of n-tuples where unit $i$ and other $(n-1)$ different units . There are $n!\binom{N-1}{n-1}$ elements in $S(i)$!
The formula is from paper: SAMPLING WITH VARYING PROBABILITIES WITHOUT REPLACEMENT: ROTATING AND NON-ROTATING SAMPLES.
Answer: The solution is to use an algorithm that selects each unit (without replacement) with a user determined probability. Usually this probability is proportionate to some measure of size. There are many such algorithms. Hanif and Brewer list fifty in their 1980 review article. Several of these algorithms (as well as newer algorithms) are implemented in the sampling package in R. See the functions that begin with the prefix "UP" for unequal probability.
Note that the 'sample()' function in base R does not actually sample with a user determined probability if the 'prob' argument is set and sampling is without replacement. This is a sequential algorithm and, as noted above, using such an algorithm can make it very difficult to, post facto, determine the probabilities of inclusion.
Comment: I had a look at Brewer & Hanif (1983), but I do not yet see why there are so many different methods of sampling _without_ replacement. I see B&H classify the various algorithms in equivalence classes, but there still seem to be many different classes. Why is there not just 'one ultimate' method of sampling without replacement? I am missing some intuition here, and therefore struggling to follow the mathematics.
Comment: Hmm. There's not  "one ultimate method" because as you note in your original question, the straightforward approach is computational intractably in all but the most trivial cases. Some methods work well in some cases but not in others, e.g. some form of rejection sampling can work well if you only want to draw 2 or 3 units from a large $n$ but becomes intractable if you want to draw a large fraction of $n$. Maybe this is a better introduction: https://www.sciencedirect.com/science/article/pii/S1574013722000673?via%3Dihub


organic groups and private files

Question: Hi everyone I was wondering if it's possible to have directories of files attached to an organic group so that only group members and admins can access those files. If so whats the easiest way to accomplish this? I tried to use a htaccess file in files/private/groups (the directory I want to store these files in) but to no avail.
Answer: For anyone attempting something similar I ultimately modified the user files module
and used the hook_file_download to only allow group members to download protected content by using the built in is_og_group_member function.

organic groups and private files


install tomcat and java and run jsp in the browser

Question: For quite a while I have worked in the LAMP stack. But now I need to work on a project in java ,jsp and servlets(Tomcat Server) I have never worked in java ,jsp before. So I need some help in setting up the stuff in my laptop so that i can execute a java and jsp script in my browser. I know there are numerous links in the web that provide tutorials. But could someone point me to good one where it shows all the steps:for eg:
Installing Tomcat
Installing java
compiling,build,test java,jsp,servlets in the browser
Or anything else that would help me get started and learn the right way to develop web applications
Answer: I think this tutorial from Lars Vogel is a comprehensive one and is quite up-to-date.
The only point not covered is "installing java", that should be your first step. This article can help you in getting used to JDK, JRE, JVM, etc.


In Drupal 7 how do you output array objects to be view able in watchdog error reports?

Question: For some reason I couldn't use devel to debug output object arrays. Is there a way to output the array data to watchdog error reporting? This would also solve the issue of having to install or enable another module.
Answer: You can use watchdog but the message part should be translatable, so any variables should use placeholders defined in the variables array. Check out format_string to see how these should work.
watchdog(
  'my_module_name',
  'Here is the printed variable:
@placeholder_name
',
  array('@placeholder_name' => print_r( $my_variable, TRUE)),
  WATCHDOG_INFO
);

Also, convention dictates that the first parameter, $type, should be the module name calling watchdog.
Answer: You can do the following to output array data to be viewed in watchdog:
// Directly use values.
watchdog("log_name", '
' . print_r( $my_object, true) . '
');

Then goto /admin/reports and look for "log_name".
Comment: Watchdog runs through the translation function, so you need to use variables. See my answer.
Answer: If you don't mind enabling another module, though, I wrote Object Log for just this kind of thing:
https://www.drupal.org/project/object_log
It's lightweight, easier to use in code, more user-friendly to view, and doesn't get pushed down the log as other log events are recorded.
Comment: rather not install another module. not exactly practical if I only needed to do it once to see the array output. thanks tho.


How to limit showing of a block just in home page?

Question: I have a library book and in the first page or homepage of my website I want to show just 4 random books in center of my page.
How to set a View block to just show in home page?
Answer: You can do this by following below way :

After creating Views Block.
Goto Admin -> Structure -> Blocks (Search your block)
Configure -> Your block
Goto Pages section. Click on "Only the listed pages" & write <front> & Save block.


How to prove that is not a regular surface.

Question: In reference to this question:
This equation define a regular surface?
How can I prove that the union of this three plane is not a regular surface?
Intuitively this is clear.
Thanks!
Answer: You can prove a regular surface must at every point locally be a graph of some function over an open set in $xy$ or $yz$ or $xz$ plane.
Consider the origin and argue it can't be a graph of any function ( since it's multi-valued).


How to specify default options in a checkbox field using Field API

Question: I am trying to add a checkbox field to user entities using the FIELD API (in function MYMODULE_install() )
I can create the field, but I can't pre-load it with the desired default values.
Where my code is wrong ?
<code>$default_notification_field_name = "field_notification_defaults";
if(!field_info_field($default_notification_field_name))   { // check if the field already exists.

    field_create_field(
        array(
            'field_name' => $default_notification_field_name,
            'cardinality' => FIELD_CARDINALITY_UNLIMITED,
            'type' => 'list_text',
            'settings' => array(
                'allowed_values' => array(
                    'group' => t('Groups to which you subscribe'),
                    'content' => t('Authored content'),
                    'comment' => t('Replies to your comments')
                )
            ),
        )
    );

    field_create_instance(
        array(
            'field_name' => $default_notification_field_name,
            'entity_type' => 'user',
            'bundle' => 'user',
            'label' => t('Default settings for notifications'),
            'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
            'required' => FALSE,
            'widget' => array(
                'type' => 'options_buttons',
            ),
            'default_value' => array('content','comment')
        )
    );
}
</code>
Answer: Try this for your instance creation:
<code>field_create_instance(
  array(
    'field_name' => $default_notification_field_name,
    'entity_type' => 'user',
    'bundle' => 'user',
    'label' => t('Default settings for notifications'),
    'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
    'required' => FALSE,
    'widget' => array(
      'type' => 'options_buttons',
    ),
    'default_value' => array(
      0 => array(
        'value' => 'comment',
      ),
      1 => array(
        'value' => 'content',
      ),
    ),
  ));
</code>
To assist you in knowing the array structure, try this:

Install the devel module
Go to the page /devel/php on your site
Run this code to see all field information on your site:

<code>// Show all fields.
dpm(field_info_fields());
// Show all field instances.
dpm(field_info_instances());
</code>


HTML/CSS - Angular material custom dialog

Question: I'm trying in every way to create a custom angular material dialog with a custom header using some css/scss and tailwindcss framework. The desired effect would be that of the figure below.
desired-effect

After many attempts, I am stuck at the following result:
current-effect

I have trouble filling the white part under the header and the material icon with the yellow background-color. Below is my html/css code:
CODE:

Dialog title

                <button class="p-1" [mat-dialog-close]
                        matTooltip="Close"
                        mat-icon-button>
                    <mat-icon>close</mat-icon>
                </button>

Dialog subtitle

            <mat-icon class="material-icons-round badge w-10 h-10">link</mat-icon>

 Some Content ...

.mat-dialog-container {
    padding: 0px;
    position: relative;
}

.mat-dialog-content {
    margin: 20px;
}

.edit-dialog-header {
    background-color: #929aa0;

    .edit-dialog-header-footer {
        background: #ffffff;
        background: linear-gradient(0deg, #ffffff 50%, rgba(146, 154, 160, 1) 50%);

        mat-icon {
            font-size: 20px;
        }

    }

    .edit-dialog-header-title, .edit-dialog-header-subtitle {
        color: #fbfbfd;
    }

    .edit-dialog-header-title {
        font-size: x-large;
    }

    .edit-dialog-header-subtitle {
        font-size: medium;
        font-weight: normal;
    }

    .edit-dialog-button-exit {
        button {
            position: absolute;
            top: 0;
            right: 0;
            border: none;
            background-color: #929aa0;

            mat-icon {
                color: #fbfbfd;
            }
        }
    }
}

.badge {
    font-weight: bold;
    color: #fbfbfd;
    background: #929aa0;
    border-radius: 50%;
    padding: 5px;
    line-height: 50px;
    vertical-align: middle;
    text-align: center;
}

Does anyone have any ideas on how I can fill in that white space under the header ??
Thank you everyone
Comment: Just want to confirm what are you trying to set to white as in your css it states `.edit-dialog-header-footer` `background: #ffffff; ` when looking at your desired effect, I don't see what that's suppose to represent.
Answer: Try to use z-index: 10 in your css class
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer).


Set maximum allowed file size for S3 multipart upload

Question: You can limit file size with content-length-range field in a browser based upload (not multipart):
http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
How can you limit it in a multipart upload? I'm using EvaporateJS.
Answer: Apologies for the late reply but I did know know there was an EvaporateJS thread here.
FWIW, use the maxFileSize option on Evaporate.prototype.add to validate maximum file size.


cs231n: train/val accuracy and number of parameters

Question: In this cs231 lection note there is a counterintuitive quote:

The gap between the training and validation accuracy indicates the amount of overfitting.
...
The other possible case is when the validation accuracy tracks the training accuracy fairly well. This case indicates that your model capacity is not high enough: make the model larger by increasing the number of parameters.

Questions:

Isn't the goal of training to achieve the validation accuracy as high as training accuracy or did I miss something?
What the intuition under increasing the number of parameters if the validation accuracy tracks the training accuracy fairly well?
Answer: I think this:

The other possible case is when the validation accuracy tracks the training accuracy fairly well. This case indicates that your model capacity is not high enough: make the model larger by increasing the number of parameters.

Is getting at the idea that training a model, in general, should yield overfitting. That is basically its design -- tweak weights until error is zero.
So, if your model is NOT overtly overfitting, then your model can probably "learn more" with more trainable parameters which in turn, should, help you get even better validation metrics.
Comment: I got the idea. Thanks

Are there any techniques to solve the trade-off between min training loss and min train/val difference in loss? IOW, when should I stop tweaking the weights?
Comment: You should freeze weights when you maximize or minimize whatever training objective you have. If it is loss, then whenever you reach the minimum. If it is F1, then whenever you reach the maximum.


What happen when model selection ranks null model as the best one and there's another model that is competitive?

Question: I'm analyzing the proportion of marked chicks vs. the number of chicks that were recaptured at one moth of age (not possible to use conventional capture-recapture analysis because we don't have a second recapture event).
The idea is to find if there is a change over time in the season using the hatch date and year as explanatory variables and their quadratic terms (looking for nonlinearity) as well as interactions. I ran models using the different combinations of explanatory variables.
glm(cbind(recapt, (mark - recaps) ~ date +
    year + year2 + date:year + date:year2,
    family="x.quasibinomial", data=df)

So we decided to use proportion analysis. The data has a little overdispersion (c-hat=1.3), so I'm using a quasibinomial family as x.quasibinomial (see: https://cran.r-project.org/web/packages/bbmle/vignettes/quasi.pdf).
When I use model selection from MuMIn package, the best model is the null model (QAIC=2572.0) as well as one model that includes an interaction (QAIC=2572.7, delta=0.68).
I already tried to change the control of my model as suggested here, but I think I don't have a convergence problem.
How can I interpret the output? How can I explain the presence of the null model at the top? Is it possible to use the second best model? what else can I change in the model setting?
Answer: This is not the way to go about the modeling process.  Think model specification and not model selection.  Formulate a model based on what you know about the problem, keeping in mind your effective sample size which can put limits on the number of parameters.  Give enough parameters to parts of the model that are important.  Then make contrasts and hypothesis tests to answer the true questions of interest.  Don't drop any "insignificant" terms.
Besides distorting all aspects of the model by doing variable selection, you are using information in the data just to select variables and not to just estimating parameters.  This results in noise and poorer prediction.
See my RMS notes for more details.
Answer: I am not discussing here my model specification, that wasn't the question. The answer to my question (from the statistics service at my university) is that I it is possible to use the next best model if it is considered equivalent (i.e. delta AIC <2)
Comment: If you want to specify or clarify your question edit your question instead of this answer.


Simple examples/applications of Bayesian Networks

Question: Thanks for reading.
I want to implement a Baysian Network using the Matlab's BNT toolbox.The thing is, I can't find "easy" examples, since it's the first time I have to deal with BN.
Can you propose some possible applications, (with not many nodes) please ^^ ?
Answer: Have a look at Tom Mitchell's "Machine Learning" book, which covers the subject starting with small, simple examples. I suspect there are many course slides you could access online which also give simple examples.
Comment: Yes, in this book the application of Bayesian Networks has been very nicely demonstrated for text classification from the word frequencies.
Answer: I think it helps to start with higher level tools to get a feel for how to construct networks before constructing them in code. Having a UI also allows you to play with the network and get a feel for the way the networks behave (propagation, explaining away, etc).
For example have a look at the free Genie (http://genie.sis.pitt.edu) and its samples, and/or the 50 node limited Hugin-Lite (http://www.hugin.com/productsservices/demo/hugin-lite) with it's sample networks. You can then check your BNT implementations to make sure they verify against the software packages.
Edit: I forgot to mention Netica which is another BN/Influence diagram software package which I think has the biggest selection of examples http://www.norsys.com/netlibrary/index.htm.


Expressão regular PHP, como remover tags html aberto?

Question: Olá! Preciso remover da minha string um trecho html que bugou, ele estra assim:
e="text-align:left;"> Texto normal ...

Isso gera um erro visual.
Outro erro que ta gerando é no final do texto ex:
<p style="text-ali ...

Aqui ficou faltando o resto da tag e fechamento, o que gera mais erros.
Tem alguma expressão regular para remover somente o (>) e (<) quando estiverem com erro de formatação, no caso uma tentativa falha de marcação html?
Answer: De acordo com essa resposta no Stack Overflow em Inglês, você pode fazer assim:
$html = preg_replace("/<([^<>]*)(?=<|$)/", "$1", $html); # remove '<' os não fechados
$html = preg_replace("/(^|(?<=>))([^<>]*)>/", "$1", $html); # remove os '>' não fechados

Ainda de acordo com a segunda resposta do link acima, temos uma explicação seguinte:
Tradução meia-boca minha:

Para um < não fechado, é possível substituir <(?=[^>]*(<|$)) por uma string vazia. Ele corresponde todos < que não são seguidas por um fechamento de > antes da próxima <, ou no fim da linha.
Para a > não aberta, você pode substituir ((^|>)[^<]*)> por $1.
  Ele coincide com o texto que começa com um > (ou o início de linha), não contém < e termina com a >. $1  representa tudo, exceto o último >.


How to Filter by a JSON Key Value Where the Key is Nested at Various Depths?

Question: I have a large JSON response where I only need to update certain fields.  Want to filter down the response, but the key/value pair I'm interested in is nested at varying levels.  I tried to use the jsonpath .. notation to find it.
* eval var testcaseArray = response.collection.item.filter(o => o..name.includes(/^(RD-T|RES-T)/));

But the second ellipses is not recognized as valid Javascript syntax.
org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:1:59 Expected ident but found .
var testcaseArray = response.collection.item.filter(o => o..name.includes(/^(RD-T|RES-T)/))

Answer: Unfortunately JSON "update" operations will require you to explicitly know the keys and the hierarchy. The JsonPath things such as * and .. won't work.
You could try a brute-force regex based find-and-replace on the JSON and then re-convert it to JSON, but I would not recommend that.
I think it will be possible to recurse all JSON key-value pairs and do this, let me see if I can figure this out and update here later.


How do you find a plane that is both parallel and a distance of X units from a given plane

Question: I've been asked to come up with equations for two parallel planes that are X units apart. I've come up with the plane $x+z-1=0$ and a parallel plane $x+z+4=0$. Would it be correct to say these planes are 5 units apart since the $d$ constant is increased by 5?
I calculated the distance between the point $(1,0,0)$ on the 1st plane and the 2nd plane and got $3.54$ which I guess proves that the the planes are not 5 units apart. But if that's the case, I'm not sure how else to go about it.
Answer: Find the normal vector to your first plane, which is $\vec{n} = (1,0,1)$. The unit vector in this direction is $\vec{u} = \frac{\vec{n}}{|\vec{n}|} = \frac{1}{\sqrt{2}}(1,0,1)$. Now pick a point on the first plane, for example, you already mentioned $(1,0,0)$. Not just add $5$ times the unit normal vector to this point to get a point which is 5 units away from the plane:
$$ (1,0,0) + \frac{5}{\sqrt{2}}(1,0,1) = \left( 1 + \frac{5}{\sqrt{2}}, \; 0, \; \frac{5}{\sqrt{2}} \right)$$
Now just find the plane which is parallel and goes through this point. In other words, plug this point in to the equation $x + z + d = 0$ and solve for $d$.
Comment: Ah I didn't think of using the unit vector. I followed your advice and got the vector $x+z-8.08=0$, then checked the distance between $(1,0,0)$ from the initial plane to the new one and it was indeed 5. Thanks for your help!


Como bloquear usuário de voltar à página anterior do navegador

Question: Existe algum método que faça com que um usuário não consiga retornar a página anterior?
Acontece que tenho um formulário de contato no qual a pessoa deve preencher e pronto. Que não seja possível ela retornar e preencher novamente.
É como se a guia do navegador criasse uma nova seção, ou algo do tipo.

É possível fazer com que seja "bloqueado" a opção voltar à página anterior?
Answer: Este script substituirá as tentativas de navegar para frente e para trás com o estado da página atual.
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

O pushState altera o referrer que é usado no cabeçalho HTTP para objetos XMLHttpRequest criados depois de alterar o estado.
Veja mais sobre.
Note que esse código não é cross-browser, use por sua responsabilidade.
ATUALIZAÇÃO
O método pushState é compatível com
Chrome - 5 >
Firefox (Gecko) - 4.0 (2.0) >
Internet Explorer - 10 >
Opera - 11.50 >
Safari - 5.0 >

Comment: Eu me referi ao método pushState.
Comment: Esse código está certo? Você disse pushState, mas no código está popstate.
Comment: Vou testar agora!
Comment: Perfeito! Funcionou! Muito obrigado!
Comment: Qual versão do seu navegador e qual navegador ?
Comment: Estou utilizando o Maxthon Cloud Browser, ele tem algum problema de incompactibilidade com algum navegador?


Optimal xcache settings for VPS 512mb ram

Question: I use ubuntu 11.10, apache2 with varnish, php5-fpm and xcache.
I have 512mb ram with 4 cpus. linux kernel version 3.
What are the optimal xcache settings?
Should I make also some changes and settings also at my kernel/system to allow it have more memory size than the default 16?
Answer: Some quick comments (I have just been reading a bit about it and tweaking my own set up).
Set xcache.count to the number of CPU cores (eg, if your 4 CPUs are dual-core, then use 8 as the value)
Only worry about cache.var_size if you are using the variable cache (via xcache_get(), etc; check the api doc )
Otherwise, I have xcache.size set to 64M and it's enough.
Using the admin/status page you might be able to see that you have too many cache misses (missed hits) and then you could increase xcache.size.


Looping through an array using Migrate Plus

Question: I'm trying to loop through an array (called "Attributes") in a JSON migration source, but I can't figure out how to do it. Here's a shortened sample of my data source:
[
  {
    "Id": "ST00000002",
    "Title": "Fast & Furious 9",
    "Attributes": [
      "0000000013",
      "0000000015"
    ]
  }
]

My ultimate goal is to check certain checkbox/boolean fields based on those attribute values, but I can't figure out how to handle each of the attributes individually.
Things I have tried so far:

Using single_value and multiple_values
Using the custom Deepen process plugin (as seen on this issue)
Using sub_process
Using the static_map plugin (to do something like this:

map:
    '0000000015': 1
default_value: 0

Using skip_on_value with not_equals: true
Using countless combinations of the above functions

I feel like this can't possibly be as difficult as I'm making it, so I hope someone can help me out. Thank you so much.
Comment: Migrate's YML is not really tailored to contain a lot of logic, I don't think there is anything built-in right now to solve this easily. While some weird logic with `concat` and `str_replace` + `regex` option might do the trick, I would advise to create a process plugin that acts as a wrapper to PHP's `in_array`
Comment: Extensive logic should go into process plugin(s), yes.
Answer: Thank you so much. I got it to work by creating a custom process plugin using "in_array", as suggested. If anyone's interested, here's the plugin I created:
namespace Drupal\migrate_veezi\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Check if value exists in array
 *
 * @MigrateProcessPlugin(
 *   id = "in_array"
 * )
 *
 * To check if value is in array, use the following:
 *
 * @code
 * field_text:
 *   plugin: in_array
 *   source: array
 *   search: 'string'
 * @endcode
 *
 */

class InArray extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $search = $this->configuration['search'];

    if ($search) {
      if (is_array($value) || $value instanceof \Traversable) {
        return in_array($search, $value);
      }
      else {
        throw new MigrateException(sprintf('%s is not traversable', var_export($value, TRUE)));
      }
    }
    else {
      throw new MigrateException(sprintf('search value is not set'));
    }
  }

}

And then I used it like this:
field_closed_caption:
    -
      plugin: single_value
      source: attributes
    -
      plugin: in_array
      search: '0000000007'


AFNetworking 2.0 API For Multi-part form upload

Question: What is the AFNetworking 2.0 method for uploading a multipart form i.e.  With AFHTTPSessionManager or AFHTTPRequestOperationManager
Here is an example of some AFNetworking < 2.0 code:
[[ASAPIClient sharedClient] enqueueHTTPRequestOperation:[[ASAPIClient sharedClient] HTTPRequestOperationWithRequest:[[ASAPIClient sharedClient] multipartFormRequestWithMethod:@"POST" path:@"/some/url" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(_selectedPhoto.image)
        {
            NSData *imageData = UIImageJPEGRepresentation([_selectedPhoto image], 0.5);

            [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
        }
    }] success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if([[responseObject objectForKey:@"result"]isKindOfClass:[NSDictionary class]] )
        {

        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }]];

Answer: ASAPIManager is a subclass of AFHTTPRequestOperationManager
[[ASAPIManager sharedManager] POST:@"/some/url" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(_profileImageView.image){
            [formData appendPartWithFileData:UIImageJPEGRepresentation(_profileImageView.image, 0.5) name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

Comment: have "name" and "filename" to be as original? and I guess ASAPIManager is a subclass of AFHTTPRequestOperationManager ?
Comment: @raistlin name and filename can be whatever you please, but it is prob good practice to make sure that the extension of the filename matches the mimeType


Manipulating Binomial Distribution

Question: Recently, I've been reading Yudi Pawitan's book, In All Likelihood.
In the book, there's a section on profile likelihood; the methods explored in this section are subsequently applied to some data on heart attack prevalence amongst two distinct groups: people taking aspirin and people subjected to a placebo; the groups are modelled as $\text{Bin}(n_{a}, \theta_{a})$ and $\text{Bin}(n_{p}, \theta_{p})$ respectively. Since $n_{a}$ and $n_{p}$ are large while the event rates are small, $X_{a}$ and $X_{p}$ are approximately Poisson with parameters $n_{a}\theta_{a}$ and $n_{p}\theta_{p}$ respectively.
You can see the example here (Pages 87 and 88).
At the end, it is shown that the profile likelihood for a parameter of interest $\theta$ is given by:
$$ L(\theta, \theta_{p}) = \text{constant} \times e^{-\theta_{p}(n_{a}\theta+n_{p})} \theta^{x_{a}} \theta_{p}^{x_{a}+x_{p}} (1)$$
where $\hat{\theta}_{p} = \frac{x_{a}+x_{p}}{n_{a}\theta+n_{p}}$, the MLE for $\theta_{p}$, should be substituted into the above model for $\theta_{p}$.
and
$n_{a}$ : number of people in aspirin group,
$n_{p}$ : number of people placebo group,
$x_{a}$ : number of heart attacks amongst aspirin group,
$x_{p}$ : number of heart attacks amongst placebo group.
also
$\theta = \frac{\theta_{a}}{\theta_{p}}$,
$\theta_{a}$ : probability of heart attack in aspirin group and $\theta_{a}$ : probability of heart attack in placebo group.
The above likelihood is then further expressed as binomial, taking the following form:
$$ L(\theta) = \text{constant} \times \left(\frac{n_{a}\theta}{n_{a}\theta+n_{p}}\right)^{x_{a}} \left(1-\frac{n_{a}\theta}{n_{a}\theta+n_{p}}\right)^{x_p} (2)$$
I have tried to understand how to get from the expression given in $(1)$ to the expression given in $(2)$, but when I make the substitution for $\hat{\theta}_{p}$, I get the following:
$$ e^{-(x_{a}+x_{p})}\theta^{x_{a}}(x_{a}+x_{p})^{x_{a}+x_{p}}\left(\frac{1}{n_{a}\theta+np}\right)^{x_{a}+x_{p}} $$
where $e^{-(x_{a}+x_{p})} = \text{constant}$ as it doesn't depend on $\theta$.
I believe this is along the right lines, but I'm not sure where to go next.
Perhaps somebody could explain how to get from expression $(1)$ to expression $(2)$.
Comment: Normally in statistical estimation problems a sharp distinction is made between variables with a hat and those without. Subscripts matter, too. Are you making such distinctions between $\theta$, $\widehat{\theta}$, $\theta_p$, $\theta_a$, and $\widehat{\theta}_p$ and, if so, what are they?
Comment: Yes, there is a distinction between each one of the above variables. More specifically, $\hat{\theta}_{p}$ is the MLE for $\theta_{p}$; the subscripts $a$ and $p$ denote serve to indicate which group the variable belongs to (aspirin or placebo): for example, $\theta_{a}$ denotes the probability (binomial parameter) of heart attack in the aspirin group.

I have edited my question to make explicit the models used in the characterisation of the scenario; I hope it is clearer now.
Answer: First, the expression (1) is the likelihood, not the profile likelihood. It becomes profile likelihood for $\theta$ (eliminating the nuisance parameter $\theta_p$) only after you substitute in (1) $\hat{\theta}_p $ for $\theta_p$, the conditional maximum likelihood estimator for $\theta_p$, which is a function of $\theta$. The likelihood (1) is based on the Poisson approximation, and is in the book by Pawitan only used to develop $\hat{\theta}_p $, since the exact binomial likelihood does not lead to an explicit solution for the conditional mle.
Then, (2) is based on the exact binomial likelihood, but using the formula for $\hat{\theta}_p $ based on the Poisson approximation. This mixed use is not commented in the book, so maybe look somewhat strange.

You did not ask for this, but nevertheless. The way to do this computations today is with R and the glm function. I will show solution with both the binomial and Poisson likelihood.
Binomial, we need to use the log link function to get the parametrization used in the book.
library(tidyverse)
pawdf <- tibble(x=c(139, 239), n=c(11037, 11034),
           T=factor(c("active", "placebo"),
           levels=c("placebo", "active")))

mod.bin <- glm( cbind(x, n-x)  ~ T,
    family=binomial(link="log"), data=pawdf)
summary(mod.bin)

mod.bin.prof <- profile(mod.bin, which="Tactive")

exp(confint(mod.bin.prof))
                   2.5 %    97.5 %
    (Intercept)       NA        NA
    Tactive     0.471508 0.7141749
    # very close to Pawitan book

Poisson:

mod.po <- glm( x  ~ T + offset(log(n)),
    data=pawdf, family=poisson(link="log"))
summary(mod.po)

mod.po.prof <- profile(mod.po,  which="Tactive")

exp(confint(mod.po.prof))
                   2.5 %    97.5 %
    (Intercept)       NA        NA
    Tactive     0.470737 0.7153891

Answer: As @kjetilbhalvorsen explains, Equation (1) is the likelihood $L(\theta,\theta_p)$:
$$
\begin{aligned}
L(\theta,\theta_p) \propto \exp\big\{-\theta_p(n_a\theta+n_p)\big\}\theta^{x_a}\theta_p^{x_a+x_p}
\end{aligned}
$$
while Equation (2) is the profile likelihood $L(\theta)$.
To derive the profile likelihood $L(\theta)$ from the likelihood $L(\theta,\theta_p)$ we want to eliminate the nuisance parameter $\theta_p$ by maximimizing $L(\theta,\theta_p)$ for each value of the parameter of interest $\theta$.
One way to find the MLE for $\theta_p$ for each fixed $\theta$ is to notice that, as a function of $\theta_p$, $L(\theta)$ is proportional to the probability density function (pdf) of the Gamma distribution:
$$
\begin{aligned}
f(x) \propto x^{\alpha - 1}\exp\left\{-\beta x\right\}
\end{aligned}
$$
where $\theta_p$ plays the role of $x$, $(x_a+x_p+1)$ is the shape $\alpha$ and $(n_a\theta+n_p)$ is the rate $\beta$.
This observation is handy because we don't have to do any derivations for find the MLE $\widehat{\theta}_p(\theta)$. We know (from Wikipedia) that the density is maximized at the mode $(\alpha-1)/\beta$. And conveniently the mode is positive as long as $\alpha\geq1$. This holds here because the shape $\alpha$ is given by $(x_a+x_p+1)$.
Finally we plug in the MLE $\widehat{\theta}_p(\theta) = (x_a+x_p) / (n_a\theta+n_p)$ into the likelihood $L(\theta,\theta_p)$ and simplify to derive the profile likelihood $L(\theta)$.
$$
\begin{aligned}
L(\theta) &\propto
\exp\big\{-(x_a+x_b)\big\}\theta^{x_a}\left(\frac{x_a+x_b}{n_a\theta+n_p}\right)^{x_a+x_p} \\
&\propto \big(n_a\theta\big)^{x_a}\left(\frac{n_p}{n_a\theta+n_p}\right)^{x_a+x_p} \\
&\propto \left(\frac{n_a\theta}{n_a\theta+n_p}\right)^{x_a}\left(1 - \frac{n_a\theta}{n_a\theta+n_p}\right)^{x_p}
\end{aligned}
$$

Manipulating Binomial Distribution


Back up log files in Redhat Enterprise Linux 5

Question: Hai guys/gals,
How can i backup var/log files/folders ?

Log files/folders changes (log updates) should be automatically updated from original log file/folder to duplicate file/folder.
Answer: If I understand, what you need,then simplest thing might be just to specify multiple saving locations in /etc/syslog.conf, example from syslog manpage.
#Kernel messages are first, stored in the kernel
file, critical messages and higher ones also go
to another host and to the console
kern.*                       /var/adm/kernel
kern.crit                    @finlandia
kern.crit                    /dev/console
kern.info;kern.!err          /var/adm/kernel-info

As you can see, every kernel message is stored in /var/adm/kernel,and every critical kernel message will be sent to logserver on machine 'finlandia' and displayed on console as well. You will have to edit logrotate in /etc/logrotate.d/syslog, so logs will be rotated properly on your backup partition.
I believe this is better solution than backup with cron,because backup-logs are created everytime something is logged :-)
Anyway, if you will be interested in creating a backup log-server on remote machine, I recommend NSA RHEL Security Guide. Page 66. It helped us quite a lot when I was setting up a Rhel server with my classmates :-)
Comment: @AsamTheCamper I hope it's good solution for my doubt. Can you pls give some exampls ?
Comment: and How can i back up /var/log/squid/... files ?
Answer: so you want to keep only one backup and not multiple backups for different points in time? than the easiest way to go should by using rsync in crontab to get your files synced every x minutes/hours/days to another folder.


Can a dichotomous variable (yes/no) be merged with a Likert measure (1,2,3,4) using z scores?

Question: I would like to create a composite scale using items that measure parent communication extracted from a UK panel survey (n=941). However although all 6 variables in question measure similar constructs - 2 of the items are dichotomous (yes/no) the other 4 are likert (1,2,3,4). My intention is to transform the 6 variables to z scores and then sum them to form the composite score which will be used in a path analysis.  I need to know if it is correct to do this, i.e., merge dichotomous variable (yes/No) and Likert scale (1,2,3,4) after they have been standardized to z scores.
Pending this being ok, would it be necessary to do an exploratory factor analysis to ensure the the composite scale measures one underlying construct or it is enough to do a reliability analysis?
This analysis is forming part of my PhD so I need to defend what I am doing and I would appreciate any guidance anyone can give me.
Comment: The following paper offers the solution to your question. A Mathematical Theory of Ability Measure based on partial credit item response. published in J. of App. Measurement, 2015 (Vol. 1).
Answer: I'm not sure about the first part of your question. But regarding the second bit: a reliability analysis of itself does not tell you if you have one underlying construct or several. You can have a high cronbach-alpha (for reliability) in the presence of two or more factors. Definitely, do the factor analysis as well as reliability. You might also want to check out the latent variable and item response literature. Some of these models are set up to handle dichotomous and polytomous outcomes - which might deal with the z-score problem as well.
Comment: Thank you I found your answer really useful.  Regards Cody
Answer: I just checked the textbook Introduction to Meta-analysis (Chapter 7: Converting Among Effect Sizes) and it is possible to standardize the outcome measures to combine them using the z scores (as you already know). Whether or not you do this will depend on the origin of the data and how similar the questions are to each other. If you believe that the 6 questions are really asking the same thing but presented using two different effect estimates then it should be fine to combine them.
Hope this helps.
AMAS
Comment: Thank you I found your answer really useful. Regards Cody
Answer: This answer is based on another answer of mine (which I've also adapted here), but this version is adapted to your question slightly.
If you're not sure your items are all measuring the same latent construct, you probably should consider exploratory item factor analysis. See these questions for some tips:

Factor analysis of questionnaires composed of Likert items
Validating questionnaires
How to carry out a Likert scale analysis?
and possibly Can one validly reduce the numbers of items in a published Likert-scale?

If (or once) you're sure your six items are all measuring the same latent construct, you could use a partial credit model to account for differences in response scaling across all six items. If the four items with 4-point Likert scale (polytomous) measurements are all on the exact same scale though, you might be better off dropping the binary items and using a rating scale model of the four polytomous items, depending partly on how much unique and valid information you get out of those binary items. John Michael Linacre and Benjamin D. Wright posted some discussions of the differences between partial credit and rating scale models over at rasch.org that might give you a better sense of what you'd be dealing with if you go the item response theory route here.
Some latent variable analysis programs will let you set certain thresholds to be equal across certain items and leave another item's threshold freely estimated. You might be able to blend the partial credit and rating scale models this way by setting your six polytomous items' thresholds (each item will have three) to be equal across items, and estimating the binary items' single threshold independently (each could also have its own threshold, depending on how different the binary items are)...but I'm not exactly sure this is all you'd need to do to have the best of both worlds.
The simple, "classical test theory" approach that weighs every item equally would probably have you just standardize all the items and average the $z$-scores, but I don't think that's a good idea, because four-point Likert scales may not approximate a continuous dimension well enough (and a binary item definitely won't; it might not even make sense), nor can you be sure that the average of four polytomous items will be approximately continuous enough. I've seen it suggested that each item's Likert scale should have at least five options to approximate a normal distribution, and at least five Likert scale items should measure the same construct if their simple sum / average is to approximate a continuous dimension. (I've seen Berry, 1993 cited as a source for an argument that five or fewer options is unacceptable, but I haven't read it myself.)
Reference
Berry, W. D. (1993). Understanding regression assumptions. Newbury Park, CA: Sage.


Verify the multiplication of two absolute abelian group elements

Question: Question
Given that $a$ and $b$ belong to an Abelian group and that $|a|=6$ and $|b|=6$, what can you say about $|ab|$?
My solution
$$
|a|=6 \\
a=6 \\
a^6=e
$$
similarly:
$$
|b|=6 \\
b=6 \\
b^6=e
$$
hence
$$
|ab|=(ab) \\
(ab)=(ab)^6=a^6b^6=ee=e
$$
therefore, $|ab|=6$, and $ab$ belongs to $G$.
Q: Pls what sis I do wrong in answering the question???
Thanks
Answer: Saying that $|a|=6$ means that $a^6=e$ and $a^k\ne e$, for $0<k<6$.
What can you say about $|ab|$? Well,
$$
(ab)^6=a^6b^6=ee=e
$$
so $|ab|$ is a divisor of $6$. Why? This is a basic property of the order of elements in a group.
Now, try your hand at finding examples with $|a|=6$, $|b|=6$ and

$|ab|=1$
$|ab|=2$
$|ab|=3$
$|ab|=6$
Answer: Here is a simple example showing what you did wrong. Let $G=C_6$ the cyclic group of order $6$, and $a$ a generator. Then $|a|=6$. Now take $b=a^{-1}$. Then also $b$ is a generator, hence $|b|=6$. However $ab=aa^{-1}=e$ so that $|ab|=|e|=1$, contradicting $|ab|=6$.
Comment: are you saying |ab| != 6?
Comment: Yes, I am saying that $|ab|=1\neq 6$.


Is it normal to see my containerized app running when I type "ps ax" from the host OS?

Question: I have a working image that I'm able to launch containers from like so
docker run -d -p 53:53/tcp -p 53:53/udp  my_lil_bind9

When I run ps ax |grep named from the host OS I see
3197 ?  Ssl  0:00 /usr/sbin/named -g -c /etc/bind/named.conf -u bind

and I see the same thing (/usr/sbin/named -g -c /etc/bind/named.conf -u bind) from inside the running container. That seems wrong. Shouldn't I only see named running inside the container? PID of named inside the container is 1.
Am I launching the container incorrectly?
Answer: Yes, this is normal.
Everything running inside the container is visible to the host. It's a container, not a VM.
What you will NOT see in the host (by default) are port bindings. Containers run in their own namespace, so to see their own port bindings instead of the bindings of Docker you need to look in those namespaces.
Comment: This seems so counterintuitive to me. Thanks.


How would one find the uncertainty in a mean if the data points themselves have zero-order uncertainty?

Question: Sorry if this question is this community's equivalent of asking a chef how to boil water, but if you had a data set that consists of:
[A±a, B±b, C±c, ..., N±n], where each value has a corresponding zero-order measurement uncertainty (as in, if you have a ruler with 1 mm ticks, the uncertainty would be 0.5 mm), you could very easily find the mean by just summing each nominal value and dividing by the number of values. But how would you find the uncertainty in that mean?
More specifically, say you had the following data set, obtained by repeated trials of a system:
[16±0.5, 21±0.5, 22±0.5]. The mean is obviously (16+21+22)/3 = 19.7. But how would you find the uncertainty of that mean?
Comment: Are the values independent? Also, what exactly do the numbers after the $\pm$ represent? Standard deviations? Standard errors?
Comment: Hi! Are you willing to assume a probability distribution over those values?
Comment: So do you have distributions like $U(15.5, 16.5)$, $U(20.5, 21.5)$, etc?
Comment: @utobi, you lost me. I'm not sure what you mean. For reference, I am a Mechanical Engineering student with not much background in statistics.
Comment: @utobi, a uniform distribution would probably make the most sense. The values were obtained by reading what is for all intents and purposes a ruler, and the zero-order measurement uncertainty is just half of the minimum ticks on the ruler.
Comment: @COOLSerdash. The values were just measurements of the same system state for multiple trial runs. The ±, as I said in my other comment, are just half the minimum tick for the measurement.
Comment: @Dave, yes. I believe that is the best assumption to make here.
Comment: Well then perhaps a parametric bootstrap procedure will fill the bill. That is, draw randomly vectors from the (hyper)-cube and compute the average of each vector.
Comment: It depends in whether you are looking for a bound on the possible error in which case it is still $\pm 0.5$ since all the errors might go the same way, or an estimate of the likely error in which case something proportional to $\frac1{\sqrt{n}}$, or the distribution of rounding errors in which case you might be interested in a [note I wrote some time ago](http://www.se16.info/hgb/rounding.pdf)
Answer: Assuming the observations are collected independently of each other, the easiest way I can think of is to propagate uncertainty by using simulation. The idea is to generate random vectors from the (hyper-)cube and take the average of their coordinates; do this a large number of times and collect all the values obtained (the histogram below).
Here is an R code to illustrate it.
<code># set up a function to handle the simulation process
gen_x <- function() {
x = c(runif(1, 16-0.5,16+0.5),
      runif(1, 21-0.5,21+0.5),
      runif(1, 22-0.5, 22+0.5))
return(mean(x))
}

N=1e+4

# evaluate the function N times
hh <- sapply(1:N, function(x) gen_x())
hist(hh)
abline(v = mean(c(16,21,22)))
</code>

The histogram shows the distribution of the average of 16,21,22 taking into account the uncertainty of $\pm 0.5$ and assuming independent uniform distributions centred at the given values. The vertical line shows the sample average $(16+21+22)/3$.
The above solution gives the entire distribution of the sample average. If you are only interested in the variance of the sample average, then that's just equal to $1/(12n)$. Indeed, If you denote the sample $X_1,\ldots,X_n$, setting $\bar X = n^{-1}\sum_i X_i$ the sample average and assuming $X_i$ are independent, we have
$$
\text{var}(\bar X) = n^{-2}(\text{var}(X_1)+\cdots +\text{var}(X_n)) = n^{-2}\frac{n}{12} = (12n)^{-1}.
$$
Here I have used the fact that if $X \sim \text{Unif}(a,b)$, then $\text{var}(X) = (b-a)^2/12$.
So to sum up, if your $n$ samples are independent and the measures can be thought of as $\pm 0.5$ around the value measured, then, under the uniform assumption of the measure within each interval, the variance of the average is $(12n)^{-1}$.
Comment: Wouldn't the variance of the mean of $n$ uniform distributions each with a range of $1$ be $1/(12n)$? In this case, $1/36$ which agrees with your simulation.
Comment: @COOLSerdash: yes you are correct. I'll update my answer adding the analytical approach based on your suggestion.


Why is 'git clone' not working with submodule?

Question: I could not clone the parent project with submodules. Only parent project was cloned.
I tried with

git clone --recurse-submodules <repor>
git clone --recursive <repo

And so many options.
Do I need to configure my Git environment to support submodules?
Here it is repositories I have tried.
Parent project
https://github.com/chamlyidunil/test-submodule-project
Common project (submodule)
https://github.com/chamlyidunil/common-utility
And it really helps you if you can provide example Git commands for the whole cycle.

git pull (get update with sub modules)

My Git version is 2.15.1 (Apple Git-101).
Comment: What do you mean when you say "didn't work"? What is the actual outcome? An error message? Unexpected behavior? You need to provide as much detail as possible when asking a question. Just saying that something "didn't work" is not enough for people reading this question.
Comment: Are you passing `--recurse-submodules` to `git pull`?
Comment: Yes I did try those options.
Comment: it just clone parent project. it not cloning submodules.
Answer: Your project has a .gitmodules file, but it doesn't have an actual submodule commit checked in.
If you want to add a submodule, you should use git submodule add to add the submodule and then commit the result.  That will add the submodule commit into the repository, which your repository is lacking at the moment.
So, for example, in your personal clone of the parent project, you'd remove the current .gitmodules file and run git submodule add https://github.com/chamlyidunil/common-utility.git common-utility and then commit the result.
Comment: Thanks for the update. i have commit .gitmodules as you said. can i know what field is missing here ?
Comment: You mean should i commit and push common-utitliy with my parent project rather than keeping reference link in parent project
Comment: I mean you should use `git submodule add` to add the submodule to your main repository.  It does more than just create a `.gitmodules` file; it creates a submodule object in the repository itself which is required for things to work.


How to add additional dependencies to chrome standalone image

Question: I am trying to run chrome container.
This works for me:
[practice]$ docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome
b7d63881869721fe66a4f00de4be7a3bfb8e922410776a7c35f827bfd08f9455
[practice]$ docker container ls
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS              PORTS                    NAMES
b7d638818697        selenium/standalone-chrome   "/opt/bin/entry_poin…"   22 seconds ago      Up 22 seconds       0.0.0.0:4444->4444/tcp   lucid_sammet

But my requirement is to have an additional package inside my container, so i created a DockerFile
FROM selenium/standalone-chrome

FROM node:latest
RUN npm install --save @ffmpeg-installer/ffmpeg

And created a build using:
[practice]$ docker build -t mychrome:1.0 .
Sending build context to Docker daemon  15.34MB
Step 1/3 : FROM selenium/standalone-chrome
 ---> c84475653f71
Step 2/3 : FROM node:latest
 ---> a511eb5c14ec
Step 3/3 : RUN npm install --save @ffmpeg-installer/ffmpeg
 ---> Using cache
 ---> 2d04ced6065c
Successfully built 2d04ced6065c
Successfully tagged mychrome:1.0

But when i create container, it gets killed by itself.
[practice]$ docker run -d -p 4444:4444 -v /dev/shm:/dev/shm mychrome:1.0
1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211
[practice]$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Here are docker inspect:
[practice]$ docker container ls -a
CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS                           PORTS               NAMES
1e6416ff6d23        mychrome:1.0                  "docker-entrypoint.s…"   2 minutes ago       Exited (0) 2 minutes ago                             compassionate_panini
b2dcd66a3f97        mychrome:1.0                  "docker-entrypoint.s…"   2 minutes ago       Created                                              elegant_mcc
[practice]$ docker inspect 1e6416ff6d23
[
    {
        "Id": "1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211",
        "Created": "2020-05-09T06:51:21.8510204Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "node"
        ],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-05-09T06:51:22.1525569Z",
            "FinishedAt": "2020-05-09T06:51:22.331137Z"
        },
        "Image": "sha256:2d04ced6065c32a7f1e2d3d28988302b7e762533f7964b8bcbe344f05ba65fdc",
        "ResolvConfPath": "/var/lib/docker/containers/1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211/hostname",
        "HostsPath": "/var/lib/docker/containers/1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211/hosts",
        "LogPath": "/var/lib/docker/containers/1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211/1e6416ff6d232cc7fb1990ac5ae425af72d6456ec2a94d6b575431edb9e04211-json.log",
        "Name": "/compassionate_panini",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/dev/shm:/dev/shm"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "4444/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "4444"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/55f20b215a1ff36c8ebb1dff18cac13e9b0a8fb30d5e81a7bd98c8d259a53cde-init/diff:/var/lib/docker/overlay2/d9ffce8fb048fc9b3f06d8bf9722848e1c634fa62c6cddf3b81c8fd69f168d15/diff:/var/lib/docker/overlay2/ac6f63198e071b53404e7f46a18e442fbb3940bd1ab33689b14c3cefd0cec63f/diff:/var/lib/docker/overlay2/27e169d3a5ecd1eb5a1a169fd295b8bcb01c03bb0de80609bf1f8b807a922ab0/diff:/var/lib/docker/overlay2/1bc8d050ec3936a42bfc5274d3857b0b507245798226de02db185a4bed2ee505/diff:/var/lib/docker/overlay2/e51f7d0d89f2480c94a247f4fece58ba82ecf0139b3d066a7154f74ea196fb67/diff:/var/lib/docker/overlay2/6a241e18bf0fed51affe0f856b9a685d81db7ecd3b5e73754ce94d3a77e66173/diff:/var/lib/docker/overlay2/8c2950f8c31da7a939c93f9fe187c52eea8317a4b64ee2c3b75b09e2db924ce5/diff:/var/lib/docker/overlay2/1fce7515c1871f43e30f3761ef340c8a85fc7de0c3902299db206a2ba0461bd3/diff:/var/lib/docker/overlay2/84d7667120601df8ff0c8187d350fe3700611a7eb9294dde6d6ce8343150551d/diff:/var/lib/docker/overlay2/26c37b434064f095df1114f55e37487094c1efcd8c4bb7b40507da171553210c/diff",
                "MergedDir": "/var/lib/docker/overlay2/55f20b215a1ff36c8ebb1dff18cac13e9b0a8fb30d5e81a7bd98c8d259a53cde/merged",
                "UpperDir": "/var/lib/docker/overlay2/55f20b215a1ff36c8ebb1dff18cac13e9b0a8fb30d5e81a7bd98c8d259a53cde/diff",
                "WorkDir": "/var/lib/docker/overlay2/55f20b215a1ff36c8ebb1dff18cac13e9b0a8fb30d5e81a7bd98c8d259a53cde/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/dev/shm",
                "Destination": "/dev/shm",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "1e6416ff6d23",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "4444/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NODE_VERSION=14.1.0",
                "YARN_VERSION=1.22.4"
            ],
            "Cmd": [
                "node"
            ],
            "Image": "mychrome:1.0",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "c14a931bf5ad40900b83e8f1ee770d270765af1ff181ff610ed2b564d12e3f13",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/c14a931bf5ad",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "51bc10f592d1c05978822f1f5c8a108dffa0581fd6c639e73984bf0760831564",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

Please let me what is wrong here.
Answer: got it working by using this dockerfile:
FROM node:latest AS node_base

RUN echo "NODE Version:" && node --version
RUN echo "NPM Version:" && npm --version
RUN npm install --save @ffmpeg-installer/ffmpeg
RUN echo "NPM Modules:" && npm ls

FROM selenium/standalone-chrome

USER root

COPY --from=node_base . .

RUN echo "NPM Modules:" && npm ls

RUN echo "file ends..."