Are ups & downs/peaks and valleys inherent in piano practice and performance?

Question: It sounds like a weird question, but I just don't know how to describe it in words;
sometimes you are really good at performing the piece, and you feel enthusiastic and more confident, other times your performance plummets, and your hands/arms are stiff and you're so bad at performing that you just can't imagine the other time you played it like perfectly.
I have been playing the piano for over 10 years, and I have been having this lately, after I started playing virtuoso pieces.
In piano competitions, I get told by the judges often that I am playing with emotion and without thinking, and that I rely too much on my fingers.
Is it normal to have such unstable piano performance skills, and is there a way to fix this?
Comment: What pieces are you playing in these competitions?  I'm assuming romantic and early 20th century pieces rather than baroque but if we knew then it might help with the answers.
Comment: Everybody has his bad and good days. That's why so many people take drugs. Some are meditating, others are praying. Did you think about drinking enough water and nutrition at all?  Do you know this book: Eugen Herrigel
Zen in the Art of Archery
Training the Mind and Body to Become One

My singing teacher recommended this to me years ago.
Comment: @JimM I am playing Chopin and Liszt pieces
Answer: Basic problem is being human! We're not machines as such, and other factors affect any performances we do - whether it's playing piano, running, going about our 'normal' day to day doings.
One telling thing is the saying 'amateurs practise till they get it right, professionals practise till they can't get it wrong.' There comes a point in practice when we know a piece mechanically, and could recite the 2 times table while playing it. We still haven't 'learned' it at that point. We need to go much deeper: trying out rubato, accelerando, de/cresendo, etc., and suck out as much from the markings, and put in as much emotion as possible. Maybe exaggerate all those and many other aspects. But none of these things can happen until we can play the piece from a mechanical aspect.
Obviously, rehearsal/practice is the answer, but not merely playing it through and through - that's the first stage, if you like. Then comes the best bit - exploring what we can do to unravel the piece, put our own mark on it, make it speak to our listener.
Experiment with different aspects, even change subtly some of the original markings if that makes the piece work better for you. Remember that even the best judges will have some subjectiveness about their judgements, no matter how small. They're human too...
Comment: " 'amateurs practise till they get it right, professionals practise till they can't get it wrong.' " Love that saying.
Answer: One thing to consider, by your own words, is that you are now playing virtuoso level performances and were not before.  And the problem started at this point.
Although I may be misinterpreting your statement, are the judges saying that you are (or are NOT) playing with emotion.  Because that is a good thing in the correct context.  Or are they implying that you are too emotional about your performance and letting that get in the way of your skills?
I would compare your situation to that of an athlete who is trying to do something new, say a runner trying a new event, or trying to run a sub 4min mile for the first time.  You are playing things that were once beyond your skill level and now you are demanding more of yourself.  That requires an adjustment period, not only of your body but of your mind and your self expectations.  Harder pieces require more time to memorize and get in the muscle memory and more skill.  All of this will get better and in a few years you may see these pieces as easy relative to what you are working on.
I go through a similar phase on the guitar.  As I get better (or I think I'm getting better) I start feeling like I'm getting worse.  My father and I are both classical guitarists and he pointed out to me one day, after hearing me practice, that my technique had improved but that I was also developing a more discerning ear and thus judging the quality of the technique with a finer scale.  In other words my criterion for "not getting it wrong" had evolved and my standards are higher (not only for myself but in judging other guitarists).  This is likely happening to you as well.  As you get better and surpass your current challenges you will demand more of yourself.  This could also explain the stiffness in your arms as complex pieces are physically challenging.  I cannot explain the judge's reaction to your playing except to say that if you are in a state where your mind and body are not relaxed that will get projected in your performance.
In my opinion, and that of my teachers, performances should be automatic.  When a piece is really fully learnt it's in the muscle memory and you can almost feel like you are listening to someone else play it.  It's like having an out of body experience.  I typically won't consider playing a piece in a formal classical recital until I can (1) play it without the sheet music, and (2) improvise on it without getting lost.  I know that may sound odd for classical but all music is subject to improv and that is a self assessment in that I'm challenging myself to fly away from the formal template and not lose my bearings.  It helps with my memory and recovering from mistakes gracefully (mistakes do happen even when you have a piece worked out).  I've heard the greatest musicians in the world make mistakes on stage.  It's part of being human like Tim said.
Comment: That 'out of body experience' rings true. Sometimes, when playing, that's a good description - I'm watching myself from somewhere, but it's not on stage. And worst of all, critically! +1.
Comment: Regarding "I typically won't consider playing a piece in a formal classical recital until I can (1) play it without the sheet music, and (2) improvise on it without getting lost." - When I was a child, I had to play piano pieces for recitals and competitions without getting (2) (even though piano concerto movements kinda enforce being able to get (2)), and I often couldn't even get it mistake-free by the time I had to publicly perform.
Answer: This is a tricky one but here is my take on this.
Am I correct in thinking that you do not have a teacher?  The reason I mention this is that if you did then you would not need to be asking the question here, you would be referring back to them.
So working on that assumption I am thinking that you are not getting enough feedback on your performances or your development as you practice.  What criteria do you apply when you feel that you have mastered a piece?  Getting the notes right is the obvious one but there is a lot more to it than that and it might be difficult to take an objective view.
I can suggest two things that might help:  firstly start recording yourself when you practice and listen back to it.  Is what you hear what you expect?  Does it sound the same to you when you listen back as it did when you were playing it?  Try to be objective, its hard but it will be ultimately beneficial.  Secondly find some recordings of prominent artists playing the same pieces (there will be loads on the internet) and listen to them.  Compare what they do with what you are doing.  Again be critical, its worth it.
Now this is going to sound a bit harsh but it will turn out to be beneficial if I am correct:  I think you may find when you do this that you are perhaps not as proficient as you think.  And that's a good thing because it gives you something to work on to improve.  You clearly have the drive and are prepared to put in the effort but if the only time you get feedback is when you take part in competitions then you are perhaps not developing your skills in the most efficient way.
Good luck with this.
Answer: Using a metronome will keep your playing tighter and with less emotion. It seems very basic but just might be what you need.


How do we make sense of normal derivatives in PDE at boundary points?

Question: In PDE, the normal derivative on a boundary comes up a lot (defined to be the $<\nabla u, v>$ where $v$ is the unit normal vector of our domain. I want to ask how exactly do we define the gradient on boundary points because plenty of textbooks for analysis in $R^n$ explicitly state that we need open sets for partial derivatives to make sense. Is there some adapted definition for derivatives for boundary points?
Now closely related to PDE and normal derivatives is Hopf lemma which I was just reading about: https://en.wikipedia.org/wiki/Hopf_lemma
It states that if a harmonic functions assumes a strict maximum on a boundary point, then its normal derivative must also be strictly positive. Now if the point was an interior point, then we know the gradient must be zero since it is a extrema, but since we have boundary point, this is not the case. So intuitively, are we suppose to imagine that our domain is actually part of some larger space and our function is actually increasing in the direction of the normal at this point in this larger space?
Comment: look up calculus on submanifolds
Comment: Have a look at directional derivatives.
Answer: As is the case much of the time in PDE's, it helps to analyze a simpler one-dimensional example:
This function is only defined on the closed interval $[0,3]$, and achieves local maxima at the endpoints. At the right endpoint $x = 3$, it is clear that the function is increasing $\textit{up to}$ that point, which is why it is a local maximum. Since the increase of a differentiable function $f(x)$ is equivalent to $f'(x) > 0$, we would like to be able to say that $f'(3) > 0$; of course, if we use the usual definition
$$ f'(3) = \lim_{h\to 0}\frac{f(3+h)-f(3)}{h} $$
then this is not defined since $f(3+h)$ does not exist for positive $h$. The standard remedy is to just consider one-sided derivatives, meaning in this case we just take negative $h$ and take the limit as it approached $0$ from the left to get
$$ f'(3) := \lim_{h\to 0^-}\frac{f(3+h)-f(3)}{h} > 0 $$
as desired.
Generalizing, in arbitrary dimensions we can always do this type of one-sided limit with the normal derivative since it approaches the boundary at a right angle and so is well defined. It should be clear then that if a point on the boundary is a local maximum, then the normal derivative at that point must be nonnegative since the function cannot be decreasing as we move towards the point in the domain, from any direction. Hopf's lemma strengthens this in the special case that the function is harmonic to say that it is strictly positive rather than just nonnegative. You are right however that we cannot make a general statement about the $gradient$ vanishing on the boundary when we have a min/max like we can on the interior; this is just like the above simple case, where we see that $f'(1) = 0$ for the local min inside the interval but do not get the same behavior for extrema on the boundary.


Remote File Explorer for Mac

Question: I have a couple employees that aren't experienced with the Linux shell. Is is possible for them, on their Macs, to be able to open a remote connection with our servers(with Finder or otherwise), browse the files, then open a file, say /etc/ssh/sshd_config, with their local editor, modify it, then when they save it saves it on the remote side?
Comment: You could set up a CIFS or AFP share on the server and then they could mount the appropriate filesystem using "Connect to server..." in the Finder.
Comment: Do *panic* and such a *transmit* becomes easy...
Comment: I like that idea larsks, I'll start working in that direction.
Answer: Yes & no & why?  When you say:

…browse the files, then open a file, say /etc/ssh/sshd_config, with
  their local editor, modify it, then when they save it saves it on the
  remote side?

Well, the sshd_config is a fairly deep system file. And any user editing that would need root access or placed in the sudoers. So why would you want folks who you say "aren't experienced with the Linux shell" to have such deep access in such a casual way?
Assuming you are confident this needs to be done, the users need to be given sudo and sftp access.  Then they could just use any FTP program to setup an SFTP connection, maneuver to the files they need to edit & the job is done.
But that is really a bad way to handle access, privileges & permissions. And the scenario you describe is absolutely horrendous from a security standpoint.
But then again, where are they accessing from? Outside of a closed network? Remotely from home?  Maybe if this were in an Intranet then this would not be so bad.  You could even setup AFP or Samba access.  But if you are talking about folks accessing a secured server across a distance, AFP an Samba are horrible choices because they are protocols that thrive in low-latency (ie: fast/no-delay) environments.  SFTP is the only choice.
Comment: Cyberduck is EXACTLY what I'm looking for. Thank you.
Comment: Well, the whole sshd_config was a hypothetical. The files that need to be edited are non system files that are owned by the user that they'd be authenticating as. But your suggestion of using an SFTP client is almost there. It would be ideal to remove the extra steps of transferring the file back forth before and after editing it.
Comment: You don't have to transfer files back & forth with SFTP. Just open an SFTP connection with an FTP tool like `Fetch`, `CyberDuck` or `Transmit`, choose the file that has to be edited & all programs allow that file to be edited in place with editors local to a users Mac like `TextEdit` or `BBEdit`.

Remote File Explorer for Mac


Dynamically attaching style in map array function

Question: I want to dynamically attach color to my react component
These are the colors I want to attach
  this.color = ["#E91E63", "#2196F3", "#FDD835"]

I am mapping an array in JSX (sort of like this)
   { this.state.graphData.map(data => {
        (<VictoryArea name="area-1" data={data} style={{ data: { fill: "#E91E63" } }}/>)
    })}

My mapped array have 6 elements.
I want element 1 and element 4 to have same color, 2 and 5, 3 and 6.
Question: Can someone please help me in figuring out how I can attach dynamic color in fill?
Answer: You can use the second argument of the map function which is the index of the element, along with the % operator to get the color dynamically.
{this.state.graphData.map((data, index) =>
  <VictoryArea
    name="area-1"
    data={data}
    style={{ data: { fill: this.color[index % this.color.length] } }}
  />
)}


How do I configure Kubernetes to use kubenet with kubeadm?

Question: I deployed a Kubernetes cluster using kubeadm.
$ kubectl get nodes
NAME                                          STATUS     ROLES                  AGE   VERSION
ip-172-31-33-9.us-east-2.compute.internal     NotReady   <none>                 48m   v1.22.2
ip-172-31-46-53.us-east-2.compute.internal    NotReady   control-plane,master   49m   v1.22.2
ip-172-31-47-245.us-east-2.compute.internal   NotReady   <none>                 6s    v1.22.2

The nodes are NotReady because I haven't installed a networking plugin. I want to use keep it simple and use kubenet. The instructions say:

Kubelet must be run with the --network-plugin=kubenet argument to
enable the plugin

but I can't figure out how to do that. I have tried adding it to various configuration files, such as /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf and /etc/sysconfig/kubelet, and restaring kubelet, but none of it works.
How do I use kubenet with kubeadm?
Comment: Hi timkay welcome to S.F. You have said you "tried it" but "none works" but yet you shared none of your attempts with us in order to gauge what you're already tried and why it might not be working. Please read the [how to ask](https://serverfault.com/help/how-to-ask) page. In the spirit of trying to be a little helpful, did you remember to run `systemctl daemon-reload` in between edits? systemd does not use the latest values on disk -- it must be forced to re-read them. Good luck!
Comment: As I said, the docs say to add `--network-plugin=kubenet` to the kubelet command line, but I never have a kubelet command line, as kubelet gets started by kubeadm. Thus, I don't have any attempts to share with you.
Answer: You can use the /etc/default/kubelet file to override kubelet arguments.
As can be found in the 10-kubeadm.conf file:
...
# This is a file that the user can use for overrides of the kubelet args as a last resort. Preferably, the user should use
# the .NodeRegistration.KubeletExtraArgs object in the configuration files instead. KUBELET_EXTRA_ARGS should be sourced from this file.
EnvironmentFile=-/etc/default/kubelet
...

I'll show you how it works.

First, I set up the Kubernetes control plane:
# kubeadm init
[init] Using Kubernetes version: v1.22.2
...

# mkdir -p $HOME/.kube
# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
# sudo chown $(id -u):$(id -g) $HOME/.kube/config

After successful initialization, we can check the value of the --network-plugin argument that kubelet is currently using and the status of the coredns Pods:
# ps aux | grep "kubelet" | grep "network-plugin"
root     27488  5.1  3.6 1816612 145808 ?      Ssl  10:42   0:01 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.5

# kubectl get pod -n kube-system | grep "coredns"
coredns-78fcd69978-bbc52          0/1     Pending   0          2m26s
coredns-78fcd69978-fdcv9          0/1     Pending   0          2m26s

From the above output, we can see that --network-plugin=cni and coredns Pods are in the Pending state.
Let's create the /etc/default/kubelet file and write the kubelet arguments there:
NOTE: You may need to customize the --pod-cidr and --pod-infra-container-image to suit your needs.
# touch /etc/default/kubelet

# echo 'KUBELET_KUBEADM_ARGS="--network-plugin=kubenet --pod-cidr=10.20.0.0/24 --pod-infra-container-image=k8s.gcr.io/pause:3.5"' > /etc/default/kubelet

# cat /etc/default/kubelet
KUBELET_KUBEADM_ARGS="--network-plugin=kubenet --pod-cidr=10.20.0.0/24 --pod-infra-container-image=k8s.gcr.io/pause:3.5"

Then we need to reload systemd manager configuration and restart kubelet:
# systemctl daemon-reload
# systemctl restart kubelet

Finally, we can check if it works as expected:
# ps aux | grep "kubelet" | grep "network-plugin"
root     27841  6.9  3.5 1890600 143760 ?      Ssl  10:47   0:01 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --network-plugin=kubenet --pod-cidr=10.20.0.0/24 --pod-infra-container-image=k8s.gcr.io/pause:3.5

# kubectl get pod -n kube-system | grep "coredns"
coredns-78fcd69978-bbc52          1/1     Running   0          6m51s
coredns-78fcd69978-fdcv9          1/1     Running   0          6m51s

# kubectl get nodes
NAME      STATUS   ROLES                  AGE   VERSION
kmaster   Ready    control-plane,master   15m   v1.22.2

You can follow these steps for all of your nodes.
Additionally, please remember that (more information can be found in the kubenet documentation):

Kubenet is a very basic, simple network plugin, on Linux only. It does not, of itself, implement more advanced features like cross-node networking or network policy. It is typically used together with a cloud provider that sets up routing rules for communication between nodes, or in single-node environments.
Comment: No need to run `systemctl daemon-reload`, since no `systemd` configuration changed that would need to be reloaded. I also don't like using `/etc/default` for custom configurations. Otherwise very helpful, thanks!
Comment: Actually `kubeadm` ["does not support kubenet"](https://unofficial-kubernetes.readthedocs.io/en/latest/getting-started-guides/kubeadm/) according to this wiki.
Comment: Hello @timkay and welcome to ServerFault! Please remember to [react to answers for your questions](https://stackoverflow.com/help/someone-answers).
That way we know if the answers were helpful and other community members could also benefit from them. Try to [accept answer](https://stackoverflow.com/help/accepted-answer) that is the final solution for your issue, upvote answers that are helpful and comment on those which could be improved or require additional attention. Enjoy your stay!
Comment: Thank you, @matt_j. I followed your instructions, which I summarized this way:

1. Install as before, using kubeadm.
2. Create a file /etc/default/kubelet, with extra kubelet parameters.
3. Restart kubelet with systemctl daemon-reload && systemctl restart kubelet.

I did that, and the command line parameters for kubelet didn't change. The env variable KUBELET_KUBEADM_ARGS would tell me that it's used by kubeadm to start kubelet, but we don't run kubeadm at all after making changes as per your instructions.
Comment: How did you check that the kubelet parameters did not change ?
Could you please use this command: `ps aux | grep "kubelet" | grep "network-plugin"` ?
Comment: I gave up on Kubernetes and wrote my own replacement.
Comment: Hello @timkay. Any updates?
Answer: kubeadm gives the possibility to use a --config yaml file that is documented here. In this file you can use the cli parameters from kubelet as extra args like --network-plugin=kubelet as network-plugin: kubelet:
apiVersion: kubeadm.k8s.io/v1beta3
kind: InitConfiguration
bootstrapTokens:
...
nodeRegistration:
...
  kubeletExtraArgs:
    ...
    network-plugin: kubenet
    pod-cidr: 10.20.0.0/24

Comment: Kubernetes is so messed up. I gave up on it a long time ago and wrote my own replacement, which is only a few hundred lines of code. I am quite disappointed that the industry seems to be a pyramid scheme. People write complex software that only highly trained people can use. Where is the craftmanship? As Elon says, "no part is the best part." Stop fixing complexity problems by making everything more complex.
Comment: @timkay True words, I can fully understand your statement :)


Add class to menu link href tag?

Question: I know that using hook_menu_link I can add classes to the
 tags but I need to add a class to the  tags within the
 of a menu. I've looked and can't find a way.
Any ideas?
Answer: You can do it from hook_menu_link. You want to access the $vars['element']['#localized_options']['attributes']['class']
Something like this
$element = $vars['element'];
$element['#localized_options']['attributes']['class'][] = 'your-class';
$output = l($link_text, $element['#href'], $element['#localized_options']);

Then return the $output in the
. Be sure to account for $vars['element']['#below'] if you have a sub-menu.
Comment: Thank you, forgot to post that I found the same solution.
Comment: Just a correction. It's a theme_menu_link not hook_menu_link.

Add class to menu link href tag?


Como usar o mesmo id mais de uma vez com o getElementById()?

Question: Olá, pessoal. Tudo bem?
Tenho um cronômetro que está em javascript e quero que ele apareça mais de uma vez em uma página específica.
O problema é que ele funciona apenas na primeira vez em que aparece na página.
Eu imagino que seja por causa dos ids que são duplicados na página em html (id="days" id="hours" id="minutes" id="seconds") quando tento duplicar o segundo cronômetro. Mas se quero chamar os cronômetros preciso usar esses ids.
Para tentar contornar o problema tentei usar o getElementsByClassName() no lugar do getElementById(). Assim, poderia usar classes em vez de ids no meu HTML. Logo, poderia chamar o código javascript através da classe mais de uma vez, sem problemas. Porém, meu código não funcionou com o getElementsByClassName(). O cronômetro simplesmente não aparece quando tento usar essa função.
Alguém tem alguma solução para que esse cronômetro funcione mais de uma vez na mesma página?

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {

      let now = new Date().getTime(),
          distance = countDown - now;

      document.getElementById('days').innerText = Math.floor(distance / (day)),
        document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
        document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
        document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);

    }, second)

dias

Horas

Minutos

Segundos

Comment: Olá, Bacco. Tudo bem?
Por alguma motivo, este código deixou de funcionar de ontem para hoje. Eu tentei entender o problema mas não consegui. Suponho que seja na função que obtém a data de hoje. Poderia me dar uma luz? Desde já agradeço a sua atenção.
Answer: Soluções tem muitas, mas com o JS que está usando, o ID é necessário
(mas tem uma alternativa com class no final).
Você pode numerar os IDs:

 Dias

...

 Dias

...

 Dias

...

E na hora de atualizar, usar um loop:
for (var i = 1; i <= 3; i++ ) {
  document.getElementById('days' + i).innerText = Math.floor(distance / (day)),
  //                             ^-- note a concatenação
  ...

Provavelmente você vai usar tempos diferentes em cada cronômetro, aí é só você mudar a referência de tempo em cada iteração do loop, seja com um array ou outra técnica qualquer, mas isso foge do problema da pergunta, que foi solucionado com o loop. Programar, no fim das contas, é isso, descobrir como usar os recursos da linguagem para resolver a tarefa.
Demonstração:

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {

      let now = new Date().getTime(),
          distance = countDown - now;

      for (var i = 1; i <= 3; i++ ) {
        document.getElementById('days'+i).innerText = Math.floor(distance / (day)),
        document.getElementById('hours'+i).innerText = Math.floor((distance % (day)) / (hour)),
        document.getElementById('minutes'+i).innerText = Math.floor((distance % (hour)) / (minute)),
        document.getElementById('seconds'+i).innerText = Math.floor((distance % (minute)) / second);
      }
    }, second)

 Dias

 Horas

 Minutos

 Segundos

 Dias

 Horas

 Minutos

 Segundos

 Dias

 Horas

 Minutos

 Segundos

Se os cronômetros forem iguais, pode usar class:
Note que o getElementsByClassName retorna vários elementos, você precisa iterar sobre eles.

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {
      let now = new Date().getTime(),
          distance = countDown - now,
          spanSeconds = document.getElementsByClassName('seconds'),
          i = spanSeconds.length,
          valueSeconds = Math.floor((distance % (minute)) / second);

      while(i--) spanSeconds[i].innerText = valueSeconds;
    }, second)

 Segundos

 Segundos

 Segundos

https://developer.mozilla.org/pt-BR/docs/Web/API/Document/getElementsByClassName
Comment: O exemplo com classe funcionou perfeitamente. Eu estava utilizando a função com classe de forma muito errada. Agradeço muitíssimo a sua atenção, Bacco. Tenha uma ótima semana!
Comment: Obrigado pela resposta, Bacco. Eu nunca pensei em colocar um contador para incrementar aos ids no código javascript. Deu muito certo, porém resolve parte do problema porque os ids do código HTML não são variáveis.

Na verdade eu não usaria tempos diferentes. Os cronômetros são iguais. Apenas se repetem na página.
Comment: Mas pensei aqui que posso criar uma função em php que incremente um valor i ao id do HTML. Como você fez no javascript. Só não sei como o valor i do html vai ser exatamente igual ao valor i do javascript. Será que este seria um bom caminho. Se sim, vou pensar como fazer isso. Assim que tiver pronto eu posto aqui.
Comment: Basta gerar o JS com o mesmo PHP que gera o HTML - sugiro não postar junto, pois vc fez uma pergunta de um problema de JS, o PHP é mera implementação e só vai acrescentar ruido (outros visitantes podem chegar a esta mesma pergunta sem necessariamente ser um projeto em PHP).
Comment: Acrescentei um exemplo com classe, ja que sao iguais


How to prove $\frac 10 \notin \mathbb R $

Question: I'm trying to prove $\frac 10 \notin  \Bbb R $ by contradiction.
That means by supposing  $\frac 10 \in \mathbb R.$
Is there a way to do this?
Thanks.
Comment: What does $\frac{1}{0}$ mean?
Comment: Indeed, remember that $\frac{a}{b}$ is another notation for $a \cdot b^{-1}$. So now you have to ask "What does $b^{-1}$ denote?" For that, you'll need to go back to the axioms of the real numbers.
Comment: so, 1/0 does not have a meaning. am I right?
Comment: Why don't you tell us *why* you think that $1/0$ does not have a meaning? If you can do this, then our answers will be helpful to you.
Comment: because 0 does not have an inverse
Answer: To prove that $\frac{1}{0}$ does not exist, it is perhaps best to start by reviewing the definition of division.
By definition, $\frac{a}{b}$ is the unique solution to the equation $a=bx$. So $\frac{1}{0}$, if it exists, is equal to the unique solution to the equation $1=0x$.
However, that equation has no solution: using the field axioms, which the real numbers satisfy, it is easy to show that $0x=0$ for any real number $x$, and $0 \ne 1$.
Therefore, $\frac{1}{0}$ does not exist.
Comment: +1 for this elementary approach. I lost the point trying to show that it is not defined formally.
Answer: If by $\Bbb R$ you mean the usual real line then the division by zero is not defined because it is not defined either for the field of rational numbers $\Bbb Q$, what is contained in $\Bbb R$.
The rational numbers are generally constructed formally through two operations defined over the set $\Bbb Z\times\Bbb Z\setminus\{0\}$:
$$\text{Addition}\quad(a,b)+(c,d)=(a+c,b+d)$$
$$\text{Multiplication}\quad(a,b)\cdot(c,d)=(ad+bc,bd)$$
for any tuples $(a,b),(c,d)\in\Bbb Z\times\Bbb Z\setminus\{0\}$, where we generally write $(a,b)\equiv\frac{a}b$, and the operations $a+b$ and $ab$ are defined on the integers. Then observe that there is no rational number of the form $(a,0)\equiv\frac{a}0$, so it doesn't have a meaning associated to it.
However, in other constructions as the one-point compactification of the real line, namely $\widehat{\Bbb R}$, we can define $\frac{a}0:=\infty$ for any $a\in\widehat{\Bbb R}\setminus\{0\}$. But in the standard real line, as I had shown above, the symbols $\frac{1}0$ doesn't have a meaning attacked to it.
Thus this is not a question that can be "proved", it is just that it is not defined at all.


Computed dependent field

Question: I have a node type (actually entityform type) with a term reference field. The terms has a description field (a long text with a HTML markup). I need to display the description of a selected term on a node edit form. Is it possible to show a description immediately after user selects new term from a list?
Comment: On the node edit form? I guess you'd need Ajax to show the description.
Comment: Is it possible to use an existing modules or I need to write my own one?
Comment: @Denis No module I know of provide this functionality. There are modules that lets you limit choices in one field basing on choice in another one, but none I know changes descriptions.
Comment: Maybe it's possible to add something like a viewfield, which shows all term descriptions. And to filter the view by a term reference field?
Answer: It seems that it's very easy to implement a computed dependent field. Suppose there is a term reference (field_section) on an edit form with YOUR_FORM_ID.
<code>function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == YOUR_FORM_ID) {

    // Add an AJAX behaviour to field_section:
    // After you will select a new term on the edit form,
    // YOUR_MODULE_NAME_form_alter and
    // _YOUR_MODULE_NAME_form_section_callback will be called.
    $form['field_section'][LANGUAGE_NONE]['#ajax'] = array(
      'event' => 'change',
      'callback' => '_YOUR_MODULE_NAME_form_section_callback',
      'wrapper' => 'nomination-desc-wrapper',
      'method' => 'replace',
      'effect' => 'fade'
    );

    // Add a wrapper for our computed dependent field.
    // At the begining it will be invisible
    $form['nomination_desc_container'] = array(
      '#type' => 'hidden',
      '#weight' => 2,
      '#attributes' => array('id' => array('nomination-desc-wrapper')),
    );

    // Add a computed dependent field. It will be shown as a text
    $form['nomination_desc_container']['nomination_desc'] = array(
      '#type' => 'item',
    );

    // This code will be executed during form creation and
    // during each AJAX-call
    if (isset($form_state['values']['field_section'])) {

      // Find taxonomy term
      $tid = $form_state['values']['field_section'][LANGUAGE_NONE][0]['tid'];
      $term = taxonomy_term_load($tid);

      // Show it's description
      $form['nomination_desc_container']['nomination_desc']['#markup'] = $term->description;

      // Display description wrapper
      $form['nomination_desc_container']['#type'] = 'container';
    }
  }
}

// Just return new wrapper body
function _YOUR_MODULE_NAME_form_section_callback($form, &$form_state) {
  return $form['nomination_desc_container'];
}
</code>

Computed dependent field


Pulling data out from a DateTime object that is inside of a DataRow?

Question: I have a little app that connects to an Oracle database that stores course completions for a training class.  The database has employee names, employee numbers, date the course was completed, and the name of the course. I have code that returns one row, shown below:
<code>            String strPerIdNo = textBox1.Text;
            String strQuery = "PER_ID_NO = " + "'" + strPerIdNo + "'";
            DataRow[] foundRows;
            foundRows = dataSet1.DataTable1.Select(strQuery);
</code>
The row contains an array of 5 elements:

[0] - System.DateTime object
[1] - String object
[2] - Int object
[3] - String object
[4] - String object

I want to instantiate a DateTime object from the DateTime object in the array at [0], but I cannot figure out how.  I want to display a message that contains the emp name and date they completed the course.
Thank you!
Answer: Okay, first, you're not instantiating anything here, because the DateTime you want already exists (or else, it wouldn't be in the DataRow!).  In addition, DateTime is a value type, not a reference type; it's not normal to think of instantiating a value type; you just initialize or copy them.
What you are looking for is to get the value of the DateTime element in your DataRow.  Here are the steps:
<code>//step 0: make sure there's at least one DataRow in your results
if (foundRows.Length < 1) { /* handle it */ }

//step 1: get the first DataRow in your results, since you're sure there's one
DataRow row = foundRows[0];

//step 2: get the DateTime out of there
object possibleDate = row["TheNameOfTheDateColumn"];

//step 3: deal with what happens if it's null in the database
if (possibleDate == DBNull.Value) { /* handle it */ }

//step 4: possibleDate isn't a DateTime - let's turn it into one.
DateTime date = (DateTime)possibleDate;
</code>
Comment: Awesome! Thanks a lot, that worked out great.  Can you tell me a little bit about what is happening in Step 4? I've never seen a statement like that.
Comment: When you have (Type)variableName, what that is doing is casting variableName to the data type in the parentheses, in this case, from type "object" to type "DateTime".  You can only do that with compatible types though.  For instance, you can convert an object into a DateTime only if it started out as a DateTime (when it lived inside the Sql Server in this case).  Type conversion is a very big topic, so have fun learning about it!
Answer: If it's a DateTime object then why not just cast it? Like

foreach(DataRow row in foundRows) {
    var dt = (DateTime)row[0];
}


Java: .Class searcher

Question: What i need is a little application which allows me to search multiple .class files for a word. Can that be done with which application?
Comment: @Christian String literals will still be in the .class file, but you're probably right about really wanting to search .java files.
Comment: Very exotic need )) Consider decompiling `*.class` files instead using some tool like JAD: http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29
Comment: It sort of depends if your word is compiled away or not. But, `javap` might help.
Comment: You do realize that .class files are binary (compiled), right? I think you mean .java files.
Answer: Grep. Grep solves all.
E.g: grep word *.class
Comment: Now, the output may be particularly ugly.  But you can set options so it'll just tell you what files match, without showing you the matches.
Comment: I'd suggest "grep -iR word *.class". Used from the root directory for class files. Searches recursively and case independently
Comment: Then you can use JD-GUI to decompile the class file and get good output. http://java.decompiler.free.fr/?q=jdgui

Java: .Class searcher


JSON serialization/deserialization Alamofire, Swift

Question: I have Alamofire request like this:
Alamofire.request("myurl", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseData { (responseData) in

let data = responseData.data

do {
   let country = try JSONDecoder().decode(MYOBJECT.self, from: data)
} catch {
   print(error)
   }
}

MYOBJECTS comes from backend and it looks like this:
data class CountryObject(
   val country: String,
   val name: String,
) : ResponseObject

The problem is that (obviously) MYOBJECT doesnt conform to decodable object. This is the error => Instance method 'decode(_:from:)' requires that 'MYOBJECT' conform to 'Decodable'
My question is do I have to replicate the object? How do I conform this object to Decodable protocol? I also need to deserialize this object (JSON) from Alamofire, is my approach correct? Any advice? Thank you!
Answer: Create a Swift model corresponding to the backend model. Look at the JSON and make a model like this:
struct Country: Decodable {
    var country: String
    var name: String
}

And decode it using the above model, like if it's returning a single object:
let country = try JSONDecoder().decode(Country.self, from: data)

If it's an array:
let country = try JSONDecoder().decode([Country].self, from: data)

Note: Use quicktype to generate your model for your JSON quickly :).
Comment: Is there any way I can use my Kotlin class and make it Decodable?
Comment: No, you can't. You're receiving data as `JSON` which doesn't contain information about any particular language class.
Answer: First of all, your CountryObject seems to be Kotlin and not Swift?
In Swift, having a class or struct conform to Decodable is just as easy as this:
struct CountryObject : Decodable {
    val country : String
    val name : String
}

Comment: Yes my CountyObject is in Kotlin! So in your answer I should replicate my object in swift?
Comment: Yes, you need a Swift version of CountryObject, or MYOBJECT, if that is the name of your class/struct.
Comment: Is there any way I can use my Kotlin class and make it Decodable?


Categorize cells by keywords

Question: I am not certain if excel can do this but I am trying to simplify the data dump that I get from twitter.
Basically what I would like to do is this:
If the tweet (in Column A) contains apple OR orange OR pear then it can be classified (in Column B) as "fruit" BUT if it has carrot OR squash OR lettuce it will be classified as "vegetable". If it has none of these then can be classified as "none"
Is this possible?
Thanks in advance.
Comment: To answer your question, that is possible using a formula. You can use array constants or you can use a range or named range to contain the list you are trying to find match from the string in Column A.
Answer: Here is using array constant and range.
=IF(SUMPRODUCT(IF(ISERROR(SEARCH({"apple","orange","pear"},A1)),0,1))>0,"Fruit",IF(SUMPRODUCT(IF(ISERROR(SEARCH({"carrot","squash","lettuce"},A1)),0,1))>0,"Vegetable","None"))
Now for example, both fruit and vegetable are present in a string, it will always test for fruit first since that is the way the formula was arranged. (e.g. "more apple on salad than lettuce" will return "Fruit").
You can also use a range that contains your list instead of the array constant.
For example, you can put your fruit list in Column C (C1:C3) and your vegetable list in Column D (D1:D3). Your formula would then be:
=IF(SUMPRODUCT(IF(ISERROR(SEARCH(C$1:C$3,A1)),0,1))>0,"Fruit",IF(SUMPRODUCT(IF(ISERROR(SEARCH(D$1:D$3,A1)),0,1))>0,"Vegetable","None"))
But you need to enter it as Array Formula using Ctrl+Shift+Enter.
Same results and rule apply when both fruit and vegetable appear on a string. HTH.
Answer: Sure.
Try this formula
=IF(
    OR(
       NOT(ISERROR(SEARCH("apple",A1))),
       NOT(ISERROR(SEARCH("pear",A1))),
       NOT(ISERROR(SEARCH("orange",A1)))
    ),
    "fruit",
    IF(
       OR(
          NOT(ISERROR(SEARCH("carrot",A1))),
          NOT(ISERROR(SEARCH("squash",A1))),
          NOT(ISERROR(SEARCH("lettuce",A1)))
      ),
      "veggie",
      "none"
  )
)

Categorize cells by keywords


Como passar um valor de parâmetro padrão dentro de um foreach no C#?

Question: Caros amigos,
Como eu poderia passar um valor de parâmetro padrão dentro de um foreach?
Exemplo, dentro do meu foreach tenho um if que faz uma determinada comparação com um atributo da minha classe certo?. Mas por padrão no c# ao fazer get nos dados de um atributo preciso passar qual o ID da posição da lista quero receber tais dados (Ex: ListaEmpregados[0].getCodigo(), ListaEmpregados[1].getCodigo(), etc).
Mas meu problema é justamente esse quero fazer o get de todos os registros com aquele atributo, no caso não saberia a posição do meu ID exatamente (EX:Ex: ListaEmpregados[N].getCodigo(), ListaEmpregados[N].getCodigo() ).
Não sei se fui muito clara, mas existe alguma parâmetro 'padrão' ou algo no tipo que me ajude nesse caso? grata!
var ListaEmpregadosPorCodigo = ListaEmpregados.OrderBy(p => p.getCodigo());

foreach ( var codigo in ListaEmpregadosPorCodigo)
{
    int iCodigo = Convert.ToInt32(codigo.getCodigo());

    if (iCodigo == ListaEmpregados[].getCodigo())
    {
        //Código
    }
}

Comment: Se `p.getCodigo()` retorna o valor de um atributo não seria melhor criar uma [propriedade](https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/classes-and-structs/properties) para tal.
Comment: Não entendi a sua necessidade. Você está percorrendo uma lista no teu foreach. Tu quer pegar a posição atual do laço de repetição?
Answer: Bom, você poderia utlizar Linq para fazer essa operação, alem de  mais leve e mais clean code
tente
var items = ListaEmpregados.Where(x =>
                   x.Any(z => z.getCodigo() ==  x.getCodigo())
            );


Erro salvar dados de um cadastro sqlite

Question: Estou com erro ao salvar dados de um cadastro de pessoas no sqlite JavaNullPointerException: invalid int:(51)3452-2470. Esse erro começou a ocorrer após eu ter aplicado uma máscara. Seguem os códigos abaixo.
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public abstract class Mask {
public static String unmask(String s) {
    return s.replaceAll("[.]", "").replaceAll("[-]", "")
    .replaceAll("[/]", "").replaceAll("[(]", "")
    .replaceAll("[)]", "");
}

public static TextWatcher insert(final String mask, final EditText ediTxt) {
    return new TextWatcher() {
        boolean isUpdating;
        String old = "";
        public void onTextChanged(CharSequence s, int start, int before,int   count) {
            String str = Mask.unmask(s.toString());
            String mascara = "";
            if (isUpdating) {
                old = str;
                isUpdating = false;
                return;
            }
            int i = 0;
            for (char m : mask.toCharArray()) {
                if (m != '#' && str.length() > old.length()) {
                    mascara += m;
                    continue;
                }
                try {
                    mascara += str.charAt(i);
                } catch (Exception e) {
                    break;
                }
                i++;
            }
            isUpdating = true;
            ediTxt.setText(mascara);
            ediTxt.setSelection(mascara.length());
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void afterTextChanged(Editable s) {}
    };
}
}

O próximo código é a minha tela de cadastro.
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import br.gestaoBd.BancoDeDados.ClienteDao;
 import br.gestaoBd.Beans.Cliente;

 public class CadCliente extends Activity {

EditText edId, edNome, edEmail, edTelefone, edEndereco, edCpf, edRg;
ClienteDao cliDao;

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.cad_clientes);
    edId = (EditText) findViewById(R.id.cadEdId);
    edNome = (EditText) findViewById(R.id.cadEdNome);
    edEmail = (EditText) findViewById(R.id.cadEdEmail);
    edTelefone = (EditText) findViewById(R.id.cadEdTelefone);
    edTelefone.addTextChangedListener(Mask.insert("(##)####-####", edTelefone));
    edEndereco = (EditText) findViewById(R.id.cadEdEndereco);
    edCpf = (EditText) findViewById(R.id.cadEdCpf);
    edCpf.addTextChangedListener(Mask.insert("###.###.###-##", edCpf));
    edRg = (EditText) findViewById(R.id.cadEdRg);
    edRg.addTextChangedListener(Mask.insert("##.###.###-#", edRg));

    Cliente clienteRecebido = (Cliente) getIntent().getSerializableExtra("Cliente");
    if (clienteRecebido != null) {
        montaTela(clienteRecebido);
    } else {
        montaTela(new Cliente());
    }

    Button btnSalvar = (Button) findViewById(R.id.btSalvar);
    btnSalvar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(Integer.valueOf(edTelefone.getText().toString()));
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(Double.valueOf(edRg.getText().toString()));
            cli.setCpf(Double.valueOf(edCpf.getText().toString()));

            if (cli.getId() > 0) {
                getCliDao().alterar(cli);
            } else {
                getCliDao().inserirCliente(cli);
            }
            ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                    ToastManager.INFORMATION);

        }

    });

    Button btnLimpar = (Button) findViewById(R.id.btLimpar);
    btnLimpar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            montaTela(new Cliente());
        }
    });

    Button btExcluir = (Button) findViewById(R.id.btExcluir);
    btExcluir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(Integer.valueOf(edTelefone.getText().toString()));
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(Double.valueOf(edRg.getText().toString()));
            cli.setCpf(Double.valueOf(edCpf.getText().toString()));
            AlertDialog.Builder builder = new AlertDialog.Builder(CadCliente.this);
            builder.setTitle("Deseja Excluir?");
            builder.setMessage("O Cliente será deletado!");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    getCliDao().excluir(cli);
                    montaTela(new Cliente());
                    ToastManager.show(getBaseContext(), "Cliente excluído",
                            ToastManager.INFORMATION);

                }

            });

            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    ToastManager.show(getBaseContext(), "Cancelado",
                            ToastManager.INFORMATION);
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });

}

private void montaTela(Cliente cliente) {
    edId.setText(String.valueOf(cliente.getId()));
    edNome.setText(cliente.getNome());
    edEmail.setText(cliente.getEmail());
    edTelefone.setText(String.valueOf(cliente.getTelefone()));
    edEndereco.setText(cliente.getEndereco());
    edCpf.setText(String.valueOf(cliente.getCpf()));
    edRg.setText(String.valueOf(cliente.getRg()));
}

public ClienteDao getCliDao() {
    if (cliDao == null) {
        cliDao = new ClienteDao();
    }
    return cliDao;
}

}

Comment: coloque a máscara em um campo somente e verifique se dá erro novamente.
Answer: Olá !
Não consegui entender o porque o corre um JavaNullPointerException, quando na verdade deveria ocorrer um NumberFormatException.
Vamos lá:
Onde deveria ter um int você está passando o número formatado (51)3452-2470 por isso ocorre o invalid int:.
Antes de salvar, você deverá remover os caracteres inválidos!
  cli.setTelefone(Integer.valueOf(edTelefone.getText().toString()));

Se o telefone é um campo Inteiro, aqui deveria ocorre um erro de NumberFormatException .
Então para corrigir vamos remover a máscara:
 cli.setTelefone(Integer.valueOf(Mask.unmask(edTelefone.getText().toString())));

Com o Mask.unmask passamos apenas os números!
Comment: Olá Thiago Luiz.. Fiz exatamente o que sugeriu e de fato não mostrou o mesmo erro. Porém ocorreu um outro erro. Nos Logs aqui só mostra que na linha onde eu fiz a alteração, conforme sugerido, está apontando erro de invalid int mas não mostra o telefone como ocorria antes.
Comment: Pode mostrar o Log? Altere sua pergunta e adicione estas informações! fica mais fácil de lhe ajudar!
Comment: Veja se este erro não está ocorrendo com o Rg ou o CPF, pois eles também possui mascaras!
Comment: Não não.. o erro é exatamente no número de telefone.. aparece invalid int  sem a máscara na tela de log, tua ajuda funcionou pois removeu a máscara..
Comment: Tente debugar e veja como está indo o número
Comment: está indo assim: NumberFormatException: invalid int "5196487698"
Comment: É um valor muito grande para um int. Sugiro você usar String, tanto para o telefone, como RG e CPF.
Answer: Sempre uso Integer.parseInt(String) para converter string em numeros, pode ajudar

Erro salvar dados de um cadastro sqlite


Regular expression problem, skipping unkown amount of matches?

Question: I am using c# but its basically not really important, my question is: is it possible, only with regular expression skipping matches?
my regex was
Text = Regex.Replace(Text, @"\[code1\]((.|\n)*?)(\<\/span\>) ", "$1");

but the problem with this, is greedy... allways gets the first match of the closing span
I have a string similar like this:
[code1]test string bladibla[code2]code2 string [code3] code3 string [code1]   end of the span string

and my ending result should be something like:
test string bladibla[code2]code2 string [code3] code3 string [code1]   end of the span string

Do you guys have any suggestions?
Answer: Assuming that substrings starting with "[code]" and ending with "" can be nested inside each other, and you are trying to find matching pairs of them, the answer is no. Regular expressions can't match nested patterns, it's one of their theoretical limitations. (I know that's not a solution, but it is permission to stop banging your head on this particular wall.)
Comment: Cheers:) I just found a nice blog entry, in case if somebody would have the same problem: http://blogs.msdn.com/b/jaredpar/archive/2008/10/15/regular-expression-limitations.aspx
Answer: I can't follow you. Your regex is definitely not greedy (*? is a lazy quantifier), so it will match from [code1] to the closest  it finds, just as in your example.
However, it will also match from the second [code1] in your sample until the following . Is it this behaviour you're trying to prevent? If so, what is the difference between the two cases? Do you only want to match the first occurrence, or do you only want to match it at the start of the string, or...?
Finally, instead of ((.|\n)*?) you can write (.*?) if you specify RegexOptions.Singleline.
Comment: I thing in graph theory means greedy, that matching the first occurence of the string, in this case a first closing span. Which is not the behaviour that I want to achieve. If you see my "starting" string and the (desired)output string, then its clear, that I want a match with the last occurence of the closing spans. Therefore I can avoid the "nestation" problem.

And why is a usage of RegexOptions.Singleline is better then a pure regular expression? I dont see the point, besides its more typing.
Comment: Interesting. Well, in regular expressions "greedy" means "try to match as much as possible". So if all you want is to match from the first `[code]` to the last ``, just drop the `?` after the `*`.
Comment: About `RegexOptions.Singleline`: Usually in regexes, the dot matches any character except newline; and nearly all regex flavors (except JavaScript) have a "dot matches all (including newlines)" option. In .NET, it's turned on via `RegexOptions.Singleline` which is more explicit than the cryptic `((.|\n)*)` construct, especially if it turns up more than once in the regex.


Time Series: How can I adjust pd.date_range(freq='B') with the Saturday included. (Python)

Question: This is my example code:
q=pd.date_range('05/13/2019',periods=100, freq='B')

Obviously, it would list out 100 the working days from 05/13/2019 with no Saturday and Sunday. However, in some Asia nations, they are, indeed, working on Saturday.
How can I fix this ? so that the result should be 100 days from 05/13/2019 with only no Sunday.
Answer: You can do this using the .bdate_range method and the 'C' (Custom) frequency. Then we pass what we want in weekmask
import pandas as pd
weekmask = 'Mon Tue Wed Thu Fri Sat'
pd.bdate_range(start="11-May-2019", periods=10, freq='C', weekmask=weekmask)

OUTPUT:
DatetimeIndex(['2019-05-11', '2019-05-13', '2019-05-14', '2019-05-15',
               '2019-05-16', '2019-05-17', '2019-05-18', '2019-05-20',
               '2019-05-21', '2019-05-22'],
              dtype='datetime64[ns]', freq='C')

As you see it did not include 12 and 19 May that were Sundays! :)
Answer: Try doing two date_ranges and remove the Sundays from the first one:
>>> q = pd.date_range('05/13/2019', periods=100, freq='D')
>>> q2 = pd.date_range('05/13/2019',periods=100, freq='W')
>>> q[~q.isin(q2)]
DatetimeIndex(['2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16',
               '2019-05-17', '2019-05-18', '2019-05-20', '2019-05-21',
               '2019-05-22', '2019-05-23', '2019-05-24', '2019-05-25',
               '2019-05-27', '2019-05-28', '2019-05-29', '2019-05-30',
               '2019-05-31', '2019-06-01', '2019-06-03', '2019-06-04',
               '2019-06-05', '2019-06-06', '2019-06-07', '2019-06-08',
               '2019-06-10', '2019-06-11', '2019-06-12', '2019-06-13',
               '2019-06-14', '2019-06-15', '2019-06-17', '2019-06-18',
               '2019-06-19', '2019-06-20', '2019-06-21', '2019-06-22',
               '2019-06-24', '2019-06-25', '2019-06-26', '2019-06-27',
               '2019-06-28', '2019-06-29', '2019-07-01', '2019-07-02',
               '2019-07-03', '2019-07-04', '2019-07-05', '2019-07-06',
               '2019-07-08', '2019-07-09', '2019-07-10', '2019-07-11',
               '2019-07-12', '2019-07-13', '2019-07-15', '2019-07-16',
               '2019-07-17', '2019-07-18', '2019-07-19', '2019-07-20',
               '2019-07-22', '2019-07-23', '2019-07-24', '2019-07-25',
               '2019-07-26', '2019-07-27', '2019-07-29', '2019-07-30',
               '2019-07-31', '2019-08-01', '2019-08-02', '2019-08-03',
               '2019-08-05', '2019-08-06', '2019-08-07', '2019-08-08',
               '2019-08-09', '2019-08-10', '2019-08-12', '2019-08-13',
               '2019-08-14', '2019-08-15', '2019-08-16', '2019-08-17',
               '2019-08-19', '2019-08-20'],
              dtype='datetime64[ns]', freq=None)


How do I tell Graphene to load my @Page?

Question: TL;DR: How do I tell Graphene which (relative) URL to load for the @Page-injected object?

I'm trying to setup my web frontend integration tests using the "State of the art", namely a combination of Arquillian, Arquillian Drone, Selenium 2 and Graphene 2.
With Arquillian, Drone and plain Selenium WebDriver (i.e. without any Graphene specific stuff), a test can look like this:
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;

import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;

import org.junit.Assert;
import org.junit.Test;

import org.junit.runner.RunWith;

import org.openqa.selenium.WebDriver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RunWith(Arquillian.class)
public class LoginIT {
    private static final Logger LOG = LoggerFactory.getLogger(LoginIT.class);

    @Deployment
    public static WebArchive createDeployment() {

        return Maven.resolver().loadPomFromFile("pom.xml")
                    .resolve("de.zalando:purchasing-frontend-general:war:?")
                    .withoutTransitivity().asSingle(WebArchive.class);
    }

    @Drone
    WebDriver driver;

    @ArquillianResource
    URL deploymentUrl;

    @Test
    @RunAsClient
    public void testLoginPage() {
        LOG.info("executing test!");

        driver.get(deploymentUrl + "");

        final String title = driver.getTitle();
        LOG.info("title: " + title);
        Assert.assertEquals("Login page title is wrong",
                            "Zalando General Purchasing – Login", title);
    }
}

(It took me a while to get the deployment right, because of non-current documentation for ShrinkWrap.)
This simple test just checks if we are redirected from the home page to the login page, and that its title is right. It works.
Graphene 2 adds an important new Feature, "autowiring" Page abstractions. Then my test could look like this (omitting imports and the deployment part as above):
@RunWith(Arquillian.class)
public class LoginIT {
    private static final Logger LOG = LoggerFactory.getLogger(LoginIT.class);

    @Deployment
    public static WebArchive createDeployment() {
        // as above
    }

    @Page
    LoginPage loginPage;

    @Test
    @RunAsClient
    public void testLoginPage() {
        String title = loginPage.getTitle();
        LOG.info("title: " + title);
        Assert.assertEquals("Login page title is wrong",
                            "Zalando General Purchasing – Login", title);
    }
}

Using this "Page abstraction" object:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPage {

    @FindBy(tagName = "title")
    private WebElement titleElement;

    public String getTitle() {
        return titleElement.getText();
    }
}

This actually works, my test doesn't fail and even outputs the right title.
But this doesn't work at all (I don't know why I seemed to think it does, I must have looked at the output of the previous test) ...
I get an "org.openqa.selenium.NoSuchElementException: Unable to locate element with name: title" with a really long stack trace (through all of Arquillian, Graphene, the Java Reflection API, the Maven Surefire Plugin and two lines of my code).
Debugging into the method shows that it finally tries to access the Html-Element, and the HtmlPage at hand is an about:blank-page, not my login page.
Is this how it is supposed to work? And why doesn't it work for me?
Then I want to test other pages than the login page, and for this I need to use other start URLs.
With plain Drone+ Selenium Webdriver, I would simply use
driver.get(deploymentUrl + "/otherPage");

as the first line of the test. But what to do with the Graphene 2 @Page-Annotation?
How do I tell Graphene which URL (relative to the deploymentUrl) to load for the @Page-injected object?
Answer: The behavior is expected. Graphene initializes Page Objects fields.
To load page automatically, you can encapsulate the location of the page object within @Location annotation. Together with @InitialPage, you can achieve the desired behavior.
Your Page Object declaration would look like:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import import org.jboss.arquillian.graphene.page.Location;

@Location("login.html")
public class LoginPage {

    @FindBy(tagName = "title")
    private WebElement titleElement;

    public String getTitle() {
        return titleElement.getText();
    }
}

Your test:
@Test
@RunAsClient
public void testLoginPage(@InitialPage LoginPage loginPage) {
    String title = loginPage.getTitle();
    LOG.info("title: " + title);
    Assert.assertEquals("Login page title is wrong",
                        "Zalando General Purchasing – Login", title);
}

Now, the login.html will be loaded automatically relatively to your contextRoot as the first action during test execution.
You can read more about this features at documentation.
Answer: I personally use inheritance and generics to achieve this (however it's maybe not the best solution). You can look for example here. You need to define AbstractPage like this
public interface AbstractPage {

    public abstract String getURL();
}

@RunWith(Arquillian.class)
public abstract class AbstractWebDriverTest
 {

    @Page
    private P page;

    @Before
    public void goToUrl() {
        driver.get(deploymentURL + page.getURL());
    }
}

Then each test class is going to implement AbstractPage with the page specified in <>. Take a look at that sample project, I hope that helps!
Comment: So goToUrl will be executed before the page is filled from the @Page annotation? But after the page object is created? I have trouble understanding this, but will try it out.
Comment: It depends, `@Before` will be executed before test (so yes - before loading the page object), `@After` of course after:)Also note that Page objects are loaded lazily, Graphene tries to load WebElements few times before it fails.


Sigma Algebras and Measure

Question:
Let $(X,A,\mu )$ be a measure space (where  denotes the measure and $A$ the
  $\sigma$-algebra) and $u : X \to \overline{\Bbb R}$ (where $\overline{\Bbb R}$ includes $-\infty, +\infty$) be a non-negative $A$-measurable function with $\int_X ud\mu < \infty$ (i.e $u$ is $\mu$-summable).
Explain why the set $\{x \in X : u(x) = +\infty\}$ belongs to the $\sigma$-algebra $A$ and prove that  $\mu\{x \in X : u(x) = +\infty\} = 0$

I am not quite sure how to approach this. I know the properties of a $\sigma$-algebra but I do not know how to explain that something is in a sigma algebra. I suppose for the second part about the measure of the set, I have to use Fatous lemma since it is specified that $u$ is non-negative and $\mu$-summable but I am not sure about that either. Would I have to use dominated convergence perhaps?
Comment: Since $u$ only takes values in $\mathbb{R}$, it cannot take the value $+\infty$, so your set is empty. Do you perhaps mean $u:X \to [0,+\infty]$, i.e. $u$ is allowed to take values from the extended real line?
Comment: Well you have to define what sets on real line are measurable if you want your question to be correct
Comment: @MisterRiemann sorry, I made an error typesetting the question.
Comment: If you mean classical Lebesgue measure, use the fact that if $u$ is $A$-measurable then for any $c \in R$ you will have $u^{-1}(c; \infty ) \in A$ to prove your first statement
Answer: In your question it is mentioned that $u:X\to\overline{\mathbb R}$ is $\mathcal A$-measurable.
Then the question rises: with respect to which $\sigma$-algebra on $\overline{\mathbb R}$?
If it is a  $\sigma$-algebra with the property that singleton subset $\{+\infty\}$  is measurable (and usually it is) then it is actually immediate that $\{x\in X\mid u(x)=+\infty\}$ is measurable. This simply because $u$ is measurable, so that $u^{-1}(\{+\infty\})\in\mathcal A$.
If it is known that the $\sigma$-algebra on $\overline{\mathbb R}$ contains sets like $(x,+\infty]$ where $x\in\mathbb R$ then it can be shown that also $\{+\infty\}$ is an element of the $\sigma$-algebra. For that see the proof of Fred.
For the question concerning $\mu(\{x\in X\mid u(x)=+\infty\})=0$ see the answer of Kavi.
Answer: For $n \in \mathbb N$ let $M_n:=\{x \in X: u(x)>n\}.$ Then $M_n \in A$, since $u$ is $A$- measurable, and
$$\{x \in X : u(x) = +\infty\} = \bigcap_{n \in \mathbb N}M_n.$$
Can you proceed ?
Answer: The fact that the set belongs to $\mathcal A$ is part of the definition of measurability of extended real valued functions. There is nothing to prove! Now suppose $\mu \{x:u(x)=\infty\}>0$. Then $\int u d\mu \geq \int _{\{x:u(x)=\infty\}}d \mu =(\infty) (\mu \{x:u(x))=\infty\}=\infty$.

Sigma Algebras and Measure


adding series of numbers [1-->5000] with tread C++?

Question: I want to add a series of numbers [1-->5000] with threads. But the result is not correct.
The goal is only to understand the threading well, because I am a beginner.
I tried this:
void thread_function(int i, int (*S))
{
    (*S) = (*S) + i;
}

main()
{
    std::vector<std::thread> vecto_Array;
    int i = 0, Som = 0;

    for(i = 1; i <= 5000; i++)
    {
        vecto_Array.emplace_back([&](){ thread_function(i, &Som); });
    }

    for(auto& t: vecto_Array)
    {
        t.join();
    }

    std::cout << Som << std::endl;
}

And I tried this:
int thread_function(int i)
{
    return i;
}

main()
{
    std::vector<std::thread> vecto_Array;
    int i = 0, Som = 0;

    for(i = 1; i <= 5000; i++)
    {
        vecto_Array.emplace_back([&](){ Som = Som + thread_function(i); });
    }

    for(auto& t: vecto_Array)
    {
        t.join();
    }

    std::cout << Som << std::endl;
}

The result is always wrong. Why?
I solved the problem as follows:
void thread_function(int (*i),int (*S))
{
    (*S)=(*S)+(*i);
    (*i)++;
}
main()
{
    std::vector<std::thread> vecto_Array;
    int i=0,j=0,Som=0;
    for(i=1;i<=5000;i++)
    {
     vecto_Array.emplace_back([&](){thread_function(&j,&Som);});
    }
    for(auto& t: vecto_Array)
    {
    t.join();
    }
    std::cout << Som<<std::endl;
}

But is there anyone to explain to me why it did not work when taking "i of loop" ?
Comment: just a warning: multi-threading isn't something that one can learn by trial and error. Even more than usual it is simple to write code that appears to be fine but isn't. Cant recommend something specifically, but you can try here: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
Comment: Does this answer your question? https://stackoverflow.com/questions/34510/what-is-a-race-condition
Comment: You need to serialize the access to `Som` between the threads, such as with a `std::mutex`, so that they don't all try to write to the same memory at the *exact* same time, corrupting the bytes being written.
Comment: I have a try : '#include
std::mutex mu;.. mu.lock();
 (*S)=(*S)+i;
 mu.unlock();'
Comment: "I solved the problem as follows" - no, you didn't *solve* the problem, you managed to produce variant of code which *hides* the problem on your particular platform and configuration. It's by no means correct multi-thread code and would broke again on any non-trivial extension of it.
Comment: what s the solution in your opinion..?
Answer:
Your attempt #1 has a race condition. See What is a race condition?
Your Attempt #2 neglects the standard, which says about the thread function these words:

Any return value from the function is ignored.

(see: https://en.cppreference.com/w/cpp/thread/thread/thread )

Your attempt #3 has a race condition.

Concurrent programming is an advanced topic. What you need is a book or tutorial. I first learned it from Bartosz Milewski's course: https://www.youtube.com/watch?v=80ifzK3b8QQ&list=PL1835A90FC78FF8BE&index=1
but be warned that it will likely take years before you become comfortable in concurrency. I am still not. I guess what you need as a beginner is std::async (see Milewski's tutorial or use Google). Even gentler learning curve is with OpenMP https://en.wikipedia.org/wiki/OpenMP , which could be called "parallelization for the masses".


Discrete-time dynamics can be modelled by the stochastic differential equation

Question: I'm reading the following paper, in which the stochastic gradient descent consists of performing partial computations of the form $$x^{k+1}=x^k-\eta_k\nabla f_{i_k}(x^{k-1})\qquad\mbox{ where }\eta_k>0,k\in\mathbb{N} \qquad(*)$$ where $i_k$ is sampled uniformly at random from the set $\{1,...,N\}$, at each iteration, starting from a random initial condition $x^0$ . The stochastic nature of SGD arises from the approximation of the gradient using only a subset of data points.

My question is, why the discrete-time dynamics in (*) can then be modelled by the stochastic differential equation (SGD) $$dx(t)=-\nabla f(x(t))\,dt+\beta^{-1/2}\,dW(t)$$

Moroever, the generator, $\mathcal{L}$, corresponding to (SGD) is defined for smooth functions $\phi$ as, $$\mathcal{L}\phi=-\nabla f\cdot\nabla\phi+\frac{\beta^{-1}}{2}\Delta\phi$$
Sorry if the question is too basic, but I'm new with this topic. Thanks!
Answer: Regarding the first question, I suppose the idea is to write the equation as $$x^{k+1}-x^{k} = -\eta_k\nabla f_{i_k}(x^{k})$$ (note that I wrote $f_{i_k}(x^{k})$ and not $f_{i_k}(x^{k-1})$ which I believe is a typo). and approximate $x^{k+1}-x^{k}\sim dx$ , and approximating the stochastic gradient term and treating it to be the same as the "true" gradient plus a noise term: $ \nabla f_{i_k}(x^{k})\sim \nabla f(x^{k})+\text{gaussian noise}$
As for the second question, I think this is the Van Kampen expansion.


função contrária de reshape2::melt (desempilhar)

Question: Estou trabalhando com data.frame e ele está organizado no formato long. Porém eu gostaria de colocar no formato wide em função de uma variável (FAT2) de tal forma que as disposições das colunas ficariam: AVA, FAT1, Banana, Ingá, Gliricídia, Pupunha.
Entretanto, não gostaria de converter em matriz, e depois novamente em data.frame. A função melt do pacote reshape2 faz no caso o contrário do que eu preciso, pois ela empilha as variáveis.
dados:
dados<-structure(list(AVA = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 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6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L), .Label = c("Março de 2016",
"Agosto de 2016", "Dezembro de 2016", "Março de 2017", "Agosto de 2017",
"Fevereiro de 2018", "Abril de 2018", "Agosto de 2018"), class = c("ordered",
"factor")), FAT1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L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1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L,
    4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L,
    4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L
    ), .Label = c("Banana", "Gliricídia", "Ingá", "Pupunha",
    "Solteiro"), class = "factor"), LUX = c(39018.33, 38870,
    40375, 39686.67, 53363.33, 55666.67, 56888.33, 57768.33,
    5029.33, 4758, 4810.67, 5044.67, 17840.67, 2917.33, 8508.67,
    9960.67, 3014, 4704.67, 5712, 3815.33, 4683.33, 49213.33,
    54353.33, 57226.67, 13939.33, 13869.33, 5100.67, 15864, 1809.47,
    1814.53, 6084.67, 2357.33, 28333.33, 37586.67, 35640, 36833.33,
    55886.67, 59886.67, 63193.33, 63346.67, 25313.33, 36593.33,
    24466.67, 38420, 26700, 29106.67, 36746.67, 52300, 25586.67,
    13106.67, 2782.67, 15677.33, 18310.67, 2864.67, 1893.13,
    2330, 5256.67, 5313.33, 3916, 5219.33, 5176.67, 6183.33,
    2959.33, 3823.33, 803.93, 1815.87, 1629.93, 1886.47, 7705.33,
    2350, 2322.6, 1715.8, 25313.33, 23700, 38420, 28253.33, 26700,
    11562.67, 49326.67, 52300, 9258, 7078, 6374, 7147, 6435,
    8366, 9639, 129220, 3481, 1973.8, 4097, 3584, 4189, 1573,
    3312, 2488, 2886, 2908, 4489, 4047, 4641, 3429, 3434, 4903,
    4341, 4352, 5019, 8046, 4060, 4552, 5445, 7159, 7870, 4004,
    5660, 9790, 8772, 6728, 129010, 128520, 27106.67, 19360,
    28766.67, 25513.33, 29606.67, 30206.67, 21666.67, 34660,
    15920, 18108.67, 6322, 2402.67, 19686.67, 28853.33, 2898,
    3403.33, 2437.33, 4086, 25520, 22993.33, 2664, 4850, 3688,
    3084.67, 22528.67, 4182, 24286.67, 4442.67, 29561.54, 29606.67,
    28740, 34120, 16304.67, 12944.67, 25466.67, 25513.33, 26006.67,
    30836.36, 35130, 34645.45, 15926.67, 16664, 24580, 15746,
    15780.67, 37533.33, 63600, 21560, 12336, 15016.67, 8820.67, 9112, 29880, 35580, 31173.33, 21893.33, 5828, 8477.33, 8122.67,
    13715.33, 7430, 14023.33, 13144.67, 6759.33, 5126.67, 7038.67,
    13430.67, 13701.33, 8657.33, 14273.33, 21368, 18332, 16500,
    16000, 14870.67, 14990.67, 13547.33, 14310, 14806.67, 13180,
    39786.67, 58420, 56646.67, 59280, 60213.33, 60633.33, 61533.33,
    64240, 46886.67, 55386.67, 9316, 43553.33, 5883.33, 5913.33,
    39906.67, 13561.33, 29660, 11585.33, 25340, 8721.33, 57513.33,
    58613.33, 5214, 60060, 9409.33, 36626.67, 22033.33, 7980.67,
    7192, 5508, 57680, 9765.33, 39020, 35806.67, 56393.33, 50346.67,
    23554, 54246.67, 63540, 62333.33, 14585, 54200, 55500, 18350,
    18340, 54100, 58200, 12260, 17285, 15520, 6565, 5650, 34116.67,
    4145, 27601.33, 3215, 2110, 2425, 4955, 5000, 2955, 3230,
    9165, 4550, 3310, 6505, 4375, 4635, 4260, 3635, 4205, 3480,
    10820, 12205, 16245, 13600, 17000, 13425.33, 11295, 11950,
    4350, 5040, 6060, 16640, 10440, 24000, 29100, 30700, 3280,
    3150, 2810, 2735, 17050, 20650, 9645, 10050, 4775, 4370,
    5575, 5340, 3490, 6555, 5060, 5015, 2375, 2320, 4015, 3265,
    7570, 6380, 28550, 26750, 4100, 3110, 14715, 15260, 4915,
    4740, 27850, 17625, 3015, 3760, 4460, 4720, 5115, 5655, 6030,
    9560, 2015, 2070, 2015, 2135, 2320, 2050, 2895, 2855, 2085,
    2355, 2160, 2000, 2600, 2955, 3050, 3020, 2010, 2030, 2990,
    2890, 3785, 3880, 4610, 3890, 2165, 2835, 4625, 4650, 4045,
    4190, 6715, 6340, 4640, 5425, 8295, 16705, 28450, 17340,
    11920, 16360, 4455, 4690, 4580, 4485, 11455, 10970, 13070,
    11050, 3080, 3650, 3425, 3225, 9400, 9245, 9250, 7560, 4015,
    3930, 14690, 15655, 24650, 25050, 10755, 9665, 4560, 2800,
    6540, 15120, 23650, 24500, 11780, 11835, 14585, 54200, 55500,
    18350, 18340, 54100, 58200, 12260, 17285, 15520, 6565, 5650,
    38184, 35550, 19769.33, 10050, 14730, 43700, 7765, 53400,
    3490, 6555, 9165, 4550, 3310, 6505, 4375, 4635, 4260, 3635,
    4205, 3480, 10820, 12205, 16245, 13600, 16700, 16920, 11295,
    11940, 6378.67, 8702, 12030.67, 12763.33, 11382.67, 10196.67,
    15526.67, 25286.67, 6464.67, 6798.67, 7080.67, 7154, 7233.33,
    7295.33, 8962, 8216.67, 5050, 5228, 5123.33, 5759.33, 4839.33,
    5850, 10330.67, 9663.33, 6067.33, 5602.67, 11512, 11443.33,
    8872, 6894.67, 15792, 17444, 6363.33, 6348, 10490, 10608.67,
    10612, 10328.67, 20473.33, 21013.33, 12346.67, 11642, 11633.33,
    10872.67, 11450, 14792.67, 15706.67, 16808.67, 5212, 6328.67,
    7770.67, 7900.67, 6811.33, 8420.67, 9960, 11131.33, 4928.67,
    5762, 3576.67, 5667.33, 4864, 8104, 8059.33, 10923.33, 8298.67,
    7838.67, 7096.67, 7933.33, 8718, 8661.33, 10809.33, 13119.33,
    11730, 11612.67, 8514.67, 10682, 11146.67, 11176, 16385.33,
    15394.67, 5042, 5016, 4355.33, 10662.67, 8518.67, 9772, 9260.67,
    14453.33, 2844, 3033.33, 3482.67, 3040.67, 8392, 8357.33,
    6963.33, 7312.67, 2083.33, 2644.67, 3127.33, 3185.33, 5400,
    6658.67, 6665.33, 7681.33, 3954.67, 3862.67, 5732, 6284.67,
    6444.67, 6130.67, 9072.67, 10302.67, 4456, 4186.67, 9228.67,
    8806.67, 7652.67, 7651.33, 11231.33, 11864.67, 10765.33,
    10205.33, 13295.33, 181760, 25786.67, 28353.33, 28133.33,
    32020, 6081.33, 6643.33, 5420.67, 6404, 9358.67, 9443.33,
    14206.67, 5926.67, 5401.33, 5755.33, 3053.33, 3208.67, 3636.67,
    8914, 5722, 2652, 8018, 7822, 8363.33, 6810, 14776, 8667.33,
    29380, 12555, 10355.33, 8673.33, 13400.67, 13861.33, 18545.33,
    5779.33, 28780, 31800, 10460.67, 14330.67, 16945.33, 14323.33,
    12078.67, 17226.67, 19428.67, 25380, 9596.67, 10008, 10206.67,
    9514.67, 8998.67, 9454, 12915.33, 13706.67, 5633.33, 6972.67,
    6780, 9155.33, 9674, 13180.67, 10200, 9502, 10344.67, 10446,
    14296.67, 14274.67, 12012.67, 11167.33, 24953.33, 24980,
    10092, 9101.33, 12308.67, 13586, 11862, 12034, 22446.67,
    25173.33)), row.names = c(NA, -640L), class = "data.frame")

Comment: Dê uma olhada na função `reshape2::dcast`.
Answer: Por primeiro, você precisa criar uma variável identificadora:
dados$id <- 1:nrow(dados)

Em seguida, as variáveis que você quer que fique na linha precisam estar no lado esquerdo da formula, e na coluna do direito. Por fim, tu precisa falar qual função você quer agregar os dados. Neses caso, coloquei sum, que não fará nenhuma diferença, apenas irá manter os dados originais (pois você tem apenas 1 valor) para cada combinação:
reshape2::dcast(dados, id + AVA + FAT1 ~ FAT2, fun.aggregate = sum, value.var = "LUX")
     id               AVA  FAT1   Banana Gliricídia     Ingá   Pupunha  Solteiro
1     1     Março de 2016 Antes     0.00       0.00     0.00      0.00  39018.33
2     2     Março de 2016 Antes     0.00       0.00     0.00      0.00  38870.00
3     3     Março de 2016 Antes     0.00       0.00     0.00      0.00  40375.00
4     4     Março de 2016 Antes     0.00       0.00     0.00      0.00  39686.67
5     5     Março de 2016 Antes     0.00       0.00     0.00      0.00  53363.33
6     6     Março de 2016 Antes     0.00       0.00     0.00      0.00  55666.67
7     7     Março de 2016 Antes     0.00       0.00     0.00      0.00  56888.33
8     8     Março de 2016 Antes     0.00       0.00     0.00      0.00  57768.33
9     9     Março de 2016 Antes     0.00       0.00  5029.33      0.00      0.00
10   10     Março de 2016 Antes     0.00       0.00  4758.00      0.00      0.00
11   11     Março de 2016 Antes     0.00       0.00  4810.67      0.00      0.00
12   12     Março de 2016 Antes     0.00       0.00  5044.67      0.00      0.00
13   13     Março de 2016 Antes     0.00       0.00 17840.67      0.00      0.00
14   14     Março de 2016 Antes     0.00       0.00  2917.33      0.00      0.00
15   15     Março de 2016 Antes     0.00       0.00  8508.67      0.00      0.00
16   16     Março de 2016 Antes     0.00       0.00  9960.67      0.00      0.00

No entanto, se você quiser agregar os dados, basta:
reshape2::dcast(dados[, -5], AVA + FAT1 ~ FAT2, fun.aggregate = sum, value.var = "LUX")

                 AVA  FAT1    Banana Gliricídia      Ingá   Pupunha  Solteiro
1      Março de 2016 Antes 182722.66   60839.33  58870.01 380706.67 381636.66
2      Março de 2016  Após  37847.99   20229.93  82551.81 255576.00 269646.67
3     Agosto de 2016 Antes  30737.00   42974.00  24697.80 300354.00 183517.00
4     Agosto de 2016  Após  69323.33  177468.22  97594.67 206847.82 216886.68
5   Dezembro de 2016 Antes  77500.66  101928.00 163812.00 118205.34 211390.67
6   Dezembro de 2016  Após 256707.32  156195.33 220407.33 385240.67 460753.33
7      Março de 2017 Antes  34390.00   34405.00 114098.00 106540.33 285535.00
8      Março de 2017  Após  40180.00   81225.00  69370.00  92315.00 126330.00
9     Agosto de 2017 Antes  20225.00   26085.00  18355.00  35565.00  42315.00
10    Agosto de 2017  Após  48835.00  108410.00  64755.00 100785.00 109135.00
11 Fevereiro de 2018 Antes 143355.00   34405.00 148573.33 109725.00 285535.00
12 Fevereiro de 2018  Após  51843.99   83628.00  59205.34  96237.33 102267.35
13     Abril de 2018 Antes  51885.33   72475.33  63535.34  96642.01 105252.68
14     Abril de 2018  Após  37445.99   51784.69  43426.00  65078.01  67080.67
15    Agosto de 2018 Antes  38343.33   96391.66  63484.67 131195.32 330319.32
16    Agosto de 2018  Após  71098.00  122475.34  84400.68 116604.00 130174.01

aí sim ele retorna o data.frame com a soma de cada uma das espécies de FAT2 para o valor de LUX.
Answer: Usando o tidyverse, você primeiro precisa criar um data.frame intermediário agregando os valores de LUX e depois espalhar ele (spread()):
library(tidyverse)

dados %>%
  group_by(AVA, FAT1, FAT2) %>%
  summarise(LUX = sum(LUX)) %>%
  spread(FAT2, LUX)

# Groups:   AVA, FAT1 [16]
   AVA               FAT1   Banana Gliricídia    Ingá Pupunha Solteiro
   <ord>             <fct>   <dbl>      <dbl>   <dbl>   <dbl>    <dbl>
 1 Março de 2016     Antes 182723.     60839.  58870. 380707.  381637.
 2 Março de 2016     Após   37848.     20230.  82552. 255576   269647.
 3 Agosto de 2016    Antes  30737      42974   24698. 300354   183517
 4 Agosto de 2016    Após   69323.    177468.  97595. 206848.  216887.
 5 Dezembro de 2016  Antes  77501.    101928  163812  118205.  211391.
 6 Dezembro de 2016  Após  256707.    156195. 220407. 385241.  460753.
 7 Março de 2017     Antes  34390      34405  114098  106540.  285535
 8 Março de 2017     Após   40180      81225   69370   92315   126330
 9 Agosto de 2017    Antes  20225      26085   18355   35565    42315
10 Agosto de 2017    Após   48835     108410   64755  100785   109135
11 Fevereiro de 2018 Antes 143355      34405  148573. 109725   285535
12 Fevereiro de 2018 Após   51844.     83628   59205.  96237.  102267.
13 Abril de 2018     Antes  51885.     72475.  63535.  96642.  105253.
14 Abril de 2018     Após   37446.     51785.  43426   65078.   67081.
15 Agosto de 2018    Antes  38343.     96392.  63485. 131195.  330319.
16 Agosto de 2018    Após   71098     122475.  84401. 116604   130174.

A tabela intermediária só precisou ser criada porque havia mais de uma linha para cada conjunto de AVA + FAT1. Caso as informações já fossem únicas para cada grupo, bastaria usar o spread().
Comment: Que solução elegante. Gostei mais do que a solução que utiliza `reshape2::dcast`.
Comment: Grato pela dica Tomás Barcellos e Marcus Nunes!!!
Comment: estou utilizando `base %>% pivot_longer(cols=all_of(c("FAT1","FAT2")),names_to = "variable",values_to = "value") %>% group_by(FAT1, FAT2) ` , e estou encontrando dificuldades ao usar `summarise(soma = sum(value))`, aparentimente ele não soma, se uso `mean()`, `sd()` fica ok, agora se uso `sum()`, ele só repete os valores. alguém sabe me dizer o porque?
Comment: Não consegui entender. Recomendo fazer outra perguntar e garantir a reprodutibilidade do exemplo/problema.


Como declarar funções em uma array declarada no bloco de uma classe?

Question: Ao mínimo tentei, mas o PHP joga um erro de síntaxe:

Parse error: syntax error, unexpected 'function' (T_FUNCTION)

Resumindo, não posso declarar funções na minha array.
Quando eu crio a minha array $ast fora do bloco da classe PMoon, funciona. Há alguma outra maneira de declarar essa array contendo funções?
<?php

/* ... */

class PMoon {

    /* ... */

    public $ast = array(

        "labelStatement" => function($label) { // o erro começa aqui
        return array(
            "type" => 'LabelStatement',
            "label" => $label
        );
        }

        /* ... */

    );

    /* ... */
}

Answer: Segundo a página do PHP sobre propriedades, isso acontece porque:

[...] São definidas usando uma das palavras-chave public, protected, or
  private, seguidas de uma declaração normal de variável. Esta
  declaração pode incluir sua inicialização, porém esta inicialização
  deve ser um valor constante - isso é, deve ser possível avaliá-lo em
  tempo de compilação e não deve-se depender de informações de tempo de
  execução.

Uma forma de resolver isso é usar o array no método __construct:
class PMoon{
    public $ast = array();

    public function __construct(){
        $this->ast = array('labelStatement' =>
        create_function('$label', 'return array("type" => "LabelStatement",
                                                "label" => $label);'
        ));
    }
}

E para usá-la, faça assim:
$moon = new PMoon;
$labelFunc = $moon->ast['labelStatement']('Foo bar');

var_dump($labelFunc);

//array(2) {
//  ["type"]=>
//  string(14) "LabelStatement"
//  ["label"]=>
//  string(7) "Foo bar"
//}

Ver demonstração


Hardy's approximation for the cosine

Question: I was reading about the Hardy's approximation for the cosine function (here and also in Mathworld):
$$\cos \left(\frac{\pi}{2} x\right) \approx 1-\frac{x^{2}}{x+(1-x) \sqrt{\frac{2-x}{3}}}$$
For $0<x<1$
What I would like to know is, how was this approximation derived? What other uses does it have? The links also include a graph showing the error between $\cos(x)$ and the approximation. There isn't much information on the internet about this interesting formula.
Comment: The same question has been recently also asked [here](http://en.wikipedia.org/wiki/Wikipedia:Reference_desk/Mathematics#September_26), on *Wikipedia Mathematics Reference Desk*.
Comment: I've read the paper refered in MathWorld, but I found nothing about this cosine approximation in it.
Comment: In the link I added, it's at equation (8), starting at the "A close approximation to cos(pix/2) for x in [0,1] is" line.
Comment: Yes. I know. And there is a referred paper to Hardy 1959 p. 68, but I found nothing there about it.
Comment: While I agree that the approximation is interesting, there needs to be a specific question suitable for answering in the Math.SE format in order for this to be a good Question.  For example, one might emphasize "how was this approximation derived?" in the context of Hardy's writings.  If the Hardy paper referred to is not apt, that lends to the Reader's confusion.
Comment: I redoubled my efforts to track down the writings of Hardy.  The citations of a kind given by Wolfram/MathWorld, likely copied from other Web pages, lead to a *book* RamanujanL: Twelve Lectures... by Hardy (1940 and republished in 1959, etc.) on subjects inspired by the work of Ramanujan.  The table of contents and searches inside the book by Google Books and Amazon do not reveal a likely page citation. Page 68 in particular is in chapter 5, on A Lattice Point Problem.
Comment: Short of trudging to the library to make a visual inspection, there seems little evidence to follow on this trail.  Of course the pagination of a newer edition might differ from the original (Hardy himself died in 1947), and Amazon seems to offer a 1999 reprint "with additional corrections" (2002) as the displayed edition.
Answer: (Cross posting my answer from the Wikipedia help desk.)
Here is a way you might reverse engineer the formula, though I have no idea how Hardy derived it.
Let $C(x) = \cos(πx/2)$. We know from the Taylor series that:$$C(x) = 1 - \frac{x^2}{\text{constant}} + \text{other terms}$$
Rewrite this as $C(x) = 1 - \frac{x^2}{K(x)}$ where K is to be determined. We also know $C(1) = 0$ from which $K(1)=1$. Expand $K$ at $x=1$ to get:
$$K(x)=1+(\text{constant})\cdot (x-1)+\text{higher terms}$$
Again, collecting the the constant and higher terms into a single function, write $K(x)=1+(x-1)L(x)$.
At this point you can get a fairly good approximation for $C$ by plugging in a linear approximation for $L$. But we also know $C(1/2)=\sqrt{2}/2$ which would imply (after some computation) $L(1/2) = 1 - \sqrt{1/2}$. So, perhaps a better approximation of $L$ would be: $$L(x)\approx 1 -\sqrt{\frac{1}{2}+m(x-\frac 1 2)}$$ (For some constant m.)
If you plug in $C(2/3)=1/2$ you get $m=-1/3$ which produces the approximation given, but other values of $m$ might work just as well or better. I found $m=-.337$ gives the lowest mean square error on the interval.
Note that there are points in the derivation where different choices could be made, for example you could write $C(x) = 1 - x^2⋅K(x)$ or $K(x)=1+\frac{(x-1)}{L(x)}$. It might be fun to explore these variations to see how they compare with the one given.
Comment: I have edited your post to make use of $\LaTeX$.  Please look it over to ensure that I haven't inadvertently changed the intent of your post.
Comment: @anorton - Looks good, thanks!

Hardy's approximation for the cosine