Como contar as mudanças de estado em campos com determinada classe dentro de uma função?

Question: Como faço para contar quantas mudanças ocorrem em todos os campos de um formulário com uma determinada classe?
Update: O que quero saber é se houve qualquer mudança em cada campo (one), e não quantas vezes houve mudança em cada campo (mesmo que o usuário mude a opção, conta apenas como uma vez - a primeira...). Resumindo, apenas quantos campos com a classe em questão foram modificados uma vez (pelo menos).
Por exemplo:
$("select, input").one('change', function () {

    var totalSelect = $('select').length;
    var totalInputs = $('input').length;
    var ocultosOuOpcionais = $('.ocultosOuOpcionais').length;
    var ocultosOuOpcionaisMudados = ?????
    var total = (totalInputs + totalSelect + ocultosOuOpcionaisMudados) - ocultosOuOpcionais;
});

Toda vez que houver uma mudança de estado em alguns dos campos com a classe .ocultosOuOpcionais, quero atualizar a variável ocultosOuOpcionaisMudados. Como posso fazer isso?
Answer: Você pode usar data-attributes para "armazenar" o estado do elemento. Por exemplo, ter um elemento (input, select, textarea) com o atributo data-foi-modificado:
<input type='text' data-foi-modificado />

E com JQuery você pode mudar esta propriedade:
$('input').one('change', function(){
  $(this).data('foi-modificado', true);
});

Posteriormente você pode fazer um filtro ou usar o próprio seletor para obter somente os elementos que estiverem com foi-modificado = "true". Segue um exemplo testando alguns elementos:

$(function(){

  // Quando houver mudança ou perder o foco, o atributo 'foi-modificado'
  // passará a ter valor 'true'.
  $('.ocultosOuOpcionais').one('change', function(){
   $(this).data('foi-modificado', true);
  });

  $('button').on('click', function(){
 // Filtrando todos em que 'foi-modificado' é true.
    var modificados = $('.ocultosOuOpcionais').filter(function(){
     return $(this).data('foi-modificado');
    });

    var mensagem = 'Modificados: ';
    modificados.each(function(indice, elemento){
     mensagem += $(elemento).prop('name') + ', ';
    });
    alert(mensagem);
  });
});
span { display: inline-block; width: 100% }

  1. <input class='ocultosOuOpcionais' type='text' name='1' data-foi-modificado/>

  2. <input class='ocultosOuOpcionais' type='number' name='2' data-foi-modificado/>

  3. <input class='ocultosOuOpcionais' type='color' name='3' data-foi-modificado/>

  4. <input class='ocultosOuOpcionais' type='tel' name='4' data-foi-modificado/>

  5. <select class='ocultosOuOpcionais' name='5' data-foi-modificado>
    <option selected>A</option>
    <option>B</option>
  </select>

  6. <input class='ocultosOuOpcionais' type='radio' name='6' data-foi-modificado/>

  7. <input class='ocultosOuOpcionais' type='checkbox' name='7' data-foi-modificado/>

<button>Quem foi Modificado?</button>
Comment: Legal, é bem isso mesmo, mas de uma forma mais elegante! +1
Comment: E agora hehe como incluo isso na outra pergunta que você respondeu? :-) Tipo, alguns campos daquela outra pergunta estão com `display=none`, então quando muda um select por exemplo, abre um campo que não está contabilizado... apesar que não sei, no seu código da outra pergunta isso já está resolvido? Porque por exemplo, pode ter 10 campos, mas apenas 8 visíveis, e se não escolher uma determinada opção, esses dois não abrirão. Neste caso a barra não vai acabar de completar antes? Deu pra entender?
Comment: Se o elemento estiver somente escondido com CSS, ele existe no documento e será contado. Não contaria se os inputs fossem criados dinamicamente
Answer: Bem, basicamente o que entendi é que você deseja capturar as mudanças de cada elemento da classe ocultosOuOpcionais e depois somá-los:
Capturando a diferença de caracteres
Como vem explicado nessa pergunta a melhor maneira de se calcular a diferença entre duas strings é utilizando o algoritmo da Distância de Levenshtein:
function levenshtein(str1, str2) {
  var m = str1.length,
      n = str2.length,
      d = [],
      i, j;

  if (!m) return n;
  if (!n) return m;

  for (i = 0; i <= m; i++) d[i] = [i];
  for (j = 0; j <= n; j++) d[0][j] = j;

  for (j = 1; j <= n; j++) {
    for (i = 1; i <= m; i++) {
      if (str1[i-1] == str2[j-1]) d[i][j] = d[i-1][j-1];
      else d[i][j] = Math.min(d[i-1][j], d[i][j-1], d[i-1][j-1])+1;
    }
  }
  return d[m][n];
}

Nesse meu exemplo a função recebe o nome de captureChanges().
Para capturar essa diferença do valor inicial e atual de uma input, usa-se o .defaultValue e o .value, respectivamente. Eu adaptei ao seu código da seguinte maneira:
var ocultosOuOpcionais = [].slice.call(document.querySelectorAll(".ocultosOuOpcionais"));
var mudados = [];
var mudancas = [];
var ocultosOuOpcionaisMudados = 0;

ocultosOuOpcionais.forEach(function (input, indice) {
  input.addEventListener("input", function (event) {
    if (event.target.defaultValue == event.target.value) {
      mudados[event.target.id] = 0;
    } else {
      mudados[event.target.id] = event.target.defaultValue;
    }
    mudancas[indice] = captureChanges(mudados[event.target.id], event.target.value);
  });

O código acima é uma adaptação ao JsFiddle do TobyMosque presente nos comentários da pergunta.
Feito isso, basta somar as diferenças de cada input:
input.addEventListener('keyup', function(){
  mudancas.forEach(function(el, index){
    ocultosOuOpcionaisMudados += parseFloat(el);
  })
  ocultosOuOpcionaisMudados = 0; // É importante que ao final se zere o valor para que não se acumule exacerbadamente
})

Juntando todo o código

function captureChanges(str1, str2) {
  var m = str1.length,
    n = str2.length,
    d = [],
    i, j;

  if (!m) return n;
  if (!n) return m;

  for (i = 0; i <= m; i++) d[i] = [i];
  for (j = 0; j <= n; j++) d[0][j] = j;

  for (j = 1; j <= n; j++) {
    for (i = 1; i <= m; i++) {
      if (str1[i - 1] == str2[j - 1]) d[i][j] = d[i - 1][j - 1];
      else d[i][j] = Math.min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]) + 1;
    }
  }
  return d[m][n];
}

var ocultosOuOpcionais = [].slice.call(document.querySelectorAll(".ocultosOuOpcionais"));
var mudados = [];
var mudancas = [];
var n = 0;
var ocultosOuOpcionaisMudados = 0;

ocultosOuOpcionais.forEach(function(input, indice) {
  input.addEventListener("input", function(event) {
    if (event.target.defaultValue == event.target.value) {
      mudados[event.target.id] = 0;
    } else {
      mudados[event.target.id] = event.target.defaultValue;
    }
    mudancas[indice] = captureChanges(mudados[event.target.id], event.target.value);
  });
  input.addEventListener('keyup', function() {
    mudancas.forEach(function(el, index) {
      n += parseFloat(el);
    })
    ocultosOuOpcionaisMudados = n;
    n = 0;

    document.getElementsByTagName("h4")[0].innerHTML = "Mudanças no total:";
    document.getElementsByTagName("p")[0].innerHTML = ocultosOuOpcionaisMudados;
  })
});
<input type="text" class="ocultosOuOpcionais">

<input type="text" class="ocultosOuOpcionais">

<input type="text" class="ocultosOuOpcionais">

<input type="text" class="ocultosOuOpcionais">

Comment: Outra excelente resposta! O SOpt é demais ou não é!? :-)


Taylor series $x\ln(2+x)$ about $0$

Question: I am trying to obtain Taylor serie from  $x\ln(2+x)$ about $0$, but somehow i dont get right solution which is:
$$\sum_{n=1}^{\infty} \dfrac{(-1)^{(n+1)}x^{n+1}}{n2^{n}}$$
here are derivates i get :
$$f'(x) =\ln(2+x) + \left.\dfrac{x}{(2+x)} \right.$$
$$f''(x) = \left.\dfrac{1}{(2+x)} \right.+\left.\dfrac{2}{(2+x)^2} \right. $$
$$f'''(x) = -\left.\dfrac{1}{(2+x)^2} \right.-\left.\dfrac{4}{(2+x)^3} \right. $$
$$f''''(x) = \left.\dfrac{2}{(2+x)^3} \right.+\left.\dfrac{12}{(2+x)^4} \right. $$
i tried with $$\sum_{k=0}^{\infty} \dfrac{f^{(k)}(0)}{k!}\cdot x^k$$
but couldnt get right result.
Comment: [This](http://www.wolframalpha.com/input/?i=Table%5BD%5Bx*Log%5B2%2Bx%5D,%7Bx,n%7D%5D,%7Bn,1,5%7D%5D) may help you find the mistake.
Comment: Your given solution is most certainly wrong.  The coefficient of $x^1$ is most certainly $\ln(2)$
Answer: Disclaimer: The given solution is wrong.

It's easier to consider simpler functions than directly taking derivatives.  For starters:
$$g(x)=\ln(1+x)\\g'(x)=\frac1{1+x}\\g''(x)=-\frac1{(1+x)^2}\\g'''(x)=\frac2{(1+x)^3}\\\vdots\\g^{(k)}(x)=(-1)^{k+1}\frac{(k-1)!}{(1+x)^k}\\g(0)=0\\g^{(k)}(0)=(-1)^{k+1}(k-1)!$$
Plugging this all in, we get
$$g(x)=g(0)+\sum_{k=1}^\infty\frac{(-1)^{k+1}(k-1)!}{k!}x^k=\sum_{k=1}^\infty\frac{(-1)^{k+1}}kx^k$$

$$\ln(1+x)=\sum_{k=1}^\infty\frac{(-1)^{k+1}}kx^k\tag1$$

Now let $x\mapsto x/2$ to get
$$\ln\left(1+\frac x2\right)=\sum_{k=1}^\infty\frac{(-1)^{k+1}}{k2^k}x^k$$
Add $\ln(2)$ to both sides:
$$\begin{align}\ln\left(1+\frac x2\right)+\ln(2)&=\ln(2+x)\\&=\ln(2)+\sum_{k=1}^\infty\frac{(-1)^{k+1}}{k2^k}x^k\end{align}$$
Finally, multiply both sides by $x$ to finish:

$$x\ln(2+x)=x\ln(2)+\sum_{k=1}^\infty\frac{(-1)^{k+1}}{k2^k}x^{k+1}\tag2$$
Answer: hint
$$\ln(2+x)=\ln(2)+\ln(1+x/2) $$
$$=\ln (2)+\frac {x}{2}-\frac {x^2}{8}+.. $$
Answer: For $|x|<1$ we have $\ln(1+x)=\sum_{n=1}^{\infty} \dfrac{(-1)^{(n+1)}x^{n}}{n}$
Your turn !
Answer: Do not use the formula with derivatives to compute a Taylor series! Do you really want to compute an infinite number of derivatives?
Use the fact that for $|x| < 1$, $$\ln(1+x)=\sum_{n=1}^{\infty} (-1)^{n+1} \dfrac{x^n}{n}$$
Then $$x \ln(2+x)=x \ln(2(1+x/2))=x \ln(2) + x\ln(1+x/2) = x \ln(2) + x\sum_{n=1}^{\infty} (-1)^{n+1} \dfrac{x^n}{n2^n}$$

Taylor series $x\ln(2+x)$ about $0$


How can I disable capitalized input?

Question: How can I prevent user uppercase letters input with
user = get.chomp

if I don`t want use
user.downcase!

I want user can`t input uppercase letters
Comment: "Preserve the user's original capitalization" means that capital letters in what the user typed should remain in the input string.  However, the rest of the question asks how to prevent the input of capitalized letters at all.  These two things contradict each other.  Can you please edit the question to be more clear?
Answer: Yes you can do that in the following way, getch takes one character at a time.
One caviat: you need to end the string with two returns.
Keep in mind that this is only the console, if you want more or fancier control use a simple GUI framework like eg Shoes of use a web-interface.
require 'io/console'

input, user = "", ""
while input != "\n"
  input = STDIN.getch
  if ('a'..'z').include? input
    print input
    user += input
  end
end
puts "\nuser = #{user}"

Answer: If you want to verify that it's all downcase the easy way is:
user = gets.chomp

if (user == user.downcase)
  # All downcase
end

You can also use a regular expression:
user = gets.chomp

if (user.match(/\A[a-z]\z/)
  # All downcase
end

That will let you customize which characters are allowed, like if _ is acceptable.
You can't prevent them from typing in upper-case letters unless you do a lot of work with something like Curses to process individual keystrokes and assume control over echoing output. This is a ton of work and I wouldn't recommend it.
Comment: Note that Ruby 2.4 is needed for `user == user.downcase` with accented characters.

How can I disable capitalized input?


Using Supervisord, how can I start a brand new worker via supervisorctl without restarting other workers?

Question: Let's say I have a number of existing workers running in supervisord. I want to add a new worker to the group as well as start the new worker. I perform the following steps:

I modify the file /etc/supervisor/supervisord.conf and add the new worker config
Back on the command line, I enter sudo supervisorctl
I run reread to read the new configuration file settings.
Attempting to run start workers:exampleWorkerName gives the error workers:"exampleWorkerName": ERROR (no such process)

So, my question is, how can I start this new worker process without affecting my other existing workers? I'd rather not perform a supervisorctl reload or /etc/init.d/supervisord restart command.
Answer: You also need to run supervisorctl update.
Comment: Running `supervisorctl update` will unfortunately restart all workers. Here's a sample of the output: `workers: stopped` followed by `workers: updated process group`. The worker status shows they were all restarted.
Comment: I should probably also say that I am using groups allowing me to restart all workers at once, so this might be the cause.
Answer: This command only updates the changes
supervisorctl reread

Restarts the applications whose configuration has changed.
supervisorctl update.

and
supervisorctl restart all

Answer: If you are still interested, after running
supervisorctl reread

you can try running
supervisorctl add <newWorker>


Green operator of Dirichlet problem is compact

Question: Let $\alpha \in (0,1]$, $\Omega \subset \mathbb R^n$ open bounded and the problem
$$ \left\lbrace \begin{array}{r c l c l}
- \Delta u&=&0&\operatorname{on}& \Omega \\
u&= & h&\operatorname{on}& \partial \Omega
\end{array} \right. \tag{DP}
$$
My exercise assume I know that forall $h \in C^{0,\alpha}(\overline \Omega)$ there is a unique $u \in C^{2,\alpha}(\overline \Omega)$ solution of (DP). Then let $T : C^{0,\alpha}(\overline \Omega) \longrightarrow C^{2,\alpha}(\overline \Omega)$ be the mapping $h \longmapsto u$, we admit it is linear bounded (linear easy).
Exercise: Show that $T :  C^{0,\alpha}(\overline \Omega)  \longrightarrow  C^{0,\alpha}(\overline \Omega) $ is a compact operator.
Attempt: Let $(h_j)$ be a bounded sequence of $ C^{0,\alpha}(\overline \Omega) $, we show $(Th_j)$ has a limit point in $ C^{0,\alpha}(\overline \Omega) $. Since $T :  C^{0,\alpha}(\overline \Omega)  \longrightarrow  C^{2,\alpha}(\overline \Omega) $ is bounded, $(Th_j)$ is bounded in $ C^{2,\alpha}(\overline \Omega) $. So by Ascoli-Arzelà there is $\sigma$ extraction and $u \in C^1(\overline \Omega)$ such that
$$
Th_{\sigma(j)} \xrightarrow[j \infty]{C^1(\overline \Omega)} u.
$$
It remains only to get the convergence of the $[\cdot ]_\alpha$ semi-norm, it is enough because then $u \in C^{0,\alpha}(\overline \Omega)$ and $(Th_{\sigma(j)})$ goes to $u$ in $C^{0,\alpha}(\overline \Omega)$-norm. If $\Omega$ is convex I can use the mean value inequality
\begin{align}
[Th_{\sigma(j)} - u ]_\alpha &= \sup_{x \neq y \in \Omega} \frac{|(Th_{(\sigma(j)}-u)(x)- (Th_{(\sigma(j)}-u)(y)|}{|x-y|^\alpha} \\
&\leq \sup_{x \neq y \in \Omega} \frac{1}{|x-y|^\alpha} \sup_{(x,y)}|(Th_{\sigma(j)}-u)'| \times |x-y| \\
&\leq \operatorname{diam}(\Omega)^{1-\alpha}||Th_{\sigma(j)}-u||_{C^1(\Omega)}
\end{align}
and finish the proof.$\square$
The problem is to control $[Th_{\sigma(j)} - u ]_\alpha$ when $\Omega$ is not convex. I suspect the problem is not consistent when $\Omega$ is not connected because in general solving differential equations on non connected sets boils down to solve the equation on each component and patch everything.
If $\Omega$ is connected (by path) I think there is a way to save my proof method, for any $\gamma :[0,1] \longrightarrow \Omega$ curve that verifies the Rolle's hypothesis and that links $x$ and $y$ the mean value inequality applied to $(Th_{(\sigma(j)}-u )\circ \gamma$ gives
$$
|(Th_{(\sigma(j)}-u)(x)- (Th_{(\sigma(j)}-u)(y)| \leq || \gamma ||_{C^1(0,1)} \sup_{(0,1)} |(Th_{(\sigma(j)}-u)' \circ \gamma| \leq || \gamma ||_{C^1(0,1)}  ||Th_{(\sigma(j)}-u||_{C^1(\Omega)}.
$$
Then denoting $\mathcal A_x^y$ the set of such curves we can consider the following metric on $\Omega$
$$
d(x,y) = \inf\{ || \gamma ||_{C^1(0,1)} : \gamma \in \mathcal A_x^y \}
$$
which looks like the geodesic metric and is such that
$$
|(Th_{(\sigma(j)}-u)(x)- (Th_{(\sigma(j)}-u)(y)|  \leq d(x,y) ||Th_{(\sigma(j)}-u||_{C^1(\Omega)}
$$
whence
$$
[Th_{\sigma(j)} - u ]_\alpha \leq ||Th_{(\sigma(j)}-u||_{C^1(\Omega)} \sup_{x \neq y \in \Omega} \frac{d(x,y)}{|x-y|^\alpha}.
$$
If the last supremum is finite the I am done.
Question:

Is the last supremum finite? I think it should depend on the geometry of $\Omega$ but still, having a result for a small class of open sets would be nice

How could I finish the proof of $T$ compact?
Answer: Here is an answer to my problem, in fact we just need to prove that a $C^1$ function on a compact set is Lipschitz.
Claim: Let $\Omega \subset \mathbb R^n$ open bounded with $C^1$ boundary and $f \in C^1(\overline \Omega ; \mathbb R)$. Then $f$ is Lipschitz.
Proof: First note that $f'$ is bounded on $\overline \Omega$ so by the mean value inequality, any $x \in \Omega$ has a convex neighborhood on which $f$ is Lipschitz. Then assume by contradiction that $f$ is not Lipschitz, there is $(x_j),(y_j)$ two sequences of $\Omega$ such that
$$
x_j \neq y_j,\quad \frac{|f(x_j)-f(y_j)|}{|x_j-y_j|} \longrightarrow + \infty.
$$
Then by compactness of $\overline \Omega$ we can assume without loss of generality that
$$
x_j \longrightarrow x \in \overline \Omega,\quad y_j \longrightarrow y \in \overline \Omega
$$
and since $f$ is continuous on $\overline \Omega$ we must have $x = y$, otherwise the latter quotient has a finite limit. It must be that $x \in \partial \Omega$ because otherwise $x \in \Omega$ where $f$ is locally Lipschitz. So use the regularity of $\partial \Omega$ to introduce $\phi : B(x,r) \longrightarrow B(0,1)$ a $C^1$-diffeomorphism such that
$$
\phi(\Omega \cap B(x,r)) = B(0,1) \cap \{ x_n > 0 \},\quad \phi(\partial \Omega \cap B(x,r)) = B(0,1) \cap \{ x_n = 0 \}.
$$
Then $f \circ \phi^{-1} : B(0,1) \cap \{ x_n > 0 \} \longrightarrow \mathbb R$ is of class $C^1$ on an open convex set and up to shrink $r$ and $B(0,1)$ we can assume that $(\phi^{-1})'$ is bounded, so that $f \circ \phi^{-1}$ has bounded derivative. Thus it is Lipschitz and for $j$ large so that $x_j,y_j \in B(x,r)$ we have
\begin{align}
 \frac{|f(x_j)-f(y_j)|}{|x_j-y_j|} &= \frac{|f \circ \phi^{-1} \circ \phi (x_j) - f \circ \phi^{-1} \circ \phi (y_j)|}{|\phi(x_j) - \phi(y_j)|} \frac{|\phi(x_j)-\phi(y_j)|}{|x_j-y_j|} \\
&\leq \operatorname{Lip}(f \circ \phi^{-1})\operatorname{Lip}(\phi),
\end{align}
contradiction.$\square$


Why is insert function always appending at end of linked list?

Question: I have written this code to insert into a linked list by position.
void insert(node *list, int data, int position) {
    int c;

    node *temp;
    node *prev;
    node *curr;

    curr = list;

    temp = malloc(sizeof(node));
    temp->num = data;

    if (curr == NULL) {
        curr = temp;
        curr->next = NULL;
    } else {
        while (curr != NULL && c != position) {
            prev = curr;
            curr = curr->next;
            c++;
        }
        if (c = 0) {
            temp->next = curr;
            curr = temp;
        } else if (curr == NULL) {
            prev->next = temp;
        } else {
            prev->next = temp;
            temp->next = curr;
        }
    }
}

However, I believe this block always executes no matter what and the data gets appended to the end of the linked list.
else if (curr == NULL) {
      prev->next = temp;

Why is curr always null? It should not get to null if the position is less than the amount of elements in the list...
Comment: First of all: `int c = 0;`
Answer: You haven't initialized c variable to 0 at the beginning. Also the condition
if(c = 0) should have been if(c == 0)
temp->next = NULL should also be done after temp->num = data else it will remain uninitialized in case of
      else if (curr==NULL) {
               prev->next=temp;
      }

These are few that I noticed.
Answer: There are multiple problems in your code:

local variable c is not initialized. Using it without prior initialization invokes undefined behavior. You should define it this way:
int c = 0;

the test if (c = 0) sets the value of c to 0 and always fails.  Use the == operator instead:
if (c == 0) {
    ...

You must return list and set list to curr is the element was inserted at the start of the list (position 0) or if the list was empty.

Here is an improved version:
node *insert(node *list, int data, int position) {
    node *temp = malloc(sizeof(node));
    if (temp == NULL) {
        return NULL;
    }
    temp->num = data;
    if (list == NULL || position <= 0) {
        temp->next = list;
        return temp;
    } else {
        node *curr = list;
        while (position-- > 0 && curr->next != NULL) {
            curr = curr->next;
        }
        temp->next = curr->next;
        curr->next = curr;
        return list;
    }
}

Comment: `void insert` ---> `node *insert`    ;)
Comment: How can you return a node* or NULL from a void function?
Comment: @user3283146: answer corrected. It needed to be *improved* further ;-)
Answer: You have a local variable there: c.
That variable has automatic storage and its start value is indeterminate.
You have to init it.
int c = 0;

Otherwise its initial value can be whatever a register old value or memory garbage at the moment the function is called, so
while (curr!=NULL && c != position)

behavior is undefined.

Moreover the if check after the while is bugged: relational operator for equality is ==
if (c=0)

must be
if (c==0)

Otherwise you are assigning 0 to c instead of test its value.


Drupal 8 : Render a field collection item in a Twig template

Question: In Drupal 8, I have a content type which use Field Collection Module like that :

field_body (FieldCollection, repeatable)

field_image_alignment(Boolean)
field_picture (Image)
field_free_text (Long Text)

I want to theme this fields.
I overrided the field template with a file named field--node--field-body--news.html (news is the content type that contains theses fields.).
Default template is this :
{% for item in items %}

{{ item.content }}

{% endfor %}

And my template overrided is like that :
{% for item in items %}
  {% if item.content['#field_collection_item'].field_image_alignment.value == 1 %}
    {{ dump(item.content['#field_collection_item'].field_picture) }}
    {% endif %}
{% endfor %}

How can I render "child" fields field_pictures, field_free_text ?
I used item.content['#field_collection_item'].field_image_alignment.valueto access to the plain value but I would like to have the rendered view.
Thanks a lot.
Answer: I've just started learning Drupal and encountered the same issue.
I solved it by creating custom field formatter:
public function viewElements(FieldItemListInterface $items, $langcode)
{
  $elements = array();
  foreach ($items as $delta => $item)
    if ($item->value !== NULL)
    {
      $builder    = \Drupal::entityTypeManager()->getViewBuilder('field_collection_item');
      $elements[] = $builder->build($builder->view($item->getFieldCollectionItem()));
    }
  return $elements;
}

Answer: Use this module for Nice Table format Look
Link: https://www.drupal.org/project/reference_table_formatter
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.  I also don't see how this module helps at all with this situation?


Kubernetes: What is the use of resource limit if we already have an HPA?

Question: Say I have resource requests and limits set to
resources:
  requests:
    cpu: "100m"
    memory: "512Mi"
  limits:
    cpu: "500m"
    memory: "1024Mi"

and targetCPUUtilizationPercentage set to 80,
so when more than 80m of CPU is utilized by pods on average, it will auto-scale.
So, what i want to understand is that the resource limit in this case will be useless, right? Or, does it play any role?
Comment: `resrouces.limits.cpu` throttles container CPU use, regardless how many pods run across the cluster. You may have 1000 of them deployed with the help of HPA, but each of them may not use more than `resrouces.limits.cpu` cpu shares.
Answer: As Zerkms has said the resource limit is per container.
Something else to note: the resource limit will be used for Kubernetes to evict pods and for assigning pods to nodes. For example if it is set to 1024Mi and it consumes 1100Mi, Kubernetes knows it may evict that pod.
If the HPA plus the current scaling metric criteria are met and Kubernetes is supposed to scale up the replicaset it will check the memory of the nodes and the memory requests of the pods before scheduling a pod for a node.
Comment: It's not kubernetes that would evict it, it's kernel would OOM.


How to retrieve all fields from database in yii framework

Question: i'm implementing line chart in my application using flot extension. I'm fetching one value  and a plot graph. I'm fetching one field like this....
foreach ($model->getGraphData()->getData() as $row) {

    $data[]=array($row['id'],$row['height']);

}

I've weight, height, chest, hips, biceps fields in my database. Can i know how to retrieve all fields in one variabl $data[].
And my model part is...
public function getGraphData()
{
    $criteria=new CDbCriteria;
    //$criteria->addCondition('CreatedDate > datetime(\'now\', \'-1 day\', \'localtime\')');

    $sort = new CSort();
    $sort->defaultOrder='updatedDate';

    return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'sort'=>$sort,
            'pagination'=>false,
    ));
}

Comment: Do you mean that you want something like array_value() to be used with $row ?
Answer: Try with this:
foreach ($model->getGraphData()->getData(true) as $row) { ...

Set 'true' as parameter in 'getData()' method.
Comment: Actually i'm getting only one field.

 `$data[]=array($row['id'],$row['height']);`
If i give weight instead of height its plotting weight values..So, can i know how to provide all fields here..
Comment: in $row now you have a object with all attributes, then try this:

foreach ($model->getGraphData()->getData(true) as $row) {

    $data[]=$row;

}


How do I create a complete record with inheritance type delegation?

Question: example/models/example.py
class Example(models.Model)
    _name = 'example.model'

    product_tmpl_id = fields.Many2one('product.template','Product Template',delegate=True,ondelete='cascade',required=True)

example/models/product_template.py
class ProductTemplate(models.Model)
    _inherit='product.template

    example_ids = fields.One2many('example.model','product_tmpl_id',string='Item')

example/views/example.xml
<form>
    <field name="product_tmpl_id" widget="many2one"/>
</form>

My understanding was that a product_template record would be automatically created with example, but this field is required and not letting me save a new record. When I perform an import of the example data adding these columns at the beginning for product_template ("exampleNN", "name", "type", "categ_id/id", "sale_ok", "purchase_ok",...) I get a matching product template with an id of "exampleNN_product_template" and identical name (though example does not have name so it must be using product template).
Comment: When you use delegation don't use Many2one instead use the fields of product template like they are the same model. You don't have to manually create related fields you have acces to all template fields like they are declared inside your new model
Answer: product_tmpl_id does not like being on the form view as it is required, yet not created yet with delegation inheritance. I used tree view instead to see product_tmpl_id. I was curious about its value after doing an import.


"Robo-Humano" Inteligente

Question: Estou fazendo um "humanozinho" que você manda mensagem, e ele te responde.
Exemplo: Se você manda "Oi"  ele te responde  "Olá, tudo bem?".
Sei que isso é básico, pode usar um switch.
switch($mensagem){
case "Oi":
    $responder  = "Ola";
    break;
case "xau":
    $responder = "Xau!";
    break;
}

Mas eu gostaria de identificar automaticamente o que ele digitar.
Exemplo: Se eu escrever uma frase "Olá, qual seu nome", ele identificaria "nome" e "olá" na frase e responderia "Olá, meu nome é João prazer!"
O que devo estudar e aprender para fazer um protótipo deste nível?
Comment: Que tal?  https://www.wired.com/2014/04/out-in-the-open-jasper/
Comment: Uma solução mais simples é usar o método explode, se eu tiver tempo vou te mostrar um exemplo simples
Answer: Podes fazer assim:
$frase = 'Olá, qual seu nome?';

$ola = stripos($frase, 'olá') !== false; // cada uma destas vai ser true ou false
$nome = stripos($frase, 'nome') !== false;
$adeus = stripos($frase, 'adeus') !== false;

switch(true) {
    case($ola && $nome):
        echo 'Olá, meu nome é João prazer!';
        break;
    case($ola):
        echo 'Olá para ti também';
        break;
    case($adeus):
        echo 'Xau';
        break;
    default:
        echo 'Não queres falar comigo?';
}

Com array:
$frase = 'Olá qual seu nome';
$palavras = explode(' ', $frase);

switch(true) {
    case(in_array('Olá', $palavras) && in_array('nome', $palavras)):
        echo 'Olá, meu nome é João prazer!';
        break;
    case(in_array('Olá', $palavras)):
        echo 'Olá para ti também';
        break;
    case(in_array('adeus', $palavras)):
        echo 'Xau';
        break;
    default:
        echo 'Não queres falar comigo?';
}

Mesmo assim prefiro a primeira, que podes logo definir as palavras/frases que pretentdes fazer match
Comment: Sim @Ivics é verdade, obagdo por ter chamado a atenção para isso
Comment: uma ótima resposta e funcional. Uma dúvida eu posso colocar um array ao invés de *olá* ?

$array = array('oi','ola','hello');
Exemplo. $ola = stripos($frase, '$array') !== false
Comment: Vou colocar uma resposta com array, mesmo resultado final @LucasBicalleto
Comment: Beleza @Miguel.
Comment: Haha @Miguel realmente a 1 seria melhor porem desta segunda forma que passou vou utilizar no meu trabalho para um projeto que tenho que fazer. Obrigado pela ótima resposta
Comment: Com `stripos` poderia dar resultado alterado, por que uma entrada por exemplo como 'Estou em Olária', entraria no `case` do olá.
Answer: Veja se isso te atende:
<form acton="#" method="post">
    <input name="speak" />
    <button>Go!</button>
</form>
<?php

 function clearId($id){
     $special = Array('Á','È','ô','Ç','á','è','Ò','ç','Â','Ë','ò','â','ë','Ø','Ñ','À','Ð','ø','ñ','à','ð','Õ','Å','õ','Ý','å','Í','Ö','ý','Ã','í','ö','ã',
        'Î','Ä','î','Ú','ä','Ì','ú','Æ','ì','Û','æ','Ï','û','ï','Ù','®','É','ù','©','é','Ó','Ü','Þ','Ê','ó','ü','þ','ê','Ô','ß',''',''',''','"','"','"');
     $clearspc = Array('a','e','o','c','a','e','o','c','a','e','o','a','e','o','n','a','d','o','n','a','o','o','a','o','y','a','i','o','y','a','i','o','a',
        'i','a','i','u','a','i','u','a','i','u','a','i','u','i','u','','e','u','c','e','o','u','p','e','o','u','b','e','o','b','','','','','','');
     $newId = str_replace($special, $clearspc, $id);

     return strtolower($newId);
}

function comparaComArray($array, $input) {
    foreach($array as $value)
        if(in_array($value, $input))
            return true;
    return false;
}

if(count($_POST) > 0) {
    $words = strtolower(clearId($_POST['speak']));
    $words = explode(' ', $words);

    $saudacoes = array('oi', 'ola', 'ei', 'hello');

    if(comparaComArray($saudacoes, $words) and !in_array('nome', $words))
        echo "Oi.
";
    else if(comparaComArray($saudacoes, $words) and in_array('nome', $words))
        echo "Oi, meu nome e jose, prazer.
";
    else if(in_array('tchau', $words))
        echo "Bye Bye.
";
    else if(in_array('seu', $words) and in_array('pai', $words) and in_array('?', $words))
        echo "Meu pai é o Antonio.
";
    else if(in_array('quantos', $words) and in_array('anos', $words) and in_array('voce', $words))
        echo "Ops, acabei de nascer, então tenho nenhum ano de idade
";
}

?>

Basicamente, o fluxo do código é coletar um campo de texto do formulário, retirar a acentuação dele separar ele em cada espaçamento (para ficar mais fácil comparar) e no final ir comparando se o array de palavras entradas tem tais palavras, de acordo com isso você dá a resposta, eu havia pensado essa coisa do array, pois quando estava fazendo vi que o usuário pode digitar oi ou olá ou outros, então implementei uma função que apenas recebe dois arrays, um com o dicionario do sistema e outro com a entrada do usuário, então ele percorre o dicionario ate encontrar uma palavra que contenha na entrada do usuário.
Exemplo de entradas e saídas:
Entrada: Olá
Saída: Oi.

Entrada: Olá qual é o seu nome ?
Saída: Oi, meu nome e jose, prazer.

Entrada: Quantos anos vocÊ tem ?
Saída: Ops, acabei de nascer, então tenho nenhum ano de idade

Entrada: Quem é o seu pai ?
Saída: Meu pai é o Antonio.

Entrada: Tchau josé
Saída: Bye Bye

Qualquer dúvida só comentar.
Fonte do tira acento: Como remover acento no upload com php?
Comment: @Ivcs ótima resposta era isso mesmo que eu gostaria e não vamos deixar de lado a resposta do Miguel que me ajudou a entender também e iriei utilizar as duas para projetos separados obrigado pessoal!

"Robo-Humano" Inteligente


Event Response not firing anonymous user

Question: I have a module in drupal8 which only job is on an event response is to redirect a URL. It works fine for everyone except anonymous users. How do I give the module privileges to fire on every user no matter if the are logged in or not.
This is the geographic_me_redirect.services.yml
services:
  me_redirect.process_me_request:
    class: Drupal\me_redirect\EventSubscriber\ResponseSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

This is the response
class ResponseSubscriber implements EventSubscriberInterface
{

    /**
     * Constructor.
     */
    public function __construct()
    {

    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {

        ///$events[KernelEvents::REQUEST][] = ['onRouteMatch', 27];
        //-- fires the event in the kernal early oo page load 20
        $events[KernelEvents::RESPONSE] = ['process_language_request',0];
        //-- For redirecting to another domain

        return $events;
    }

    public function process_language_request(FilterResponseEvent $event)
    {

    return my logic

    }
}

Comment: Can you  explain more about method **process_language_request**, condition, process you want?
Answer: You can't do this when the redirect is already stored in the internal page cache. Because anonymous traffic is served from this cache before any event is fired.
You have to use this kill switch:
\Drupal::service('page_cache_kill_switch')->trigger();

If you put this in your event subscriber and clear the cache, then you prevent, that the response is cached in the internal page cache.
Comment: @Duncanmoo, while you can use this kill switch almost anywhere, I meant with event subscriber in this example `process_language_request(FilterResponseEvent $event)`, not the class, because you can put multiple event subscribers in one class.
Comment: Not sure where others have placed `\Drupal::service('page_cache_kill_switch')->trigger();` but it worked for me to add to the constructor `__construct()`.
Answer: If you just want redirect to URL you can use class like this:
<?php

namespace Drupal\my_event\EventSubscriber;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class MyEventSubscriber.
 *
 * @package Drupal\my_event
 */
class MyEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['processEvent', 0];
    return $events;
  }

  /**
   * Redirect and cache with anonymous user
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   * @param \Drupal\Core\Url $url
   */
  protected function setResponse(GetResponseEvent $event, Url $url) {
    $response = new TrustedRedirectResponse($url->toString(), 301);
    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([])
      ->addCacheTags(['rendered']));
    $event->setResponse($response);
  }

  /**
   * Process with difference condition
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   */
  public function processEvent(GetResponseEvent $event) {
    $logic = $this->checkLogic();
    if ($logic) {
      $this->setResponse($event, Url::fromUri("https://www.example.com"));
    }
  }

  /**
   * Check logic redirect
   * @return boolean logic
   */
  protected function checkLogic() {
    return $logic;
  }
}

Magic here is method setResponse. I use event KernelEvents::REQUEST and set cache in method setResponse. It's working with anonymous user.
Comment: Hi, this is working great except for the redirects keeps looping could you give me an example inside the checklogic(). I am assuming that it stops an. The redirect from looping. Also with this could use $response = new RedirectResponse($url); $response->send();
Comment: what's condition you want redirect to url?


Providing root reducer in @ngrx/store 4.0

Question: In @ngrx/store 2.0 we could provide the root reducer as a function and from there we split our logic inside the application. After I updated to @ngrx/store 4.0 I cannot use this feature any more from what I can see the reducers need to be a map of reducers which will create objects under the same keys in the state. Is there a way to use the old behavoir in @ngrx/store 4.0 In my state components are aware one of another and I need to be able to split my state dynamically also I need to be able to dispatch actions to the right reducer in my own way. Also app is splitted in multiple lazy loaded routes which in some cases reuse the data from another feature.
 StoreModule.provideStore(reducer, {
      auth: {
        loggedIn: true
      }
    })

StoreModule.forRoot(reducers, {
      initialState: {
        auth: {
          loggedIn: true
        }
      }
    })

I need reducers to be a function which gets the full state and dispatches it to the correct reducer, Is there a way to achieve this behavior?
Answer: After I had a second look over ngrx repo I figured it out. To achieve the wanted result we need to replace the @ngrx/store reducer factory  with a new implementation. I injected a new reducer factory and right now the  application works as before. Simple code sample on how to replace the reducer  factory it.
// This factory replaces @ngrx combine reducers so we can manage how we split the keys inside the state
export function combineReducersFactory(
    reducers: any,
    initialState: any = {}
): ActionReducer<any, Action> {
    return function combination(state = initialState, action) {
        const nextState: any = reducers(state, action);
        return nextState !== state ? nextState : state;
    };
}

export const NG_RX_STORE_PROVIDER = [
    StoreModule.forRoot(rootReducer, createEmptyState()),
];

export const NG_RX_REDUCER_FACTORY = [
    {
        provide: REDUCER_FACTORY,
        useFactory: () => combineReducersFactory
    }
];

@NgModule({
    imports: [
        ...NG_RX_STORE_PROVIDER
    ],
    declarations: [...APP_COMPONENTS, ...AG_GRID_COMPONENTS],
    providers: [...NG_RX_REDUCER_FACTORY]
})
export class AppModule {
}

Answer: You can set up a meta reducer to receive every event and manipulate the state from its root. Here is an example way to set it up:
const myInitialState = {
  // whatever you want your initial state to be
};

export function myMetaReducer(
  reducer: ActionReducer<RootStateType>
): ActionReducer<RootStateType> {
  return function(state, action) {
    if (iWantToHandleThisAction) {
      state = doWhatIWantWith(state);
    }
    return reducer(state, action);
  };
}

@NgModule({
  imports: [
    StoreModule.forRoot(myInitialState, { metaReducers: [myMetaReducer] })
  ]
})
export class AppModule {}

Comment: `myInitialState` is undefined and the wrong parameter for sure
Comment: Replace `myInitialState` with `{}` and then it works. This parameter isn't the initial state, but an `ActionReducerMap`. Since in this scenario, nothing is mapped and all is handled by the meta reducer, it works.
Comment: Sorry - I meant for that to be a placeholder for whatever you want to pass in as your initial state - will edit to make that more clear.
Answer: The StoreModule forRoot() function accepts a reducerFactory which can be used as follows:
export function myReducerFactory(reducers: any, initState: any) {
  return (state = myInitialState, action) => myCustomReducer(state, action);
}

@NgModule({
  // ...
  imports: [
    StoreModule.forRoot(null, { reducerFactory: myReducerFactory })
  ]
  // ...
})
export class AppModule {
}

Answer: This works for me:
// your old reducer that handled slicing and dicing the state
export function mainReducer(state = {}, action: Action) {
    // ...
    return newState;
}

// new: metaReducer that just calls the main reducer
export function metaReducer(reducer: ActionReducer<AppState>): ActionReducer<AppState> {
    return function (state, action) {
        return MainReducer(state, action);
    };
}

// new: MetaReducer for StoreModule.forRoot()
export const metaReducers: MetaReducer<any>[] = [metaReducer];

// modified: app.module.ts
@NgModule({
    // ...
    imports: [
        // neglect first parameter ActionReducerMap, we don't need this
        StoreModule.forRoot({}, {
            metaReducers: metaReducers,
            initialState: INITIAL_STATE // optional
        }),
    ]
})


is there a way to have array_column() keep the $input array key?

Question: Suppose I have an array of records, keyed by some ID, and I use the array_column() function to extract one piece of data from each record.
$records = array(
    1234 => array(
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    4567 => array(
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
);

The result from array_column($input, 'first_name') is a numerically indexed array (with new keys 0, 1, ...). Is there a way of keeping the keys from the input array?
Comment: `$newArray = array_combine(array_keys($records), array_column($records, 'first_name'));`
Answer: array_map(function ($r) { return $r['first_name']; }, $records)

will do (for your precise case).
It is more or less equivalent to this (PHP 7+):
(function () use ($records) {
    $result = [];
    foreach ($records as $key => $r) {
        $result[$key] = $r['first_name'];
    }
    return $result;
)()

Answer: When the id would also be available in the data array's you could use the third argument of array_column.
For example:
array_column($records, 'first_name', 'id');
Comment: Sorry, I should have made it clear - the desired data isn't available in the arrays, only as the key.
Answer: Here's a simple function I often use:
function array_column_with_keys(array $array, string $column): array {
    return array_combine(
        array_keys($array),
        array_column($array, $column));
}

So using your example array,
var_export(array_column_with_keys($records, 'first_name'));
will return:
array (
  1234 => 'John',
  4567 => 'Sally',
)


Como testar arrays inteiros em javascript?

Question: Boa noite!
Preciso criar uma função que aceite um array de números e que retorne true se ele contiver pelo menos um número par e false, caso contrário.
O código abaixo até faz isso, SQN:
var ParOuImpar = function(num){
    var i, condicao;
    var True = "True", False = "False";

    for(i=0; i<num.length; i++){

        if ((num[i] % 2) == 0) {
                condicao = True;
            }
        else if ((num[i] % 2) != 0) {
            condicao = False;
        }

    }

    return condicao;
};

Alguns testes, realizados no console do Chrome:
Quando todos os números são pares.
ParOuImpar([6,6,6]);
"True"
Quando todos os números são impares.
ParOuImpar([1,1,1,1,1,1]);
"False"
Quando um único número é par e deveria aparecer true.
ParOuImpar([16,1,1,1,1, 1]);
"False"
Quando existe um único número impar e deveria aparecer true, pois todos os outros são pares.
ParOuImpar([6,6,6,7]);
"False"
Quando o último e o primeiro número do vetor são pares.
ParOuImpar([16,1,1,1,1, 16]);
"True"
Entendi que a função precisa analisar todo o vetor e depois verificar se ele tem pelo menos um número para e retornar verdadeiro ou falso, mas não estou sabendo codificar isso.
Alguém pode me ajudar? Desde já, muito obrigada!
Answer: O seu laço está retornando se o último elemento é par ou ímpar, já que o valor da variável condicao está sendo modificado para cada elemento (note que se você passar um array vazio, a função retornará undefined). Se você quer que a função retorne true se existir qualquer número par, então você pode fazer exatamente isso - quando achar o primeiro número par, retorne true. Se o laço (for) terminar, quer dizer que não há nenhum número par no array, então você pode retornar false.
var ParOuImpar = function(num){
    for (var i = 0; i < num.length; i++) {
        if ((num[i] % 2) == 0) {
            return "True";
        }
    }

    return "False";
}

Exemplo no jsFiddle: http://jsfiddle.net/n9tay0hn/
Comment: Deu certo! Muito obrigada!
Answer: Existe uma alternativa mais "funcional" para a solução desse problema.
Utilizando o método every que checa se todos os valores de um array respeitam determinada condição:
const hasPair = (arr) => (
    !arr.every((e) => e % 2 === 1)
);

E você pode utilizar da seguinte maneira:
hasPair([1, 1, 1]); // false
hasPair([1, 1, 2]); // true

Dessa maneiro o código fica mais limpo e o número de efeitos colaterais diminuem.
Clique aqui para saber mais sobre o  método every:


What could indicate autocorrelation from the below correlogram?

Question:
I would like to ask you a question about autocorrelation from my table. Autocorrelation slows down and then it is up and again slows down. It could indicate non-stationarity of time series?
Answer: Acf reminds cosine, so your autocorrelation function looks like the one from sine wave.
Check here:
https://math.stackexchange.com/questions/1518206/finding-the-autocorrelation-of-a-sine-wave
also here can be informative for you:
Sinusoidal acf plot


Select Command in zend framework

Question: Im am new in Zend Framework.
I have this structure of codes .
DBTable
 class Application_Model_DbTable_Employee extends Zend_Db_Table_Abstract
{

 protected $_name = 'tab_employee';
 }

Model
 public function selectAllEmployees(){
   $tblEmployee = new Application_Model_DbTable_Employee();
   $tblEmployee->select('*');
 }

But i can can't get all the data of all the employee .
Comment: Can anybody help me to find the solution ?
Answer: public function selectAllEmployees(){
  $tblEmployee = new Application_Model_DbTable_Employee();
  return $tblEmployee->fetchAll($tblEmployee->select());
}

Answer: Try this code in model:
public function selectAllEmployees(){
    $tblEmployee = new Application_Model_DbTable_Employee();
    $rowset = $tblEmployee->fetchAll();
    return $rowset;
}

For further information read this http://framework.zend.com/manual/1.12/en/zend.db.table.rowset.html#zend.db.table.rowset.to-array
Answer: Model function
    public function selectAllEmployees()
    {
       $selectSql = $this->select();
       $selectSql->from($this->_name, array('*'))
                  ->order(id DESC');

        return $this->fetchAll($selectSql);
    }

in the controller
$employeeModel = new Application_Model_Employee();
$employees = $employeeModel->selectAllEmployees();

Comment: This is incomplete, you forgot to access the `dbTable` as a gateway. This code would work in the `dbTable` itself
Answer: Maks3w is correct as well as terse.
Here is a little more detail.
There are a number of ways to use your Application_Model_DbTable_Employee to access and query your tab_employee table of your database.
The easiest way is to query directly from the dbTable model itself:
 class Application_Model_DbTable_Employee extends Zend_Db_Table_Abstract
{

    protected $_name = 'tab_employee';

    public function selectAllEmployees()
    {
       //$this refers to the current dbTable object
       $select = $this->select();
       //when querying from the dbTable the from() parameter is assumed to be $this->_name, array('*')
       //there several other sql commands available to the select(), where(), orWhere(), join()
       $select->order('id DESC');

       $result = $this->fetchAll($select);

       return $result;
    }
}

Controller code:
public function indexAction(){
        model = new Application_Model_DbTable_Employee();
        $employees = $model->selectAllEmployees();
        $this->view->employees = $employees
    }

Often a mapper model is used to access the database and provide the data to an entity model. This is also very common a relatively simple to accomplish. The key item to remember when designing the mapper is to include code to access the dbTable model as the database adapter, often called the gateway, here is some example code:
<?php
//This is one way to build a mapper
abstract class My_Model_Mapper_Abstract
{
    /**
     * Instance of Zend_Db_Table_Abstract
     */
    protected $tableGateway = null;

    /**
     * Will accept a DbTable model passed or will instantiate
     * a Zend_Db_Table_Abstract object from table name.
     */
    public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
    {
        if (is_null($tableGateway)) {
            $this->tableGateway = new Zend_Db_Table($this->_tableName);
        } else {
            $this->tableGateway = $tableGateway;
        }
    }

    /**
     * Get default database table adapter
     */
    protected function getGateway()
    {
        return $this->tableGateway;
    }

    /**
     * findAll() is a proxy for the fetchAll() method and returns
     * an array of entity objects.
     *
     * @param $where, primary key id
     * @param string $order in the format of 'column ASC'
     * @return array of entity objects
     */
    public function findAll($where = null, $order = null)
    {
        $select = $this->getGateway()->select();

        if (!is_null($where)) {
            $select->where('id = ?', $where);
        }
        if (!is_null($order)) {
            $select->order($order);
        }
        $rowset = $this->getGateway()->fetchAll($select);

        $entities = array();
        foreach ($rowset as $row) {
            $entity = $this->createEntity($row);
            $this->setMap($row->id, $entity);
            $entities[] = $entity;
        }

        return $entities;
    }

    /**
     * Abstract method to be implemented by concrete mappers.
     */
    abstract protected function createEntity($row);
}

The concrete model might look like:
<?php

class Application_Model_Mapper_Employee extends My_Model_Mapper_Abstract
{
    protected $tableName = 'tab_employee';
    //I hard code the $tableGateway though this is probably not the best way.
    //$tableGateway should probably be injected, but I'm lazy.
    public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
    {
        if (is_null($tableGateway)) {
            $tableGateway = new Application_Model_DbTable_User();
        } else {
            $tableGateway = $tableGateway;
        }
        parent::__construct($tableGateway);
    }
    //create the Entity model
    protected function createEntity($row)
    {
        $data = array(
            'id'       => $row->id,
            'name'     => $row->name,
            'password' => $row->password,
        );
        $employee = new Application_Model_Employee($data);

        return $employee;
    }
}

to use this in a controller might look like:
public function indexAction(){
    model = new Application_Model_Mapper_Employee();
    $employees = $model->findAll();
}

and the most direct way to query your database is least recommended way, directly from the controller:
public function indexAction(){
    model = new Application_Model_DbTable_Employee();
    $employees = $model->fetchAll();
    $this->view->employees = $employees
}

I hope this provides you some help and not to much confusion.

Select Command in zend framework


What is the best programmatic way for determining whether two variables are linearly or non-linearly or not even related

Question: What is the best programmatic way for determining whether two predictor variables are linearly or non-linearly or not even related, maybe using any of the packages scipy/statsmodels or anything else in python.
I know about the ways like plotting and manually checking. But I am looking for some other programmatic technique that is almost certain to differentiate whether a bivariate plot would be linear or non-linear or no relationship between them in nature.
I hear about the concept of KL divergence somewhere. Not really sure of the concept and in-depth, and whether can it really be applied for this sort of problem.
Comment: Even the helpful answers so far seem to assume, or to focus on, an idea of relationship meaning a single-valued relation between variables with noise as extra. . A simple counter-example is points in a circle on a scatter plot, which might or might not qualify as a relationship.
Comment: For what purpose do you need to programmatically determine determine if two variables are linearly related? As the posters have said, there isn't necessarily a single programmatic way, but in certain contexts/uses, there may be a good way.
Comment: distance correlation can also detect noisy circles. see Cliff AB answer for nonlinear correlation measures
Answer: It is very difficult to achieve what you want programmatically because there are so many different forms of nonlinear associations. Even looking at correlation or regression coefficients will not really help. It is always good to refer back to Anscombe's quartet when thinking about problems like this:

Obviously the association between the two variables is completely different in each plot, but each has exactly the same correlation coefficient.
If you know a priori what the possible non-linear relations could be, then you could fit a series of nonlinear models and compare the goodness of fit. But if you don't know what the possible non-linear relations could be, then I can't see how it can be done robustly without visually inspecting the data. Cubic splines could be one possibility but then it may not cope well with logarithmic, exponential and sinusoidal associations, and could be prone to overfitting. EDIT: After some further thought, another approach would be to fit a generalised additive model (GAM) which would provide good insight for many nonlinear associations, but probably not sinusoidal ones.
Truly, the best way to do what you want is visually. We can see instantly what the relations are in the plots above, but any programmatic approach such as regression is bound to have situations where it fails miserably.
So, my suggestion, if you really need to do this is to use a classifier based on the image of the bivariate plot.

create a dataset using randomly generated data for one variable, from a randomly chosen distribution.

Generate the other variable with a linear association (with random slope) and add some random noise. Then choose at random a nonlinear association and create a new set of values for the other variable. You may want to include purely random associations in this group.

Create two bivariate plots, one linear the other nonlinear from the data simulated in 1) and 2). Normalise the data first.

Repeat the above steps millions of times, or as many times as your time scale will allow

Create a classifier, train, test and validate it, to classify linear vs nonlinear images.

For your actual use case, if you have a different sample size to your simulated data then sample or re-sample to get obtain the same size. Normalise the data, create the image and apply the classifier to it.

I realise that this is probably not the kind of answer you want, but I cannot think of a robust way to do this with regression or other model-based approach.
EDIT: I hope no one is taking this too seriously. My point here is that, in a situation with bivariate data, we should always plot the data. Trying to do anything programatically, whether it is a GAM, cubic splines or a vast machine learning approach is basically allowing the analyst to not think, which is a very dangerous thing.
Please always plot your data.
Comment: @CliffAB this was never meant to be a serious solution. I was trying to point out the absurdity of not plotting the data,
Comment: @Michael also, linearity is an important *assumption* of linear regression. When you say  *"lead to a rejection of linear relationship according to any reasonable criterion"* what criterion do you have in mind ? The t test in a linear reg of Y ~ X tests the null hypothesis that the regression coefficient is zero. It is not a test for linearity. You can easily have a non significant t test when the association is clearly linear, and a highly significant one when it is clearly nonlinear. Then there is the questsion of the significance level to choose, and all that.
Comment: "Even looking at...regression coefficients will not really help..."---that is not true. The standard errors of the regression coefficients would differentiate somewhat the four plots. Certainly the lower right corner plot would lead to a rejection of linear relationship according to any reasonable criterion.
Comment: @Michael but these are just examples. The bottom right plot could very conceivably be linear, with a true outlier due to some measurement mistake
Comment: Yeah I thought that would be what you wanted. I just think it's very difficult. It's a very interesting question though, and I'm still thinking about it.
Comment: @develarist I think a main issue is that a programmatic way of dealing with the nuances would most likely be some sequential decision making such as: Test for A, if A then deal with A THEN Test for B, if B then deal with B.  But what if A and B are interacting TOGETHER?  How would we know that maybe taking A out changes now how to deal with B? It gets really complicated to look at two series and really know what is happening, but we can simulate it and let the machine learn how to handle some of these things.  Obviously it is still constrained to what nuances we know, but this is all feasible.
Comment: @RobertLong, haha you got me then! I mean in the OP's defense, there are plenty of scenarios when there's just too many variables to look at all of them. (-1) removed.
Comment: @RobertLong, Im not really sure, whether you meant something like a computer vision kind of solution for detecting the relationship.
Comment: Yes, that's exactly what I meant.
Comment: Ya. I thought of that long back. But Im not sure whether I ll get any ready made datasets for that. Or as this is a common use case which might be helpful for a lot of people, so maybe someone might come up with some pretrained model?? I mainly was looking for something like plug n play.
Comment: @Robert Long Would this approach be any better than normalizing the data and extracting features on the difference between the 2 series and feeding that to a classifier (assuming we have a labeled dataset).
Comment: A test of non-linearity that doesn't require the simulation of a third dataset would be nice. After all, we already have the two predictors of interest and are only interested in their relationship, not some third predictor!
Comment: @Tylerr I would expect similar results. It would be interesting to find out!!
Comment: @develarist of course and those tests exist but they all fail to pick up on a lot of nuances and coding for all of those nuances would be hard which is why leveraging some ML to learn those might give you some advantages.  Simulating these nuances and adding noise to create training data wouldn't be too bad.
Comment: but the nuances are already there. why simulate anything thats already there, and why would something artificial help with picking up something that already exists any better?
Comment: @develarist I take your point but what is your solution to the problem ?
Comment: (-1) I don't know how to say this nicely, but this idea is nuts. Note that this is extremely complicated (why are we doing image recognition for bivariate analysis??) **and** doesn't do anything to help answer the original issue it stated to address of "looking for patterns outside a set of parameterizations we set in advance".
Answer: Linear/nonlinear should not be a binary decision.  No magic threshold exists for informing the analyst things like "definitely linear".  It's all a matter of degree.  Instead, consider quantifying the degree of linearity.  This can be measured relative to explained variation in Y by two competing models: one that forces linearity and one that doesn't.  For the one that doesn't a good general-purpose approach is to fit a restricted cubic spline function (aka natural spline) with say 4 knots (the number of join points, here the number of points at which the 3rd derivative is allowed to be discontinuous) needs to be a function of the sample size and expectations about the possible complexity of the relationship.
Once you have both linear and flexible fits you can use either log-likelihood or $R^2$ to quantify explained variation in Y.  As discussed in the RMS you can compute an "adequacy index" by taking the ratio of model likelihood ratio $\chi^2$ statistics (smaller model divided by larger model).  The closer this is to 1.0 the more adequate is a linear fit.  Or you can take the corresponding ratio of $R^2$ to compute relative explained variation.  This is identical to computing the ratio of the variances of predicted values.  More about relative explained variation is here.
When you do not know beforehand that something is linear, we use such quantifications to inform us about the nature of the relationship but not to change the model.  If using standard frequentist models, to get accurate p-values and confidence bands one must account for all the opportunities the model was given to fit the data.  That means using the spline model for estimates, tests, and confidence bands. So you could say "allow the model to be nonlinear if you do not know beforehand it is linear".  And most relationships are nonlinear.
Comment: do you have a working example of the cubic spline test, and how it, or other methods, separate out the degree of linearity and degree of non-linearity as quantities?
Comment: There are many examples in my RMS course notes at https://hbiostat.org/rms
Answer: The biggest problem you have here is that "non-linear relation" is not well defined. If you allow for any non-linear relation, there's basically no way to tell if something is "completely random" or just follows a non-linear relation that looks exactly like something that might come out of a "completely random" set up.
However, that doesn't mean you have no way to approach this problem, you just need to revise your question better. For example, you can use the standard Pearson's correlation to look for linear relations. If you want to look for monotonic relations, you can now try Spearman's Rho. If you want to look for potentially non-monotonic relations that still provide some ability to predict y given x, you can look at distance correlation. But note that as you get more flexible in what you call "correlated", you will have less power to detect such trends!
Answer: It's relatively simple to measure linearity. To distinguish between non-linear relationship and no relationship at all, you're basically asking for a chi-squared test with a number of boxes equal to the number of possible values. For continuous variables, that means if you do a full resolution test, you'll have only one data point per box, which obviously (or I hope it's obvious) doesn't yield meaningful results. If you have a finite number of values, and the number of data points is sufficiently large compared to the number of values, you can do a chi-squared test. This will, however, ignore the order of the boxes. If you want to privilege possible relationships that take into account order, you'll need a more sophisticated method. One method would be to take several different partitions of the boxes and run the chi-squared test on all of them.
Getting back to the continuous case, you again have the option of taking a chi-squared of a bunch of different partitions. You can also look at candidate relationships such as polynomial and exponential. One method would be to do a nonlinear transformation and then test for linearity. Keep in mind that this can cause results that you may find non-intuitive, such as that x versus log(y) can give a p-value for linearity that's different from exp(x) versus y.
Another thing to keep in mind when doing multiple hypothesis tests is that the $\alpha$ you choose is how much probability mass you have to distribute among all false positives. To be rigorous, you should decide beforehand how much you're going to distribute among all the hypotheses. For instance, if your $\alpha$ is $0.05$ and you have five alternative hypotheses you are testing, you can decide beforehand that you'll reject the null only if one of the alternatives have $p < 0.01$.
Comment: is there a name for the method(s) you are describing, or link to their full procedure or implemented examples


Location parameter for Poisson distribution

Question: According to wikipedia location parameter is such a number $x_0$ that satisfies:
$$f_{x_0, \theta} (x)= f_\theta(x - x_0)$$
My main goal is to calculate second order Taylor expansion of probability mass function of poisson distribution around location parameter. To do this my first idea was just to derive form of this location parameter:
In our example location parameter $k_0$ will be a number that satisfies:
$$\frac{\lambda^ke^{-\lambda}}{k!} = \frac{\lambda^{k - k_0}e^{-\lambda}}{(k-k_0)!}$$
$$\frac{1}{k!} = \frac{\lambda^{-k_0}}{(k - k_0)!}$$
$$-\ln(k!)=-k_0 \ln(\lambda) - \ln[(k -k_0)!]$$
Let's rewrite $\ln(k!)$:
$$\ln(k!) = \ln((k - k_0)! \cdot (k - k_0 + 1) \cdot k-k_0+2 \cdot ... \cdot k) = \ln(k - k_0) + \ln[\prod_{i = 1}^{k_0} k - k_0 + i]$$
Putting this together:
$$-\ln(k-k_0) - \ln[\prod_{i = 1}^{k_0} k - k_0 + i] = -k_0 \ln(\lambda) - ln[(k - k_0)!]$$
$$k_0 = \frac{\ln[\prod_{i = 1}^{k_0} k - k_0 + i]}{\ln\lambda}$$
My questions are:

Are my calculations correct? Is my calculated parameter $k_0$ really a location parameter?

Is it necessary to first derive location parameter for calculating Taylor expansion afterwards? Is there any way around?
Comment: The Poisson distribution is discrete. In Taylor expanding you are probably assuming it is continuous.
Comment: There is no reason to expect that equation to have an integer solution which makes the concept of a location parameter not really relevant. More you seem to be actually trying to do is describe the fluctuations around the mean as being Gaussian-like, which can be done, but you first need to center and rescale so as to produce a small parameter ($\lambda^{-1/2}$ in this context) with which to expand.
Comment: Nevertheless, is my derivation correct?
Answer: I think you misapply the characterization you cite on wiki, which I believe simply says that the location parameter is a horizontal shift--being thought of as a newly added parameter--  to a PMF or PDF. See the more general notion of group family. The location parameter doesn't need to "solve" anything.
Instead, what you are solving is when the Poisson PMF is equal at two different points in its support, namely $k$ and what you have labelled as $k-k_0$. Since the Poisson PMF is nonmonotonic (see pic below), there may be two points with equal mass, but since the distribution is discrete, this is not necessarily guaranteed for arbitrary $k$.  Moreover, as $k$ gets large, the PMF monotonically tends toward zero, so sufficiently large $k$ will have no partner point with the same mass.

Not sure what you want to do with Taylor expansions...
Comment: Hmmm Okay.. To summarize Am I correct saying that when I define my density as $f(k, \lambda) = \frac{\lambda^{k - k_0}e^{-\lambda}}{(k-k_0)!}$, in this case $k_0$ is a location parameter?
Comment: I'm just struggling with applying definition of location parameter to Poisson distribution. How it should look like in this probability mass?
Comment: Sure-as per the link I shared on group family, I think it makes sense in that case to refer to $k_0$ as a location parameter for a shifted Poisson having support $k\in\{k_0,k_0+1,...\}$


Approximating interactions in OLS

Question: Suppose I have a simple linear model with two variables and their interactions:
$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_1 x_2 + \beta_4 x_1^2 + \beta_5 x_2^2 + \epsilon$
where the $\beta_i$ can, of course, be estimated by OLS. Assume that the standard Gauss-Markov assumptions of OLS hold, and that data points are sampled i.i.d. My question is the following: Is there a way to approximate this model such that the approximation is separable in $x_1, x_2$?
Clearly, I could just omit the term $\beta_3 x_1 x_2$ and obtain a separable model at the cost of accuracy, but I'm wondering if there is an approach which would better approximate the original model? I'm only interested in predicting $y$, so the metric by which an approximation would be assessed would be the additional error in introduces in predicting $y$. In other words, I'm interested in an approximation which minimizes the difference in sum-squared-residuals relative to OLS.
The approximation need not be linear in its parameters (or even parametric). This seems related to the idea behind partitioned regression. I also know that orthogonal polynomials are commonly applied to function approximation, but again, am not sure if it would be useful here.
If anyone has any suggestions about where to look for some ideas/theory I'd be happy to hear them.
Comment: Your problem will not be sufficiently well defined until you can provide a quantitative way to evaluate how well any approximation works.  How are we supposed to measure the goodness of an approximation?  The usual methods based on likelihoods or sums of squares are not available because there are no data in evidence.
Comment: Thanks, I've edited my post to clarify the meaning of a "good" approximation.
Comment: I don't follow this. Why don't you just include the interaction term & then use OLS? That will do exactly what you want. What, then, is your question?
Comment: @gung - there are sometimes computational advantages to having a separable model. If the cost (in terms of accuracy) incurred by using an approximation is not too high then it may be an acceptable price to pay for computational efficiency.
Answer: If you really need separability for some reason, you can often get a reasonable approximation by transformation of both response and predictors; however the resulting relationships - while still smooth - will generally require additive modeling.
You might, for example look into approaches like ACE (alternating conditional expectations -- see Breiman, L. and Friedman, J. H. (1985). "Estimating optimal transformations for multiple regression and correlation.",
JASA
80
, 580-78. This is implemented as ace in package acepack for R), for example.
You can do simpler things; if you fit reasonably flexible models in the two predictors (such as via splines for example), you can use Box-Cox transformations (and even estimate the $\lambda$ parameter) to sometimes get reasonable transformations for the response. While less flexible this may be easier to interpret and explain.
There are a wide variety of other approaches to getting approximate transformations for additivity -- indeed it's essentially the same notion as Lafay anamorphosis in nomography which dates back well over a century.
Comment: Thanks @Glen_b - this sounds like a promising approach. A quick look into ACE makes it seem similar to GAMs which had also seemed like a possible route to take. As to this statement: "There are a wide variety of other approaches to getting approximate transformations for additivity" - can you suggest any good surveys of the topic?
Comment: @aht I don't presently recall any surveys of the topic as a general thing; a bunch of different approaches touch on the topic in some way. GAMs won't generally help you if you don't transform the y (the interaction is what makes it not additive, a more flexible form of additivity doesn't get you far if you don't change how far from additive the relationship is); once you do something to make the relationship close to additive, GAMs should do the rest of the job just fine.
Comment: As a simple example consider a relationship (without error) like $y = 9x_1^2 + 6 x_1x_2+x_2^2 + 12x_1+4x_2+8$. That $x_1x_2$ term makes it not-additive; if you model it as $y=f(x_1)+g(x_2)$ you'll have a very distinct pattern in your residuals (a sort of saddle shape). But if you look at $\sqrt{y-4}$, in this case you get a nice linear  function in $x_1$ and $x_2$ and zero error. In general no transformation will induce actual additivity of the predictors but you can often get a quite reasonable approximation.
Comment: The introduction of [this paper on ACE](http://www.jds-online.com/files/JDS-156.pdf) does mention some of the approaches and in passing mentions the distinction between non-transformative approaches like GAM and methods that transform (like ACE)

Approximating interactions in OLS


pushing apache2 past 1500 concurrent connections

Question: I am trying to scale to 4000 concurrent connections on a ubuntu/apache box.
It is 8 core / 64gb ram, so it is not hitting memory or cpu, or any resources for that matter. The problem is with configuration. running on aws.
Serving a static file that says 'hello world';
What i have tried so far:
<IfModule prefork.c>
StartServers       500
MinSpareServers    2000
MaxSpareServers   4000
ServerLimit      5000
MaxClients       50000
MaxRequestsPerChild  10000
</IfModule>

It works perfectly until 1500 concurrent users, then every connection added after that fails or times out.
What else can i look at?
Comment: Is there anything in any logs? What are the ulimits?
Comment: Are you *sure* you're not hitting your RAM limit?  The prefork MPM uses a lot. 1500 x 40MB = 64GB.  Show us your measurements.
Comment: @Ladadadada Memory doesn't work that way, I'd suspect theres < 1G of usage for that type of request. +1 for the measurements though.
Comment: Actually, a more reliable way of finding what's wrong would be to examine the failures in greater detail.  What exactly do you mean by *fails*? TCP RST packet? 503 response?  Something else?  And what stage do the timeouts occur in?  The three-way handshake? While waiting for the response?  After the headers but before the body? Is there a pattern you can use to predict whether you will get a timeout or a failure for a given request?
Comment: @Ladadadada: 20,000 concurrent connections on Apache pre-fork in 24Gb - see http://www.stdlib.net/~colmmacc/Apachecon-EU2005/scaling-apache-handout.pdf
Comment: @symcbean I have no doubt it's possible if you pay attention to your config (and other tuning) but assuming that you can't run out of RAM just because you have 64GB is an assumption worth challenging.  Incidentally, that's an excellent PDF and well worth the OP reading.
Comment: Would also be useful to know how many requests you are sending at 4000 concurrency plus what tool you are using to do it.
Comment: I will try to reply to all of your questions in 1 response! Am using blitz.io ulimit is set to 1000000
Answer: Have you tried adjusting Apache's ulimit? It's set in /etc/apache2/envvars.

## If you need a higher file descriptor limit, uncomment and adjust the
  ## following line (default is 8192):
  #APACHE_ULIMIT_MAX_FILES='ulimit -n 65536'
Answer: Try this setting it will help
keepalive: On
keepalivetimeout: 5
maxclients: 1500
maxkeepaliverequests: 100
maxrequestsperchild: 100000
maxspareservers: 100
minspareservers: 50
serverlimit: 2560
startservers: 50
timeout: 300


disable dates in jQuery datepicker with dates from MySQL

Question: I'm trying to disable certain dates from jQuery datepicker. I know this subject is talked about often but usually only in regards to regulars dates such as holidays or weekends. I'd like to pull the days from a MySQL table instead. For disabling regular dates the codes is;
$(function() {
  $("#datepickerthing").datepicker({
    altField: '#actualDate',
    minDate:'0',
    maxDate: '+6M',
    beforeShowDay:  nationalDays
  });

  var natDays = ["4/22/2009","4/23/2009","4/24/2009","4/25/2009","4/26/2009","5/27/2009","5/28/2009","6/26/2009","6/27/2009","6/28/2009","6/29/2009","6/30/2009"];
  function nationalDays(date) {
    var sDate = (date.getMonth()+1).toString() + "/" + date.getDate().toString() + "/" + date.getFullYear().toString();
    if ($.inArray(sDate, natDays) != -1) return [false,"","Not this day!"];
    else return [true, ""];
  }
});

What I don't understand is how to get a string of dates from a database into the variable "natDays" and make sure they are formatted properly.
Thanks in advance for any help anyone can offer.
Answer: You'll need to make an Ajax request.

Script in PHP to create a string of properly formatted dates from your database
Return this string from the ajax request
.split() them into your array variable.

To properly format your dates, I'd recommend explode()ing them from your database, then dropping them into something like date("m/d/y",mktime(0,0,0,4,5,2010)) (the 4,5,2010 comes from your exploded date).


Crystal Reports date from DB

Question: I have a problem to display a date in crystal reports. The field is from database, and it shows the time, too. I need to display only the date.
I observed that if I click on the Text Format from the date, in the Font tab at Sample it is showed with time. I think that is the problem, but I can't modify, I can't delete the time from the Sample box.
Do you have any idea how to resolve this?
Answer: The data-type of the column inside the database seems to be text/varchar instead of datetime.
The best would be to fix the data-type on the table inside the database.
If you don't have the option to change the datatype directly on the database, you can use following formula to convert it to DateTime inside the report.
If IsDate({Table.DateTimeColumn}) Then DateTime({Table.DateTimeColumn})

On the properties of the formula field there will be the option for the different formats then.
Comment: Thanks for the tip. I managed to change, by clicking on the formula Format Editor, and there I selected the correct format

Crystal Reports date from DB


Adding noise to a column of data

Question: I am working with this optdigits data set from UCI machine learning repository and want to create a new training dataset with noise. How to randomly add noise to a vector in R? say corrupt 10% of the values of the vector.
Comment: What software are you using?
Comment: corrupt in what way?
Comment: change 10% of the values of the vector to a random class (0 to 9).
Answer: It depends on the kind of noise you want to add.
Here's an example:
x <- runif(100,100,150)  # this is our original vector, which I'm just making up

corrupt <- rbinom(length(x),1,0.1)    # choose an average of 10% to corrupt at random
corrupt <- as.logical(corrupt)
noise <- rnorm(sum(corrupt),1000,200) # generate the noise to add
x[corrupt] <- x[corrupt] + noise      # about 10% of x has been corrupted

Here's a plot of corrupted values against the original ones:

You should substitute your own vector and the kind of noise.
Edit: I've just seen your response to my question. To get a random value from 0 to 9, you use sample like so:
noise <- sample(0:9,sum(corrupt),replace=TRUE)

and because you're replacing rather than adding, you then do:
x[corrupt] <- noise

Giving this on the same data as before, and with the same values replaced:

If you wanted to replace a precise number of values (exactly 100 of 1000 values say, rather than an average of 100), you could sample to choose from a set of indices indicating which values to replace.
Comment: I suggest you be very careful to work on *copies* of the data.

Adding noise to a column of data


Linux forward proxy for client authentication

Question: I need to use a simple HTTP forward proxy proxy for Linux to do mutual SSL authentication.
The proxy needs to attach a client certificate to HTTP request and then upgrade HTTP to HTTPS.
I have tried to do that with Nginx, Apache only to reach a dead end.
https://superuser.com/questions/604352/nginx-as-forward-proxy-for-https?rq=1
http://apache-http-server.18135.x6.nabble.com/How-to-pass-a-Client-Certificate-through-a-Reverse-Proxy-td4754227.html
I tried squid but it's too complicated in installation and configuration.
What should I go for (I don't mind commercial software or free ones)?
Comment: Apache is the easiest one to implement I think.
Answer: I don't see a reason to connect first using an insecure protocol and redirect to HTTPS afterwards.
The way this is done using the apache web server is quite simple, you can use any of the fields of the client certificate to authenticate your users:
Require              ssl-verify-client
SSLRequireSSL
SSLOptions           +FakeBasicAuth +StrictRequire
SSLRequire           %{SSL_CIPHER_USEKEYSIZE} >= 256
SSLRequire           %{SSL_CLIENT_S_DN_O} eq "Awesome Company" \
                 and %{SSL_CLIENT_S_DN_OU} eq "Development" \
                 and %{SSL_CLIENT_S_DN_CN} in {"John Doe", "Jane Doe"}

Read the online documentation for further guidance.
Comment: I already have a similar configuration to what you suggest inside my reverse proxy. However, I'm trying to do it with a _forward_ proxy, so that the applications inside my DMZ (which use HTTP) can communicate with outside services using a single client certificate.


Selecionar elementos ignorando itens específicos SIMPLE HTML DOM

Question: Estou parseando uma tabela. Mas dentro dessa tabela existe uma outra tabela e está difícil encontrar os elementos inteiros. Vou colar o código para exemplificar melhor.

        Dados Gerais

Dados de Nomes

                 Nome

                 João da Silva

                 Maria da Silva

Dados de Técnicos

                 Data

                 10/09/2019

                 11/09/2019

Faço o find dos tr ele retorna todos os tr
$trs = $tabela->find('tr');

Mas gostaria que ele ignorasse os tr que estão dentro da tabela que está dentro da tabela.
---------- Pergunta editada  ----------
Bom, eu fiz um foreach para contar quantos trs tinham dentro da tabela e fiz o find com a quantidade exata de trs. Exemplo segue abaixo.
$contar = $tabela->find('tr');
$c=0;
foreach ($contar as $k) {
    $c++;
}
$trCorreto = $trs[$c];

Comment: Não porque eu não quero o primeiro tr, quero o terceiro tr onde tem o td "Dados Técnicos"
Comment: Postei a solução que consegui
Comment: Uai, mas aí vc tá fazendo algo completamente diferente do que perguntou e comentou. Releia a sua pergunta e veja que a solução que vc colocou -- o que é errado, pois o campo de pergunta é apenas para "a pergunta" --, está totalmente alheia a solução que colocou.
Comment: Não está diferente! Apenas usei uma solução paralela. Eu queria que ele ignorasse os TR dentro do segundo TR. O que fiz foi contar os TR dentro do segundo TR para pulá-los quando eu fizer o loop. O que dá no mesmo. Entendo que essa não é a melhor solução ou a solução oficial, mas ela resolveu o problema.
Answer: Bom, sua pergunta não está muito clara mas pelo que entendi você não quer selecionar os elementos tr das tabelas aninhadas.
Então para obter somente os elementos tr que são filhos, você pode utilizar a função do JQuery chamada children.
$('#tabela').children('tr');


Algebraic manipulation: $\sum_{r=1}^n \frac{n-r-1}{n-2} \frac{n-r}{n-1} \frac{1}{n} = \frac{1}{3}$

Question: If you're up for a tedious algebraic manipulation, I'm stuck.
The following is true: $\sum_{r=1}^n \frac{n-r-1}{n-2} \frac{n-r}{n-1} \frac{1}{n} = \frac{1}{3}$.
However, I can't for the life of me figure out the how to show it.
Comment: Do you know binomial coefficients? That's what this looks like. What sort of class or exercise level is this for?
Answer: No tedious algebraic manipulation required!
Consider the following experiment: say that we choose a sequence $x_1,x_2,x_3$ from $\{1,\ldots,n\}$, without replacement.  What is the probability that $x_1$ is the smallest of the three numbers?
On the one hand, this probability is $\frac{1}{3}$ by symmetry. Why?  Given any three distinct numbers $a,b,c\in\{1,\ldots,n\}$, the sequences $abc$, $acb$, $bac$, $bca$, $cab$, and $cba$ are all equally likely to occur.
On the other hand, we can split into cases based on what that smallest number is. We first choose which number $r$ we assign to $x_1$.  This assignment occurs with probability $\frac{1}{n}$.  Then, from the remaining $n-1$ elements, we choose any of the $n-r$ numbers bigger than $r$ for $x_2$ (probability $\frac{n-r}{n-1}$); finally, from the remaining $n-2$ elements, we choose any of the $n-r-1$ remaining elements that exceed $r$ (probability $\frac{n-r-1}{n-2}$).
So, all told, we find that the probability should be
$$
\sum_{r=1}^{n-2}\frac{1}{n}\cdot\frac{n-r}{n-1}\cdot\frac{n-r-1}{n-2},
$$
which differs from your sum only in limits of summation; and, you'll notice that the terms $r=n-1$ and $r=n$ that are missing here are both $0$ in your sum.
So, because these two different expressions (the sum and $\frac{1}{3}$) are both the probability of the same event, they must be equal.
Now, if you PREFER tedious algebraic manipulation, it actually isn't too bad here.  Note that changing your index of summation from $r$ to $k:=n-r$ yields
$$
\sum_{r=1}^{n}\frac{n-r-1}{n-2}\cdot\frac{n-r}{n-1}\cdot\frac{1}{n}=\frac{1}{n(n-1)(n-2)}\sum_{k=1}^{n-1}k(k-1).
$$
(Again, I've dropped indices of summation that contribute zero.) But, we can write
$$
\sum_{k=1}^{n-1}k(k-1)=\sum_{k=1}^{n-1}k^2-\sum_{k=1}^{n-1}k.
$$
Recall these identities:
$$
\sum_{i=1}^{m}i=\frac{m(m+1)}{2}\qquad\sum_{i=1}^{m}i^2=\frac{m(m+1)(2m+1)}{6}
$$
With these,
$$
\sum_{k=1}^{n-1}k^2-\sum_{k=1}^{n-1}k=\frac{(n-1)n(2n-1)}{6}-\frac{n(n-1)}{2},
$$
so that the original sum is
$$
\begin{align*}
\frac{(n-1)n(2n-1)}{6n(n-1)(n-2)}-\frac{n(n-1)}{2n(n-1)(n-2)}&=\frac{2n-1}{6(n-2)}-\frac{1}{2(n-2)}\\
&=\frac{2n-4}{6(n-2)}\\
&=\frac{1}{3}.
\end{align*}
$$
Answer: The sum can rewrite in this way:
$$\frac{1}{(n-2)(n-1)n}\sum_{r=1}^n(n^2-nr-n-nr+r^2+r)=$$
$$=\frac{1}{(n-2)(n-1)n}\left(n^3-n(\frac{n(n+1)}{2})-n^2-n(\frac{n(n+1)}{2})+(\frac{n(n+1)(2n+1)}{6})+(\frac{n(n+1)}{2})\right)=$$
$$=\frac{1}{6(n-2)(n-1)n}(6n^3-3n^3-3n^2-6n^2-3n^3-3n^2+2n^3+3n^2+n+3n^2+3n)=$$
$$=\frac{1}{6(n-2)(n-1)n}(2n^3-6n^2+4n)=\frac{1}{6(n-2)(n-1)}(2n^2-6n+4)=$$
$$=\frac{1}{3(n-2)(n-1)}(n^2-3n+2)=\frac{(n-2)(n-1)}{3(n-2)(n-1)}=\frac{1}{3}$$


Lilypond - Convert number to markup

Question: I would like to create a shorthand for a compound markup command, say MVE
#(define-markup-command (shorthand layout props text) (number-or-markup?) (interpret-markup layout props #{ \markup \bold \italic #text #}))
However, this errors out with "error: not a markup" when passed a number. How would I type-coerce the argument into markup?

Adding a nested \markup is "unexpected".
\simple only takes strings to begin with.
Yes I know passing "number" avoids the issue but it's not ergonomic.
Answer: Well, instead of #text you could write #(if (number? text) (number->string text) text).  The obvious idea #(format #f "~a" text) would fail if text happened to be a markup that isn't a string.
Answer: Based on user73384 finding the core conversion function (number->string), I'm using
#(define-markup-command (to-markup layout props text) (number-or-markup?) (interpret-markup layout props #{ #(if (number? text) (number->string text) text) #}))
as a helper.

Lilypond - Convert number to markup