SSH agent forwarding on debian squeeze

Question: Im trying to set up SSH forwarding like this
osx > debianA > debianB
I can connect to debianA fine, using ssh -A and it has the following env vars when i do:
SSH_AGENT_PID=1543
SSH_AUTH_SOCK=/tmp/ssh-giwdYY1542/agent.1542
SSH_CLIENT='92.233.199.x 38954 22'
SSH_CONNECTION='92.233.199.x 38954 108.171.179.x 22'
SSH_TTY=/dev/pts/0

When i try to connect to debianB, the agent is not used!
ssh -v output ends with:
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/nic/.ssh/id_rsa
debug1: Trying private key: /home/nic/.ssh/id_dsa
debug1: Next authentication method: password

Then im asked for a password.
I have not set any ForwardAgent no directives in ssh_config and dont have a .ssh/config at all. sshd_config has not got AllowAgentForwarding in it. I have tried all of these directives as yes also.
debianA and debianB both have identical ssh_config and sshd_config (verified with diff) so the really weird thing is connecting OSX > debianB > debianA works fine!!
Im totally out of ideas! Has anyone come across this before?
Cheers! NFV
Update 1
One other thing i noticed is that when connecting osx > debianA the last thing it does in the preamble is spit out the Agent pid:
Nics-iMac:~ nic$ ssh -A nic@cloud01
Linux cloud01 2.6.32-5-xen-amd64 #1 SMP Tue Mar 8 00:01:30 UTC 2011 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
You have new mail.
Last login: Tue Nov 27 06:42:47 2012 from xxx
Agent pid 717  <<< HERE ***********
nic@cloud01:~#

debianB does not do this, otherwise the preamble is identical, could this be a clue?
NFV
Answer: On debianB, check the contents and permissions of ~/.ssh/authorized_keys. sshd will also whine in the logs if the permissions are wrong (too wide).
Comment: Thanks, ive checked this file and both servers have only one entry, my id_rsa.pub from the mac. Also monitored the syslogs of both servers while connecting and nothing strange appearing.
Answer: Figured this one out, I had eval ${ssh-agent} at the foot of /etc/profile, must have been overwriting settings from the forwarded agent.
Thanks
NFV

SSH agent forwarding on debian squeeze


What is the purpose of %mdat (as compared to %udat) in Embperl?

Question: I saw that session handling mentioned an %mdat as well as %udat hash. What is the difference and when and why would I use the %mdat hash?
Answer: As noted in Embperl POD,

You can store any data in the %mdat hash and if any request comes to the same Embperl document, you will see the same values in that hash again.

Also, please note that the "you will see" wording in POD above is somewhat misleading, which may have contributed to your confusion.
The main Embperl documentation provides a more precise answer that removes the confusion:

The next time any user hits the same Embperl page, Embperl fill the %mdat hash from Apache::Session with the same values as you have stored within the last request to that page.

Please note the text I highlighted in bold - any user. Typical session data (as stored in %udat) is only stored and accessible for a specific user.
Therefore, %mdat acts as a sort of per-individual-embperl-page but user-independent data store.
To answer your "when" question, an example of using %mdat in practice would be per-page visit counter.
Comment: BTW, I must admit that in several years of Embperl based web development I *never* had any reason to use `%mdat`


equality of inverse limits in $R=k[x_1,x_2,...]$

Question: Let $k$ be a field, $R=k[x_1,x_2,x_3...]=k[x_i]_{\mathbb{N}_0}$ and $\mathfrak{m}=(x_1,x_2,x_3,...)$.
I want to check whether the following equality is true or not:

$\varprojlim{\mathfrak{m}/\mathfrak{m}^{i+1}}= \mathfrak{m}(\varprojlim{R/\mathfrak{m}^i})$

I claim that this equality is true. And I claim

$\varprojlim{\mathfrak{m}/\mathfrak{m}^{i+1}}=L= \mathfrak{m}(\varprojlim{R/\mathfrak{m}^i})$, where $L=\{f\in k[[x_i]]_{i \in \mathbb{N}_0} | f(0)=0\}$

My try:
I define $\phi_i: L \longrightarrow \mathfrak{m}/\mathfrak{m}^{i+1}: p \mapsto p + \mathfrak{m}^{i+1}$.
Let $F:\mathbb{N}^{op} \longrightarrow \mathcal{C}$ such that $F(i)=\mathfrak{m}/\mathfrak{m}^{i+1}$ and $F(i\geq j)= \mathfrak{m}/\mathfrak{m}^{i+1}  \longrightarrow \mathfrak{m}/\mathfrak{m}^{j+1}$.
We want to check that $F(i\geq j) \circ \phi_j=\phi_i$:
$F(i\geq j): \mathfrak{m}/\mathfrak{m}^{i+1} \longrightarrow \mathfrak{m}/\mathfrak{m}^{j+1}: p + \mathfrak{m}^{i+1} \mapsto p + \mathfrak{m}^{j+1}$
$F(i\geq j) \circ \phi_i: L \longrightarrow p/\mathfrak{m}^{j+1}: p \mapsto p + \mathfrak{m}^{j+1}$
$\phi_j: L \longrightarrow \mathfrak{m}/\mathfrak{m}^{j+1}$
And this is $F(i\geq j)\circ \phi_i =\phi_j$.
Now we have to see that if there is a $(L',\alpha)$ satisfying the same condition, then there exists a unique morphism $u:L\longrightarrow L'$ such that $\phi \circ u = \alpha$. But I do not know how to check that.
I know I still need to prove that the right inverse limit is equal to $L$.
But how could I prove the fact mentioned above?
Thank you.
Answer: In case someone come back to this post one day, I will answer what I found.
The equality does not hold.
$\mathfrak{m}(\varprojlim{R/\mathfrak{m}^i})\subset \varprojlim{\mathfrak{m}/\mathfrak{m}^{i+1}} $
To see it, we can check that $$g(x_1,x_2,x_3,...)=\sum_{n=1}^{\infty} x_n^n$$ is not in $\mathfrak{m}(\varprojlim{R/\mathfrak{m}^i})$. But it is in $\varprojlim{\mathfrak{m}/\mathfrak{m}^{i+1}}$.


Equations for VAR model with GARCH errors

Question: How do we actually write the VAR-GARCH model? I don't really understand it.
Here is the VAR($m$) process:
$$ x_t = \phi_0 + \sum_{i=1}^m \phi_i x_{t-i} + \epsilon_t; $$
and here is the GARCH(p,q):
\begin{eqnarray*}
Var[\boldsymbol{x_t}|\boldsymbol{I}_{t-1}] &=& Var[\boldsymbol{\epsilon_t}|I_t] \\
\sigma_t^2 &=& \alpha_0 + \sum_{l=1}^{p} \alpha_l \sigma^2_{t-l} + \sum_{m=1}^{q} \beta_m x^2_{t-m} \\
\end{eqnarray*}
As I understand, the variance is modeled as GARCH and we use VAR to model the conditional mean of the variables. How do we actually write the complete equation of VAR($m$)-GARCH($p,q$)?
Answer: You are pretty close to your goal already, but you should replace $x$s with $\epsilon$s in the conditional variance equation. Note also that VAR is a multivariate model, i.e. the dependent variable is a vector rather than a scalar. Then the GARCH model needs to be multivariate as well because it needs to characterize the conditional covariance matrix of a vector of errors.
So for VAR($m$)-GARCH($p,q$) you have
$$
\begin{aligned}
x_t &= \phi_0 + \sum_{i=1}^m \phi_i x_{t-i} + \epsilon_t \\
\epsilon_t &= \Sigma^{1/2}_t u_t \\
\Sigma_t &= \alpha_0 + \sum_{l=1}^{p} \alpha_l \Sigma_{t-l} + \sum_{m=1}^{q} \beta_m \epsilon_{t-m}\epsilon'_{t-m} \\
u_t &\sim i.i.d(0,I)
\end{aligned}
$$
where $x_t$ and $\epsilon_t$ are vectors; $\phi_0$ and $\alpha_0$ are parameter vectors; $\Sigma_t$ is the conditional variance matrix of $\epsilon_t$; $I$ is an identity matrix; and $\phi_1$ through $\phi_m$, $\alpha_1$ through $\alpha_p$, and $\beta_1$ through $\beta_q$ are parameter matrices. Some restrictions in the equation of $\Sigma_t$ are needed to ensure $\Sigma_t$ is a valid covariance matrix (positive definite). Also, the equation for $\Sigma_t$ could be replaced by an equation for vech-torized $\Sigma_t$ (stacking the columns below and including the diagonal) to avoid having a matrix as a dependent variable; that would change the representation but not the basic idea.
I was trying to stick to your notation as closely as possible; you would encounter somewhat different notation in time series textbooks (e.g. using capital letters for matrices, vech-torizing $\Sigma_t$, etc.).


Find the partial fraction for: $\frac{1}{(x^2+1)^2(x-1)}$

Question: I want to find the partial fraction of: $$\frac{1}{(x^2+1)^2(x-1)}$$
Although I want this expressed through the format of finding the complex number that goes into $x$ so that I can get this equation in the form:
$$\frac{1}{(x^2+1)^2(x-1)}-\frac{Ax+b}{f(x)}$$
Where $f(x)$ represents the value of the denominator left from the original equation after finding the complex root.
I want to repeat this until I find the partial fractions mainly so that I have enough practice in understanding partial fractions through this method.
My approach:
I know that $(x^2+1)$ has a complex number given by: $x^2+1 = 0 \implies x = \sqrt{-1}$ Therefore $x = \pm i$
Plugging this into the equation above, I should get:
$$\frac{A(\pm i )+b}{(\pm i -1)}$$
Where $Ax+b = 1$
Although I'm unsure on how to proceed from here and would greatly appreciate assistance from mathematics community.
Answer: The decomposition into partial fractions has the form
$$\frac{1}{(x^2+1)^2(x-1)}=\frac{A}{x-1}+\frac{Bx+C}{x^2+1}+ \frac{Dx+E}{(x^2+1)^2}$$
To obtain $A$, multiply both sides by $x-1$ and set $x=1$.
For $D$ and $E$, multiply by $(x^2+1)^2$ and set $x=i$.
Last, for $B$, multiply by $x$ and let $x\to\infty$. For $C$, you can set $x$ to any particular value which is not a pole of the fraction, e.g. $x=0$.
Comment: for $Dx+E$ I get $\frac{1}{i-1}$ surely this can be simplified further? Or am I missing the picture here. As for the solution to $Bx+C$ I'm unaware on how to proceed when we multiply by $x$, do I factor out the $x$ to get $\frac{x(Bx+C)}{x^2+1}$ if $x \to \infty$ for $Bx$ then that goes off to zero. How do I proceed from here?
Comment: @Stackcans: For $Dx+E$, you write $\frac 1{i-1}$ in the form $x+iy$ and identify the real parts and the imaginary parts. For $x\to \infty$, you calculate the limits of each side, e.g., $\frac{x(Bx+C)}{x^2+1}\to B$.
Comment: This is still rather complex for me. I'll have to do more practice on partial fractions and complex numbers. Though I'll be sure to update my response until then


why small weights are preferred in neural networks

Question: I'm viewing the CS231n lectures and trying to understand some of the regularization concepts. I think I understand the rationale behind "spread out" weights that are preferred by L2 regularization, e.g. regularization penalty is higher for weights [1, 0] than for [0.5, 0.5]. Intuitively, the latter set of weights would use more of your input features. But why does the absolute value of weights matter, as opposed to only their relative values? I've heard that using L1 regularization helps with "feature selection" because in preferring small weights, some eventually shrink very close to zero. But wouldn't the same effect be observed if some weights were just relatively much smaller?
Comment: What do you mean by *"wouldn't the same effect be observed if some weights were just relatively much smaller?"*?
Comment: By example: why are weights [1, 0.1] better than [100, 10]. I think that jkm addressed it, thanks for your help!
Answer: The magnitudes matter.
Recall that the operation a neuron performs is y=A(wx+b), where A is the activation function, w is weight, b is bias and x is, of course, the input. This means the multiplication by the weight kernel occurs before computing the activation.
Now, if you were using only linear activations, then it indeed wouldn't matter -  the derivative of a linear function is a scalar constant, so by changing the weights you're just rescaling the outputs.
For NNs though, what you want out of your deep layers is non-linearity. That's where the magnitudes of weights start to matter.
In most activation functions, very small weights get more or less ignored or are treated as 'evidence against activation' so to speak.
On top of that some activations, like sigmoid and tanh, get saturated. A large enough weight will effectively fix the output of the neuron to either the maximum or the minimum value of the activation function, so the higher the relative weights, the less room is left for subtlety in deciding whether to pass on the activation or not based on the inputs.


Populate iTunes playlist from csv file

Question: Could anyone offer a way to populate my playlist with songs from a csv file/text file formatted like this:
song title,artist?
I can do it for title alone but can't specify it must have a certain artist.
EDIT: Here is an example of how I'm getting them by titles:
set TheFile to read file "Macintosh HD:Applications:Automator stuff:01b iTunes Scripts:SongList.txt"
tell application "iTunes"
    set thePlaylist to playlist "SongList"
    try
        delete every track of thePlaylist
    end try
    set MySongs to paragraphs of (TheFile) -- read artist names (separated by newlines) from the file
    repeat with AnItem in MySongs -- get all tracks from each artist
        set AnItem to (contents of AnItem)
        if AnItem is not "" then try -- don't bother with empty names
            set MyTracks to (location of file tracks of playlist "Music" whose name is AnItem)
            --can also modify the above from "is" to "contains" or "_begins with_"
            add MyTracks to thePlaylist
        on error errmess -- oopsie (not found, etc)
            log errmess -- just log it
        end try
    end repeat
end tell

Comment: Show us how you're doing it for the title alone.
Answer: OK, figured it out! Couldn't work out how to work around titles with commas in them (which I have a few of), so I ended up using tab separating them instead. So, once I have my tab-separated file, this code did the trick:
set thisTSVFile to (choose file with prompt "Select the CSV file")
readTabSeparatedValuesFile(thisTSVFile)

set theList to readTabSeparatedValuesFile(thisTSVFile)

tell application "iTunes"
    set myPlaylist to playlist "Test1"
    set sourcePlaylist to playlist "Music"
end tell

repeat with i from 2 to number of items in readTabSeparatedValuesFile(thisTSVFile)
     --gets first column
    set theName to item 1 of item i of theList
     --gets second
    set theArtist to item 2 of item i of theList
    tell application "iTunes"
        duplicate (some track of sourcePlaylist whose name is theName and artist is theArtist) to myPlaylist
    end tell
    delay 0.1
end repeat

on readTabSeparatedValuesFile(thisTSVFile)
    try
        set dataBlob to (every paragraph of (read thisTSVFile))
        set the tableData to {}
        set AppleScript's text item delimiters to tab
        repeat with i from 1 to the count of dataBlob
            set the end of the tableData to (every text item of (item i of dataBlob))
        end repeat
        set AppleScript's text item delimiters to ""
        return tableData
    on error errorMessage number errorNumber
        set AppleScript's text item delimiters to ""
        error errorMessage number errorNumber
    end try
end readTabSeparatedValuesFile

Answer: You can use ObjectiveC (or probably Swift too) with XCode to do the heavy lifting (parsing the files) then hit iTunes from there, although it will likely be a lot slower than running in the iTunes process through its script menu.
Here's some ObjectiveC code that gets the current track title; you can adapt the method to suit a more complicated script like populating a playlist.
+(NSString *)getTitle {
    return [self runAppleScriptAndReturnResult:@"Tell application \"iTunes\" \nreturn the name of the current track\nend tell"];
}

+(NSString *)runAppleScriptAndReturnResult:(NSString*)script {
    NSAppleScript *appleScript=[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:@"with timeout of 3 seconds\n%@\nend timeout\n", script]];
    return [[appleScript executeAndReturnError:nil] stringValue];
}

Comment: Thanks, Charlie. I know nothing of Objective-C, so probably will just stick with AppleScript based idea.

Populate iTunes playlist from csv file


Is wrk benchmark tool reliable for testing fastest php framework

Question: So I tried to test php framework on my localhost (6 year old i7 pc) using:
wrk -t12 -c100 -d30s http://127.0.0.1

Laravel without DB I've got: 698 request per second
Cakephp: 1,400 rps
Swoole : 197,000 rps
Swoole with middleware (fastroute, etc) for API: 176,000 rps

Is wrk reliable and I can tell to my boss that my api can process 170k request per second?
Answer: Yes, Wrk is one of the most respected benchmarking tool but you can not tell you boss that your application will handle 176,000 requests/second
because there will be some added conditions which will reduce the application performance. To get the correct benchmark score you can test by replicating all those conditions on your development environment and try benchmarking.
Conditions like

Database Connection (if Application is using Database)
Server Configuration
Reverse Proxy from your HTTP Server (i.e. Nginx or Apache) Very important
And other application-specific conditions
Answer: I also have one Swoole based application with a little processing and DB connection.
I benchmarked the application using wrk.
First without Nginx proxy using my Swoole server on localhost
and then using Nginx reverse proxy please find below the benchmark score
Comment: what's the point of nginx proxy in a modern website? you can load html anywhere then your javascript will call swoole api directly.
Also swoole with mysql Coroutine gives me 90k rps... same db that i used on production api
Comment: @JohnLaniba will you please share your localhost config example where the domain points.


Como deixar um elemento invisível quando o valor é 0?

Question: Estou fazendo uma espécie de "sistema de notificações" bem simples em CSS.
O que eu quero, é que quando o número de notificações for (0) ele fique com display:none;.
Conheço um jeito que eu acho que é possível fazer.
Ex: .bolinha [style*="text-align:center;"] { display:none; } <- Acho que é possível adapta-lo, só não sei como fazer.
Vou deixar uma imagem ilustrando para um melhor entendimento:

Answer: Faça o mesmo sistema que muda o número do elemento mudar o estilo.
Segue exemplo em PHP, adapte para a linguagem do seu sistema:
// Antes:
echo "$comentarios";

// Mude para:
$estilo=($comentarios==0)?'invisivel':'bolinha';
echo "$comentarios";

Aí basta criar o .invisivel {display: none}.
Ou com JS:
contador = document.getElementById("contador");
contador.className = (contador.innerHTML == '0')?'invisivel':'bolinha';

Não esqueça de por o id="contador" no elemento, ou atualizar o JS pro id já existente.

Veja o demo no JSFiddle (mude o valor e aperte Run).
Comment: @AlexandreLopes só não esqueça que se for um JS que atualiza o contador, você deve incluir estas duas linhas dentro do atualizador, ou chamar com algum timer. Aí só vendo o caso concreto mesmo.
Comment: Para ser mais claro, quero integrá-lo ao WHMCS.
E ele não é de código aberto, ou seja, é tudo criptografado.
Queria algo somente com CSS. :(
Comment: Nem JS dá pra por?
Comment: Sim!!!!!!!!!!! :D :D :D :D
Comment: Eu já iria perguntar se era possível com JS. :D
Comment: Muito booooooom......
Obrigadão @Bacco você é demais!
Answer: Infelizmente usando apenas CSS não é possível selecionar um elemento pelo seu texto. Uma opção seria colocar um atributo neste elemento para diferenciá-lo, exemplo:
Em seu elemento span, coloque um atributo, por exemplo data-value:
0

E no CSS, faça:
span.bolinha[data-value="0"]{display:none;} /*Oculta o elemento com data-value="0"*/

Exemplo: JSFiddle
Comment: Excelente dica!
Comment: Vou usar a dica do @Bacco para esse projeto, e vou usar sua brilhante dica para outro projeto! Vai ficar muito legal! Obrigadooooo......
Comment: @AlexandreLopes fico feliz em ajudar.


How to check if payment completed in MPL?

Question: Using PayPal MPL, how could the back-end server check whether the payment completed?
As I understand the MPL controls the entire flow, no need for back-end server calls - but what if the server needs to validate and register the purchase completion.
UPDATE First of all, thank you for the answers so far.
We have two requirements/preferences that can guide us to refine our process:

The payment should be validated as soon as possible. Customer should access the paid services right after the purchase.
For the validation process we should use minimum proof data from the app. Consider the following scenario: purchase completed, but the back-end server went offline - so the client app needs to store the proof data (transaction id, payment id) in order to validate later. But what if the client looses the proof data (app reinstall, etc.) in the meantime- how can then the client and the back-end server get back in sync?

Because of req #1, we don't prefer IPN. According to the IPN documentation:

Although PayPal usually processes IPN messages immediately, IPN is not synchronized with actions on your website. Internet connectivity is not always 100% reliable and IPN messages can be lost or delayed. The IPN service automatically resends messages until the listener acknowledges them. The service resents messages for up to 4 days.
    Because IPN is not a real-time service, your checkout flow should not wait for the IPN message before it is allowed to complete. If the checkout flow is dependent on receiving an IPN message, processing can be delayed by system load or other reasons. Configure your checkout flow to handle a possible delay.

The process described in the iOS SDK docs involves various API calls to verify the payment, but those calls need some proof data from the client app. But what if the client looses proof data? (req #2) Maybe the proof data could be sent to the back-end before the payment? In that case the back-end server could store the proof data until it can be validated. That process would go like this:

Client app initiates a PayPal payment
Client app sends proof data/payment info to the back-end server
Back-end server stores payment info
Client app follow through the payment process with PayPal
Client app notifies back-end that the payment can be validated (no additional data needed)
Back-end server validates payment using the data from step 2.

For this we need an API call with a parameter that is available in step 2, but most id-s are available only after payment completed. Any advices?
Answer: You should get a response back, indicating the payment was complete.  However if you are wanting to some validation and register the purchase complete outside of the respons, you got back from the MPL, you would either have to be using an API call or IPN.  You could use a API call to check the status of the transaction or using IPN and connecting to your database and verify that the order is complete.
Answer: See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/.
These docs are for the new iOS SDK being announced today, but the verification should be the same for the old MPL. (Though of course the hope is that you will like the new SDK better than the old MPL)


States with a variable

Question: I have to do a form and in this form I have a select to choose a value, from this value I load a node and from this node I get a boolean.
With this boolean I have to show or not another form field, but I don't find the way to do this.
First I try to add an #access to the field I need to show or not, and the access value is defined by this : $access = ($is_liberte ? TRUE : FALSE);
And here is the form element :
$form['info_voyage']['order_id'] = array(
  '#title' => t('Order ID'),
  '#type' => 'select',
  '#access' => $access
);

And to reload this I try to add a callback on the first field with this function :
function _ga_facture_date_callback($form, $form_state){
  return $form['info_voyage']["product_id"];
}

This function reload the form (I think), when I change the field with the callback the function is called and the form is recalculated, so my access value change in the form field but the field doesn't appear.
What am I doing wrong?
I also think to do a states on the field to show but I have searched and I doesn't find any way to do a form states with a variable, and not another field.
Comment: The AJAX callback needs to return the element that has changed, not the element that triggered the change. Similarly the wrapper around product_id needs to match the wrapper in the `#ajax` property in the order_id element
Comment: Why are you returning `product_id` when you've changed `order_id`?
Comment: It's my first field, it's a select and in this select I choose a product, when I select an item I return this to 'reload' the form, and I use the product_id to load some orders to add them in the `order_id` field and change the access to TRUE. The access is changed but the form is not refresh so the field doesn't appear, and I don't know how to do this without reloading the page
Comment: Possible duplicate of [Dynamic select list in the form (dependent dropdown)](https://drupal.stackexchange.com/questions/10112/dynamic-select-list-in-the-form-dependent-dropdown)
Comment: It's not a direct dependent dropdown, but thanks @Clive I found the solution (I wrap my product_id and order_id) and return the wrapper in the ajax
Answer: Presuming that the node IDs for the primary select are known or can be retrieved dynamically following some conditions, you can use the following pattern to display and populate the secondary select conditionally.
/**
 * Implements hook_form().
 */
function form_example_form($form, &$form_state) {

  $options = [];

  $nodes = node_load_multiple([
    '70',
    '71',
    '72',
    '73',
    '74',
    '75',
  ]);

  foreach ($nodes as $product) {
    $options[$product->nid] = $product->title;
  }

  $form['node_select'] = [
    '#type'    => 'select',
    '#title'   => t('Select a node'),
    '#options' => $options,
    '#ajax'    => [
      'callback' => '_secondary_select_ajax_callback',
      'wrapper'  => 'foo-bar',
    ],
  ];

  // You need a wrapper to provide a HTML ID to be targeted by the callback.
  $form['secondary_select_wrapper'] = [
    '#type'       => 'container',
    '#attributes' => ['id' => 'foo-bar'],
  ];

  // The secondary select is hidden initially.
  $form['secondary_select_wrapper']['secondary_select'] = [
    '#type'    => 'select',
    '#title'   => t('Select a value'),
    '#options' => [],
    '#access'  => FALSE,
  ];

  $form['submit_button'] = [
    '#type'  => 'submit',
    '#value' => t('Click Here!'),
  ];

  return $form;
}

/**
 * Secondary Select AJAX Callback.
 */
function _secondary_select_ajax_callback(&$form, &$form_state) {

  $options = [];
  $nid = $form_state['values']['node_select'];
  $node = node_load($nid);

  // Do whatever you need to do to populate your options.
  // ...

  $form['secondary_select_wrapper']['secondary_select']['#access'] = TRUE;
  $form['secondary_select_wrapper']['secondary_select']['#options'] = $options;

  return $form['secondary_select_wrapper'];
}

Comment: I can't do like that because I use the value from the select to load a node, and from this node I get the value to use.
Comment: @JessyChenavas – Answer updated. Use the callback to conditionally display and populate the secondary select by retrieving the primary select's node id.

States with a variable


Audio being skipped during fast ontouch IOS

Question: I have created a flip tile memory game. A sequence of tiles will flip over displaying a colour. The user must remember the sequence and repeat it. When the user selects correctly a correct Mp 3 is played. On the Iphone if the tiles are selected quickly the audio isn't being played for each touch, its as though the audio is being skipped for some. link

const elements = {
    gameContainer: $('#game-container'),
    gameMenu: $('#game-menu'),
    audioPlayer: document.querySelector('#player'),
    audioPlayer2: document.querySelector('#player2'),
    audioPlayer3: document.querySelector('#player3'),
    tiles: $('.tile'),
    correctAlert: $('#correct-alert'),
    wrongAlert: $('#wrong-alert'),
    failAlert: $('#fail-alert'),
    alertModal: $('#alert-modal'),
    stageNumber: $('.stage-number'),
    maxStageNumber: $('.max-stage-number'),
    gamemodeCheckbox: $('#gamemode-checkbox'),
    stageProgress: $('#stage-progress'),
    waitText: $('#wait-text'),
    wonAlert: $('#won'),
    goText: $('#go-text')
};

function tileClicked(tile) {
  console.dir(tile)
  // only allow clicking on tiles when game is started and game is not showing pattern
  if (!game.showing && game.started && !tile.classList.contains('flip-card-onclick')) {

    flipTile(tile);

    // check if game reached maximum number of stages i.e. game has been won
    if (game.playerMove <= game.maxStageNumber) {

      // check if current move (tile clicked) matches the tile in the generated pattern
      if (parseInt(tile.id) == game.currentGame[game.playerMove]) {
        // increase the pattern pointer
        game.playerMove++;

        // play sound when correct tile has been clicked
        elements.audioPlayer.pause();
        elements.audioPlayer.currentTime = 0;
        elements.audioPlayer.play();

        // check if we reached the end of the current pattern
        if (game.playerMove == game.currentGame.length) {
          // update the progress bar
          elements.stageProgress.css('width', `${(game.currentGame.length / game.maxStageNumber) * 100}%`);

          // show alert prompting user to go to the next stage
          elements.correctAlert.modal('show');
        }
        // current move did not match current pattern, wrong move
      } else {

        if (game.strictGamemode) {
          elements.audioPlayer2.play();
          // show fail alert and prompt to restart or exit game if strict mode has been selected
          elements.failAlert.modal('show');
        } else {
          // show wrong move alert and prompt to show pattern again
          elements.audioPlayer2.play();
          elements.wrongAlert.modal('show');
        }
      }
    }
  }
}

<audio controls id="player" class="d-none">
         <source id="player-src" src="assets/audio/correct.mp3">
      </audio>
<audio controls id="player2" class="d-none">
         <source id="player-src-2" src="assets/audio/incorrect.mp3">
      </audio>
<audio controls id="player3" class="d-none">
         <source id ="player-src-3" src="assets/audio/won.mp3">
   </audio>
Comment: It's hard to tell without being able to recreate the situation. Could you make such a reproducible example?
Comment: [link](https://drive.google.com/file/d/1NhC_jWI-mqLL4NxLwcvxAMheZVJfiMOL/view?usp=sharing) @EmielZuurbier heres a link to a screen recording of it on the iphone. I want the correct sound to play with each tap on the tile. As seen in the video we only listen to it once.
Comment: Okay, add the video link to your question so that others can see it too. Can you be more specific of which sound is expected at what moment. How do you play the other sounds in your JS file?
Comment: @EmielZuurbier  I added more of the js code to my post. Im fetching the audio player via ID.
Answer: It is very hard to tell where your bug comes from, so your solution may not be so easy to find. Some research might tell you some things but otherwise there is an alternative you could try.
The Web Audio API is an interface where you can get more control over the audio you play. So in your case instead of manipulating the <audio> element, use the Web Audio API to play your audio files.
Down here I've created a snippet which utilizes this API. It currently selects all of your <audio> elements and extracts the sound into a node which then can use to play the sound. This gives you control over how the sound plays.
So here it creates an object, which is stored in the sounds constant, that holds all the names as keys and the players as values. Something like this:
const sounds {
  'correct': MediaElementAudioSourceNode,
  'incorrect': MediaElementAudioSourceNode,
  'won': MediaElementAudioSourceNode
};

Each of those MediaElementAudioSourceNode are the sounds which can be played. Later in the script there is a playSound function, which plays one of the sounds found in your sounds object.
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();

const audioElements = document.querySelectorAll('audio');

const createAudioSources = audioElements => {
    const audioSources = {};
    for (const audioElement of audioElements) {
        const name = audioElement.dataset.name;
        const track = audioContext.createMediaElementSource(audioElement);
        audioSources[name] = track;
    }
    return audioSources;
};

const sounds = createAudioSources(audioElements);

function playSound(track) {
    const sound = sounds[track];
    if (sound === undefined) return;
    sound.connect(audioContext.destination);
    sound.start(audioContext.currentTime);
};

playSound('correct');
playSound('incorrect');
playSound('won');

So all of this could be added above your original script so that the sound files are loaded and ready for use. And then use the playSound() function anywhere in your script whenever you want to play anyone of the sounds. Example below:
function tileClicked(tile) {
  console.dir(tile)
  // only allow clicking on tiles when game is started and game is not showing pattern
  if (!game.showing && game.started && !tile.classList.contains('flip-card-onclick')) {

    flipTile(tile);

    // check if game reached maximum number of stages i.e. game has been won
    if (game.playerMove <= game.maxStageNumber) {

      // check if current move (tile clicked) matches the tile in the generated pattern
      if (parseInt(tile.id) == game.currentGame[game.playerMove]) {
        // increase the pattern pointer
        game.playerMove++;

        // play sound when correct tile has been clicked
        playSound('correct');

        // check if we reached the end of the current pattern
        if (game.playerMove == game.currentGame.length) {
          // update the progress bar
          elements.stageProgress.css('width', `${(game.currentGame.length / game.maxStageNumber) * 100}%`);

          // show alert prompting user to go to the next stage
          elements.correctAlert.modal('show');
        }
        // current move did not match current pattern, wrong move
      } else {

        if (game.strictGamemode) {
          playSound('incorrect');
          // show fail alert and prompt to restart or exit game if strict mode has been selected
          elements.failAlert.modal('show');
        } else {
          // show wrong move alert and prompt to show pattern again
          playSound('incorrect');
          elements.wrongAlert.modal('show');
        }
      }
    }
  }
}

Also, add a data-name attribute to each <audio> element so that JavaScript knows how to call each player and it's accompanying sound.
<audio controls id="player" class="d-none" data-name="correct">
  <source id="player-src" src="assets/audio/correct.mp3">
</audio>
<audio controls id="player2" class="d-none" data-name="incorrect">
  <source id="player-src-2" src="assets/audio/incorrect.mp3">
</audio>
<audio controls id="player3" class="d-none" data-name="won">
  <source id ="player-src-3" src="assets/audio/won.mp3">
</audio>

All my code above is untested and might throw an error, or worse, makes no difference at all. But hey, at least it's worth a shot.


On Rules Event Present Splash Screen To Flagged User

Question: Hello i was wondering what would be the best path to take to achieve my goal. I am working on a website. I am using Rules and Flag modules. I was hoping to set up a rule that when a member has been flagged then an event would happen that would be like a big cartoon splash YOUVE BEEN FLAGGED (with an image and maybe possibly sound)
Im sure that this could be within the scope of drupal. Could anyone suggest a possible way of doing this?
Thanks
Answer: One possible way is define your own Rules action against on that event.
Check the api: (assuming you are using D7)
http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook_rules_action_info/7
Use jQuery to pop up an alert or whatever you like.
Comment: Thanks gilzero. Ive been caught up with other things on my site for a while to worry about how to make big farty noises on it lol. Im using D6 gilzero. I think youve pretty much answered my question for me. I know ive a lot of questions to ask within but i think your solution would be the way to go. I have Rules installed there and i use it minimally for now. I will return to this.


Git merge into past commit

Question: We have a git history that looks like this. This is already pushed to remote but can I possibly merge the branches at certain commits?  Or am I limited to only merging the commit at the very top?

where blue is origin/master and magenta is a feature branch that has been physically copied into the master branch.
Comment: How do you want to merge the two branches? merge the feature branch into a past commit from master branch or the opposite?
Comment: Yeahp feature into one of the existing master commits
Comment: if you merge, you get a merge commit that is above both its children. You can merge anything with anything, but in your case the result would not be on master anymore. However, it is possible to rebase master onto that commit, but that would require push --force, which changes history and can cause lots of trouble. If that's what you want to do, let me know I'll take more time to detail how this weekend
Comment: I still want to maintain the master and feature's history though. What would it look like if I did that? Wouldn't the existing history still be there?
Comment: @JarrenOng I added an answer for merge feature branch into an old commit on master branch, you can have a try.
Answer: Assume the commit history as below, and you want to merge feature branch into commit B:
...---A---B---C---D  master

...---E---F---G---H  feature

Then you can execute below commands:
git checkout commitB
git merge feature --allow-unrelated-histories

Assume the merge commit id commit M as below commit history:
                  C---D  master
                 /
      ...---A---B---M
                   /
...---E---F---G---H  feature

Then you can execute the commands:
git rebase --onto commitM commitB master
git push origin master -f

And now the commit history will be:
      ...---A---B---M---C'---D'  master
                   /
...---E---F---G---H  feature

Comment: Yes, use `git merge feature --allow-unrelated-histories` instead.
Comment: To resolve merge conflicts, you can modify and save all the conflict files firstly, and then use `git add .` and `git commit` to finish the merge :)
Comment: Problem with this is that the branches are on unrelated histories. I can't do a merge.

I have to do a `git pull origin/master --allow-unrelated-histories` which puts me at the top.

Should I create a branch at commitB and push that? Then I think I can do `--allow-unrelated-histories` and then `git merge feature` ?
Comment: Thanks for that. I didn't know you could do that on merge. This works but I'm just having problems resolving conflicts. Thanks very much!!
Comment: hi, i know this is old but something here doesn't add up to me and i was wondering if you could explain.
right after performing the merge, isn't commitM the new child of commitB? and thus when performing the git rebase --onto line with commitB as the  we are basiclly rebasing commitM on top of commitM?
how does git know to treat commit C of master as the child of B when in deatched head state commit M is the child?
Answer: Being in the master branch then
git merge "commit-id"
This should do it
Comment: I don't think this was exactly what the OP was looking for based on the comments, but I think it answers the (unclear) original question, and it answers my question.
Answer: If possible, a merge between the two branch HEAD is preferable, as it will add a new commit (a merged commit) to the master branch, allowing for an easy (fast-forward) push.
Anything else might change the history, making you do a git push --force (which can be problematic if you have other collaborators using the repo)

Git merge into past commit


LDAP Account Expiry Script Help

Question: I need to find a way of automatically  notifying LDAP account users as to when their passwords will expire and also force them to change their passwords.
I am fairly new to LDAP.I am running openldap 2.3.43.el5 on RHEL 5.3
I am trying  to find a solution (possibly in a script form) but i am open to other tried and tested solutions.
What i am aiming to do is to parse,filter  or format the LDAP query output from the command below (example)
slapcat -b "cn=Manager,dc=berkerly dc=ac dc=uk"
such that i get an output that shows the user cn (name) and the users pwChangedTime field from the LDAP database  for example
cn: jbloggs :
pwdChangedTime: 2011078159Z

or better still all on  the same line like
cn: jbloggs :pwdChangedTime: 2011078159Z

This way i can tell when the users passwords was last changed and then based on our password policy work out when the LDAP account users passwords will expire.
In effect this will enable me  work out whos passwords expires soon from a mini report.
I am hoping to do this in a script but  not sure how to achieve this from the slapcat command output.
Is there a way or command  in LDAP, of listing a users cn (name) and pwdChanged time or other fields.I am an LDAP newbie and i am only familiar with slapcat command which  lists all the LDAP users and their various attribute fields i the LDAP database. This slapcat output is not easy to grep and awk to find exactly what i am looking for.
Also i need confirmation as to whether the field pwdChangedTime:  truly represents the date when the password for that user was last changed.
Finally is there a way of forcing users to change their LDAP passwords as you do on normal local Unix,Linux accounts.
Your help would be greatly appreciated.
Comment: Does this answer your question? [what is the simple Command to check password expiry time of an openldap user account](https://serverfault.com/questions/422864/what-is-the-simple-command-to-check-password-expiry-time-of-an-openldap-user-acc)
Answer: OpenLDAP itself can be extended with overlays. Take a look at its Password Policies overlay.
What kind of applications are your LDAP users using?
Comment: all sorts but i kind of figured it out  thanks for your  help anyway, i really appreciate that
Answer: I think the output should be greppable like this (not tested):
slapcat -b "cn=Manager,dc=berkerly dc=ac dc=uk" | egrep "(cn:|pwdChangedTime)"

this should output the cn and pwdChangedTime for all users.
How I would do this:
1) get a userlist with slapcat
2) for every user in that list, get the cn and pwdChangedTime using above grep.
Another option is to use perl, wich has an LDAP lib. With this lib it is easy to
get data out of LDAP.
3) check take the date out of the pwdChangedTime var.
I don't know if u can force users to change their passed with LDAP. I think there is a way, just not sure about it.
hope my post is helpfull.
P.S.: sorry I can't post more code examples but I am at work atm.
Comment: Thanks a million i have already worked this out ,i really appreciate your help i used ldapsearch instead of slapcat but they all achive similar result.Thanks
Answer: It is certainly possible, though hardly advisable and definitely not scalable, to dump the LDIF in order to determine which users' passwords will expire and when. The method you propose requires a full table scan of the directory followed by some text wrangling to get it all on one line and so forth.
As far as I know, OpenLDAP supports the Password Expired and Password Expiring controls. These controls are returned from the server in the bind response. Their purpose is to inform clients of the state of a users' password as it relates to the password policy. These controls are described in VCHU.
Using these controls makes clients responsible for users notification and are already supported by UNIX login clients, for example (although the Solaris client is broken, see this article). When your client receives a bind response and checks for the presence of the password expired control (if the authentication was unsuccessful) and the password expiring control, then client can then take appropriate action. Clients must always check for controls in LDAP responses.
Having the notification performed by the client is flexible, configurable, dynamic and scalable. Having the notifications done by the server is none of those things.
There are other things that could be done to enhance the authentication experience, for example, using an LDAP assertion control with a filter that checks the pwdChangedTime and make the bind conditional on the success of the filter.
Comment: The two controls you refer to are the ancient ('90s) Netscape ones, although some directories support these, OpenLDAP does not. Instead it uses [*Password Policy for LDAP Directories*](https://tools.ietf.org/html/draft-behera-ldap-password-policy-10) (the revision distributed with current OpenLDAP-2.4 source is v11). There are two distinct controls "request" and "response", and all [ppolicy](http://www.openldap.org/software/man.cgi?query=slapo-ppolicy&sektion=5) messages happen that way.

LDAP Account Expiry Script Help


Unable to find a document class... com.apple.InterfaceBuilder3.CocoaTouch.XIB

Question: I have two versions of Xcode installed: Xcode 4 in /Developer/ and Xcode 3 in /User/Xcode3/.
While working on an iPhone app in Xcode 4 I suddenly got this error:

I have no idea where or why this has started. I thought it might be related to this post, but the main solution which has received 32 up votes does not work for me. I did notice that my Xcode 4 folder was missing the InterfaceBuilder app for some reason which I then copied and pasted from my Xcode 3 folder. Not that it made any difference.
Any ideas?

EDIT 1
Also, I should note that even though when I 'get info' on the project and it states that it defaults open to Xcode 4 when I double click on the project it opens with Xcode 3. Therefore I choose to open with Xcode 4. Still doesn't help.

EDIT 2
Also, when I click on the .xib files, I just see string values, no GUI.
Answer: I completely reinstalled Xcode 4 and that seemed to do the trick. But I must say I am quite paranoid when I open up projects. I have the impression that if I use the wrong version of Xcode with the wrong project this problem will come back.
Any illumination on this bug would be greatly appreciated.


Switching out the autocomplete items in a user based entity reference

Question: I'm working with an entity reference field in Drupal 8.3. It resides on a node and references users using the autocomplete widget. I have it setup to use an entity reference view for both what it is doing the lookup on and what it is showing. However no matter what modifications I seem to make to the view the auto complete always returns the referenced email address the new search criteria from the view is working ( it looks up the email by first or last name). Instead of the email however, I'm trying to instead show the users first name and last name as listed on the user entity.
I'm not sure if this is a bug in 8 as I remember this working in 7. Please let me know if there is anything I'm missing. If you need more info please just let me know. Thanks in advance for any help you can provide.
Answer: In case anyone else stumbles on this... Its currently broken in 8.0x+ https://www.drupal.org/node/2174633


How to calculate confidence scores in regression (with random forests/XGBoost) for each prediction in R?

Question: Is there a way to get a confidence score (we can call it also confidence value or likelihood) for each predicted value when using algorithms like Random Forests or Extreme Gradient Boosting (XGBoost)? Let's say this confidence score would range from 0 to 1 and show how confident am I about a particular prediction.
From what I have found on the internet about confidence, usually it is measured by intervals. Here is an example of computed confidence intervals with confpred function from the lava library:
library(lava)
set.seed(123)
n     <- 200
x     <- seq(0,6,length.out=n)
delta <- 3
ss    <- exp(-1+1.5*cos((x-delta)))
ee    <- rnorm(n,sd=ss)
y     <- (x-delta)+3*cos(x+4.5-delta)+ee
d     <- data.frame(y=y,x=x)
newd  <- data.frame(x=seq(0,6,length.out=50))
cc    <- confpred(lm(y~poly(x,3),d),data=d,newdata=newd)
if (interactive()) { ##'
  plot(y~x,pch=16,col=lava::Col("black"), ylim=c(-10,15),xlab="X",ylab="Y")
  with(cc, lava::confband(newd$x, lwr, upr, fit,  lwd=3, polygon=T,
                          col=Col("blue"), border=F))
}

The code output gives only confidence intervals:

There is also a library conformal, but I it also is used for confidence intervals in regression: "conformal permits the calculation of prediction errors in the conformal prediction framework: (i)
p.values for classification, and (ii) confidence intervals for regression."
So is there a way:

To get confidence values for each prediction in any regression problems?

If there isn't a way, would it be meaningful to use for each observation as a confidence score this:
the distance between upper and lower boundaries of the confidence interval (like in the example output above). So, in this case, the wider is the confidence interval, the more uncertainty there is (but this doesn't take into account where in the interval is the actual value)
Comment: Look in the `randomForestCI` package by Stephan Wager, and associated paper with Susan Athey. Note it provides CIs only' but you can make a prediction interval from it by computing the residual variance.
Answer: What you are referring to as a confidence score can be obtained from the uncertainty in individual predictions (e.g. by taking the inverse of it).
Quantifying this uncertainty was always possible with bagging and is relatively straightforward in random forests - but these estimates were biased. Wager et al. (2014) described two procedures to get at these uncertainties more efficiently and with less bias. This was based on bias-corrected versions of the jackknife-after-bootstrap and the infinitesimal jackknife. You can find implementations in the R packages ranger and grf.
More recently, this has been improved upon by using random forests built with conditional inference trees. Based on simulation studies (Brokamp et al. 2018), the infinitesimal jackknife estimator appears to more accurately estimate the error in predictions when conditional inference trees are used to build the random forests. This is implemented in the package RFinfer.

Wager, S., Hastie, T., & Efron, B. (2014). Confidence intervals for random forests: The jackknife and the infinitesimal jackknife. The Journal of Machine Learning Research, 15(1), 1625-1651.
Brokamp, C., Rao, M. B., Ryan, P., & Jandarov, R. (2017). A comparison of resampling and recursive partitioning methods in random forest for estimating the asymptotic variance using the infinitesimal jackknife. Stat, 6(1), 360-372.


Possible division by zero when repeatedly factoring and canceling (x-r) and evaluating the resulting polynomial at x=r...

Question: The following proof is from 'Two Proofs of the Existence and Uniqueness of the Partial Fraction Decomposition', page 4.

Lemma 2.1. Let $h(x), g(x) \in R[x]$ (real polynomials), $k$ a positive integer, and $r \in \mathbb R$ such that $g(r) \neq 0$. If $A_1,...,A_k \in \mathbb R$ such that $h(x)(x-r)^k+A_1g(x)(x-r)^{k-1}+A_2g(x)(x-r)^{k-2}+$
$...+A_kg(x)=0$, then $A_1=A_2=...=A_k=0$.
Proof: If we evaluate $h(x)(x-r)^k+A_1g(x)(x-r)^{k-1}+A_2g(x)(x-r)^{k-2}+...+A_kg(x)=0$ at $x=r$, we get $h(x)(0)^k+A_1g(x)(0)^{k-1}+A_2g(x)(0)^{k-2}+...+A_kg(x)=0$. So that $A_kg(r)=0$. However, $g(r) \neq 0$ therefore, $A_k=0$.
Now our equation reads $h(x)(x-r)^k+A_1g(x)(x-r)^{k-1}+...+A_{k-1}g(x)(x-r)=0$. Factoring out and canceling $x-r$, gives us $h(x)(x-r)^{k-1}+A_1g(x)(x-r)^{k-2}+...+A_{k-1}g(x)$
$=0$.
Therefore, applying the same argument again we find that $A_{k-1}=0$. Continuing in this fashion we find that $A_1=A_2=...=A_k=0$.

My question is whether it is legal to repeatedly factor and cancel $(x-r)$ and at each step evaluate the resulting polynomial at $x=r$. Doesn't the domain of the resulting polynomial exclude $x = r$?
Alternatively I have looked at this post for a different proof but I am not sure how to apply the given answers to prove the above lemma.
Comment: Yes, the factoring and cancellations are legal since they are polynomials. The domain of a polynomial is always $\mathbb{R}$. So you can evaluate it at any point.
Answer: Yes, it's legal: if $k=1$ you are finished. If $k>1$, after the first step you find that
$$
h(x)(x-r)^k+A_1g(x)(x-r)^{k-1}+\dots+A_{k-1}g(x)(x-r)=
(x-r)\bigl(h(x)(x-r)^{k-1}+A_1g(x)(x-r)^{k-2}+\dots+A_{k-1}g(x)\bigr)
$$
is the zero polynomial. Since $x-r$ is not the zero polynomial, we conclude that
$$
h(x)(x-r)^{k-1}+A_1g(x)(x-r)^{k-2}+\dots+A_{k-1}g(x)=0
$$
If you still doubt it, take derivatives:
$$
h'(x)(x-r)^k+kh(x)(x-r)^{k-1}+
A_1g'(x)(x-r)^{k-1}+(k-1)A_1g(x)(x-r)^{k-2}+\dots+
A_{k-1}g'(x)(x-r)+A_{k-1}g(x)=0
$$
and evaluating at $r$ gives $A_{k-1}g(r)=0$, so $A_{k-1}=0$.
Then you can go on in the same way.


Sequantially make text elements on fade in on page load in react component

Question: Hello on page load of a react component I would like text elements to fade in one after another.using css preferably.
Example:

Hi
 (fades in)
Then

boo
 (fades in)

woo
 (fades in)```

Any help is appreciated!

Answer: Here's an example of how to define an animation in CSS, and then render a list with progressively longer animation start delays based on index:

const FadeList = () => {
  const listItems = ['Stantz', 'Spangler', 'Venkman', 'Zeddmore'];

  return (

      {listItems.map((item, idx) => (
        <li className="fade-list-item" style={{ animationDelay: `${500 * idx}ms` }}>{item}

      ))}

  );
}

ReactDOM.render(
  <FadeList />,
  document.getElementById("react")
);
.fade-list-item {
  opacity: 0;
  animation-name: fadein;
  animation-duration: 500ms;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes fadein {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

Comment: Thank you! How would you do this if you're not creating a list item but instead content with an  and following p tags that all have different styling
Comment: You're welcome :)  To do several unrelated items in this manner, you could carefully orchestrate delay times on each element w/ CSS in order to get the desired effect.  It would probably be relatively easy, although it might not scale well for maintainability.  You could also create a wrapping component that would clone each top level element and apply a style to it, but that would only work one level deep.  Alternatively, you might look for third-party libraries that achieve this effect.


Quando eu clico na id de referencia da tag não chama a pagina que eu quero

Question: Não consigo fazer funcionar de forma alguma...me ajudem por gentileza!

Comment: A página fica na raiz? Porque, quando você usa `vaiparaessapagina.php`, se você estiver num caminho que tenha "sub paths" na url, ele vai alterar só o último path.
Comment: Exemplo, se você fazer `location.href = 'index.php'` em uma página assim: `exemplo.com/teste/teste`, ele vai redirecionar assim `exemplo.com/teste/index.php`. Confirme para nós.
Comment: Sim. Está, nada acontece...continua na mesma pagina...experimentei colocar um alerta e assim o alerta entra e mostra a mensagem, mas a pagina continua no index.php
Comment: Já conferiu as requisições no console?
Comment: Observe:

Vaiparaessapagina
Comment: Emilio, será que não é porque você já tem um `href` na tag que você está colocando a ação? Adicione esse trecho à pergunta.
Comment: Wallace Maxters pode me ajudar a fazer essas consultas no console? Eu não sei...eu apenas vejo que a página ainda é o index.html no caminho do browser
Comment: dê uma olhada na minha resposta, jovem. Vê se isso te ajuda.
Answer: O Autor da Pergunta informou que tem o seguinte trecho de código:

        Vaiparaessapagina

O código para mudança de página é o seguinte:
document.getElementById("ClicouNaTag").addEventListener(
    "click",function() {
        window.location.href = "vaiparaessapagina.php";
    }
);

O problema é que o elemento a#ClicouNaTag tem o atributo href que faz com que o redirecionamento seja feito para a própria página. Assim, esse redirecionamento vai impedir que o evento click seja processado.
É importante lembrar que, em muitos casos onde se usa captura dos eventos no Javascript, deve-se impedir a ação padrão do elemento através do método event.preventDefault().
Altere seu código para:
document.getElementById("ClicouNaTag").addEventListener(
    "click",function(event) {
        event.preventDefault();
        window.location.href = "vaiparaessapagina.php";
    }
);

E, já que não vai usar o href="index.php", eu substituiria esse trecho por # ou por javascript: void(0).
Assim:
 ...

Comment: Não deu certo. E veja aqui o código:

Não funciona de modo algum. O ALERTA funciona mas não vai para a pagina de forma nenhuma.
Comment: Pessoal, Obrigado! Eu consegui...

Ainda penso em outra dúvida: tenho uma variavel global, posso altera-la dentro do javascript?

document.getElementById("ClicouNaTag").addEventListener(
    "click",function(event) {
        event.preventDefault();
        **varGloal = '1';**
        window.location.href = "vaiparaessapagina.php";
    }
);
Comment: @EmilioDamiSilva se for o caso, faça outra pergunta, mas pode sim. Pra alterar uma variável global, basta declará-la fora do escopo da função com `var`e dentro da função atribuir um valor a ela, sem declarar com var).
Comment: @EmilioDamiSilva recomendo essa leitura: https://pt.stackoverflow.com/questions/2513/quando-se-deve-usar-var-no-javascript
Comment: Obrigado @Wallace Maxters
Eu ainda não sei como dar nota nas respostas, mas é 10!!!!!!!
Obrigado!!!!


Can you use both diatonic major and minor scale with any mode?

Question: I am learning the modes right now for the Harmonic Major scale. I usually get the idea of a mode by droning some key and then playing all notes of that modem to sort of internalize its sound, and I thought of also trying diatonic chords instead of just notes. But, the diatonic scale is both major and minor.
Lets take Phrygian b4 as an example, which if I understand correctly is the 3rd mode of Harmonic major scale. My question is this: if I want to learn the diatonic chords for Phrygian b4, should I use the diatonic major, or the diatonic minor, for this mode? Or, to rephrase the question: can you use both diatonics with any mode, or is major only supposed to be used with some modes, and minor with others?
I hope it makes sense. Thanks
Answer: 'Only supposed to' is the key! So many questions on this site seem to feel that music theory is music law, and to contavene that is bad.
Music theory is basically based on what actually has been found to work well, from centuries ago to now. It's more a sort of guide rather than 'thou shalt'. Often those 'rules' are broken - for many reasons, one being if we all kept religiously to them all, music would have stagnated decades ago.
More important arbiters are ears - if you feel (hear) that something sounds o.k., then it's usable - in fact, oft-times, it could still be justified theoretically!


Cannot commit when use mysqli_multi_query with multiple queries

Question: I'm trying to commit a mysql multi query, but I can't...
When the mysqli_multi_query "query" has multiple queries cannot commit it. But, when the mysqli_multi_query "query" has an unique query, it is committed correctly. In both cases the execution is OK.
For example:
// No commits
$query = "insert into table(id) values (3); insert into table(id) values (4); insert into table (id) values (5);";
$connection = getConnection( ... );
mysqli_multi_query( $connection, $query );
mysqli_commit( $connection );

This code commits:
// This will commits
$query = "insert into table(id) values (3)";
$connection = getConnection( ... );
mysqli_multi_query( $connection, $query );
mysqli_commit( $connection );

Answer: You don't need to issue multiple queries for this, one INSERT query can contain many rows of values to insert at once. It's also much faster than issuing multiple separate queries.
INSERT INTO table (id) VALUES (3), (4), (5)

Then you can use mysql_query/mysqli_query instead of the rarely used multi query stuff.
Comment: Yes but is a multi_query function, multi_query is multiple queries in one CALL.


What Algorithm to cluster web user sessions without knowing the number of clusters?

Question: I created user sessions from server log data. Based on the URLs I categorized each server request according to the respective page content (e.g. topic_1 = main page, topic_2 = team members, etc.). The Table shows the number of times the user requested a page belonging to a topic in one session.
I want to cluster the sessions to find groups of sessions with similar interests and respectively similar browsing patterns. There are about 100 topics. The first 15 topics are requested frequently. The other topics are like a sparse matrix, but important to differentiate the sessions.
Its an exploratory data mining project. I don't know how many interest groups there are. So I'm looking for an algorithm that doesn't need a specified number of clusters (so no k-means or the like). The database contains about 1 million sessions. Perhaps you can suggest an implementation in R.
user_session  topic_1  topic_2  topic_3  topic_4     topic_99 topic_100
------------------------------------------------ - - ------------------
1             1        4        0        0           0        0
2             1        2        0        0           1        0
3             1        0        5        2           0        0
4             1        0        6        3           0        1
...

Answer: One option: Try hierarchical clustering. e.g.
df <- read.table(header=T, text="
user_session  topic_1  topic_2  topic_3  topic_4     topic_99 topic_100
1             1        4        0        0           0        0
2             1        2        0        0           1        0
3             1        0        5        2           0        0
4             1        0        6        3           0        1")
d <- dist(df[, -1]) # '?dist' for details
hc <- hclust(d)
plot(hc)
rect.hclust(hc, k=2)

The dendrogram suggests two clusters:

To get them:
cbind(session=df$user_session, cluster=cutree(hc, k=2))
#      session cluster
# [1,]       1       1
# [2,]       2       1
# [3,]       3       2
# [4,]       4       2

Comment: Thanks for your answer! I experimented with the distance metric and the cluster method. I think the manhattan metric works best for my high dimensional data. And I used Ward's cluttering algorithm. http://postimg.org/image/x2k9r3xwr/
Answer: One way to cluster without knowing the number of clusters beforehand is the "Chinese Restaurant Process," which is described (along with an implementation in R) in this r-bloggers post.


Does dropout have any benefits when overfitting isn't a concern?

Question: I'm training a transformer based deep learning model in a regime where overfitting isn't a concern. Infinite training samples are generated on demand and never repeated, so there is no training dataset to overfit on. I've confirmed experimentally that performance on a fixed validation dataset is no worse than training performance.
Is there any potential/likely benefit to including dropout in this model? Is there anything to support it resulting in better trained performance when overfitting isn't a concern?
I've tried some basic experiments and found that dropout leads to dramatically reduced performance in the early stages of training, but I haven't let it run for very long.
Comment: The fact that each training sample is not repeated, doesn't mean you could not overfit on them. And are you really confident that your check with a single "fixed validation dataset" covers all your future generalization requirements?
Comment: @frank Yes. Training samples are generated from a uniform distribution over all possible valid inputs, and that is exactly what I want to optimise the model for.  The validation set that I have is also from this same distribution. If I ever wanted to get more specific than that I would do a fine tuning step at a later date.

The premise of this question is that overfitting is not a concern. The question is whether dropout may still have other benefits.
Answer: Even if overfitting is not a concern, dropout could still help. Neural networks are (most of the time) trained with backpropagation, i.e. stochastic gradient descent (SGD). And it is known that the stochastic aspect of SGD often helps it to escape local minima. While the main source of stochasticity is the random blocks in each epoch (with the blocks much smaller than the total dataset), techniques like dropout (might) add a different type of stochasticity that could perhaps improve your results.
So, while you can never be certain of anything with DNNs, I would definitely give dropout a try.
Comment: I am not aware of any such paper showing significant benefits, and it would also surprise me a bit. Furthermore, you say you are using transformers i.e., some pre-designed architecture that others have probably put a lot of afford into optimizing. So I would not mess with this design unless I have a lot of time and money that I can spend optimizing it for my special purposes.
Comment: This is a fair point, but I'm particularly interested in whether there's any empirical evidence suggesting that it's worth trying. I'm working with limited resources and can't justify trying long training runs with it on a weak hypothesis like this, but if there are papers or practical experience showing that it can be significantly beneficial in this case then I'll give it a go.
Comment: Transformers generally use dropout, so I'm actually going against the norm by setting it to zero. That's part of what prompted my curiosity on this. I think it's the right call for my particular use case, but there's a lot of black magic and best practice based on empirical results that goes into training transformers, so there's a chance that I'm wrong.
Answer: One interpretation of dropout is that you can analog it as an ensemble of many neural nets.
When training, each node in the networks has some probability to be dropped.
This means that in every training step, the network architectures are different.
And when testing, we weightedl combined many networks together into a single one.
However, in training, the dropped networks' capabiliteis are less capatible then the full networks.
Thus the performance of the ensembled one might still not outperforme the full one without dropout in training.


Weak vs strong law of large numbers

Question: Let $\{X_n\}_{n \in \mathbb{N}}$ be a sequence of real i.i.d. random variables with mean $\mu$. Let $S_n$ be the sum of the first $n$ elements of this seqeuence,
$$S_n = \frac1n\sum_{i=1}^n X_i.$$
Then the weak law of large numbers states that for any $\epsilon > 0$
$$\lim_{n\rightarrow \infty}P(|S_n - \mu| > \epsilon) = 0 \tag{1}$$
and the strong law of large number states that
$$P(\lim_{n \rightarrow \infty}|S_n - \mu| = 0) = 1 \tag{2}$$
I have read a number of questions regarding these two laws, but I'm still having some trouble seeing the subtle differences between them and what they're saying on a less technical level. I suspect part of my confusion could be related to a few questions I have on convergence in probability vs convergence a.s., which I've posted as a separate question.
My current intuition is as follows. For fixed $\epsilon$ the weak law tells us that we will increasingly be likely to be near $\epsilon$ of $\mu$ as $n \rightarrow \infty$. In other words, if we fix a large $n$ then it is likely that $S_n \in (\mu - \epsilon, \mu + \epsilon)$. However, since the probability is only $0$ in the limit (1), it can be nonzero at this fixed $n$, and so there is a chance that $S_n$ might fall outside of this interval. As $n$ increases, the likelihood of $S_n$ falling outside this range decreases. On Wikipedia they state

The weak law states that for a specified large $n$, the average $\overline{X}_n$ is likely to be near $\mu$. Thus, it leaves open the possibility that $|\overline{X}_n - \mu| > \epsilon$ happens an infinite number of times, although at infrequent intervals.

How did they conclude that $S_n$ might fall outside the range an infinite number of times?
What I am less sure about is what the strong law is exactly saying. For example, if we again choose large $n$, wouldn't we again have nonzero probability that $S_n$ will fall outside of some neighorhood around $\mu$, since (2) only holds in the limit? However on Wikipedia they say

The strong law shows that this (by this they are referring to the passage I quoted above) almost surely will not occur. It does not imply that with probability 1, we have that for any $\epsilon > 0$ the inequality $|\overline{X}_n - \mu|$ holds for large enough $n$, since the convergence is not necessarily uniform on the set where it holds.

But I am not sure how this gives anymore information than the weak law already does. How does it rule out "bad" events occurring infinitely often as in the weak law?
As another example, in Ross's book on probability he says:

The weak law of large numbers states that, for any specified large value $n^*$, $(X_1 + \cdots + X_{n^*})/n^*$ is likely to be near $\mu$. However, it does not say that $(X_1 + \cdots + X_n)/n$ is bound to stay near $\mu$ for all $n$ larger than $n^*$. Thus, it leaves open the possibility that large values of $|(X_1 + \cdots + X_n)/n - \mu|$ can occur infinitely often (though at infrequent intervals). The strong law shows that this cannot occur. In particular, it implies that, with probability 1, for any positive value $\epsilon$, $$\Big| \sum_{i=1}^n \frac{X_i}n - \mu \Big|$$ will be greater than $\epsilon$ only a finite number of times.

But again, I do not see how his last claim follows from convergence a.s. as in (2).
Answer: I think a lot of the confusion in settings such as this can occur because the notation often used in statistics does not remind the reader than $S_n$ is not a number. It's a function. We have a probability space $\Omega$, and each $S_n$ is a function $S_n:\Omega\to\mathbb{R}$. For any $\omega\in \Omega$, $S_n(\omega)$ is a sequence of numbers. For different $\omega$, we may get different sequences which may have different behaviors.
Convergence in probability does not say anything about any particular $\omega$. It says something about $\Omega$ overall, roughly that $\mathbb{P}(\{\omega\in\Omega:|S_n(\omega)-\mu|>\epsilon\})$ is small for large $n$ (and, more precisely, thatn for any $\epsilon$, this sequence approaches zero as $n\to\infty$). This is what is meant when it says that $S_n$ is likely to be near $\mu$ for large $n$. But I think that the statement about $n^*$ is (without mentioning it) transitioning to talking what's happening at a specific $\omega$. We can say that fo r $n^*$, $S_{n^*}$ is likely to be near $\mu$ but if $S_{n^*}(\omega)$ is near $\mu$ for some particular $\omega$, it is not necessarily the case that $S_n(\omega)$ is near $\mu$ for this same $\omega$ and later $n^*$. The strong law precludes this because if $\omega\in \Omega$ is such that $\lim_n S_n(\omega)=\mu$, then for any $\epsilon>0$, $\{n:|S_n(\omega)-\mu|>\epsilon\}$ is finite. Note that both of these last two conditions are about a single $\omega$ and are about a sequence of numbers, $S_n(\omega)$, not random variables (functions) $S_n$. Therefore if $\omega$ is such thbat $\{n:|S_n(\omega)-\mu|>\epsilon\}$ is finite, then $S_n(\omega)$ does not converge to $\mu$, and the set of such $\omega$ has probability zero.
Let's imagine what could be happening to get convergence in probability but not convergence a.s. Let $\Omega=[0,1)$ endowed with the usual Lebesgue measure $\mathbb{P}$. Let $F_1^1:\Omega\to \{0,1\}$ be $1$ on the whole interval $[0,1)$. Let $F^2_1,F^2_2:\Omega\to\{0,1\}$ be such that $F^2_1$ is $1$ on the first half of $[0,1)$ and $0$ on the second half. Let $F^2_2$ be $1$ on the second half of $[0,1)$ and $0$ on the first. More generally, let $F^n_1,\ldots,F^n_n:[0,1)\to\{0,1\}$ be such that $F^n_k$ is $1$ on $[(k-1)/n,k/n)$ and zero on the rest of $[0,1)$.
Note that for $0<\epsilon<1$, $$\mathbb{P}(|F^n_k-0|>\epsilon)=1/n,$$ because the set where $|F^n_k-0|>\epsilon$ is $[(k-1)/n,k/n)$. So if $X_1,X_2,\ldots$ is an enumeration of $F^1_1,F^2_1,F^2_2,F^3_1,F^3_2,F^3_3,\ldots$, $X_m$ converges to $0$ in probability. But for any particular point $\omega\in[0,1)$, $X_m(\omega)$ does not converge to $0$. This is because $X_m(\omega)$ will be $1$ for one of the functions $F^1_1$, one of the functions $F^2_1,F^2_2$, one of the functions $F^3_1,F^3_2,F^3_3$, etc. So these "bad sets" $A_m=\{\omega\in\Omega:|X_m-0|>\epsilon\}$ have probabilities going to zero, but they bounce around enough so that each point occurs in infinitely many of the $A_m$ (but it will take longer and longer between $m$ in which a particular $\omega$ appears). More specifically, the $A_m$ seequence is $A_1=[0,1)$, $A_2=[0,1/2)$, $A_3=[1/2,1)$, $A_4=[0,1/3)$, $A_5=[1/3,2/3)$, $A_6=[2/3,1)$, etc. So $\mathbb{P}(\{\omega\in\Omega:\lim_n X_n(\omega)=0\})=0$, not $1$.
If there were a sequence of iid random variables $Y_n$ such that $X_n=(Y_1+\ldots+Y_n)/n$, then this sequence would satisfy the weak law of large numbers but not the strong law, because $X_n$ converges to zero in probability but not a.s. However, there is no such sequence of $Y_i$ (indeed, one way to prove that there can be no such $Y_i$ is exactly because if it did exist, then the sample means $X_n$ would converge a.s. by SLLN).
Comment: Thank you very much! The point about $S_n$ vs $S_n(\omega)$ is exactly what I was missing.

Weak vs strong law of large numbers


Show that $\log|\sin(z)|$ is the real part of a holomorphic function

Question: $D$ is a connected, simply connected domain with $\sin(z)$ never zero on D. Show that $\log|\sin(z)|$ is the real part of a holomorphic function.
My question is: how to show $\sin(z)$ maps a simply connected set to a simply connected set?
Answer:
My question is: how to show $\sin(z)$ maps a simply connected set to a simply connected set?

It need not. If $D$ is for example the upper half plane, the line $\operatorname{Im} z = 1$ is mapped to an ellipse that winds around $0$. However, since $D$ is by assumption simply connected, and $\sin$ has no zeros in $D$, the logarithmic derivative
$$\cot z = \frac{\cos z}{\sin z}$$
has a primitive $h$ on $D$. $h'(z) = \cot z$ means that $e^{-h(z)}\sin z$ is constant, and by adding a suitable constant to $h$ you can achieve
$$\sin z = e^{h(z)}$$
on $D$. Then you have $\log \lvert\sin z\rvert = \operatorname{Re} h(z)$.
Comment: So where is the branch cut?
Comment: There is no branch cut. Although the image $\sin (D)$ may wind around $0$, you can still have a logarithm of $\sin$ on $D$. It's like $e^z$ on $\mathbb{C}$, the image of that also winds around $0$, but a logarithm of $e^z$ exists ($z \mapsto z - 2\pi i$ is one). The thing is that in a simply connected domain, all paths from one point to another are equivalent (homotopic), so whenever you have a closed path, if you follow a logarithm of $f(z)$, where $f$ has no zeros on $D$, you get back to the value you started with.
Answer: Try $$\log(sin(z)).$$ Recall that $\log(re^{i\theta}):=\log(|r|)+i(\theta+2\pi k)$.
Comment: You need to prove the domain of $sin(z)$ is simply connected first, so you can give it a branch cut.
Comment: Yes. I overlooked that that was your actual question.


Any continuous non-constant map from $Q_p$ to $R$

Question: Consider $Q_p$ and $R$ where $Q_p$ is $p-$adic numbers with $p-$adic topology. If $Q_p\to R$ is a ring homomorphism, then certainly it must be trivial as $Z\to Z$ inducing $Q\to Q$ but infinite series of p-adic element does not converge in $R$ in general.
$\textbf{Q:}$ It is natural to ask whether one can classify all continuous maps $Hom_{Cts}(Q_p,R)$ besides constant maps. It is certainly possible to get just set theoretical embedding by axiom of choice. Does $Hom_{Cts}(Q_p,R)$ have non-constant functions? I do not see an obvious choice of candidate for non-constant maps.
Answer: There are many continuous, non-constant functions; for example, the $p$-adic norm is one such (as is any positive power of the $p$-adic norm).
Comment: @user45765 In fact, $\mathbb{Z}_p$ is uncountable. For the homeomorphism to the Cantor set, no AC is needed. You can see a nice explicit proof here: http://www.personal.psu.edu/axk29/TOPOLOGY/p-adic.pdf
Comment: (Topologically, $\mathbb{Q}_p$ is a countable disjoint union of $\mathbb{Z}_p$ which looks like the Cantor set, so there are of continuous maps.)
Comment: Oh, in that case, I was dumb. I forgot the obvious $p-$adic norms. Why cantor sets are homeomorphic to $Z_p$ here? It looks like $Z_p$ is countable but cantor set is not. Do I need axiom of choice?
Comment: Thanks a lot for clarification.


Django query order depending on starts_with and contains

Question: I try to make a special contains filter in django such that,

if items are cba, abc, abd etc.. and
if I want to get the items that contains ab,

the list should be ordered as abc,bca because abc starts with ab even though they both contains ab.
How can I make such query in django effectively ?
My query is at below
EmployerIndexed.objects.filter(name__icontains=empkw)

Answer: If I understand what you're asking, you want an alphabetical sort?
EmployerIndexed.objects.filter(name__icontains=empkw).order_by('name')


allowedaction from objectType opencmis

Question: I m working with  acl and i can't do this
Session.getTypeDefinition().getChildren().getAllowableActions()
any help and thx
Comment: StackOverflow only allows for english-written content.
Answer: Type definitions don't have Allowable Actions. Only concrete objects (documents, folders, etc.) have Allowable Actions (and maybe ACLs).

allowedaction from objectType opencmis


How can we do overloading in php?

Question: In java we call it overloading when we define two methods with different numbers of arguments.How do we do it in php or javascript where number of parameters passed need not be equal to arguments defined.
Answer: Javascript:
function testing(){
     console.log(arguments);//<-- all func args
}

PHP:
function testing(){
    var_dump(func_get_args());//<-- all func args
}

Comment: But you "cannot" (E_STRICT error) overload a method in PHP (without using func_get_args()) when the original one has other parameters than the new one.
Comment: and you can test the type of the passed argument if reqd. `typeof`  in JavaScript or `is_type()` in PHP.
Comment: thanks this is cool. Knew it but couldnt relate it to java way was thinking that more than one methods will be required.
Comment: @sushil -- why would you want more than one method?
Comment: @neal i am in complete agreement with you know. My java days were hanging over me. Thanks for your answer.
Comment: @Neal Because that is the 'normal' way you overload methods. You can't strictly overload methods in PHP or JavaScript. This is just a workaround.
Comment: @w3d: You mean [gettype()](http://www.php.net/manual/function.gettype.php)? You should rather use is_*() (e.g. is_array()) to check for a specific type! See the warning in the manual.
Comment: @user603003 I meant `is_bool()`, `is_string()`, `is_int()`, etc. I was trying to refer to this generically as is_type() but that didn't come across in the formatting, `is_*()` is better - thanks. :)
Answer: You can assign default values to the parameters like so:
function example(a = 1, b = 2, c = 3) {
  //Do something
}

example(10, 5);

Comment: ... only in PHP, not JavaScript
Comment: Ah yes, sry, in javascript I believe you can just specify the parameters and then test if they have been assigned values in the body of the function.

How can we do overloading in php?


In add filter criteria "user" not coming from FILTER list in add views

Question: I am following the book "The Definitive Guide to Drupal 7" where I am trying to add a new view. But when I tried to add filter,I can't find the User in the FILER list . I am very beginner to Drupal,though I know PHP .
Answer: It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.
Comment: Thnk you Volker...I was googling this over 48hrs ! Thanks a lot.
Answer: You first need to go to "Add relationships" to Content: Author
Now go back to "Add filter criteria" and you will see the user filter and a lot more user information you can use.
This was a change from Views 2 to Views 3 I think.


I am looking to match patterns for all wikimedia sites I tried using the following regular expression. But it doesn't match

Question: "/wiki*[.]org/i"

string : https://www.wikidata.org/wiki/Wikidata:Main_Page
I am parsing the url to extract the host using parse_url() and then running a check with preg_match()
if(preg_match($blacklistedTemplate, $urlData['host']))

The check still seems to fail.
Answer: * is not a wildcard. It matches 0 or more occurrences of the previous character.
wik.org
wiki.org
wikii.org
wikiii.org

. matches any character:
/wiki.*[.]org/i

You can check the regex online
From re_format -- POSIX 1003.2 regular expressions

An atom is [...] '.' (matching any single character) [...]

and

An atom followed by '*' matches a sequence of 0 or more matches of the atom.
Answer: the "*" (Star, Kleene-Star-Operator) is a QUANTIFIER (0-n times), the "[]" are a definition of a character class (one of the following)...
so your regex translates into:
match: "wik", then match "i" (0-n times), then match any of "." and "org"
that's wrong indeed and must be corrected:
"/wiki.*[.]org/i"
Answer: The parse_url() in PHP will return this array:
Array ( [scheme] => https [host] => www.wikidata.org [path] => /wiki/Wikidata:Main_Page )
Array ( [scheme] => http [host] => nl.wikipedia.org [path] => /wiki/Brainfuck )

So a possible solution could look like this:
(en|nl|www).wiki.*[.]org

Note: for example Wikipedia starts with the language(nl,en,etc) so you will have to add all of them to the list
Comment: Matteo's answer allows me to check for all sub domains without listing out each language. Also we don't need to track new languages that may be added over time.
Comment: Yes, it would. I am going ahead with that one.


Como fazer requisição GET/POST com Node.JS?

Question: Preciso fazer uma requisição tanto post como get de uma REST API, queria saber como fazer a requisição com Node.js?
Encontrei alguns artigos na internet mas nada sucinto.
Comment: Aqui: http://stackoverflow.com/questions/5643321/how-to-make-remote-rest-call-inside-node-js-any-curl
Answer: O nodejs têm uma API nativa para HTTP, http.request, que funciona assim:
var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST', // <--- aqui podes escolher o método
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

var req = http.request(options, (res) => {
  res.setEncoding('utf8');
  let data = '';
  res.on('data', d => data += d);
  res.on('end', () => {
    console.log('Terminado! Data:', data);
  });
});

req.on('error', (e) => {
  console.log(`Houve um erro: ${e.message}`);
});

// aqui podes enviar data no POST
req.write(postData);
req.end();

A resposta pode ser usada dentro de res.on('end', () => {.
Existem bibliotecas que simplificam isto, uma delas é o request. Nesse caso a API pode ser assim:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Aqui podes ver o HTML da página pedida.
  }
})

Comment: O código não ganhou destaque de sintaxe, que estranho. É javascript isso?
Comment: @diegofm sim, é JavaScript, estranho. Vou juntar as tags.
Answer: Acho que a maneira mais fácil de fazer requisições é com o Request
https://www.npmjs.com/package/request
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Além desse meio com callbacks você pode usar promises e async/await.


Is it possible to use notes on 2 different staves in Lilypond with one beam? If so, how?

Question: Suppose I want to use eighth notes which differ widely in pitch, so that half of the eighth notes fall in a bass clef and half of them are best represented in a treble clef. Is there a way to use one beam to connect these notes on two different staves in Lilypond?
Comment: Look at this documentation node: http://lilypond.org/doc/v2.19/Documentation/notation/common-notation-for-keyboards#cross_002dstaff-stems
Comment: You already have a piano score consisting of a treble and a bass clef?
Answer: A Voice can change Staff (the respective Staff has to exist at that point of time, if necessary by using \skip as appropriate).
Try
\new PianoStaff <<
  \new Staff = "treble" {
    \new Voice {
      \repeat unfold 8 { \change Staff = "treble" c''16
             \change Staff = "bass" c,16
               }
    }
  }
  \new Staff = "bass" \with { \clef "bass" } { \skip 1 }
>>

which gives
Answer: Yes, this is possible, but there are some quirks you may encounter:
upper = \relative c' {
                      g''8  \change Staff = "LH" g,,,
 \change Staff = "RH" a'''  \change Staff = "LH" fis,,,
 \change Staff = "RH" b'''  \change Staff = "LH" e,,,,
 \change Staff = "RH" c'''' \change Staff = "LH" d,,,,

}
lower = \relative c {
\clef bass
 s2
}
\score {
 \new PianoStaff <<
  \new Staff = "RH" \upper
  \new Staff = "LH" \lower
 >>
}

Hm, a warning:
warning: cannot find context to switch to
 \change Staff = "RH" b'''
                            \change Staff = "LH" e,,,,

This means that the Staff named "LH" did not "exist" where another Staff was trying to reference it. So we need to keep both staves "alive." A spacer rest does nicely:
upper = \relative c' {
                      g''8  \change Staff = "LH" g,,,
 \change Staff = "RH" a'''  \change Staff = "LH" fis,,,
 \change Staff = "RH" b'''  \change Staff = "LH" e,,,,
 \change Staff = "RH" c'''' \change Staff = "LH" d,,,,

}
lower = \relative c {
\clef bass
 s2 s2 % (or s1)
}
\score {
 \new PianoStaff <<
  \new Staff = "RH" \upper
  \new Staff = "LH" \lower
 >>
}

You can control the when and where of beaming, as well. For when, see 1.2.4 Automatic beams > Selected Snippets > Changing beam knee gap: \override Beam.auto-knee-gap = #6; for where, you can specifically move the beams:
upper = \relative c' {
                      g''8  \change Staff = "LH" g,,,
 \change Staff = "RH" a'''  \change Staff = "LH" fis,,,
 \override Beam.positions = #'( -4.5 . -4.5 )
 \change Staff = "RH" b'''  \change Staff = "LH" e,,,,
 \change Staff = "RH" c'''' \change Staff = "LH" d,,,,

}
lower = \relative c {
\clef bass
 s2 s2 % (or s1)
}
\score {
 \new PianoStaff <<
  \new Staff = "RH" \upper
  \new Staff = "LH" \lower
 >>
}


React HOC that takes argument instead of component and returns component

Question: How do I create a React HOC that takes argument instead of component (let's say the argument is from useParams() of react router dom) and returns a component with the given argument (with hooks)
I tried
import React from 'react'

const ResultsContent = searchValue => {
  const Content = props => {
    return (

{searchValue}

    )
  }
  return Content
}

export default ResultsContent

then
let { value } = useParams()
const Content = ResultsContent(value)

return (

      <Content></Content>

)

and I got _results__WEBPACK_IMPORTED_MODULE_5___default(...) is not a function
Comment: What problems are you facing, and what have you tried yet?
Comment: I tried to create a function that takes the argument and then inside the function I created the component then the function returns the component. so I exported this function and it didn't work
Comment: Could you provide your current code?
Comment: `const ResultsContent = searchValue => {
  const Content = props => {
    return (
      {searchValue}
    )
  }
  return Content
}

export default ResultsContent`
Comment: then `const Content = ResultsContent(value)`
Comment: Update your question, please.
Comment: Sure, I updated it. i'm new here so I just saw how to update it
Answer: You could do something like this:
import React from "react";
import ReactDOM from "react-dom";

const resultsContent = (searchValue) => {
  const Content = (props) =>
{searchValue}
;
  return Content;
};
const Content = resultsContent("a");

const rootElement = document.getElementById("root");
ReactDOM.render(<Content />, rootElement);

**Also check if you import your ResultsContent with a default import not named import:
import ResultsContent from './your-path-to-the-file';**
Comment: Thanks! it works, it was the import like you said


Intersection of all maximal ideal in a semi-simple ring.

Question: I have met the statement below many times, either here on this site or while reading through books, but I am for my life is unable to prove why it is correct. Here is the statement:
If $R$(commutative ring with $1$) is semisimple, then the intersection of all maximal ideals is $0.$ Also, why the fields associated with each maximal ideal has empty intersections with each other?
Could someone provide an explanation of this to me, please?
Comment: Is the ring $R$ commutative?
Comment: @Bernard yes it is
Answer: In generality by the Artin-Wedderburn Theorm, a ring with unity $R$ is semisimple if and only if there is an isomorphism
$$
R \cong \prod_{k= 0}^{m} \operatorname{Mat}_{n_k}(D_k)
$$
where $m \in \mathbb{N}$ and each ring $\operatorname{Mat}_{n_k}(D_k)$ is the ring of $n_k \times n_k$ matrices over a division ring $D_k$. Note that if $R$ is commutative, each $n_k = 1$ and each division ring $D_k$ is a field. It can be shown that the Jacobson radical is a proper two-sided ideal of $R$ with
$$
J(R) = \bigcap_{\substack{\text{Maximal right ideals}\\\mathfrak{m} \triangleleft R}}\mathfrak{m}.
$$
In particular, the Jacobson radical of $R$ coincides with the intersection of all maximal right ideals of $R$; note that in the case $R$ is commutative, this is just the radical of $R$ as all right ideals are two-sided for free. We are then done once we show the following result:
Theorem For a ring $R$ with unity, if $R$ is semisimple then $R$ is Artinian and $J(R) = 0$.
Proof Assume that $R$ is semisimple and note that by the Artin-Wedderburn Theorem we can assume that $R$ is a finite product of matrix rings over division rings. In fact, by a routine induction we can even assume that $R = \operatorname{Mat}_m(D) \times \operatorname{Mat}_n(E)$ for division rings $m$ and $n$. At any rate, it is routine to check that for any rings with unity $A, B$
$$
J(A \times B) = J(A) \times J(B).
$$
Using this we find that
$$
J(R) = J(\operatorname{Mat}_m(D) \times \operatorname{Mat}_n(E)) = J(\operatorname{Mat}_m(D)) \times J(\operatorname{Mat}_n(E)) = 0 \times 0 = 0
$$
because each ring $\operatorname{Mat}_{n_k}(D_k)$ is a simple ring and $J(\operatorname{Mat}_{n_k}(D_k))$ is a two-sided ideal of $\operatorname{Mat}_{n_k}(D_k)$ not equal to $\operatorname{Mat}_{n_k}(D_k)$. Finally, $R$ is Artinian because it is a finite product of simple rings. $\square$
This explains why the intersection of all maximal ideals of a finite product of fields is $0$. Essentially, the maximal ideals of a commutative unital semisimple ring look like
$$
\mathfrak{m}_i = \left(\prod_{j=0}^{i-1} 0\right) \times D_{n_i} \times \left(\prod_{j = i+1}^{m} 0\right)
$$
i.e., $\mathfrak{m}$ is $0$ in all terms of the product except one. Intersecting two distinct such ideals gives you $0$ because the only nonzero terms do not live in common pieces of your product.
Comment: The last paragraph is a pretty simple explanation, is it not? The general theory is just to show you exactly what structure is at play with your question.
Comment: Ok thank you! ..... I have another question with bounty also related to semi-simple rings ... just in case you want to take a look at it. I guess it is much easier than my above question. Here it is https://math.stackexchange.com/questions/4094931/semi-simple-rings-and-fields
Comment: Is not there a much simpler explanation than this?