How to completely disable the default Cursor.TEXT for a TextArea object

Question: I've tried CSS as well as setting the cursor through scene and the object itself, nothing seems to work it always comes up with that cursor.
I'm not talking about the caret or caret position either, I mean the actual mouse cursor when you hover over a TextArea which I want either removed or changed to the default pointer.
<code>textArea.setCursor(Cursor.DEFAULT);
scene.setCursor(Cursor.DEFAULT);
.text-area {
    -fx-cursor: default;
}
</code>
Answer: Because the text area uses a scroll pane internally, your mouse is really over the content of the scroll pane. So this works:
<code>.text-area .content {
    -fx-cursor: default ;
}
</code>
Comment: Please mark the answer as correct; it will make it easier for others to find it.


Reversible Encryption - Not Defined but Showing as Enabled?

Question: I'm reviewing our complex password policy that was setup by a previous admin and I'm trying to gain some clarification on the setting for Reversible Encryption. In our organization, reversible encryption is not needed and should be disabled. When I review the GPO that's in place and I can see that for the setting:
Store passwords using reversible encryption: Not Defined
My understanding is that if it's set to 'Not Defined', then the default value is set to Disabled but maybe I'm incorrect on this. When I run rsop on my system, it reflects the Not Defined status.
Where I'm a bit confused though is when i run the PS cmdlet Get-ADDefaultDomainPasswordPolicy; I'm seeing the ReversibleEncryptionEnabled property as being set as True.
Shouldn't this be reflective of Disabled, per how my Password Policy GPO is configured?
Answer: That means the setting was Enabled at one time, then changed to Not Configured.
You will need to change the setting to Disabled to revert back.
You may also want to enable the setting:
Administrative Templates > System > Group Policy
Security Policy Processing: Process even if the group policy objects have not changed
And do the same for Registry Policy Processing if you want to make sure that settings are applied consistently.


Set default TTL in Varnish 4.0?

Question: I am new to Varnish, and I am running v4.0 on Debian Wheezy.
I would like to set a default TTL across my cache of 4 weeks (very static content).
From reading the docs I think the answer is to set a default_ttl option somewhere in my VCL file. I have searched the docs but can only find one reference to it.
I've found this question but I think the answer must be out of date, because it doesn't work for me.
Could someone clarify how to do this in Varnish 4.0?
UPDATE: Here's my config file (the default that ships with Varnish 4.0, except that I've pointed the backend at localhost):
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_backend_fetch {
    set obj.ttl = 4w;
}

sub vcl_recv {
    # Happens before we check if we have this in cache already.
    #
    # Typically you clean up the request here, removing cookies you don't need,
    # rewriting the request, etc.
}

sub vcl_backend_response {
    # Happens after we have read the response headers from the backend.
    #
    # Here you clean the response headers, removing silly Set-Cookie headers
    # and other mistakes your backend does.
}

sub vcl_deliver {
    # Happens when we have all the pieces we need, and are about to send the
    # response to the client.
    #
    # You can do accounting or modifying the final object here.
}

Comment: Welcome to ServerFault. This question will likely be closed as a duplicate, since the same question already exists. I know that the current answers haven't helped you, so I suggest placing a bounty on the original question to bring more attention to it, and possibly receive more recent answers. Also, if you find the answer elsewhere, you can add that as an answer to the original question of course.
Comment: Er, it's not a duplicate. I explicitly linked to that question in my original question and said the answer doesn't apply to 4.0. How can that be a duplicate? Or is SF now so keen on closing questions down that you can only ask a question once for one version of a tool, and never again get answers for any other version of a tool? :(
Comment: Also, how is this question not a clear problem statement?
Comment: There's no difference in the syntax, and the other answers appear to work just fine in Varnish 4.0. From the information you've given us, it appears that you haven't actually tried them -- or anything else!
Comment: possible duplicate of [Varnish Cache - default TTL?](http://serverfault.com/questions/389202/varnish-cache-default-ttl)
Comment: your *question* is a duplicate, it doesn't matter if the answers helped you or not. Unfortunately your question or the former question wasn't tagged w/ the specific version, but that can be changed.
Comment: The question is not a duplicate. The question is about Varnish 4.0 and is explicitly flagged as such. The older question is about an older version of Varnish. The older answers do not apply to this question.
Comment: It's like saying "this question was answered for Chrome 1.0, so you cannot ask it for Chrome 32". It's just not helpful for users and it's not helpful for the site.
Comment: try adding your config file to this question and it can be voted on to reopen.
Answer: default_ttl is a runtime parameter. You can set it when you start varnishd.

default_ttl
Units: seconds
  Default: 120.000
  Minimum: 0.000
  Flags: The TTL assigned to objects if neither the backend nor the VCL code assigns one.

You can set this parameter 2 different ways. Whichever way you choose will do the exact same thing.
You can use the shortcut -t

-t ttl    Specifies a hard minimum time to live for cached documents. This is a shortcut for specifying the default_ttl run-time parameter.

or, you can use the -p param=value
So for example, you could start varnishd like this:
Using shortcut:
varnishd -a 127.0.0.1:8081 -T 127.0.0.1 -t 2419200
Using longer form:
varnishd -a 127.0.0.1:8081 -T 127.0.0.1 -p default_ttl=2419200
The number 2419200 is 4 weeks in seconds.
Comment: Note you can set this in your `DAEMON_OPTS` config (e.g., in `/etc/varnish/varnish.params`) which does the same as above, same format, e.g., `DAEMON_OPTS="-p default_ttl=3600"`
Answer: The accepted answer is one way of achieving the goal. However, in fact you can perfectly set the default TTL in the /etc/varnish/default.vcl file like so:
sub vcl_backend_response {
 set beresp.ttl = 4w;
}

Comment: This answer is at best incomplete: using this strategy will cache all response codes, including 5xx statuses, which is hardly desirable :(

Set default TTL in Varnish 4.0?


Trabalhar com listas sem ser usando Array() em PHP

Question: Sei que no PHP pra quase todo tipo de lista, trabalhamos com Array(), mas seria esta a única forma de trabalhar com listas em PHP?
Existe alguma outra forma de trabalhar com listas de objetos em PHP, parecido com as classes do Collections (List, Map, etc)?
Answer: A partir do php 7.2 foi disponibilizada uma nova extensão para se trabalhar com estutura de dados mais rígidas. Os tipos existentes são:

Hashable
Sequence
Vector
Deque
Map
Pair
Set
Stack
Queue
PriorityQueue

Sim existem outras estruturas de dados além do padrão Array(), elas estão na biblioteca SPL, que vem por padrão desde o PHP5.0.
Alguns tipos são:

SplStack
SplQueue
SplHeap
SplMaxHeap
SplMinHeap
SplPriorityQueue
SplFixedArray
SplObjectStorage
Comment: Ah, rapaz! Mal vi seus movimentos :D
Answer: Sim, existe no PHP algumas classes padrões (da SPL- Standard PHP Library) que fazem muito bem esse trabalho.
Geralmente essas classes implementam as interfaces ArrayAccess, Iterator ou IteratorAggregate.
A interface ArrayAccess permite acesso e definição de membros da classe como se fosse um array.
Eis alguns exemplos:
SplStack
Essa classe funciona como uma pilha. Quando você adiciona um elemento via SplStack $stack[], ao invés de adicionar o elemento no final como se faz num array comum,  ele adiciona ao início.
Exemplo:
$stack = new SplStack;

$stack[] = 1;

$stack[] = 2;

$stack[] = 3;

print_r(iterator_to_array($stack));

Isso retornaria:
[
     2 => 3,
     1 => 2,
     0 => 1,
 ]

SplFixedArray
A classe SplFixedArray é utilizada para determinar um número fixo de elementos para um array. Você determina na instância qual é o número de elementos que estarão presentes nessa estrutura. É semelhante ao Array do javascript, já que você não pode nomear os índices, mas os índices são apenas numéricos. Se você tentar colocar um tamanho maior que o esperado, uma exceção será lançada.
Exemplo:
$arr = new SplFixedArray(3);

$arr[0] = 0;

$arr[1] = 1;

$arr[2] = 2;

Algumas pessoas dizem que fizeram testes e obtiveram uma economia 33% vezes menor que um array comum, mas esse é o tipo de coisas que não costumo me focar.
SplObjectStorage
Essa classe serve para você armazenar objetos. A grande diferença dela é que, quando você define um objeto nela, o mesmo é passado como índice dessa "estrutura".
 $s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);

Esses são alguns exemplos, mas existem outros, que já foram citadas pelo @rray.
Comment: Me pergunto pq tem um exemplo da SPLStack .... :D
Comment: Acho que entendi sua piada @rray :D
Comment: As respostas do rray e bigown são excelentes, mas você exemplificou o uso de algumas das possibilidades.
Answer: Por padrão não existe. Nada impede de você criar tipos novos que implemente especificamente cada uma destas estruturas e algoritmos relacionados. Provavelmente usando o array concretamente dentro da estrutura.
Também pode usar alguma biblioteca que já implemente isto para você, como o caso da citada pelo rray (que parece ser bem ruim, por sinal :P) que é uma extensão.
Em tese também é possível implementar alguma estrutura em C e expô-la ao PHP, mas quase ninguém faz isto, teria uma vantagem de performance bastante interessante.
Algumas pessoas já fizeram isto, já que eles também consideraram a SPL uma porcaria.
Coloquei no GitHub para referência futura.
Comment: É tão boa que em boa parte das páginas tem explicação das funções e recursos que você não pode usar por causa dos bugs :)
Comment: Deve ser porque eu disse que a biblioteca parece ser ruim. A pessoa deve achar que ela é ótima. Por isso "todo mundo está usando em seus códigos".
Comment: Mas pelo jeito o povo gostou dela assim mesmo :D
Comment: Queria saber o que está errado.
Comment: Não entendi também o -1.


Methodology for debugging serial poll

Question: I'm reading values from a sensor via serial (accelerometer values), in a loop similar to this:
while( 1 ) {
   vector values = getAccelerometerValues();
   // Calculate velocity
   // Calculate total displacement
   if ( displacement == 0 )
       print("Back at origin");
}

I know the time that it takes per sample, which is taken care of in the getAccelerometerValues(), so I have a time-period to calculate velocity, displacement etc. I sample at approximately 120 samples / second.
This works, but there are bugs (non-precise accelerometer values, floating-point errors, etc), and calibrating and compensating to get reasonably accurate displacement values is proving difficult.
I'm having great amounts of trouble finding a process to debug the loop. If I use a debugger (my code happens to be written in C++, and I'm slowly learning to use gdb rather than print statements), I have issues stepping through and pushing my sensor around to get an accelerometer reading at the point in time that the debugger executes the line. That is, it's very difficult to get the timing of "continue to next line" and "pushing sensor so it's accelerating" right.
I can use lots of print statements, which tend to fly past on-screen, but due to the number of samples, this gets tedious and difficult to derive where the problems are, particularly if there's more than one print statement per loop tick.
I can decrease the number of samples, which improves the readability of the programs output, but drastically decreases the reliability of the acceleration values I poll from the sensor; if I poll at 1Hz, the chances of polling the accelerometer value while it's undergoing acceleration drop considerably.
Overall, I'm having issues stepping through the code and using realistic data; I can step through it with non-useful data, or I can not really step through it with better data.
I'm assuming print statements aren't the best debugging method for this scenario. What's a better option? Are there any kinds of resources that I would find useful (am I missing something with gdb, or are there other tools that I could use)? I'm struggling to develop a methodology to debug this.
Answer: A sensible approach would be to use some interface for getAccelerometerValues() that you can substitute at either runtime or build-time, such as passing in a base-class pointer with a virtual method to override in the concrete derived class.
I can describe the mechanism in more detail if you need, but the ideal is to be able to run the same loop against:

real live data
real live data (and save it to file)
canned real data saved from a previous run
fake data you cooked up as a test case

Note in particular that the 'replay' version(s) should be easy to debug, if each call just returns the next data from the file.
Comment: In effect, simulate the data - that sounds so obvious now. Thanks!
Answer: I would debug your code with fake (ie: random) values, before everything else.
It the computations work as expected, then I would use the values read from the port.
Also, isnt' there a way to read those values in a callback/push fashion, that is, get your function called only when there's new, reliable data?
edit: I don't know what libraries you are using, but in the .NET framework you can use a SerialPort class with the Event DataReceived. That way you are sure to use the most actual and reliable data.
Answer: Create if blocks for the exact conditions you want to debug. For example, if you only care about when the accelerometer reads that you are moving left:
if(movingLeft(values) {
   print("left");
}

Answer: The usual solution to this problem is recording. Your capture sample sequences from your sensor in a real-time manner, and store them to files. Then you train your system, debug your code, etc. using the recorded data. Finally, you connect the working code to the real data stream which flows immediately from the sensor.

Methodology for debugging serial poll


Prove nth derivative of $(1+x)^x$ is divided by n

Question: I stuck with my solution.
$f(x) = (1+x)^x$
Needed to prove that function's $n$th derivative is divided by $n$ in $0$.
$n \mid  f^{(n)}(0) $
$(1+x)^x = \sum_{i=0}^x \binom {x} {i}$
If $n > x$ that's ok. We get $f^{(n)}(0) = 0$ cause derivative of sum is sum of derivatives and each member of sum of derivatives $= 0$ (in $x = 0$).
If $n \le x$ we can find just one summand which does not turn into $0$. This number has form of $\binom {x} {n}x^n$
Let $\binom {x} {n} =  \alpha$ So $\alpha \in \mathbb{Z}$
And we should prove that $(\alpha x^n)^{(n)}$ is divided by n; I suggest that $(\alpha x ^n)^{(n)} = \alpha n (n-1) (n-2) \cdots 2x$ and it's of course is divided by n. But I checked my suggest in wolfram and wolfram told me I'm wrong. Could you help me find my fault?
Comment: what is the first derivative?
Comment: With the zero $x$ we have interest just in $x^1$ which have coefficient $\binom {x} {1}$ so derivative of it is 1. $\binom {0} {any} = 1$ as I remember. At total derivative in $x = 0$ is 1 and 1 is divided by 1.
Answer:
$(1+x)^x = \sum_{i=0}^x \binom {x} {i}$

Sorry, but no. That is for positive integer powers, but $x$ is not an integer in general. And it varies, so you have to differentiate with respect to the exponent too.
One way to handle this is to take the logarithm and use implicit differentation:
$$\begin{align}\frac {d}{dx}\ln f(x) &= \frac {d}{dx}(x\ln(1+x))\\
\frac{f'(x)}{f(x)} &= \ln(1 + x) + \frac{x}{1+x}\\
f'(x) &= f(x)\left(\ln(1 + x) + \frac{x}{1+x}\right)\\
f'(x) &= (1+x)^x\ln(1+x) + x(1+x)^{x-1}
\end{align}$$
As you can guess, the higher powers get worse. You'll need to figure out the pattern to them, and use induction to prove your result.


"Doubling" array in prepared statement to fill duplicate placeholders

Question: God this is so annoying. I have a messagesystem with inbox, outbox, and a conversation view. The conversation view shows both sent and received messages with a specific user, and since I only use one table for the messages (sender_status/receiver_status to control which of the users involved in the message have deleted it, read it etc.)
I have checkboxes next to my list, one for each message, it works fine in my queries both for inbox and outbox:
<input type="checkbox" name="message_delete[]" value="<?= $message['mid']; ?>"/>

I need to apply the messageupdate to the correct status when I try to delete in the conversation-view:
Normal query, i.e. inbox, works fine:
$questionmarks = str_repeat("?,", count($mid_array) - 1) . "?";
$st = $db->prepare("UPDATE messages SET sender_status = 'DELETED' WHERE mid IN ($questionmarks)");
            $st->execute($mid_array);

Conversation-query, does not work:
$st = $db->prepare("UPDATE messages SET (receiver_status = 'DELETED' WHERE mid IN        ($questionmarks) AND to_user = '{$user_id}'), (sender_status = 'DELETED' WHERE mid IN ($questionmarks) AND from_user = '{$user_id}')");
            $st->execute( WHAT TO PUT HERE );

I have tried array($mid_array, $mid_array) in the execute which I thought would work. Also several other somewhat stupid solutions that I can´t get to work. I´m probably missing some easy function here but none of the ones i´ve tried have worked, hence my question. Need Help!! thanks in advance.
Comment: your second query is totally invalid. you cannot have multiple `where` clauses like that.
Answer: Try something more like
UPDATE messages
SET
    receiver_status = 'DELETED',
    sender_status = 'DELETED'
WHERE mid IN ($questionmarks) AND ('$user_id' IN (to_user, from_user))

to get around the multiple where issue in your original query.

SET
   receiver_status = IF(to_user   = '$user_id', 'DELETED', receiver_status),
   sender_status   = IF(from_user = '$user_id', 'DELETED', sender_status)
WHERE mid IN ($questionmarks)

instead, then?
Comment: The problem here is that I then will set the message to deleted for the user that is not currently trying to delete the message, no?
Comment: Trying it right now, I will vote it when I can confirm it works :P, and if so - thanks a lot!
Comment: Thanks man it worked, upped you and checked it now. small note to someone who wants to copy it though, there is an iffy little comma ',' missing from after the parenthesis in between the two SET options, you should probably update that. Anyway, thanks again!
Answer: Whoa.
You just can't do that, with prepared statements or without.
It's SQL syntax, not PDO.
So, just run 2 separate queries with 2 separate sets of data.
By the way, for some reason you're not using placeholders in your query - so, you're in danger.


HTML5 e JavaScript - Múltiplos Vídeos Play/Pause

Question: Fala pessoal tudo bem? Tenho uma página onde possuo 2 vídeos em HTML5, não estou usando nem um outro player. Gostaria de saber como consigo fazer com que quando clique em um vídeo e que, os outros não reproduzam todos ao mesmo tempo.
Na minha cabeça pensante seria um função que identificasse se o vídeo foi clicado, se está rodando e ou e já foi finalizado a reprodução dele.
Na NET tentei procurar em Inglês algo mas sem sucesso, vi muitos códigos e sem ideias.
Agradeço de coração se algum STACK OVER NINJA puder me dar uma força com isso!

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Video</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Vídeos Exemplos

        <video controls class="w-100 meus_videos">
                <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

Video 01

        <video controls="" class="w-100 meus_videos">
                <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

Video 02

Comment: Veja se entendi bem o que você quer: você tem 3 videos, e sempre reproduzir um por vez? É isso? Nunca deixar que mais de um vídeo esteja em reprodução?
Comment: Olá amigo, exatamente, bem isso que preciso. Teve um amigo que até comentou um exemplo mas não era exatamente o que precisava...
Answer: Em todos os vídeos você adiciona a classe parado:
<video controls class="w-100 meus_videos parado">

Sempre que começar a execução de um vídeo com a classe parado, você dispara um evento:
$('.parado').on('play', function() {

Esse evento executa um laço que pega todos os vídeo que tiverem a classe *rodando e pausa o vídeo:
$(".rodando").each(function(){
    $(this).removeClass('rodando').addClass('parado');
    $(this).get(0).pause();
});

Após pausar o vídeo, é atribuído a classe rodando para o vídeo que foi clicado e é dado play neste vídeo:
$(this).removeClass('parado').addClass('rodando');
$(this).get(0).play();

Segue código completo:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Video</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Vídeos Exemplos

        <video controls class="w-100 meus_videos parado">
                <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

Video 01

        <video controls="" class="w-100 meus_videos parado">
                <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

Video 02

Comment: Muito bom, era exatamente isso que precisava! Agradeço pelo tempo em responder e muito mais pelo tempo que em ficou em cima do desenvolvimento desta função!


Introducing behavioural states into hidden markov model?

Question: I have a hidden markov model which models movement. A map is split into even sized grids and the hidden states are the grids.
I want to improve this model by adding behavioural states (so that movement is different if the data suggests the animal is in a different behavioural state). However, I have no idea how this can be done.
Any guidance would be appreciated, I hopefully would like to implement this in R.
Answer: You are trying to include external variables to influence HMM. Use heterogeneous HMM. you will get transition probability as a function of external variables ( behavior state in your case). DepmixS4 is the best package to implement in R.-
This article is without external variable, but a good start.
http://machinelearningstories.blogspot.com/2017/02/hidden-markov-model-session-1.html


Looking for mathematical optimizations when translating formulae to code

Question: I'm writing an app which translates formulae into executable code. I've been experimenting with fairly obvious optimizations such as factoring (reducing number of multiplications) in order to make the code run faster. Can anyone suggest any other performance-related optimizations that could be performed when translating formulae to code? Thanks.
Comment: Make sure polynomials are always in Horner form.
Comment: Another one: isolate common subexpressions. For example, if you're optimizing something like $2\cos^3 x-\cos^2 x+1$, the right optimization is to cache the value of the cosine in some temporary variable $u=\cos\,x$, and then rewrite the polynomial in terms of the temporary variable in Horner form: $(2u-1)u^2+1$.
Comment: @J.M. thanks, subexpression analysis is one of the things I'm already working on
Answer: The code
double x = a / b + c / d;

typically takes about twice as long to execute as the equivalent expression
double x = (a * d + b * c) / (b * d);

because floating point division is very slow whereas addition and multiplication are fast.

As well as that there are the obvious things to do like pre-computing constant values, and replacing
double x = a + 0.0; double y = b * 1.0; double z = c / 1.0;

with the equivalent expressions
double x = a; double y = b; double z = c;

This isn't quite so nonsensical as it may appear: the constants 1.0 and 0.0 might not be the values originally written, but rather the results of some intermediate computation.
You could also optimize pow(x, 2) to x * x and the like, although any decent compiler should do this for you.
Comment: But are these two expressions equivalent in floating-point arithmetic?
Comment: Thanks! Is the performance difference a well-known value (say, on a modern-day Quad-core CPU)?
Comment: @Dmitri, a rule of thumb is that addition takes 3 units, multiplication 4 units and division 32 units of time (e.g. clock cycles).
Comment: @lhf No (although I don't think that's really a problem - how often do you care about the *exact* floating point representation of your result?). A more serious problem is that if you perform this optimization you might induce an overflow, if any of your intermediate products are larger than the maximum double value supported on your system.
Comment: I optimize power methods already. As for calculations resulting in multiplication by 1, I think it's really hard to detect those unless I encounter something obvious like `x*(y/y)`
Comment: Even then, it might not always be right to optimize out stuff like `y/y` to `1`.
Comment: Chris: Hmm... if `a/b` and `c/d` are both tiny and of opposite sign, somehow it looks that the "optimized" expression is more cancellation-prone than the original one...
Comment: Could be true. It is 'optimised' for speed, not accuracy :)
Answer: I think you'd better leave such optimizations to the compiler. Or do you have evidence that the compiler cannot do justice to your formulas?
Comment: @Dmitri, sure, every compiler is gcc but you can bet that optimizing compilers will do a good job. There has been *decades* of research on that. My point is: don't try to outsmart the compiler; you may even force it to generated *worse* code than if you just wrote what you meant.
Comment: I don't think a compiler can optimize `a*x*x + b*x` to become `x*(a*x + b)` :) and that's just a simple case.
Comment: @Dmitri, try `gcc -S -O2` on the program `int f(int a, int b, int x) { return  a*x*x + b*x; }
int g(int a, int b, int x) { return  x*(a*x + b); }`. The generated code is the *same*. Using `double` instead of `int` does generate different code but it's probably because the compiler is aware that floating-point arithmetic is not distributive.
Comment: Okay, so `gcc` can optimize this, but I don't think *every* compiler can do this. I don't think it's correct to rely on the compiler optimizing things for you.


How to exclude a class from 'exception throw' processing

Question: I am working with cocos2d, in particular the cocos Dhension audio engine. It turns out that it is quite noisy (throwing exceptions), and i would like to exclude it when turning on 'exceptions throws'. Is there a way to exclude a specific class ?
Comment: Did you ask this also on AppCode forum/support?
Comment: not yet ... errr ... ive been quite noisy on there lately, trying to lie low fow a while ! but i will. I'll let you know. Btw, giant leap with the latest EAP build , solves quite a few issues for me.
Comment: I'm very interested in the correction of slow index on change target/device as I told you as 'giampaolo' on the AppCode forum: http://devnet.jetbrains.net/thread/440501;jsessionid=6257F6CC99F3C4E0C693521C724B3179?tstart=0
Comment: right now its looking very good for me ... change target in 2 seconds ... but my app aint your app ! who knows :). The editor is screaming fast compared to 1.6.n and first EAP that came out.
Comment: do you think that my answer is the right one? Did u investigated more on this?
Answer: I think that you can't. AppCode cannot do more that lldb (or gdb) does. I checked lldb documentation and I didn't found what you are looking for. So, neither AppCode can.
Comment: have not found how to exclude the noisy class, but at least (EAP 2.0), i can disable exception processing until a specific breakpoint is hit.


How do you reduce latency for calls fowarded from an Australian twilio number?

Question: We're experiencing 1 second call latencies to calls forwarded from an Australian twilio number which makes Twilio call forwarding unusable.
Is there any way to reduce this?
Is there a better alternative to Twilio for this solution in Australia?
Comment: Stackoverflow.com is for /programming/ questions. Please try superuser for general software questions.
Answer: Restomm is an open source based alternative to look at. Restcomm is compatible with the Twilio APIs. You can setup connectivity via local ITSPs in Australia for best latency.
http://www.telestax.com/restcomm/
Also available on AWS Marketplace: https://aws.amazon.com/marketplace/pp/B00FFHJ6SU


What's this horizontal bar notation in liturgy called?

Question: I just came across a liturgical peace using horizontal bars as notation for parts where a continuous reciting tone is used. I'd like to know whether there's a specific name for this bar notation (and ultimately, how to reproduce it in LilyPond). Can anybody help me out here?
Comment: This is one way of notating a "reciting tone" for liturgical congregational chant.
Comment: Another common notation is just to use a breve.
Answer: I couldn't find other examples, but based on the content I'll take a guess.
I think that the long note means to chant the lyrics on that tone. The page looks a bit like Gregorian Chant notation with modifications to a 5-line staff. The last system has two notes over a single syllable which has a special symbol in Chant notation. There is no rhythm indicated so I'd guess that the rhythm is the normal speech rhythm of the text. I'm basing my guess on this: http://media.musicasacra.com/pdf/neumes.pdf.
Comment: Lilypond call this "recitativic chant", and there is no proposed method of typesetting it other than a single, non-elongated breve (http://lilypond.org/doc/v2.18/Documentation/notation/working-with-ancient-music_002d_002dscenarios-and-solutions#transcribing-gregorian-chant)
Comment: @Kilian Foth that sounds like THE answer...
Comment: Related: [How to draw a rectangle for reciting tone in chant transcription in LilyPond](https://music.stackexchange.com/q/62044/21766)
Answer: Actually, with the help of this post, I already got a little farther. Now I only need to find out how to align the text correctly with the beginning of the line, instead of centering the line start over the text. Any ideas? Here's the code:
<code>\version "2.16.2"
\include "deutsch.ly"

ohr = \markup {
  \with-dimensions #'(0 . 0) #'(0 . 0)
  \translate #'( 0 . -0.3)
  \combine \filled-box #'(-0.3 . +0.3) #'(0 . 0.3) #0 % Naht
  \filled-box #'(-0.8 . +0.8) #'(0 . 0.15) #0         % Strich
}

balken = {
   \once \override Glissando #'after-line-breaking =
    #(lambda (grob)
      (let* ((left-bound (ly:spanner-bound grob LEFT))
             (left-Y (assoc-get 'Y (ly:grob-property grob 'left-bound-        info))))
       (ly:grob-set-property! left-bound 'stencil #f)
       (ly:grob-set-nested-property! grob '(right-bound-info Y) left-Y)))

   \once \override Glissando #'thickness = #6
   \once \override Glissando #'(bound-details left  padding) = #-0.5
   \once \override Glissando #'(bound-details right padding) = #1.3
   \once \override Glissando #'(bound-details left text) = \markup \rotate     #-90 \ohr
   \once \override Glissando #'(bound-details right text) = \markup \rotate     #90 \ohr
   \once \override Glissando #'springs-and-rods = #ly:spanner::set-            spacing-rods
   \once \override Glissando #'minimum-length = 10
   <>\glissando
}

 \score {
   <<
   \new Staff <<
    \new Voice = "Alt"
      \relative c'' {
        \key g \major
        \clef treble
        \time 1/4
        \autoBeamOff
            \override Score.SpacingSpanner #'packed-spacing = ##t
            \set Score.timing = ##f
            \balken g
        a g g
        \break
        \balken g
        fis g g
        \break
        \balken g
        a g
        \break
        \balken g
        fis g
        \break
        \balken g
        a g
        \break
        \balken g
        fis g
        \break
        g a g(fis) fis
      }
      \addlyrics {
        "Herr tue meine" Lip- pen auf.
        "dass mein Mund deinen Ruhm ver-" kün- di- ge.
        "Gott, gedenke mein nach deiner" Gna- de.
        "Herr, erhöhre mich mit deiner treuen" Hil- fe.
        "Ehre sei dem Vater und dem Sohne und dem Heiligen" Geis- te
        "wie im Anfang, so auch jetzt und alle Zeit und in Ewigkeit."     A- men.
        [Hal- le- lu-_ ja]
      }
      >>
  >>
  \midi {
  }
  \layout {
   \context {
    \Staff
    \remove "Time_signature_engraver"
    \remove "Bar_engraver"
    \override Stem #'transparent = ##t
    \override Flag #'transparent = ##t
    \override Beam #'transparent = ##t
   } % context
  } % layout
} % score
</code>
The result looks like this:
Comment: This looks like a separate question to me, you can post as many questions as you want.  More critically, this is not an answer to your original question.   The idea here is to have specific questions and (ranked) answers, not a flowing discussion thread (http://music.stackexchange.com/tour)
Comment: @Dave His question includes the parenthetical, "(and ultimately, how to reproduce it in LilyPond)", so it does seem like he is answering part of his own question here. potofcoffee, could you possibly add an image or link showing what this Lilypond code looks like?
Comment: @ToddWilcox, I edited the answer and provided an image.
Comment: @ToddWilcox My bad...
Comment: @Dave, I'm sorry, I thought this was covered under my original question.
Comment: Duh! I forgot `\override LyricText.self-alignment-X = #LEFT`.


UIDatePicker with 5 min interval get date on appear with interval

Question: I have spent about 3 hours trying to get a UIDatePicker to do what I want it to do. I have it setup as an action of a UITextField to segue to a new view controller with a UIDatePicker. This is all working. I have been able to select a date and send it back to the original view controller.
The problem is that I am using 5 minute time intervals. If I don't move the date picker "wheels" and select my done button to return to the parent controller the non-interval time is returned. So 11:37 returns 11:37 when I need 11:40. However, if I change the "wheels" it returns the rounded time. The datepicker is currently showing the 5 minute intervals on appear. Any clues to lead me to the right solution? I have tried setDate and minuteInterval on the UIDatePicker on viewDidAppear to no avail. Below is the code I have been using:
protocol DatePickerDelegate {
    func datePickerDidSelect(selectedDate: String)
}

class DatePickerVC: UIViewController  {

@IBOutlet weak var pickerView: UIDatePicker!

var selectedDate = ""
var delegate : DatePickerDelegate?

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

override func viewDidAppear(_ animated: Bool) {
    //setDate()
    //Have tried using setDate and minuteInterval here
}

func formatDate() -> DateFormatter {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM d, yyyy h:mm a"
    return dateFormatter
}

func setDate() {
    let dateFormatter = formatDate()
    selectedDate = dateFormatter.string(from: pickerView.date)
    self.delegate?.datePickerDidSelect(selectedDate: selectedDate)
    print(selectedDate)
}

@IBAction func datePickerChanged(_ sender: Any) {
    setDate()
}

@IBAction func doneBtnPressed(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

@IBAction func cancelBtnPressed(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}
}

Answer: you could check the date and round it to your needs like this:
override func viewDidLoad() {
    super.viewDidLoad()

    let calendar = Calendar.current
    var dateComponents = calendar.dateComponents([.month, .day, .year, .hour, .minute], from: datePicker.date)
    guard var hour = dateComponents.hour, var minute = dateComponents.minute else {
        print("something went wrong")
        return
    }

    let intervalRemainder = minute % datePicker.minuteInterval
    if intervalRemainder > 0 {
        // need to correct the date
        minute += datePicker.minuteInterval - intervalRemainder
        if minute >= 60 {
            hour += 1
            minute -= 60
        }

        // update datecomponents
        dateComponents.hour = hour
        dateComponents.minute = minute

        // get the corrected date
        guard let roundedDate = calendar.date(from: dateComponents) else {
            print("something went wrong")
            return
        }

        // update the datepicker
        datePicker.date = roundedDate
    }
}

feel free to ask if anything is unclear!
Comment: I got this to work, however had to change `datePicker.date = roundedDate` to `datePicker.setDate(roundedDate, animated: false)`. But in the meantime had actually decided on deactivating the done button until a time was selected/changed, as more than likely in this app they won't be selecting the start time being right now.
Answer: Another alternative is to create an extension that allows you to tweak intervals on the date value that's set when the UIDatePicker is initialized.
extension Date {
    var nearest30Min: Date {
        var dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
        guard let hours = dateComponents.hour else { return self }

        switch dateComponents.minute ?? 0 {
        case 0...14:
            dateComponents.minute = 0
        case 15...44:
            dateComponents.minute = 30
        case 44...59:
            dateComponents.minute = 0
            dateComponents.hour = hours + 1
        default:
            break
        }

        return dateComponents.date ?? self
    }
}

After your UIDatePicker is initialized, you could update the datePicker's value with the following code:
datePicker.setDate(datePicker.date.nearest30min, animated: false)


Is there a D7/Services module for sane field content I/O?

Question: For instance, a GET request to the standard endpoint node/1.json returns an object with fields like this:
{
   ...

   "field_my_field":{
      "und":[
         {
            "value":"yucky"
         }
      ]
   }

   ...
}

To build an easy to use API, we would want to GET and POST objects with fields like this:
{
   ...

   "my_field": "clean"

   ...
}

It would be easy to implement the vast majority of field types this way. I thought there was a module for this, but I can't find it.
Comment: I don't think there could be, fields are more complex than your desired output. e.g. there's a node field called `body`; if you were to add `field_body` as well, you'd immediately have a collision and one of the values would be lost. Similarly if it's multi-lingual, if the fields are multiple cardinality, have multiple columns, etc, they can't be generically represented in that way. I'd love to see a solution, though, I've been ruling Drupal out of API projects for exactly this reason lately
Answer: With the Services module, no. However you could build a Page display with Views datasource, that accepts a node id as a contextual filter. The fields you specify in the View can then be configured to "clean up" the property name (or just turn off the label to use the machine name of the field), and then the value will be "flat".


Buffering data from sockets?

Question: I am trying to make a simple HTTP server that would be able to parse client requests and send responses back.
Now I have a problem. I have to read and handle one line at a time in the request, and I don't know if I should:

read one byte at a time, or
read chunks of N bytes at a time, put them in a buffer, and then handle the bytes one by one, before reading a new chunk of bytes.

What would be the best option, and why?
Also, are there some alternative solutions to this? Like a function that would read a line at a time from the socket or something?
Answer: Single byte at a time is going to kill performance.  Consider a circular buffer of decent size.
Read chunks of whatever size is free in the buffer.  Most of the time you will get short reads.  Check for the end of the http command in the read bytes.  Process complete commands and next byte becomes head of buffer.  If buffer becomes full, copy it off to a backup buffer, use a second circular buffer, report an error or whatever is appropriate.
Comment: Can you explain me the concept "circular buffer" please?
Comment: @Math - it is basically an array that wraps the end around to the beginning.  Pointers keep track of the head & tail & current position, etc.  See http://en.wikipedia.org/wiki/Circular_buffer
Answer: The short answer to your question is that I would go with reading a single byte at a time. Unfortunately its one of those cases where there are pros and cons for both cases.
For the use of a buffer is the fact that the implementation can be more efficient from the perspective of the network IO. Against the use of a buffer, I think that the code will be inherently more complex than the single byte version. So its an efficiency vs complexity trade off. The good news is that you can implement the simple solution first, profile the result and "upgrage" to a buffered approach if testing shows it to be worthwhile.
Also, just to note, as a thought experiment I wrote some pseudo code for a loop that does buffer based reads of http packets, included below. The complexity to implement a buffered read doesn't seem to bad. Note however that I haven't given much consideration to error handling, or tested if this will work at all. However, it  should avoid excessive "double handling" of data, which is important since that would reduce the efficiency gains which were the purpose of this approach.
<code>#define CHUNK_SIZE 1024

nextHttpBytesRead = 0;
nextHttp = NULL;
while (1)
{
  size_t httpBytesRead = nextHttpBytesRead;
  size_t thisHttpSize;
  char *http = nextHttp;
  char *temp;
  char *httpTerminator;

  do
  {
    temp = realloc(httpBytesRead + CHUNK_SIZE);
    if (NULL == temp)
      ...
    http = temp;

    httpBytesRead += read(httpSocket, http + httpBytesRead, CHUNK_SIZE);
    httpTerminator = strstr(http, "\r\n\r\n");
  }while (NULL == httpTerminator)

  thisHttpSize = ((int)httpTerminator - (int)http + 4; // Include terminator
  nextHttpBytesRead = httpBytesRead - thisHttpSize;

  // Adding CHUNK_SIZE here means that the first realloc won't have to do any work
  nextHttp = malloc(nextHttpBytesRead + CHUNK_SIZE);
  memcpy(nextHttp,  http + thisHttpSize, nextHttpSize);

  http[thisHttpSize] = '\0';
  processHttp(http);
}
</code>
Answer: Indy, for example, takes the buffered approach.  When the code asks Indy to read a line, it first checks its current buffer to see if a line break is present.  If not, the network is read in chunks and appended to the buffer until the line break appears.  Once it does, just the data up to the line break is removed from the buffer and returned to the app, leaving any remaining data in the buffer for the next reading operation.  This makes for a good balance between a simple application-level API (ReadLine, ReadStream, etc), while providing for efficient network I/O (read everything that is currently available in the socket, buffer it, and ack it so the sender is not waiting too long - fewer network-level reads are needed this way).
Answer: TCP data stream is coming in at one IP packet at a time, which can be up to 1,500 or so bytes depending on the IP layer configuration.  In Linux this is going to be wait in one SKB waiting for the application layer to read off the queue.  If you read one byte at a time you suffer the overhead of context switches between the application and kernel for simply copying one byte from one structure to another.  The optimum solution is to use non-blocking IO to read the content of one SKB at a time and so minimize the switches.
If you are after optimum bandwidth you could read off longer size of bytes in order to further reduce the context switches at the expensive of latency as more time will be spent out of the application copying memory.  But this only applies to extremes and such code changes should be implemented when required.
If you examine the multitude of existing HTTP technologies you can find alternative approaches such as using multiple threads and blocking sockets, pushing more work back into the kernel to reduce the overhead of switching into the application and back.
I have implemented a HTTP server library very similar to torak's pseudo code here,  http://code.google.com/p/openpgm/source/browse/trunk/openpgm/pgm/http.c  The biggest speed improvements for this implementation came from making everything asynchronous so nothing ever blocks.
Answer: Start by reading one byte at a time (though noting that lines end with cr/lf in HTTP) because it's simple. If that's not sufficient, do more complex things.
Comment: But be prepared to also handle single cr and single lf as end of line, since there are many client & server out there that are not really HTTP compliants...
Answer: Read a byte array buffer at a time. Reading single characters will be dog slow because of the multiple context switches between user and kernel mode (depending on the libc actually).
If you read buffers, you need to be prepared that the buffer could eighter be not filled completely (watch the length return), that the buffer does not contain enough bytes to line end or that the buffer contains more than one line.
It is a common pattern in network applications how to map your line or fixed-size block requests to that variable steam of buffers (and often implemented wrong, for example a 0 byte length answer is possible). Higher languages will hide you from this complexity.

Buffering data from sockets?


SpamAssassin trying to read config files under /root/

Question: I have mail gateway servers configured to use MailScanner + Postfix + SpamAssassin as described here, along with MailWatch as a web front end.
When sa-learn is run from MailWatch (it's run as the postfix user), it throws this error:
SA Learn: config: path "/root/.spamassassin" is inaccessible: Permission denied, Learned tokens from 0 message(s) (1 message(s) examined)

Running "sudo -u postfix spamassassin --lint -D" gives this bit of info:
dbg: config: read file /etc/mail/spamassassin/mailscanner.cf
warn: config: path "/root/.spamassassin" is inaccessible: Permission denied
dbg: config: mkdir /root/.spamassassin failed: mkdir /root/.spamassassin: Permission denied at /usr/lib/perl5/site_perl/5.8.8/Mail/SpamAssassin.pm line 1577
dbg: config: Permission denied
dbg: config: using "/etc/MailScanner/spam.assassin.prefs.conf" for user prefs file

The bayes tokens are learned correctly, however this error is a minor annoyance and I'd like to fix it... Either by forcing SpamAssassin to not check the /root/.spamassassin/ directory for the config & prefs, or to fix MailWatch so it calls sa-learn correctly & doesn't throw this error.
Answer: The real fix is to disable "per-user" config in spamassassin and globally set the Baysean DB, but a quick patch would be to add the "-H" option to sudo to use postfix's home directory where it should have permission to write as postfix.
Comment: This sounds like it might be along the correct lines, but I'm still looking for specific documentation on how to accomplish this... once I do & if it turns out to be correct, I'll post it here and check this as answered unless someone beats me to the punch.
Comment: Of course the other option is to symlink /root/.spamassassin to ~postfix/.spamassassin
I've done this on one machine and it does work as long as the permissions are ok.
Answer: This is not a bug it is because you are running the sa-learn command with an invalid user. For example my setup uses the standard debian-spamd user.
# sa-learn -u debian-spamd --dbpath /var/lib/spamassassin/.spamassassin/bayes --dump magic
0.000          0          3          0  non-token data: bayes db version
0.000          0         84          0  non-token data: nspam
0.000          0       6565          0  non-token data: nham
0.000          0      15128          0  non-token data: ntokens
0.000          0 1510837441          0  non-token data: oldest atime
0.000          0 1519232775          0  non-token data: newest atime
0.000          0          0          0  non-token data: last journal sync atime
0.000          0          0          0  non-token data: last expiry atime
0.000          0          0          0  non-token data: last expire atime delta
0.000          0          0          0  non-token data: last expire reduction count

And for accounts
# sa-learn --ham -u debian-spamd --showdots --dir /var/vmail/mydomain.com/support/cur/*
.
Learned tokens from 1 message(s) (1 message(s) examined)

I have 20 email accounts on the server and crons to match for ham and spam and never the error. Make sure your setup and user:group correct on relevant files/directories.
Link to a quick tutorial on how to fix
https://www.devcu.com/forums/topic/745-spamassassin-is-inaccessible-permission-denied/
Answer: This could be a workaround:
# chmod o+x /root
# mv -f /root/.spamassassin /root/.spamassassin.err
# ln -s /var/spool/MailScanner/spamassassin /root/.spamassassin
# mkdir -p /var/spool/MailScanner/spamassassin
# chown postfix.apache /var/spool/MailScanner/spamassassin
# chmod 770 /var/spool/MailScanner/spamassassin

Comment: This was my original thought for a workaround, but making /root traversable by anyone doesn't really give me the warm fuzzies... While I don't think it's necessarily a security risk, I'd rather avoid it if at all possible.
Answer: Shouldn't you use the spamassassin daemon spamd instead? Then you'd use the spamc command instead of spamassassin. Basically, run spamd from its startup script, and use spamc from your mailscanner.
Comment: I see. Then you should tell sa-learn to use some other place ( postfix-writable) to store its data with the --dbpath option.
Comment: The bayes database is already writable by postfix, which is why tokens are being learned correctly - what I'm trying to fix is sa-learn checking the root directory for config files first & throwing an error before correctly using the global config file in /etc/MailScanner/ and moving on.
Comment: MailScanner doesn't actually use spamd, spamc, or the spamassassin script directly, it calls the installed perl modules.
Answer: Did you try adding --dbpath parameter, like this ?
sa-learn --dbpath /var/lib/amavis/.spamassassin/ ....

Comment: Yup, and it still throws the "config: path "/root/.spamassassin" is inaccessible: Permission denied" error
Answer: The Cause
The cause is that spamassassin (which is called by sa-learn, spamc, spamd, spampd etc), tries to read a per-user config file from $HOME.
This happens even if the config option allow_user_rules is set to 0 (IMO this is probably a bug and it's been round a long time).
As it can't find this folder (because of permissions) it then tries to create the folder.
As those who run sa-learn inside a cron know this is very annoying as we get a failure email even from a successful run.  Just google the error config: path "/root/.spamassassin" is inaccessible: Permission denied and see how many people this affects (and the insecure fixes they suggest).  The only safe solution for cron was to ignroe it and pipe stdout and stderr to /dev/null, but that's a bit extreme.
It does this regardless of what -C or -p or --dbpath options are passed, so you can't fix it either in the command line options or the global config.
The Fix
The solution, that worked for me, is to call sa-learn and pass a temporary $HOME environment variable pointing to a location where the non-root user running spamassassin can write, in my case this is /var/cache/spampd:
e.g.
HOME=/var/cache/spampd sa-learn --spam /var/vmail/jason/.SPAM/cur


How to print column values in Mutator before execute?

Question: Below is the code I going to insert into cassandra
Set<String> keys = MY_KEYS;
Map<String, String> pairsOfNameValues = MY_MUTATION_BY_NAME_AND_VALUE;

Set<HColumn<String, String>> colums = new HashSet<HColumn<String,String>>();
for (Entry<String, String> pair : pairsOfNameValues.entrySet()) {
    colums.add(HFactory.createStringColumn(pair.getKey(), pair.getValue()));
}

Mutator<String> mutator = template.createMutator();
String column_family_name = template.getColumnFamily();
for (String key : keys) {
    for (HColumn<String, String> column : colums) {
        mutator.addInsertion(key, BASIC_COLUMN_FAMILY, column);
    }
}
mutator.execute();

There are some cases where I don't know how many columns are inserted into the mutator. Is there any to print the data before/after the execution method.
I tried Mutationresult.tostring(). It gives the following response.

MutationResult took (3750us) for query (n/a) on host:
  localhost(127.0.0.1):9160

Also Mutator to String didn't give me desired result.
Please help.
Answer: Yep, try mutator.getPendingMutationCount() before executing the query.
Other than that, you'll have to push the logic of counting what columns you are adding to the mutator manually. The toString() doesn't give you what you want as you are supposed to bind the mutator.execute() to a MutationResult. E.g:
MutationResult mr = mutator.execute();

But the mutation result doesn't give you much more either. You can know these 3 things (2 really...)
// the execution time
long getExecutionTimeMicro();
long getExecutionTimeNano();
// host used for the exec.
CassandraHost getHostUsed();


Which staff's meter does note in one staff tied to note in other staff use?

Question: The image below shows Rachmaninoff's Prelude in G minor, Op. 23, No. 5, measure 43 (IMSLP). The treble staff is in 4:4; however, the bass staff has 24 sixteenth notes in it, and though not marked, these are probably meant to be arranged into triplets: every three sixteenth notes fit into the space of two sixteenth notes from the treble staff. Sixteenth notes in the bass staff are therefore shorter than sixteenth notes in the treble staff, and the same goes for eighth notes, etc.
The question is this: the marked note in the middle of the treble staff is linked to a note from the bass staff. What length does that note have? Does it have the length of an eighth note from the treble staff (half a beat), or the length of an eighth note from the bass staff (a third of a beat)? And offset to which note is it played? In other words, does it belong conceptually in the bass staff?
I would go further and actually ask: are there two superimposed F# notes in the bass staff? A sixteenth and an eighth? And what's that eighth doing there? Which staff does it belong to?
Comment: When doing arithmetic to understand rhythm patterns, there's no point thinking in *staffs*. Every *voice* has to add up to one whole bar, and there are far more than two voices in this music. The cross-staff beam helps you by indicating which notes belong to the same *voice*.
Comment: Note that the last part of the highlighted measure implies that **an eighth note from the bass staff still takes up half a beat**.
Comment: The main indication of multiple voices is the direction of the stems; the beaming is a secondary indication.  There is one voice that is exclusively in the bottom staff and another voice that is sometimes in the bottom staff and sometimes in the top staff.  The first three notes in that voice are a G quarter note, an F sharp eighth note, and a G eighth note.  The first two of those notes are in the bottom staff.  The third note is in the top staff.
Comment: Kilian: I hear you, but here the voices follow different meter rules depending on which staff they belong in, and so the voice assignments to the staff do matter. That pair of notes sits in both staffs. Dekkadeci: yeah it would seem so. That pair of eighths seems to be conceptually a part of the treble staff.
Comment: @MihaiDanila no, the triplets do not depend on the staff, but only on the voice.  Only one voice has triplets.  That voice could also have such a range that some of its notes were written in the upper staff.  The voice that has eighth notes could be written entirely in the lower staff.  The fact that one voice is distributed across multiple staves is a red herring.
Comment: @phoog thank you for clarifying. How does one tell how many voices there are and where they are? Those extra rests (well, in this measure, extra notes) in the treble staff that come together with other notes, are those the main indicator that there are multiple voices? And because that is absent from the bass staff, there is only one voice in that staff? Looking at the treble staff, are there two voices for half the measure and one voice for the other half?
Comment: Excellent, thank you for this insight! This should probably be a question+answer of its own.
Answer: In this piece there are four distinct "voices" being played simultaneously.

The left hand part constitutes one "voice", the "bass voice".
The right-hand octaves are the "melody voice".
The notes between the octaves that fill out the chords are an "inner harmony voice".
The quarter-note G, the F# in question, the G it's beamed with, the A half-note, and the A-B eighth notes in the bass staff all constitute a second "melodic voice" that echos the main melodic voice.

Imagine this piece arranged for orchestra, say, and each of those parts would be given to a different instrument. It's just that the piano can play them all simultaneously.
So for the F# in question, it happens that two voices "sing" it simultaneously: the bass voice sings it as a triplet sixteenth note; the "inner melody" voice sings it as an eighth note. The two voices are indicated, in part, by the double stem. The bass voice continues its arpeggio down from the F#; the inner melody voice continues it up to the G in the treble clef. It's written overlapped to make clear that the left hand should take the note even though it is also a participant in the right-hand part.
Conceptually, the F# has both the length of a triplet sixteenth and an eighth note. When played, the eighth note takes precedence, since it's in the more emphasized voice.
The same situation exists with the G on beat one, which is the same G given in the right-hand octave on that beat. Rather than double-stem the note, it's written twice so that its progression to the left-hand F# is clear.
Comment: @MihaiDanila The marked F# and G form and eighth-note pair totaling 1 beat. Both notes are part of the same "voice", they just happen to be written in different staves to indicate which hand should play which.
Comment: @MihaiDanila Could you clarify what you mean by "meter"? The meter is the same for both staves.
Comment: Thank you for this answer. Does the marked G belong have a triplet eighth length or a simple eighth length? It seems from your answer that the latter is the case: an F# and a G connected by a beam are both conceptually in the treble clef and respect the rules in it. (If so, also see Giovanni's answer below, which claims the opposite.)
Comment: Thank you. And on what basis does that voice follow the meter rules of the treble staff and not those of the bass staff? Does it have to do with the logic of voices that you explained in your answer? (Also, thank you for updating the question to name the piece!)
Comment: One suggestion: your answer doesn't explicitly state that the inner melody voice follows the meter rules in the treble staff, and that therefore the marked G is a basic eighth. Consider stating that explicitly. (It's also not clear why the F# and the G are part of the inner melody voice; is it because that's the only logical way to think of it due to the octaves taking up the main melody? OTOH, the F# and the G are both marked, just like the octave notes, so why not main melody?)
Comment: I use "meter" to loosely refer to the amount of time that the notes take. Is there a better term? There is something different about the lengths of the notes in the two staffs; is there a technical name for that?
Comment: @MihaiDanila Just FYI, I'm going to be unavailable for a while, but when I can, I'm going to open up a chat room to discuss further. That will help me give the most clear answer.
Comment: @MihaiDanila, I've set up a [chat room](https://chat.stackexchange.com/rooms/127105/room-for-aaron-and-mihai-danila) in the interest of making sure all your questions are answered, and then I can update the post here to reflect our discussion.
Answer: "Which staff's meter" isn't a particularly useful question, because the two staves have the same meter, which is C, meaning 4/4.  Rachmaninoff uses sextuplet sixteenth notes implicitly in the bass voice, which is apparent because of the proportional underlay and because there are 24 of them in the measure.  He doesn't write the usual 6 or 3 to indicate this, and he doesn't change the meter.
That the implied tuplet affects only the bass voice is apparent from the fact that all of the other voices comprise eighth notes that have the same duration as three bass notes, quarter notes that have the same duration as six bass notes, and so on.  There is no reason to think that the whole staff is affected.
In a comment you wrote

the voices follow different meter rules depending on which staff they belong in

"Depending on which staff they belong in" isn't correct.  The bass voice has triplet sixteenths, and all the other voices don't.  The staff doesn't matter.
Some further thoughts:

Sixteenth notes in the bass staff are therefore shorter than sixteenth notes in the treble staff...

Actually, some eighth notes in the bass staff (in earlier and later passages) have the same length as those in the treble staff.  But, more importantly...

and the same goes for eighth notes, etc.

...is completely untrue.  There are no triplet eighth notes anywhere.  Every eighth note is 1/8 of a measure, and they all have twice the duration of a "normal" sixteenth note and three times the duration of a triplet sixteenth note.
Answer: This is called cross staff beaming. It's used as an alternative to ledger lines. In this case, the phrasing still belongs to the bass staff, but the pitch is notated in the treble staff.
Comment: No problem! I agree with Aaron that it is just a normal eighth.
Comment: Thank you for this answer. I'm waiting for Aaron's clarification, but it seems he is claiming that the marked G is a basic eighth note rather than a triplet eighth note.
Answer: You're working under a basic misconception.
"Sixteenth notes in the bass staff are therefore shorter than sixteenth notes in the treble staff, and the same goes for eighth notes, etc."
No.  16ths (and 8ths, and quarters) are the same length everywhere.   But those notes in the bass stave aren't 16ths.  They're triplet 16ths.  Three to an 8th note.  It's just that the '3' is omitted.   Naughty, but not uncommon when, as here, context makes it obvious that they're triplets.


CS0029 C# 'Cannot implicitly convert type string[] to string'

Question: I'm making an application to edit the properties of .mp3 files. I have to say I'm pretty new to programming and stackoverflow, so I might be doing something very obviously wrong. Please forgive me! This is the code I am using:
private void btnApply_Click(object sender, EventArgs e)
{
    var file = TagLib.File.Create(filepath);
    if (!string.IsNullOrWhiteSpace(txtGenre.Text))
    {
        file.Tag.Genres = new string[] {txtGenre.Text};
    }
    if (!string.IsNullOrWhiteSpace(txtArtist.Text))
    {
        file.Tag.Performers = new string[] {txtArtist.Text};
    }
    if (!string.IsNullOrWhiteSpace(txtTitle.Text))
    {
        file.Tag.Title = new string[] {txtTitle.Text};
    }
    file.Tag.Performers = new string[] { txtArtist.Text };
    file.Tag.Title = txtTitle.Text;
    file.Save();

    if (!ReadFile())
    {
        Close();
    }
}

The odd thing to me is that I only get an error for this part:
if (!string.IsNullOrWhiteSpace(txtTitle.Text))
{
    file.Tag.Title = new string[] {txtTitle.Text};
}

With this being underlined red:
new string[] {txtTitle.Text}

What am I missing here? I've been looking for a very long time but I just can't seem to find any solutions. Thank you in advance! I am also using TagLib, by the way.
Comment: Do you understand the difference between `string` and `string[]`?
Comment: You are trying to put a `string[]` value into a `string` variable. `file.Tag.Title` is a `string`
Comment: You can try with: `file.Tag.Title = txtTitle.Text;`
Comment: @Luctia Please don't mangle question titles with status information like "SOLVED:". Accepting answers is here for this purpose.
Answer: Change this:
file.Tag.Title = new string[] {txtTitle.Text};

to:
file.Tag.Title = txtTitle.Text;

Title type is string, not array of strings (not string[]), but you try to assign array - because of it you get error. Other fields have type string[] (array of strings), that's why you get error only with Title.
Also, you try to assign value to Title 2 times:
if (!string.IsNullOrWhiteSpace(txtTitle.Text))
{
    file.Tag.Title = new string[] {txtTitle.Text};    // first time
}
file.Tag.Performers = new string[] { txtArtist.Text };
file.Tag.Title = txtTitle.Text;                       //second time

You need to assign only one time. Also, when you assign second time you assign it correctly without error.
The same situation with Performers - you assign first time inside if statement and second time after the last if.
Comment: Thanks, this removed the underlining, but it doesn't work as intended. The idea is to not edit anything when the textbox is empty. This works with txt.Genre, but not with title or artist. Going to have to figure that one out myself, I suppose. Thanks nonetheless!
Comment: @Luctia, see edited answer. Delete two lines before `file.Save()`. These lines: `file.Tag.Performers = new string[] { txtArtist.Text };` and `file.Tag.Title = txtTitle.Text;`
Comment: Ah yes, I tried and tested that just now. It works now. Thank you for your help!
Answer: Change the code like this and try
file.Tag.Title = txtTitle.Text;


Interação com array multidimensional em php

Question: Tenho esses dados:
$answers = [
    'text-1626173297126' => [
        'Capítulo teste',
        'Juarez Neri Antônio Pereira',
        'CAVALEIROS DA LUZ'
    ],
    'text-1626173306001' =>
    [
        'Pedro Ds',
        'RenGraminhani',
        'CAR CESAR TANURI'
    ],
    'text-1626173476932' => [
        'firstname.lastname@example.com',
        'email@example.com',
        'caranuri.com'
    ]
];

Eu preciso que a primeira coluna (text-1626173297126) fique na primeira coluna de uma tabela de html;
text-1626173306001, na segunda coluna;
text-1626173476932, na terceira;
Eu tentei fazer, algo como:
foreach ($answers as $k => $value) {
    echo '
';
    foreach ($value as $val) {

        echo '', $val, '	';
    }
    echo '
';
}

Saída desejada
Answer: Quer seus dados exibidos em colunas trabalhe-os como se fossem uma tabela com array_column().
A função array_column() aceita um array multidimensional como entrada onde cada elemento(array ou objeto) representa uma linha em uma tabela, e cada sub elemento(elemento do elemento) representa uma coluna nessa tabela:
$answers = [
    'text-1626173297126' => [
        'Capítulo teste',
        'Juarez Neri Antônio Pereira',
        'CAVALEIROS DA LUZ'
    ],
    'text-1626173306001' =>
    [
        'Pedro Ds',
        'RenGraminhani',
        'CAR CESAR TANURI'
    ],
    'text-1626173476932' => [
        'email@example.com',
        'email@example.com',
        'caranuri.com'
    ]
];

foreach (range(0, count($answers) - 1) as $idx) {   //Itera pelos índices das linhas da tabela.
  echo '
';
  foreach (array_column($answers, $idx) as $val){  //Itera pelas colunas dessa linha.
    echo '', $val, '	';
  }
  echo '
';
}

Teste o código no Repl.it
Resultando em:

    Capítulo teste
    Pedro Ds
    firstname.lastname@example.com

    Juarez Neri Antônio Pereira
    RenGraminhani
    email@example.com

    CAVALEIROS DA LUZ
    CAR CESAR TANURI
    caranuri.com


Event unbinding in AngularJS

Question: I'm very new to both angular and MVC programming so im not sure if im doing this correctly.
I have a jquery snippet I wanna use one some of my partials both not all of them. But since the event listeners never expire due the page never reloading I was wondering how I would register my events, listen to them and destroy them the angular way sort of speak.
I read somewhere you should use $scope.on but I don't really understand how it works.
Example
app.controller('PageCtrl', function ($scope, $location, $http) {

  // jQuery to collapse the navbar on scroll
  $(window).on( "scroll", function() {
  if ($(".navbar").offset().top > 50) {
      $(".navbar-fixed-top").addClass("top-nav-collapse");
      $(".logotype-white").addClass("logotype-hide");
      $(".logotype-grey").removeClass("logotype-hide");
  } else {
      $(".navbar-fixed-top").removeClass("top-nav-collapse");
      $(".logotype-white").removeClass("logotype-hide");
      $(".logotype-grey").addClass("logotype-hide");
  }
});

app.controller('OtherCtrl', function (/* $scope, $location, $http */) {
$(function() {
      $(".navbar-fixed-top").addClass("top-nav-collapse");
      $(".logotype-white").addClass("logotype-hide");
      $(".logotype-grey").removeClass("logotype-hide");
});

A friend of mine suggested I should use namespaces and just unbind all my events but that's not the angular way I guess?
Comment: Have you seen http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background/15012542 ?
Comment: Yeah I read that through and I realize I probably shouldn't be using jquery in the first place but I don't know how I would rewrite that jquery snippet to angular.
Answer: In order to achieve this in angularjs, you need the use of ng-class directive to toggle class, and to listen to the window scroll event within your controller.
Here is a similar demo:

angular.module('myApp', [])
  .controller('MyCtrl', function($scope, $window) {

    $scope.currWindowScroll = 0;

    angular.element($window).bind('scroll', function() {
      $scope.currWindowScroll = $window.scrollY;
      $scope.$apply();
    });

  });
.fixed {
  position: fixed;
  padding: 30px 10px;
}
.fixed div {
  padding: 10px;
  width: 300px;
  margin: 10px auto;
  background-color: yellow;
}
.red {
  background-color: red !important;
}

 500 }">
        This has red background if scroll > 500

Comment: Thank you so much this seems to be exactly what I was looking for. I was thinking that the answer somehow would relate to creating my own directive but I couldn't find a good example of someone using the scroll event in a directive.
Comment: Basically, you only use a custom directive if you have to modify the DOM. Since you only need to listen to window scroll, ng directives might suffice.

Event unbinding in AngularJS


Is there a way to compare linear regression slopes by permutation tests?

Question: I have some species $\times$ year matrices and analyse the temporal dynamics by regressing distance between years on $\sqrt{ {\rm time \ lag} }$. Since the data points are not independent and since I get $(n^2-n)/2$ distances for a time series of length $n$, it's problematic to use the standard way of determining the significance of the regression slope. I thus applied a Monte Carlo permutation procedure and compared the distribution of the random slopes with the observed slope. No problem so far; most of my regression slopes are significant at $p<0.0001$. My question: How do I compare the slopes for different species $\times$ year matrices? The parametric approach is still not a solution due to the problems outlined above, but I am not aware of a solution based on permutation procedures.
Comment: Even the ordinary regression fit may be invalid because the $(n^2-n)/2$ points reflect at most $n$ independent observations, causing extreme interdependence.  So, testing significance appears to be the least of the concerns here.  It looks like you need a different approach to the analysis altogether.
Comment: can you give examples how your "species x year" matrices look like?
Comment: ... and clarify what 'distance between years' means?
Comment: @psj: My matrices consist of species (several dozens) in rows and years (25) in columns. For the MCPP I shuffle the column positions randomly (10,000 times).
Comment: @onestop: Dissimilarity between years were measured by Hellinger distance, that is, Euclidean distance of Hellinger transformed data. Hellinger transformation: N'ij = √(Nij/∑Nij) where Nij is the population size of species i in year j, and ∑Nij is the sum of individuals across all species in year j.
Comment: @whuber: I'd be eager to get a suggestion...
Comment: I cannot offer an alternative because I do not know what's in the data (what exactly has been recorded about these "species"?) and knowing the purpose of the analysis.  Your research might be better served by reformulating the original question to provide this information.
Comment: @whuber: It's population size (=number of individuals) of species per year (and they are bird species, by the way). The aim is to check species composition change over time. When there is directional change, then years further apart should show larger Hellinger distances than years closer together.
Comment: Thanks: the problem is getting clearer.  I'm still not sure what exactly you mean by "check" the composition change over time and why that requires making all possible comparisons between species.  Could you perhaps share a high-level description of your scientific objective for this analysis? Also, there is a preliminary issue concerning what a "population" is.  I doubt you truly know the populations: these must either be estimates or summaries of observations, but which are they precisely?  That will influence the interpretation of any analyses.
Answer: In principle, you can use a permutation test on any function on data of two groups. To compare regression slopes, you simply pick to species, shuffle the data points between the groups randomly, but instead of comparing the mean value of each permuted group, compare the regression slope. You may have to center your data before computing the regressor (which may be linear or custom built, as long as it can be described by a single parameter after centering the data). I'm not sure how to deal with multiple comparisons in permutation test -- for a few categories, Bonferroni correction will do the trick, but I guess with several dozen species that will kill any effect... Ideas on this?


How to show $\displaystyle a_{n}=\frac{4^{2n+1}}{n^{2n}}$ is a descending sequence?

Question: I have to show that the sequence
$$a_{n}=\frac{4^{2n+1}}{n^{2n}},\qquad n\geq1$$
is descending.
I thought about proving
$$\frac{a_{n+1}}{a_{n}}<1$$
However, since
$$\frac{a_{n+1}}{a_{n}}=\frac{16n^{2n}}{(n+1)^{2n+2}}$$
I have no clue at all how I could make this.
Answer: You have$$\frac{a_{n+1}}{a_n}=\left(\frac4{n+1}\right)^2\left(\frac n{n+1}\right)^{2n}.$$It's clear that this is smaller than $1$ if $n>3$. And$$\frac{a_{n+1}}{a_n}=\begin{cases}1&\text{ if }n=1\\\frac{256}{729}&\text{ if }n=2\\\frac{729}{4096}&\text{ if }n=3.\end{cases}$$
Answer: When $n>4$, then
$$
a_n=\frac{4^{2n+1}}{n^{2n}}=4\left(\frac{4}{n}\right)^{2n}>4\left(\frac{4}{n+1}\right)^{2n}>4\left(\frac{4}{n+1}\right)^{2n+2}=a_{n+1}
$$
And, $a_1=64, a_2=64, a_3=\frac{16384}{729}<23, a_4=4, a_5=\frac{4194304}{9765625}<1$.
Answer: Hint: Maybe $$\left(\dfrac{n}{n+1}\right)^{2n} = \left(\dfrac{n+1}{n}\right)^{-2n} = \left[\left((1+\dfrac{1}{n}\right)^{n}\right]^{-2}$$ is a known sequence...
Answer: We have
\begin{eqnarray}
a_1&=&4^3=64\\
a_2&=&\frac{4^5}{2^4}=64
\end{eqnarray}
and for $n\ge 3$,
\begin{eqnarray}
\frac{a_{n+1}}{a_n}&=&\frac{4^{2n+3}\cdot n^{2n}}{(n+1)^{2n+2}\cdot 4^{2n+1}}\\
&=&\frac{16}{(n+1)^2}\cdot\left(\frac{n}{n+1}\right)^{2n}\\
&<&\frac{16}{(3+1)^2}\cdot 1^{2b}\\
&=&1
\end{eqnarray}
i.e. $a_{n+1}/a_n<1$ for $n\ge 3$. Therefore the sequence is decreasing.
Answer: It is enough to prove that
$$\frac{4^{2(n+1)+1}}{(n+1)^{2n+2}}\le \frac{4^{2n+1}}{n^{2n}}\iff\frac{16}{(n+1)^{2n+2}}\le \frac{1}{n^{2n}}\\16n^{2n}\le(n+1)^{2n+2}\iff 16n^{2n}\le n^{2n}(n+1)^2+(n+1)^2\sum_{k=1}\binom{2n}{k}n^{2n-k}\\16\le(n+1)^2+(n+1)^2\sum_{k=1}\binom{2n}{k}n^{-k}$$
Then one finish verifiant that inequality is true for $n=1$ and $n=2$
Answer: $$a_{n}=\frac{4^{2n+1}}{n^{2n}}\implies \log(a_n)=(2n+1)\log(4)-2n\log(n)$$
$$\Delta_n=\log(a_{n+1})-\log(a_n)=2 (n \log (n)-(n+1) \log (n+1)+\log (4))$$
Rewrite
$$(n+1) \log (n+1)=(n+1)\log(n)+(n+1)\log \left(1+\frac{1}{n}\right)$$ and use Taylor expansion
$$\Delta_n=\left(\log \left(\frac{16}{n^2}\right)-2\right)-\frac{1}{n}+\frac{1}{3
   n^2}+O\left(\frac{1}{n^3}\right)$$
$$\frac{a_{n+1}}{a_n}=e^{\Delta_n}=\frac{16}{e^2 n^2} \Bigg[  1-\frac{1}{n}+\frac{5}{6 n^2}+O\left(\frac{1}{n^3}\right)\Bigg]$$ So, as soon as $n>\frac 4 e$, that is to say $n\ge 2$, $\frac{a_{n+1}}{a_n}<1$


stringByRemovingPercentEncoding resulting in null string

Question: I've got a file path /Users/alexandra/Downloads/folder%20with%20spaces/ and I want to remove the percent encoding and make it a file URL. Using the method stringByRemovingPercentEncoding  makes the string null.
The documentation says "A new string with the percent-encoded sequences removed, or nil if the receiver contains an invalid percent-encoding sequence.", but I don't see %20 for a space being wrong?
Answer: You didn't show us your non-working code in Objective-C, but this works fine on my machine (in Swift):
if let path = "/Users/alexandra/Downloads/folder%20with%20spaces/".removingPercentEncoding {
    let url = URL(fileURLWithPath: path)
    print(url) // file:///Users/alexandra/Downloads/folder%20with%20spaces/
}

On the other hand, since you've already wrongly acquired percent encoding in a string pathname, why not just stick file:// in front of it and be done with it?
let path = "/Users/alexandra/Downloads/folder%20with%20spaces/"
if let url = URL(string: "file://" + path) {
    print(url)
}

Comment: This already helped me with my problem. Thanks for making me understand urls better :)


Why cannot I print $form in my template file?

Question: I have a "video" content type. I want to customize the template file for edit form,
page--node--add--video.tpl.php, but when I render (or print) $form, it returns NULL.
What is the problem?
Answer: There's no $form variable available in page.tpl.php (see the docs for a full list of available vars).
If you're trying to output the page content it's done like so:
<?php echo render($page['content']); ?>


How to create a Bean type programmatically?

Question: I'm building a module that creates set of blocks using Bean module. How do I can create a Bean Type programmatically in order to be able to create the blocks?
Answer: Bean uses ctools plugins for its types. Per the docs:
/**
 * Implements hook_bean_types().
 *
 * Beans uses ctools plugins to define the block types.
 * All plugin files must be registered in the .info file.
 */
function hook_bean_types() {
  $plugins = array();
  $plugins['plugin_key'] = array(
    'label' => t('Title'),
    'description' => t('Description'),
    // This is optional. Set it to TRUE if you do not want the plugin to be
    // displayed in the UI.
    'abstract' => FALSE,
    'handler' => array(
      'class' => 'ClassName',
      'parent' => 'bean',
      // This should be pointing to the path of your custom bean plugin module.
      'path' => drupal_get_path('module', 'example_bean') . '/plugins',
      // Class files should be named accordingly in order to support ctools
      // autoloading procedures.
      'file' => 'ClassName.class.php',
    ),
  );
  return $plugins;
}

Comment: How does this show how to attach a new bundle to the bean entity type? I don't think I understand...
Comment: If you put this code in a module, it'll attach a new bundle to the entity type @Felix. Not really much more to explain, that's how the module developers chose to implement it, as a ctools plugin
Answer: It is pretty simple.

<?php
$bean = bean_create(array('type' => 'my_bean_type'));
$bean->label = 'Administrative Label';
$bean->title = 'Bean Title';
$bean->delta = 'bean-machine-name';
$bean->field_block_content = array(
'en' => array(array(
  'value' => '
Text
',
  'format' => 'wysiwyg_editor',
)),
);
$bean->save();
?>

Comment: I know this. I don't know how to create the Bean type. I mean I don't want to create the `my_bean_type` in admin UI
Answer: From looking at the code in bean_admin_ui_type_form_submit() I've put together the following function:
/**
 * @param $machine_name
 * @param $label
 * @param string $desc
 */
function create_bean_type($machine_name, $label, $desc = '') {
  $plugin_info = array(
    'name' => '',
    'label' => '',
    'description' => '',
    'type' => '',
    'editable' => TRUE,
    'handler' => array(
      'info_file' => TRUE,
      'class' => 'BeanCustom',
      'parent' => 'bean',
      'file' => 'BeanCustom.class.php',
      'path' => drupal_get_path('module', 'bean_admin_ui') . '/plugins',
    ),
  );
  $bean_type = new BeanCustom($plugin_info);
  $bean_type->type = $machine_name;
  $bean_type->setLabel($label);
  $bean_type->setDescription($desc);
  $bean_type->save(TRUE);
  drupal_flush_all_caches();
}

I've not used the _bean_admin_default_plugin() function in case this code is running with the bean_admin_ui module disabled.
You can use this function like this:
create_bean_type('baked_bean', 'Baked Bean', 'A baked bean is a bundle attached to the bean entity type. Also if you eat too many you may fart.');


Swift Compiler performance

Question: I got this statement in Swift code which produces an error when executing in playground:
let colors: [String: [Float]] = ["skyBlue" : [240.0/255.0, 248.0/255.0, 255.0/255.0,1.0],
"cWhite" : [250.0/255.0, 250.0/255.0, 250.0/255.0, 1.0]]

The error is : expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
Then I changed the arrays element type to Double which just works fine.
However I am asking myself why this happens ?
As I said using Double it works just fine. So my guess is that Swift tries to guess the type and therefore Double works better in this example than Float.
Comment: Similar issues have been reported before, and (as I understand it) the problem is always the automatic type inference. You should file a bug report at Apple.
Comment: Thank you for your comment. But if the type inference is the problem here it isn't really a bug which is solvable, right ? Because the problem isn't my list but the model of type inference in general. Because this list could be expanded with more complexity infintely.
Comment: The types can be inferred from the context, and it works for a dictionary of a single color, therefore I would consider it a bug (but I am not a compiler expert). – In this concrete case you can work around it by converting each number in the array to a  Float explicitly: `[Float(240.0/255.0),  ...`.
Comment: Ok thank you. This would dramatically decrease readability but looks like the right way to go. I really would like to give you credit for that. So if you would provide it as an answer I could accept your answer. Thanks however :)
Answer: Similar issues have been reported before, and (as I understand it) the problem is the automatic type inference for "complicated" expressions. You should file a bug report at Apple.
It compiles with a dictionary of one color, but not with two.
In this concrete case, you can work around it by converting each number in the array to a Float explicitly:
let colors = [
    "skyBlue" : [Float(240.0/255.0), Float(248.0/255.0), Float(255.0/255.0),Float(1.0)],
    "cWhite" : [Float(250.0/255.0), Float(250.0/255.0), Float(250.0/255.0), Float(1.0)]
]

Swift Compiler performance


To evaluate $\lim_{x \to 0^+} \frac{\log(x)}{\sqrt x}$ using inequality

Question: To evaluate $$\lim_{x \to 0^+} \frac{\log(x)}{\sqrt x}$$
I know that $\log(x) < x$ for $x > 0$. So dividing by square root of $x$ and taking limits gives me nothing. Which inequality should I use here?
Thanks
Answer: $$\lim_{x \to 0^+} \log(x)=-\infty$$
$$\lim_{x \to 0^+} \sqrt{x}=0^+$$
$$\lim_{x \to 0^+} \frac {\log(x)}{\sqrt{x}} =-\infty$$
You don't need inequality here
Answer: If we substitute $t=\frac{1}{x}$ then
$$\lim_{x \to 0^+} \frac{\log(x)}{\sqrt x}=\lim_{t \to +\infty} {(-\sqrt{t}\cdot\log{t})} = -\infty$$
since $\log{t}>1$ for $t>e.$


Javascript if invalid date fill with null

Question: I have a date object from an html form.
const start = new Date(document.querySelector('input[name="start"]').value)

If the start time is left blank, I want the value returned to be an empty string. How can this be done?
Answer: You can try this code:
const value = document.querySelector('input[name="start"]').value
let start = ''
if (value !== '') {
  start = new Date(document.querySelector('input[name="start"]').value)
}

Answer: You just need to check upon the input value before using it into the Date constructor:
const start = document.querySelector('input[name="start"]').value !== "" ? new Date(document.querySelector('input[name="start"]').value): "";

Demo:

function logIt() {
  const start = document.querySelector('input[name="start"]').value !== "" ? new Date(document.querySelector('input[name="start"]').value) : "";
  console.log(start);
}
logIt();
<input name="start" type="date" onchange="logIt()" />


How do bean managed transactions work?

Question: I am new both to EJB and Bean Managed Transactions. After scrapping the Internet, I found that I could write a EJ session Bean which does transactions the "bean-managed way", like this:
@TransactionManagement(value=TransactionManagementType.BEAN)
@Stateless
public class OperationBean {
    @Resource
    private UserTransaction userTransaction;
    public void operation() {
        try{
            userTransaction.begin();
            Op1();
            Op2();
            Op3();
            userTransaction.commit();
        } catch(Exception e){
            userTransaction.rollback();
        }
    }
}

However, I do not understand what happens if an exception is thrown by Op3(). How are Op1() and Op2() undone?
Another question is how do I bind this to JSF? I need to write a form in JSF that sends its data to the server and the OperationBean does 3 operations based on the received data. These operations do involve database operations(3 updates) and do not make sense individually.
Thanks!
Answer: When you call userTransaction.begin(), simply saying JTA begins transaction on database level.
Now all the data modifications you perform are done inside transaction.
If everything is OK, execution comes to userTransaction.commit() and database fixes transaction.
If something's going wrong, you call userTransaction.rollback() in catch block and database drops all the modifications you do after begin().
In two words it is difficult to explain how database transactions work, but basically database isolates all changes during transaction from other clients until commit() or rollback() is called and prevents external updates of data you are working with.
In JSF you can create @ManagedBean and inject your OperationBean into it with @EJB annotation.
You should get something like this
@ManagedBean
public class Operation {
    @EJB
    private OperationBean operationBean;

    public void doOperation() {
        operationBean.operation();
    }
}

and in your view
<h:form>
    <h:commandButton action="#{operation.doOperation}" value="Do Operation"/>
</h:form>

So you're doing it right. Assuming you really need bean managed transactions, not container managed.
Comment: "JTA begins transaction on database level" - how does it know which database am I using in Op1(), Op2() and Op3(). Do these methods need to contain something to notify JTA what database am I modifying?
Comment: You want to make changes in multiple databases? This approach works in case of single DB. Multiple DBs bring you to distributed transactions, so you should look for `XAResource` usage examples.
Comment: I am using a single database. But do I need to use it in a given way or can I just use java.sql.Connection and java.sql.PreparedStatement classes for updating the DB?
Comment: If you use EJB, there's no reason to work without JTA. So inject `@PersistenceContext private EntityManager em;` and make calls to DB with `em.createQuery()` (for JPA queries) or `em.createNativeQuery()` (for SQL). For updates, create JPA mapping and use `em.merge(obj)`.
Comment: This is a poor answer. The question does not indicate that any database is used at all, and your comments here do not further help your answer. Is this to indicate that all JTA must and can only be used for databases? I am still trying to figure out how to roll back (in the example above) op1, and op2 if no database is involved and this answer does not answer that at all. This answer doesn't even answer how the database does get involved implicitly even if the OP does mean to use a database.

How do bean managed transactions work?


Drupal Multiupload Filefield Widget conflict with mutiselect ajax dropdown

Question: I have created a multiupload field in my node using Multiupload Filefield Widget. I am using the code below to alter the default node form.
There is an ajax based dependent dropdown field in the form i.e city dependent on country.When I select a single country the form work fine. But when I select multiple values form the country list I get the follwing error:
An illegal choice has been detected. Please contact the site administrator.
I get this particular error when there is the multiupload form element present. When I remove the element from $form its works fine with multiple selected values.
Please help me out to solve this problem.Thanks in advance!
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'mynode_node_form':
            $country_list = load_countries();
            $selected_country = (isset($form_state['values']['country'])) ? $form_state['values']['country'] : key($country_list);

            $form['countries'] = array(
                '#type' => 'select',
                '#title' => t('Select Your Country'),
                '#options' => $country_list,
                '#default_value' => $selected_country ,
                '#ajax' => array(
                    'callback' => 'city_dropdown_callback',
                    'wrapper' => 'city_wrapper',
                ),
                '#multiple' => TRUE,
                '#required' => TRUE,
            );

            $cities_list = load_cities($selected_country);
            $selected_cities = (isset($form_state['values']['cities'])) ? $form_state['values']['cities'] : key($cities_list);
            $form['cities'] = array(
                '#type' => 'select',
                '#title' => t('Select Your City'),
                '#prefix' => '
',
                '#suffix' => '
',
                '#options' => $cities_list,
                '#default_value' => $selected_cities,
                '#multiple' => TRUE,
                '#required' => TRUE,
            );

    }
}
function city_dropdown_callback($form,$form_state){
    return $form['cities'];
}

Answer: Solved by issues by updating jquery.form.js to version 3.51.
Found the solution at : https://www.drupal.org/node/153774#comment-9202403


Register all user defined functions

Question: I need a little work around this thing. I'm trying to register all my defined functions in twig. I used the code below trying to achieve my goal but it doesn't work.
Inside my test.twig I called one defined function
                {{ site_url() }}
but I get this error : Unknown "site_url" function.
I don't know what's wrong because I can easily print the list of all my defined functions inside my foreach as follows :
                echo $v . "\n";
Here's my phone syntax
        // ALL USER FUNCTIONS

        $arr = get_defined_functions();

         foreach ($arr['user'] as $k => $v){
            // $this->_twig is my twig loader

            return $this->_twig->addFunction(
    new Twig_SimpleFunction(
    $v,
    $v
    ));

        }

Answer: Your return is obsolete, now you are only registering the first user defined function
$arr = get_defined_functions();
foreach ($arr['user'] as $v){
    // $this->_twig is my twig loader
    $this->_twig->addFunction(new Twig_SimpleFunction($v, $v));
}

Comment: Thanks for your reply. I still have the twig syntax error stating that site_url function is unknown.

Register all user defined functions


This query will give results in phpmyadmin but empty set in PDO

Question: SELECT id FROM locations WHERE location_name='saint françois'

will give me a set
but gives me an empty set when i use the query function of PDO
$stmt = $this->dbh->query("SELECT id FROM locations WHERE location_name='".htmlspecialchars(htmlentities(str_replace("'","\'",$get['location'])))."'");

Comment: What is the `datatype` and `Collation` of field `location_name` in your database ??
Comment: collation:latin1_swedish_ci and datatype:varchar(255)
Answer: $stmt = $this->dbh->dbh("SELECT id FROM locations WHERE location_name=?");
$stmt->execute([htmlentities($get['location'])]);

But you should never store HTML entities in database.
Instead, you have to store your text as is, as franÇois
And query it without converting,
$stmt = $this->dbh->dbh("SELECT id FROM locations WHERE location_name=?");
$stmt->execute([$get['location']]);

you have to properly indicate the data encoding, either for the table and connection.


Probability of Sum of random variables with uniform distribution

Question:
If $X\sim U[3,5]$ and $Y\sim U[2,6]$. Then what is the probability of $X+Y>7$, given $X$ and $Y$ are independent?

I'm confused on how does this get integrated for $X+Y>7$?
Answer: The distribution will be the convolution of the two distributions for $X$ and $Y$, a trapezoid (thanks to @kimchi lover for pointing out the shape of the distribution).
Then just find the area under the trapezoid  from $7$ to $11.$
$$\textrm{Probability} =  1/2 + 1/4 = 3/4.$$

See here for another example of two uniform distributions convolved:
Find PDF of given random variable $Z=\frac{(X+Y)}{2}$
Comment: The density function for the sum of 2 uniforms looks like a triangle _only_ when the lengths of their supports are equal (as is the case in your cited Q).  Otherwise it looks like a trapezoid.
Comment: Could you brief more please? Because i do not see this as a triangle distribution here.
Comment: Yes, you are right!
Answer: Defining a new pair $X^\prime:=\frac{X-3}{2}\sim U[0,\,1],\,Y^\prime:=\frac{Y-2}{2}\sim U[0,\,2]$ of independent variables, we want $P\left(X^\prime+Y^\prime=\frac{X+Y-5}{2}>1\right)$. Conditional on $X^\prime=x\in[0,\,1]$, this is equivalent to $P(Y^\prime>1-x)=\frac{2-(1-x)}{2}=\frac{1+x}{2}$. Now we average this over the distribution of $X^\prime$, viz.$$\int_0^1\frac{1+x}{2}dx=\frac34.$$
Comment: wondering how did you reduce given distribution to X′:=X−3/2∼U[0,1],Y′:=Y−2/2∼U[0,2] ?
Comment: @NikjilJain More generally, if $Z\sim U[a,\,b]$ and $d>0$ then $\frac{Z-c}{d}$ is uniformly distributed and has the obvious extrema, viz. $\frac{Z-c}{d}\sim U\left[\frac{a-c}{d},\,\frac{b-c}{d}\right]$.
Answer: Draw a rectangle in the $x,y$ plane, with vertex set $\{(3,2),(5,2),(3,6),(5,6)\}$ and draw the line $x+y=7$ and shade the region in the rectangle above the line, that is, shade the convex hull of the points $\{(3,4),(5,2),(3,6),(5,6)\}$.  The desired probability is the ratio of the shaded area to the area of the rectangle.  Which of course is $(8-2)/8=3/4$.