Why can't I change the priority of my Firebase reference (Permission denied)

Question: In my Firebase, I have an object that looks like this:
person
---- name
---- age

When I try to create it for the first time, I use this command:
firebaseRef.child("person").setValue(...)

That works fine.
Sometimes I want to create this entry with a priority, and this can be done like this:
firebaseRef.child("person").setValue(..., myPriority)

This works fine as well.
However, the priority should be updated later. I tried the following:
firebaseRef.child("person").setPriority(myPriority)

Unfortunately, this fails with the error message "Permission denied". Why is this?
The security rules for that reference are as follows:
"person": {
    ".read": true,
    ".write": true,
    "name": { ".validate": "newData.isString()" }
    "age": { ".validate": "newData.isNumber()" }
    "$other": { ".validate": false }
}

As can be seen, the node is both readable and writeable.
Comment: this behaviour has been fixed and will be in production by the end of next week.
Answer: The problem:
The reason for the "Permission denied" error is obviously in the security rules.
The problem is that the priority is stored in the "hidden" property .priority which is rarely mentioned in the documentation.
That property is not shown in the Firebase Forge (dashboard) but can be seen when exporting the raw JSON.
Now the directive "$other": { ".validate": false } prevents any property other than name and age from being validated. Thus the error "Permission denied" is raised.
I don't know, however, why the object can be written in the first place when using setValue(..., myPriority). This should cause an error as well.
The (half-way) solution:
Now it seems obvious to add a new directive to the security rules that looks like this:
".priority": { ".validate": true }

But this doesn't work. Firebase Forge responds with:
Key names can't contain ".", "#", "$", "/", "[", or "]" (unbound names start with "$")

This means that we cannot properly solve this issue. We have to adjust our existing security rules with some drawback: The rule "$other": { ".validate": false } has to be removed when we want to update priorities, leaving us with an imperfect validation.
Comment: In addition to this answer, one work-around for now is `"$other":{".validate":"$other.beginsWith('.')"}` - we're working hard on some fixes that make this whole area far more intuitive
Comment: Hi Chris, thanks for your tip. Are there any news about this?


My brain doesn't click when there is a linear map over there

Question: In linear algebra, very often problems can be solved by realizing a linear map and using rank nullity theorem. But I just can't see it myself without someone pointing out. For example Set of polynomials linearly dependent
What should I do with it?
Answer: I would say practice. There really isn't so much a "click" as just having a reportoire of techniques, examples and counterexamples, and a keen eye to spot which one is (probably) most useful.
You don't always see all the work behind answers here (or examples and theorems in a textbook), but I can promise you that many of them are the result of at least two or three failed attempts, before finally hitting the right approach. Those that aren't are usually written by people who have made those failed attempts on similar problems in the past, and don't even try them because they already know what will and won't work.
To paraphrase Pavel Grinfeld from several of his videos online: You have learned a field of mathematics once you have made every mistake you could possibly make.


Data from ajax post is passing null to the controller

Question: AJAX call -

Here countryId is passed as "AU" for example -
$("#Countries").change(function () {
        var countryId = this.value;
        $.ajax({
            url: '/Registers/GetStates',
            type: "POST",
            data: { 'data': countryId },
            success: function (states) {
                $("#States").html(""); // clear before appending new list
                $.each(states, function (i, state) {
                    $("#States").append(
                        $('<option></option>').val(state.Id).html(state.Name));
                });
            }
        });
    });

After calling the GetStates method 'countryId' is always passed as null in the controller method. Not sure what I'm missing here.
I tried JSON.Stringify({ 'data': countryId }) also. Can anyone help me out ?
Controller Action -

[HttpPost]
public SelectList GetStates(string countryId)
{
     return Helper.GetStates(countryId);
}

Answer: The parameter in your action method should be exactly same as the parameter name in the 'data' option of ajax.
In your case it is 'countryId'
[HttpPost]
public SelectList GetStates(string countryId)
{
     return Helper.GetStates(countryId);
}

Change your ajax data option accordingly.
data: { countryId: countryId },

It will work.


App running fine on device on debug mode but crashing when I'm running it independently

Question: My app working fine on device on debug mode but as soon as I'm running my app without Mac or Xcode debug mode it getting crash.
Comment: with device connected you can look at the crash logs in Organizer window of Xcode. What do they tell you?
Comment: Hi Kai,
Thanks for reply, but its not showing perfect when my device is connected.
Answer: You can try change Your provisioning profile to development type.


Linear combination of two independent normal random variables only normally distributed function?

Question: I have the intuition that it is, but I have no idea on how to show it.
More formally, let $X$, $Y$ be two independent random variables, with
$X \sim \mathcal{N}(\mu_1,\,\sigma_1^{2})$
$Y \sim \mathcal{N}(\mu_2,\,\sigma_2^{2})$
and in general $\mu_1 \neq \mu_2$, $\sigma_1 \neq \sigma_2$, and all of them are different from zero.
Let $Z$ be defined as $Z = f(X,Y)$, with $f:\,R^2 \rightarrow R$.
Is the linear combination (i.e. $f(X,Y) = aX + bY$, with $a,b \in R$) the only $f$ for which $Z \sim \mathcal{N}(\mu_3,\,\sigma_3^{2})$ ?
Comment: You mean linear combinations, not just the sum, right?
Comment: yes, I should have specified, my bad... I guess I meant more the type of operation.
Comment: @J.R.C. Then please edit your question.
Comment: is it ok like this? (sorry, I'm quite inexperienced here)
Comment: @J.R.C. Sure. But the answer to your original question is "no", since a linear combination of X and Y is normally distributed as well.
Comment: @callculus you are completely right. Another small issue is that the title is right on the character limit, if I replace sum by linear combination it no longer fits.
Comment: Having the full question in the title is not mandatory. Particularly when the question is long. It must be informative enough, that's all.
Comment: @J.R.C. The whole question should not be written in the title. It is sufficient to write something like "Distribution of the sum of normally distributed variables"  In the text field you specify the question.
Comment: @callculus should I then edit the title and remove any references of the sum in the post?
Comment: @J.R.C. If the sum is part of the question then you can keep it in the title. The important issue for the other users is that it is obvious what is the question and what are your own thoughts. I´ve made an edit for the title. It is a suggestion only.
Answer: The answer is Yes.
Assume that $X$ and $Y$ are two independent and normal random variables that are not necessarily identically distributed. Then they are jointly normal (because they are independent), which is important here.
Then the only function of $X$ and $Y$ leading to a normal random variable has to be linear; i.e has the form
$$ f(X,Y) : = aX + bY$$
for some constants $a$ and $b$.
This result is known as Cramér–Wold theorem (see for example: this lecture note). It is a consequence of the uniqueness of characteristic functions and the particular form of the characteristic function of normal distributions.
Another way to see this is to note that if $f (X,Y)$ is normal with positive variance,  you must be able to write it in terms of a standard normal random variable $N$ by whiting  (scaling and shift). But you can always do this also for the given random variables $X $ and $Y$.
For some counter examples when $X$ and $Y$ are not jointly normal, see the answer of this question: Are any linear combination of normal random variables, normally distributed?
Comment: I don't understand how to apply the Cramér-Wold theorem in relation to this result. If I understand correctly, the theorem states that the distribution of a random n-vector is completely determined by all its one-dimensional projections. So in this case, because I have a vector of two random variables I have to consider all combinations $t_1X + t_2Y$, which we know that are normally distributed. But how does this help me to show that only the linear combination preserves the normal distribution?
Comment: I can see your point regarding using only Cramer-Wold theorem. But If normal distributions are closed under linear maps, doesn't this mean that we do not need any other functions to describe normal variables, because any other function should be linear by closure?
Comment: Maybe another approach could be helpful. The question is if there any nonlinear function that will lead to a normal variable. Assume that you have only one normal random variable $X$ and assume an arbitrary function $f$, such that $Z= f(X)$. Assume that $Z$ is normal. Then you can show a contradiction by applying the change of variable formula: https://en.wikipedia.org/wiki/Probability_density_function#Dependent_variables_and_change_of_variables because the determinant of the derivative will be independent of $Z$ only if $f$ is linear. Otherwise, its clear that you get a contradiction.
Comment: That approach seems more helpful to me indeed. I was going to reply to your previous comment saying that I'm not sure how to show that the other side of the arrow follows: you are saying that linear transformation $\Rightarrow$ closed, but why does that imply closed $\Rightarrow$ linear transformation? For example, a set can be part of different groups under different operations, right?
Comment: You are right; what I wrote means that linear functions are sufficient. the second arrow only refer to existence.. there exists a linear transformation.
Comment: Regarding the approach of the change of variable formula, would it be showing that $f(X)$ is linear be sufficient to show that $f(X,Y)$ has to be linear too? For example, $f(X)=X^2$ and $f(X,Y)=XY$ wouldn't necessary have the same distribution, right?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/82423/discussion-between-user144410-and-j-r-c).


Does Safari associate a browser window name with the domain that opened it?

Question: I have a multiple-domain network of sites.  In one domain, some javascript opens a new smaller window and gives it a name of "controls".  If you go to a second domain and click to open "controls" again (same window name), it opens a new window rather than updating the one that already exists.
Is it possible that Safari associates the domain with the opened window so that one domain doesn't accidentally (or mischievously) change another domain's window?  Other browsers (non-Webkit, at least) don't seem to behave this way.  I haven't been able to find any clear explanation of what the logic here is.
Answer: No, what you are looking for is called session ID.
http://en.wikipedia.org/wiki/Session_ID
Comment: Thanks for the reply.  I'm actually unable to use sessions in this case, and I'm only trying to open a new window, not track user behavior.

openwin('http://www.example.com/mypage.html', 'mywindow', 'width=100,height=300');


Spring Integration Null correlation not allowed. Maybe the CorrelationStrategy is failing?

Question: I am getting the error `Null correlation not allowed.  Maybe the CorrelationStrategy is failing?
This forum thread seemed to resolve it with something like the below, however that approach Is not working for me, http://forum.spring.io/forum/spring-projects/integration/102054-aggregator-correlation-strategy-failing.
My understanding is that the inbound-streaming-channel-adapter puts FILE_NAME as a header value, and I'd like to join on that.
    <int-ftp:inbound-streaming-channel-adapter
    auto-startup="true" id="ftpListener" channel="ftpChannel"
    session-factory="ftpSessionFactory" remote-directory="/export/home/udyj"
    filename-pattern="test1.txt">
    <integration:poller fixed-rate="5000"
        max-messages-per-poll="-1" />
</int-ftp:inbound-streaming-channel-adapter>

<int-ftp:inbound-streaming-channel-adapter
    auto-startup="true" id="ftpListener2" channel="ftpChannel"
    session-factory="ftpSessionFactory" remote-directory="/export/home/udyj"
    filename-pattern="test2.txt">
    <integration:poller fixed-rate="5000"
        max-messages-per-poll="-1" />
</int-ftp:inbound-streaming-channel-adapter>

<bean id="correlationStrategy"
    class="org.springframework.integration.aggregator.HeaderAttributeCorrelationStrategy">
    <constructor-arg value="FILE_NAME.substring(0,3)" />
</bean>
<integration:aggregator id="nuggetAggregator"
    input-channel="ftpChannel" output-channel="sendMQDistributionChannel"
    correlation-strategy="correlationStrategy">
</integration:aggregator>

Answer: Look, you say HeaderAttributeCorrelationStrategy, what definitely expect a header name to get. but at the same you specify the header name as a FILE_NAME.substring(0,3) which looks more like an expression. And you get null because there is really no such a header.
If you want to evaluate an expression, consider to use ExpressionEvaluatingCorrelationStrategy instead:
<bean id="correlationStrategy"
    class="org.springframework.integration.aggregator.ExpressionEvaluatingCorrelationStrategy">
    <constructor-arg value="headers.file_name.substring(0,3)" />
</bean>


Irrationality of "primes coded in binary"

Question: For fun, I have been considering the number
$$
\ell := \sum_{p} \frac{1}{2^p}
$$
It is clear that the sum converges and hence $\ell$ is finite.  $\ell$ also has the binary expansion
$$
\ell = 0.01101010001\dots_2
$$
with a $1$ in the $p^{th}$ place and zeroes elsewhere.  I have also computed a few terms (and with the help of Wolfram Alpha, Plouffe's Inverter, and this link from Plouffe's Inverter) I have found that $\ell$ has the decimal expansion
$$
\ell = .4146825098511116602481096221543077083657742381379169778682454144\dots.
$$
Based on the decimal expansion and the fact that $\ell$ can be well approximated by rationals, it seems exceedingly likely that $\ell$ is irrational.  However, I have been unable to prove this.
Question: Can anyone provide a proof that $\ell$ is irrational?
Comment: Perhaps the question you meant to ask was whether $\ell$ is _trancendental_?
Comment: The sequence of digits appears, with some references, at https://oeis.org/A051006
Comment: It is *never* easy to see that a number is transcendental (aside from Liouville numbers).
Comment: Also discussed here: http://mathoverflow.net/questions/24270/a-number-encoding-all-primes
Comment: And how to prove it is irrational if the sum is taken over any infinite subset of primes? Sorry i misread, would be more interesting if you asked about transcendental.
Comment: I thought about it being transcendental or algebraic also, but I did not see how first to prove that it was irrational.  It seems I overlooked the obvious here.  At any rate, is it also easy to see if $\ell$ is transcendental?
Comment: @JavaMan: It is certainly not easy for me!  Presumably your number is transcendental, "almost all" real numbers are. But the gaps between consecutive primes are not even close to being large enough to use a Liouville-type approximatibility argument.
Comment: I proved explicitly a few weeks ago that the sequence of prime numbers is not periodic. The proof is trivial see: http://arxiv.org/abs/1305.0954. Hopefully of use here also.
Answer: That $\ell$ is irrational is clear. There are arbitrarily large gaps between consecutive primes, so the binary expansion of $\ell$ cannot be periodic. Any rational has a periodic binary expansion.
The fact that there are arbitrarily large gaps between consecutive primes comes from observing that if $n>1$, then all of $n!+2, n!+3, \dots, n!+n$ are composite.
Answer: If it was rational, then the binary expansion would eventually repeat -- but the distribution of primes doesn't repeat.
To wit: if the repeat had period $n$ and $p$ was a prime large enough to be inside the repeating part, then $p+pn=(1+n)p$ would have to be prime, which obviously isn't the case. On the other hand, the repeating period cannot consist of all zeroes, because there are infinitely many primes.
Comment: Thanks for your help.  I wish I could've accepted both answers.
Answer: Well to prove that this number is irrational you must know that a rational number has a periodic sequence of digits in any basis after a fixed digit. That is if $r=0.f_{1}f_{2}...f_{n}...$ then $f(n+T)=f(n)$ for some $T \in \mathbb{N}$ and $\forall n \geq k_{0} \in \mathbb{N}$. (check that!).
Then supposing by absurd, let $n_{0}$ be a natural such that $n_0\geq k_0$ and $n_{0}$ is prime then $1=f(n_{0})=f(n_{0}+T)=f(n_{0}+2T)=...=f(n_{0}+n_{0}T)=1$ absurd because $n_{0}+n_{0}T$ is not prime.
An interesting question arises is that number Algebraic, i.e., that is solution of a polinomial equation with rational coefficients?


Decimais sem arredondar em javascript

Question: Como faria para conseguir o seguinte resultado.
quero diminuir um numero de casas decimais após a virgula sem que o numero arredonde ?
ex: 5,8608 --> 5,860
já testei diversas funções e formas mas todas sobem o numero para 5,861.
Desde já agradeço quem puder contribuir.
Answer: Multiplica os números que queres pela ordem de grandeza igual ao número de casas decimais. Depois tiras a parte decimal e divides de novo pela mesma ordem de grandeza. Algo assim:

function ajuste(nr, casas) {
  const og = Math.pow(10, casas)
  return Math.trunc(nr * og) / og;
}

console.log(ajuste(3.456, 2)); // 3.45
console.log(ajuste(4.123, 2)); // 4.12
console.log(ajuste(-4.123, 2)); // -4.12

EDIT: Editei a resposta para usar Math.trunc em vez de Math.floor
Comment: Esse método produz resultados inexperados com números negativos.
Comment: @v.k. obrigado, corrigi
Answer: Complementando a outra resposta (que antes de ser editada estava usando Math.floor), para funcionar também com números negativos, uma opção é usar Math.trunc em vez de Math.floor:

function ajuste(nr, casas) {
    const og = Math.pow(10, casas);
    return Math.trunc(nr * og) / og;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12

Também daria para fazer assim:

function ajuste(nr, casas) {
    const sign = Math.sign(nr);
    if (sign === -1)
        nr *= -1;
    const og = Math.pow(10, casas);
    return Math.floor(nr * og) / og * sign;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12

No caso, usei Math.sign, que retorna 1 para números positivos e -1 para negativos.
Depois, se o número é negativo, ajusto-o para que seja positivo, e no final eu multiplico pelo sign (assim, caso seja -1, o resultado volta a ser negativo).

Por fim, outra opção é usar Math.floor ou Math.ceil dependendo do sinal do número:

function ajuste(nr, casas) {
    const og = Math.pow(10, casas);
    return (nr > 0 ? Math.floor(nr * og) : Math.ceil(nr * og)) / og;
}

console.log(ajuste(-3.456, 2)); // -3.45
console.log(ajuste(-4.123, 2)); // -4.12

console.log(ajuste(3.456, 2));  //  3.45
console.log(ajuste(4.123, 2));  //  4.12
Answer: let nteste=5.8608
console.log(nteste.toFixed(3))  //dessa maneira arredonda para 5.861
let numero=5.8608
let numero2=numero*1000  // como nesse caso tu quer 5.860 então é preciso guardar na variavel numero2 todos esses algarismos multiplicando por 1000
numero2=parseInt(numero2)/1000  // o parseInt é necessário para que apenas a parte inteira seja dividida por 1000
console.log(numero2.toFixed(3)) // estou fixando 3 casas decimais
Comment: Estou aprendendo a programar e essa foi a maneira que consegui resolver o seu problema. espero ter ajudado!

Decimais sem arredondar em javascript


How to to redirect a form to a certain node for anonymous users?

Question: In a custom module, I have a form that is triggered by an option in a menu.
I'd want this form to be redirected automatically (without action of the user) to a certain node (/node/2) when the user is not authenticated.
In the public function buildForm(array $form, FormStateInterface $form_state) {, I know how to not display the fields of the form for the anonymous user:
$oCurrentUser = \Drupal::currentUser();
if ($oCurrentUser->isAnonymous()) {
} else {

some fields...

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
];
return $form;
}

I guess that redirection might be done with   $form_state->setRedirect('entity.node.canonical', ['node' => 2]);
but I don't know how to make it work...
Any idea?
Answer: The class implementing FormInterface is allowed to return an instance of a class extending the Response class, despite FormInterface::buildForm() not documenting it. See what a comment in the FormBuilder::retrieveForm() code says.

Exceptions should not be used for code flow control. However, the Form API currently allows any form builder functions to return a response.
  @see https://www.drupal.org/node/2363189

This means that code similar to the following one would actually work.
public function buildForm(array $form, FormStateInterface $form_state) {
  // Verify the currently logged in user is an anonymous user and redirect.
  if ($this->currentUser()->isAnonymous()) {
    return $this->redirect('entity.node.canonical', ['node' => 2]);
  }
}

Although, since Do not allow form builder functions to return Response objects (the bug report linked in the comment) is open for Drupal 8.8.x, that code could not work anymore, in future.
See also the following comment in the FormBuilder::buildForm() code.

Exceptions should not be used for code flow control. However, the Form API does not integrate with the HTTP Kernel based architecture of Drupal 8. In order to resolve this issue properly it is necessary to completely separate form submission from rendering.
  @see https://www.drupal.org/node/2367555

The linked issue is Deprecate EnforcedResponseException support (a task, not a bug report).
A module that works also after the change described in that issue is implemented would:

Associate a controller to the route, not a form builder
In the controller method associated with the route, redirect the anonymous users to the node page, or render the form for authenticated users
class RedirectOrFormController extends ControllerBase {
  public function showForm() {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('entity.node.canonical', ['node' => 2]);
    }

    return $this->formBuilder()->getForm('Drupal\\locale\\Form\\TranslateEditForm');
  }
}

Replace 'Drupal\\locale\\Form\\TranslateEditForm' with the fully qualified name of the form builder.
Comment: That was my thought precisely, but I wonder how can we do that for ContentEntity forms
Answer: In buildForm() you can return a redirect response the same way as in a controller:
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('entity.node.canonical', ['node' => 2]);
    }

    // build $form for authenticated users

    return $form;
  }

Use $form_state->setRedirect() if you want to redirect in a form submit handler.

Using buildForm() as controller by specifying _form instead of _controller is documented and widely used (not in FormInterface, but on DO: https://www.drupal.org/docs/8/api/routing-system). It's unlikely core will ask devs to replace it by their own controller.
Answer: Using kiamlaluno's advice, the route for the menu is now associated to /association/showMembership.
association.membership_showMembership:
  path: '/association/showMembership'
  defaults:
    _controller: '\Drupal\association\Controller\MembershipController::showMembership'
    _title: 'Membership'
  requirements:
    _access: 'TRUE'

The controller class uses the following code.
class MembershipController extends ControllerBase {
  public function showMembership() {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('entity.node.canonical', ['node' => 2]);
    }
    return $this->formBuilder()->getForm('Drupal\association\Form\Membership');
  }
}

The Membership form doesn't redirect users in buildForm().
Answer: yes, you are right. you can redirect to the node using the code that you have mentioned. There is another way to set the redirection check the below code.
use the name space :

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse(node url);
$response->send();
exit(0);

I don't know what you are trying to achieve hope this code may help you.
Comment: exits should not be needed
Comment: @Kevin is correct: `exit()` should not be used.
Comment: This is also not how redirects are done in a form builder.


How to think about the tensions of polytonality with 3 or more keys?

Question: If two keys are played simultaneously (bitonality), I usually think of the tensions by the number of notes that are not included in both Keys:
C Major
C D E F G A B
G Major
G A B C D E F♯
Difference of one note = Little tension
But how should I think about 3 or more keys (Polytonality) simultaneously?
Answer: One way to conceptualize it is to think of it in the same way, just from the other side. In other words, let's not count the number of different pitches, but let's count the number of pitches that are the same.
Between C and G major, there are 7 common tones (C D E G A B), which results in a high amount of uniformity and thus little tension. Seven is the highest number of common tones shared among two major keys.
Now, let's do the same thing with three keys. To C and G major, let's add A major. These three collections share four pitches (D E A B). In contrast, let's consider C, G, and A♭ major. These three collections only share two pitches (C G), and therefore will have less uniformity (=more tension) than the collection of C, G, and A major.
Note that the highest number of common tones between three major keys would be five (think C, G, and D major, which share D E G A B); this gives you a basis on which to compare polytonal relationships among major keys.
With all that said: whether this is the best way to measure tension in polytonal music is another question.

A Possible (but Incomplete) Systematic Approach
If you're looking for an easy way to compare the number of common tones, take the two key signatures the farthest apart, and determine their difference in accidentals. Subtract this number from 7, and that will be the number of common tones. among the keys.
For instance: between C, G, and F, the greatest difference in key signatures is 2 (G has one sharp, F has one flat, which is a difference of two accidentals). The common tones shared between these three keys will be 5, because 7-2=5. Between C, D, and D♭, the greatest key signature difference is between D and D♭, a difference of 7 accidentals (!); this means that there are precisely zero common tones between these three major keys.
The system breaks down with a large number of accidentals and if you allow enharmonic spellings as common tones; consider the common tones between C, G♭, and C♯ major. The largest difference between key signatures is 13 (6 flats to 7 sharps), yet these three keys actually yield one enharmonic common tone: F (which is spelled as E♯ in C♯ major). I'm not sure yet how to make sense of this within this system. In this case, I would suggest respelling C♯ as D♭; suddenly the key signature difference is 6 flats, which results in one common tone. But we can't always spell keys enharmonically...
Comment: "With all that said: whether this is the best way to measure tension in polytonal music is another question."
Relevant to this point, "Density Degree Theory" by Orlando Legname: http://www.oneonta.edu/faculty/legnamo/theorist/density/density.html

This takes Hindemith's ideas of tonality and consonance/dissonance and expands them out to several octaves; it may be worth looking at for figuring out just how dissonant a tension may be when far away from the "bottom" key. But that's a judgement call, really.
Comment: Thank you Richard. I'm very glad you're around to answer all of my questions. By the way, I couldn't find a "Poly-tonality" tag to add to this question. If you are able, would you mind adding it to the list of available tags? My thanks, again.


Chart/visual for negative binomial regression

Question: My wife is presenting a study at a conference poster session. She has a correlation of sorts [1] where kids' self-assessment of asthma ("I felt a lot better" or "I felt a little better or not better") matches doctors' assessments (0 to 6, low numbers are better). And we need a visual for the poster.
I'd have thought that a correlation graph would be the way to go, but the x- and y-values are both on discrete scales, so if you plot them, (1) there is no cloud of values to see and (2) there is no obvious trend.
Here are the buckets (value + count of occurrences) for people who felt a lot better:
<code>>>> print(a_lot_better)
{0: 66, 1: 9, 2: 3, 3: 2}
</code>
And here are buckets for people who felt a little better or not better:
<code>>>> print(a_little_better)
{0: 79, 1: 31, 2: 5, 3: 6, 6: 1}
</code>
If you sum up the numbers like this:
<code># python
def print_dict(d):
    total = float(sum(d.values()))
    composite = 0.0
    for k, v in sorted(d.iteritems())
        print("{0}: {1}".format(k, v / total))
        composite += (k * v) / total
    return composite
</code>
You get this:
<code>>>> print_dict(a_lot_better)
0: 0.825
1: 0.1125
2: 0.0375
3: 0.025
0.2625

>>> print_dict(a_little_better)
0: 0.647540983607
1: 0.254098360656
2: 0.0409836065574
3: 0.0491803278689
6: 0.00819672131148
0.5327868852459017
</code>
And that is more obviously different, but I don't know how to present this visually (assuming even that this is a legitimate summary).
How should we present this data to be visually obvious that there is an interesting and significant relationship?
[1] As broadly understood by a statistics-civilian.
Comment: There are some good ideas here: http://stats.stackexchange.com/questions/56322/graph-for-relationship-between-two-ordinal-variables
Comment: @Dimitriy Masterov: Thanks, this is great. Much of the search relies on having the correct domain terminology for the search. If I'd described this as a relationship of ordinal variables, I might have stumbled on this link earlier.
Answer: The heading "negative binomial regression" is a puzzle here as the distribution is  defined only on the grades 0, ..., 6, so can't be negative binomial on that ground alone.
However, your calculation of the discrete probability distribution strikes me as exactly right and that suggests showing two histograms, which is only a step away from your probability distributions. It would be widely conventional to show bars with a little space between them to show that the scale is discrete. In fact some would go further and prefer the bars to be shrunk to spikes.
In the thread pointed to by Dimitriy Masterov, the proposals of table-like plots are essentially identical in spirit.
A Mann-Whitney test is quite encouraging here.
This isn't, in my view, a correlation problem at all. You have two distributions of ordinal (graded) variables.
Comment: Excellent, thank you. We are not working with stata or R, but are instead shoehorning this into Powerpoint with Excel using bar charts of the two series' discrete probability distribution. Not quite so sexy but still passable. Thanks very much!
Comment: Sorry about the misleading "negative binomial regression." I gather my wife was describing some other problem at the same time and I was confused into believing it was the same topic.
Answer: Most important is to figure out what the message you want to communicate is and try to find a graph whose message is close to that.
Some graphs that might spur some ideas:
Comparing bar charts (aka discrete histograms) shows the different distributions but perhaps misleads since score=0 has a higher bar for "little better" than "lot better", though it's relatively less common.

A mosaic plot (aka spine plot) makes the population difference and the relative sizes clearer but it's harder to make out the distribution shape.

Overlaid smooth distribution curves emphasizes the different distribution shapes but with a loss of detail.
Comment: Density estimation seems a real stretch here. Nice mosaic plot. The histograms can show proportions rather than raw counts.
Comment: Good point, I thought about going into whether the 0-6 score should really be modeled ordinal or just more of a rounded continuous measure, which might allows means comparisons, etc., but that's far beyond my expertise. (And of course I chopped off the negative scores from the axis :) )
Comment: There is plenty of stuff on density estimation respecting the support in e.g. Silverman's book. That's in my experience typically not implemented; you have to fix things yourself.
Comment: Thanks a lot for this. I appreciate that you put in the effort to produce graphs. The spine plot is my personal favorite but my wife's adviser on this overruled. So it goes. FWIW, I think you have the "a little better" and "a lot better" labels reversed in the first graph (though the counts of patients are correct).
Comment: @hughdbrown why do you say the first graph has the wrong labels. The Y axis is count and the first two bars are at about 80 and 30 which agrees with the "little better" data values of 79 and 31. Perhaps you were expecting percents on the Y axis, which would probably be better as Nick mentions.
Comment: @xan: You're right -- I was looking at the first bucket and expecting 80% for "a lot better" but instead seeing a count of 60. Yeah, I do think the point is clearer with percentages.


What would be a comprehensive but safe set of html tags to use with the HTML Filter but compatible Markdown?

Question: I want to use the Markdown filter on my pages, but using the HTML filter messes it up. However I still want to use it. Does anyone have an idea what other tags should be allowed beside these and what the safety issues are?
This the list I currently use - what else should be added?

 <src>

Answer:

But you don't need enable all of it, just simple reorder the filters, and put the markdown filter under the html filter. So the html filter will drop the unavailable tags, before the markdown process the text, and build own html.
Edit:
Checked the OpenAtrium's dedicated Markdown filter, it has the following in HTML

Markdown PHP Version: 1.0.1n
Markdown Extra Version: 1.2.4
And own filter weights:
Comment: The markdown filter is the last filter, but I still need to disable the HTML filter to get correct Markdown


pip and virtualenv (w/o virtualenvwrapper): pip install package_name gives permission denied but using sudo installs globally

Question: I have the neurolab package version 0.2.0 in /usr/local/lib/python2.7/dist-packages.
Now I would like to install neurolab version 0.1.0 in a virtual environment.
This is after installing pip and virtualenv:
~$ mkdir neuro_env
~$ cd neuro_env
~/neuro_env$ virtualenv envi
~/neuro_env$ source envi/bin/activate
(envi)~/neuro_env$ pip install neurolab==0.1.0

Then the install fails, with at the end of the error the line:
IOError: [Errno 13] Permission denied: '/home/username/.pip/pip.log'

But when I install it with permissions like this:
(envi)~/neuro_env$ sudo pip install neurolab==0.1.0

Then version 0.1.0 is just installed globally again (in /usr/local/lib/python2.7/dist-packages)
I read I could use the -E flag, but that is not possible anymore it seems:
error: no such option: -E
So how do I install neurolab version 0.1.0 only for my project in~/neuro_env?
Edit
(envi)~/neuro_env$ ls -l /home/username/.pip
total 4
-rw-r--r-- 1 root root 874 2012-07-28 13:18 pip.log

Comment: It looks like `/home/username/.pip/pip.log` is owned by root or has the wrong permissions (or it doesn't exist yet, but `/home/username/.pip` has similar problems). Can you add the output of `ls -l /home/username/.pip` to your question?
Answer: The problem is that your /home/username/.pip/pip.log file is only writable by root, so when you try to use pip as another user you don't have permission to update the log file and the whole operation fails.
Changing the ownership of the log file (using sudo chown username:username /home/username/.pip/pip.log) or removing it (using sudo rm /home/username/.pip/pip.log) should fix your problem.
Comment: If the log file was created when you were using `sudo pip …` that would probably explain the permissions.
Comment: Thnx! Strange that my .pip/pip.log has these permissions by default.
Answer: if you are using windows. type in powershell or terminal:
python -m pip install WHATEVER


HP Z400 workstation with RHEL5 LINUX OS; NO MORE REACHABLE, need to reboot

Question: The LiNUX RHEL5 Workstation Z400 stop answering to ping and it was no more possible to connect to it, even on the local console; The workstation was not reachable in anay way.
The only method I found is to restart the station (switch off, switch on) and after that everything works fine
Have somebody an idea on what can have happened
I don't see explanation of this in the /var/log/messages
Some more informations:
Placement/routing of a FPGA was running
I have often this problem with Z400 system hang; The last time , there was quite a little activity on this Workstation BIOS Information
Vendor: Hewlett-Packard
Version: 786G3 v03.12
Release Date: 09/13/2010
Address: 0xE0000
Runtime Size: 128 kB
ROM Size: 2048 kB

lsb_release –a
LSB Version: :core-3.1-amd64:core-3.1-ia32:core-3.1-noarch:graphics-3.1-amd64:graphics-3.1-ia32:graphics-3.1-noarch Distributor ID: RedHatEnterpriseServer Description: Red Hat Enterprise Linux Server release 5.5 (Boron) Release: 5.5 Codename: Boron
I had contact with HP but for the moment no explanation discussion, about Samba configuration... But as the problem does not occur systematically...
Comment: So you're saying the console was non-responsive as well, so it's not a network issue. Is there anything that was written to the console/stout? Is this regularly happening/reproducable? If it regularly happens, is there any way you can leave it at a non-graphical screen to see if there's some kind of kernel dump of errors?
Comment: Yes, everything is frozen; this happen sometimes; I don't know where i can try to find any informations abou the problem,nothing interesting in teh /var/log/messages, i only see informations while restarting the system; People that where using the system remotly only see that tey can't do anything
Comment: This question belongs on SuperUser or Linux/Unix
Answer: This sounds like normal-ish behavior when the processor is too busy to service normal requests.
Try renicing the process doing the routing to a lower priority, or perhaps try setting CPU affinity, and try and free up a core for processing GUI and ethernet interrupts.
Answer: Did this occur during the flashing process on the FPGA? If so, you may be causing the crash or system hang at that point. Is this repeatable?
Comment: This occur while running the process of routing the FPGA; it happens many times but not every time and I don't know where to search, I don't see anything in the var/log/messages. It did not happen while flashing the FPGA
Comment: while doing the place and route process for the FPGA; the tool from provider crash and after that no possibility to do anything; the tools is customized to use all the 4 processor's core to do the place and route


How can I achieve 3NF with a database that has multiple date fields and two different users?

Question: I hope to reach 3NF with my database that is not particularly well made but functions ok...My main concern is whether there is a need for perfect 3NF, if there is such a thing, and if I should make adjustments on any of the tables to get to a good enough 3NF?! help me just understand if the level of normalization form this db is 3NF and good enough to pass as 3NF...
*please bear with me, this is my first web project, therefore my first database!
Answer: 3NF usually, but not always, makes a lot of sense. At the very least, databases in 3NF tend to be smaller and the chances of inconsistencies reduces considerably.
Looking at your database, as a starting point, here are some thoughts:

users. Make your primary key sensible. Is userid unique? Is the username-mobileno combo unique? Surely uniqueness cannot be defined by a combo of all three. A common strategy is to have userid as the primary key, with the username-mobileno as a unique constraint. If that works for you, see #2
username-mobileno/userid. There appears to be significant confusion in the use of these three columns in the child tables. Only users' primary key should migrate to the child tables.
servicepost child tables. servicepost_details and ratings. username appears to be redundant in these child tables (available in parent tables).
bids. It appears to be another child of servicepost. username, mobileno appear to be redundant (available in parent tables).
user_details. What's this table required for? If there is just one row per user, dump the table and move relevant columns into users.
servicepost_details. Here again, is it possible to have multiple rows in this table for one in servicepost? If not, dump it, and move relevant columns into servicepost.
Comment: "should I use their ids?" (in child tables). Yes, that is precisely the purpose of a primary key. Later, when you need "real life" information for say, reporting, use a join statement.
Comment: thanks alot @RudyF...I get it now, but would i be able to register the user with the fields in the table while adding the further info from user details later on?
Comment: userid is unique...and in regards to the username, can you help me differentiate between the user who posts the 'servicepost' and the one who bids for it? I thought I would do it with the username...should I use their ids?...and with bids, the date of the bid and the user who made it, as well as if it is accepted or not I thought needed their own table...was that wrong?
Comment: "Would i be able to register the user with the fields in the table while adding the further info from user details later on?" ... sure, through an UPDATE statement.
Comment: "can you help me differentiate between the user who posts the 'servicepost' and the one who bids for it?". In a true 3NF, you wouldn't have users.usertype ... because that is determined by information in servicepost and bids. Besides, can a "client" not become a "bidder" (like on eBay?).
Comment: thanks for the update...those are good points, I already have plenty of data in the users table and after log in is when they have an option to add further details or not...so would me getting rid of the user details table, and adding those fields to the users table mess the structure and flow up? and whats the best option to follow?...keep in mind my project is due tuesday, so major structural change may not be so advantageous considering the amount of work I still have remaining...
Comment: what about that table?
Comment: "What about that table?" Presumably, you are talking about "bids". Yes, I'd imagine that bids is required.

Whoa! It looks like you've made changes to the database layout. This looks a lot better.

What's the primary key for the table, bids? Is it servicepostid, bid? That works, on the (obvious) assumption that each servicepost will attract 0 to many bids.

The tables users, servicepost and bids make sense to me, but I'm not sure how ratings fits in.
Comment: About ratings: I understand that a servicepost is being rated, but is the userid (in ratings) a "bidder", the winning "bidder" or someone completely independent. If it's either of the first two, then ratings should be a child table of bids with a 0-1 relationship.
Answer: Every normal form, from 1NF through 5NF was invented (or perhaps discovered) for a reason.  There are consequences to departing from the normal form.  As @RudyF has already pointed out, the normal form usually, but not always, makes a lot of sense.
If you are a beginner, the chances are you do well to ignore BCNF, 4NF, and 5NF for now.  The consequences of departing from 1NF are that you lose keyed access to some of the data.  The consequences of departing from either 2NF or 3NF is that the same fact is stored more than once in the database, raising the possibility that it will be stored inconsistently in two places, creating a contradiction inside the database.
As to your question of whether you have to adhere to "true 3NF" or not,  this boils down to whether you are prepared in your database update applications to assure that a self contradicting database will never be committed, or whether a database that yields inconsistent results will bother you.
It's not hard to get to 3NF.  You need a key for each table.  Typically you name a key as primary key even if there is more than one possible key.  A key can be composed of more than one column.  You then make sure that non key data depends on the key, the whole key, and nothing but the key  (so help me Codd).  You can't answer the questions about dependency without reference to the subject matter.
When you are normalizing, don't be too concerned about speed or efficiency.  You can tweak the design for speed before you build.
I hope this doesn't repeat stuff you already know.  It's easy to learn this stuff.  Becoming proficient is not so easy.


FastCGI process has failed frequently recently - for WP on IIS 7.5

Question: We have a Windows 2008 R2 server. We have hosted WordPress website on it. The website shows 500 internal error frequently. On enabling the detail mode, it gave the following message:

HTTP Error 500.0 - Internal Server Error
  The FastCGI process has failed frequently recently. Try the request again in a while.

Resetting the server starts the website.
The issue has been quite often and we are unable to find any further information regarding the cause. Neither we are able to replicate the issue.
We have enabled sysloging in php.ini but to no avail.
Comment: this issue still exists? I remember YT used have this issue often ...
Comment: Can you please share phpinfo details?
Comment: What about general windows logging? Event viewer and IIS request log \ exception log might be useful. anything special there?

Also, did you enable FastCGI php logging? `fastcgi.logging = 1` in php.ini?
Answer: I have some Suggestions:

You can Increase your php memory_limit at least 16M or more in php.ini.
you can check if there is some detailed messages in event log then you can figure out the issue.
you can switch to other php handlers like nginx or other.
In Some cases mysql processes occurs this type of issue. So check MySql processes of the server(Many times it gives timeout error but in some cases it gives error 500)
Answer: It's difficult without log verbosity, but I had the same issue.  You can see if this works for you:
Try maximizing your "Instance MaxRequest" in your FASTCGI Configuration.
IIS root > FastCGI Settings : Thenchoose php-cgi.exe for WP, then edit and increase the Instance MaxRequests


Algoritmo de ordenação, Stream Java

Question: Ao trabalhar com Stream atualmente uso o método sorted para ordenar, exemplo:
    Stream<Integer> stream = Stream.of(3, 2, 1);
    stream.sorted(); // saida será 123

Qual o algoritmo de ordenação desse método?
Tem maneiras mais eficientes de ordenar usando Stream?
Comment: Provavelmente é o TimSort que é usado, mas não tenho como garantir essa informação
Answer:
Qual o algoritmo de ordenação desse método?

Estou no Java 11.
Primeiro, vejamos como o método sorted() é declarado na interface Stream:
Stream<T> sorted();

Ok, isso não nos ajuda. Ele é um método abstrato sem implementação default. Então, para achar a implementação, vejamos o código do Stream.of(...):
@SafeVarargs
@SuppressWarnings("varargs") // Creating a stream from an array is safe
public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

Agora, o código do Arrays.stream(...):
public static <T> Stream<T> stream(T[] array) {
    return stream(array, 0, array.length);
}

E depois:
public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {
    return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);
}

Observe que os valores agora estão armazenados em um Spliterator.
Agora o StreamSupport.stream(...):
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {
    Objects.requireNonNull(spliterator);
    return new ReferencePipeline.Head<>(spliterator,
                                        StreamOpFlag.fromCharacteristics(spliterator),
                                        parallel);
}

A classe java.util.stream.ReferencePipeline não é uma classe pública, mas o seu código ainda assim pode facilmente ser visto dentro da JDK:
abstract class ReferencePipeline<P_IN, P_OUT>
        extends AbstractPipeline<P_IN, P_OUT, Stream<P_OUT>>
        implements Stream<P_OUT>  {

Então, vamos ver a classe interna Head, que é enfim a implementação de Stream que procuramos:
static class Head<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {

A classe interna Head herda da classe externa ReferencePipeline e não sobrescreve o método sorted. Então, olhemos na superclasse (ReferencePipeline):
@Override
public final Stream<P_OUT> sorted() {
    return SortedOps.makeRef(this);
}

A classe SortedOps também não é pública. Vejamos que método é esse makeRef:
static <T> Stream<T> makeRef(AbstractPipeline<?, T, ?> upstream) {
    return new OfRef<>(upstream);
}

A classe OfRef é interna à SortedOps:
private static final class OfRef<T> extends ReferencePipeline.StatefulOp<T, T> {
    /**
     * Comparator used for sorting
     */
    private final boolean isNaturalSort;
    private final Comparator<? super T> comparator;

    /**
     * Sort using natural order of {@literal <T>} which must be
     * {@code Comparable}.
     */
    OfRef(AbstractPipeline<?, T, ?> upstream) {
        super(upstream, StreamShape.REFERENCE,
              StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED);
        this.isNaturalSort = true;
        // Will throw CCE when we try to sort if T is not Comparable
        @SuppressWarnings("unchecked")
        Comparator<? super T> comp = (Comparator<? super T>) Comparator.naturalOrder();
        this.comparator = comp;
    }

    /**
     * Sort using the provided comparator.
     *
     * @param comparator The comparator to be used to evaluate ordering.
     */
    OfRef(AbstractPipeline<?, T, ?> upstream, Comparator<? super T> comparator) {
        super(upstream, StreamShape.REFERENCE,
              StreamOpFlag.IS_ORDERED | StreamOpFlag.NOT_SORTED);
        this.isNaturalSort = false;
        this.comparator = Objects.requireNonNull(comparator);
    }

    @Override
    public Sink<T> opWrapSink(int flags, Sink<T> sink) {
        Objects.requireNonNull(sink);

        // If the input is already naturally sorted and this operation
        // also naturally sorted then this is a no-op
        if (StreamOpFlag.SORTED.isKnown(flags) && isNaturalSort)
            return sink;
        else if (StreamOpFlag.SIZED.isKnown(flags))
            return new SizedRefSortingSink<>(sink, comparator);
        else
            return new RefSortingSink<>(sink, comparator);
    }

    @Override
    public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
                                             Spliterator<P_IN> spliterator,
                                             IntFunction<T[]> generator) {
        // If the input is already naturally sorted and this operation
        // naturally sorts then collect the output
        if (StreamOpFlag.SORTED.isKnown(helper.getStreamAndOpFlags()) && isNaturalSort) {
            return helper.evaluate(spliterator, false, generator);
        }
        else {
            // @@@ Weak two-pass parallel implementation; parallel collect, parallel sort
            T[] flattenedData = helper.evaluate(spliterator, true, generator).asArray(generator);
            Arrays.parallelSort(flattenedData, comparator);
            return Nodes.node(flattenedData);
        }
    }
}

Note o Arrays.parallelSort(flattenedData, comparator);. É aqui que alguma ordenação está sendo feita:
@SuppressWarnings("unchecked")
public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) {
    if (cmp == null)
        cmp = NaturalOrder.INSTANCE;
    int n = a.length, p, g;
    if (n <= MIN_ARRAY_SORT_GRAN ||
        (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
        TimSort.sort(a, 0, n, cmp, null, 0, 0);
    else
        new ArraysParallelSortHelpers.FJObject.Sorter<>
            (null, a,
             (T[])Array.newInstance(a.getClass().getComponentType(), n),
             0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
             MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
}

E então temos a linha TimSort.sort(a, 0, n, cmp, null, 0, 0); denunciando que o algoritmo usado é o TimSort em alguns casos (no caso do if). Se isso cair no else, vejamos esse ArraysParallelSortHelpers.FJObject.Sorter:
static final class FJObject {
    static final class Sorter<T> extends CountedCompleter<Void> {
        static final long serialVersionUID = 2446542900576103244L;
        final T[] a, w;
        final int base, size, wbase, gran;
        Comparator<? super T> comparator;
        Sorter(CountedCompleter<?> par, T[] a, T[] w, int base, int size,
               int wbase, int gran,
               Comparator<? super T> comparator) {
            super(par);
            this.a = a; this.w = w; this.base = base; this.size = size;
            this.wbase = wbase; this.gran = gran;
            this.comparator = comparator;
        }
        public final void compute() {
            CountedCompleter<?> s = this;
            Comparator<? super T> c = this.comparator;
            T[] a = this.a, w = this.w; // localize all params
            int b = this.base, n = this.size, wb = this.wbase, g = this.gran;
            while (n > g) {
                int h = n >>> 1, q = h >>> 1, u = h + q; // quartiles
                Relay fc = new Relay(new Merger<>(s, w, a, wb, h,
                                                  wb+h, n-h, b, g, c));
                Relay rc = new Relay(new Merger<>(fc, a, w, b+h, q,
                                                  b+u, n-u, wb+h, g, c));
                new Sorter<>(rc, a, w, b+u, n-u, wb+u, g, c).fork();
                new Sorter<>(rc, a, w, b+h, q, wb+h, g, c).fork();;
                Relay bc = new Relay(new Merger<>(fc, a, w, b, q,
                                                  b+q, h-q, wb, g, c));
                new Sorter<>(bc, a, w, b+q, h-q, wb+q, g, c).fork();
                s = new EmptyCompleter(bc);
                n = q;
            }
            TimSort.sort(a, b, b + n, c, w, wb, n);
            s.tryComplete();
        }
    }

E novamente, vemos o TimSort.sort(a, b, b + n, c, w, wb, n); lá.
Conclusão: O algoritmo usado é o TimSort.

Tem maneiras mais eficientes de ordenar usando Stream?

Isso depende muito da distribuição dos dados. Sem assumir nada sobre a distribuição dos dados, o algoritmo TimSort é um excelente algoritmo estável, com tempo de processamento Θ(n log n) e que tende a bater outros algoritmos que também são Θ(n log n). O TimSort é baseado no MergeSort, mas ele tenta se aproveitar de ordenamentos parciais dos dados sempre que possível para otimizar algumas coisas e pode seletivamente utilizar o InsertionSort em determinadas partes pequenas onde isso seria mais rápido que o MergeSort. Esse algoritmo também aproveita-se de várias outras possíveis otimizações.
Dito isso, é difícil haver uma forma mais eficiente de ordenar um Stream qualquer do que desse modo que serve para o caso geral. É difícil encontrar algum algoritmo de ordenação que possa bater o TimSort no caso geral. Além disso, a implementação dada ainda tenta paralelizar essa aplicação do TimSort se o array for grande o suficiente (é o que ocorre no ArraysParallelSortHelpers.FJObject.Sorter) para tentar obter um desempenho ainda melhor.
No entanto, se o seu Stream não for um Stream qualquer e sim algo que você saiba de antemão que tenha uma determinada estrutura ou ordenação específica da qual você pode tirar proveito para uma ordenação melhor, então nesses casos específicos, uma outra forma de ordenação melhor pode ser possível. Mas aí, cada caso é um caso.

Algoritmo de ordenação, Stream Java


Which module(s) should I use to create a customer support section?

Question: I've got a site where I need to get a customer (not client) support system set up. Support Ticketing System, unfortunately, is geared towards client support. I think Storm is too (it's huge, in any case).
The way I see it, I've got a few options:

Set up a different installation of Drupal entirely and use something like OpenAtrium or Drupal Commons for the support area. OMG overkill. Plus I'd like to just have it be a coherent part of my current site, same theme and shared logins and all that.
Patch Support ticketing system, or Storm, or whatever module I wind up using.
Use CaseTracker + Mailhandler to get a simple system, but I'll probably wind up still needing to do an amount of configuration to get it working.
Give up and use something like Trellis Desk on a subdomain.

One thing that maybe makes my search a little harder is that I'm adamant about having inbound email integration. The same way that we do, customers want to email an address and get a support ticket created. If this functionality isn't there, they'll send an email.
Comment: To which Drupal version are you interested?
Comment: It's enough to use the relative tag.
Comment: @kiamlaluno Thanks for cleaning it up. I sure am glad Drupal StackExchange appears to have the equivalent of path_redirect when the aliases change :)
Answer: See Similar Module Review page and choose the one that works best for you.
Comment: I should have mentioned that I'd checked out that page already. I'm asking here because none of those are really good enogh. They don't assume both that the site *itself* is the main topic of the support section (or the one particular thing on it, in this case a service it provides). Is there something similar to Trellis Desk or Kayako eSupport for Drupal or am I better off using one of those and not trying to do this in Drupal? I'm OK with that - I just want to do due diligence before going that route.
Comment: Case tracker and support modules are pretty much stable. I have used it in the recent past. I am not sure about Trellis Desk or Kayako eSupport perhaps  you can play around its hook to extend it for your needs or hack it if not possible.
Comment: Yeah, I contacted the maintainer of Support ticketing system to see about joining forces. If I'm going to struggle through this, I want to give something back the community. It feels strange to use a third-party product. That's my last resort. For now I have the issue queue anyway as a workaround since the service I need this for has a Drupal module. I'll award you the answer...since it's basically the answer in terms of what Drupal has at the moment.
Comment: If you are considering support module beware of db_affected_rows(). I had duplicate insert and key error problems with it.
Answer: I've seen the Feedback module used with great success, I would recommend trying it out.
Comment: Interesting, but I'm looking for something that I could to set up more of a dedicated support area. It seems like Feedback is for giving page-specific Feedback. I may be wrong; could you describe more why you recommended that? I'm commenting based on having seen it used on a site before and having looked at its project page and screenshots.


Correlation of Fixed Effects in lmer

Question: I'm a psycholinguistics student with few knowledge in statistics and I have some doubts about a Correlation of Fixed Effects in lmer function (lme4 package).
My response variable is RT (Reaction Time in a self-paced reading experiment) and my independent variables are Ant (PP, NP) and Verbo (SG, PL).
I have modeled the data with intercepts for Sujeitos (the people who are doing the task) and Item (the sentences i've used), asking for principal effects and interactions between the variables. Here is the model lmer(RT~Ant*Verbo+(1|Sujeitos)+(1|Item)) and that's the coefficients for fixed effects:

So, I have made a table of the coefficients for the interactions.
My problem is: that -0.705 and -0.716 correlation effects are a problem for my interaction terms? I'm saying this because the coefficients for the condition NP:SG came from the coefficients of SG only:

and the coefficients for PP:PL came from the PP only:

So, to me, there is no problem here, because I'm not contrasting PP:SG x PP (correlation = -0.705) and I'm not contrasting PP:SG x SG ((correlation = -0.716)). But I do that when getting the coefficients for PP:SG:

In the last case, there is a contrast between PP:SG x PP and SG. So, the correlation could be a problem. Is this correct? And, if so, how can I deal with this? I've read some thinks in Jaeger's blog and in this book: Howell, 2010. Statistical Methods for Psychology, but it doesn't help much.
Thank you.
Answer: No, it is not a problem. The correlation arises from the fact that your two categorical predictors are entered as dummy codes, and are therefore not orthogonal to the interaction term, even in the case of balanced data. So we fully expect both the predictors themselves (i.e., the vectors of predictor values) and the parameter estimates to be correlated. It is exactly the same issue in fixed-effects-only regression using, for example, lm().
If you want, you can recode your categorical predictors using sum-to-zero contrasts (e.g., contr.helmert(2)), and the correlations between the interaction and simple effects should be lessened. But it shouldn't make any difference as far as the test of the interaction term is concerned.
Comment: But, @Jake Westfall, it's that way even if I'm concerned the p-values. I'm saying that because the correlation could inflate de error term. So, the p-values could be anti-conservative.
Comment: I understand. So refit the model under the contrast codes I suggested and see if you get a different answer.
Comment: I do that, using contr.helmert(2) for both categorical variables and the output was completely different: the correlation was reduced to almost zero values, but the coefficients changed to. The standard error was reduced to. But I'll analyse this data another hour. Thank you very much.
Comment: The simple effects will be different, but the interaction should be the same. Is this what you see?
Comment: Yes, it is! But I'm reading somethings in Crawley's R book about Helmert contrasts and trying to understand what I'm doing here. I'm saying that because the effects of AntPP became very significative. It could be that way because Helmert contrasts the first level NP against all other levels. But in that case I have only two levels (NP and PP), so "all other" are only PP and the result should be the same. But... I didn't undesrtand it very well (yet).
Comment: We don't have the space here to discuss the theoretical issues of how different coding schemes work. So I will just say that if you want to examine the main effects of Ant and Verbo, it would be easiest to do this in a separate model where the interaction term has been omitted.

Correlation of Fixed Effects in lmer


Prove that there are infinitely many natural numbers that are not powers of any prime.

Question: I am wondering whether there is a way to prove that the set consisting of all natural numbers that are not powers of any prime is infinite. For example, 6 is such a natural number. Just to make this clear, what I mean is that any numbers that are powers of 2,3,5,7... (prime numbers) are not in the defined set. So 2,4,8 ; 3,9,27 are not in the set.
For a set to be infinite, I mean the following:

I am trying to this by proving that this set is equivalent to $ \Bbb N$ but it is really hard to find an explicit bijection. Another way to do this is that I can prove the set consisting of all natural numbers that are powers of a primes is countably infinite. But it seems that the complement of a countably infinite set in $ \Bbb N$ may not be countably infinite?
Can someone please give me a hand? Thanks.
Comment: If $n$ is odd, $n >1$, can $2n$ be a power of a prime?
Comment: `p*(p+1)` for any prime?
Comment: $p q$, for $p$ and $q$ distinct primes?
Comment: What do you mean by giving a hand???
Comment: @Sagar Mishra: The phrase "give me a hand" is an idiom. It means "help me" (e.g., "help me up").
Comment: Oh thanks for this. Actually I'm weak in idioms and all
Comment: @AndreasCaranti I have edited the question. It should be clear now.
Comment: Could you **stop** tagging everything with [set-theory] when it clearly does not fit the tag?
Comment: you can construct infinitely many, which are easily mapable to the natural numbers eg 2*3->1, 2*2*3*3 ->2 etc.
Comment: I'm not sure I understand your question. What about the set $\{6^n : n \in \mathbb{N} \}$? This set doesn't contain any element which is a power of a prime, and it's easy to make a bijection from this set to $\mathbb{N}$.
Answer: $\newcommand{\Set}[1]{\left\{ #1 \right\}}$$\newcommand{\N}{\mathbb{N}}$Is there any reason why you would want an explicit bijection?
Because you can prove that your set
$$
X = \Set{ x \in \N : \text{$x$ is not a power of a prime}}
$$
is in a bijection with the natural numbers without making the bijection explicit.
First note that
$$
n \mapsto 2 \cdot (2 n + 3)
$$
is an injective map from $\N$ to your set $X$. (I have taken $2 n + 3$ so that it works whether one includes zero in $\N$ ot not.)
Then $x \mapsto x$ is an injective map $X \mapsto \N$.
This guarantees that there is a bijection $\N \to X$.
Comment: Aha! Very smart answer. Thanks so much. I get it.
Answer: From your example, you can get $6^1$, $6^2$, etc. Thus you can set up a one-to-one correspondence $\Bbb N\to\{6^{n+1}:n\in\Bbb N\}:n\mapsto 6^{n+1}$.
Comment: Please have a look at the edited question. I have provided the definition for a set to be infinite.
Comment: @Y.X. : I have added some explanation. Is it clear now?
Answer: If i understand your question correctly, your set is defined as :
$S = n \in \mathbb N | n \ne p^q$ for any prime $p$ and positive integers $q$
It is sufficient to prove that a subset of $S$ is infinite.
Consider the subset $P = n!, n \in \mathbb N, n\ge 3$ clearly, it satisfies your condition that they are not the powers of a single prime.
Now suppose we have a set $T = [1,2,....,n]$ such that $P(T) = n$ for some natural n. ($P(T)$ denotes the cardinality of set $ T$). For there to exist a bijection $f: P \to T, P(T) = P(P)$. But clearly, $(n+4)! \in P$. Which means that the cardinality of $P$ is at least $(n+4) -3 =n+1$. Thus there cannot exist any bijection,for any natural $n$. Thus, $P$ is an infinite set. Since, $P \subset S$, $S$ is also infinite.
I just made the proof up right now. If there are anu fatal errors,please point it out. I will remove/edit the answer likewise.


Can I ignore "Intellisense: (E0028) expression must have a constant value"?

Question: I'm creating a bitmask class to handle more than 64 bits. I would like to generate the masks at compile time. Below compiles and runs fine, but spits out error messages in VS 2017 when using the Ctor to set a single bit. Runs with no error messages in Ming-w64. Can I safely ignore VS?
<code>#include <type_traits>
#include <array>

// N is number of uint64's required to hold bits, code below simplified for up to 128 bits
template<int N>
class CoreBitmaskBase
{
public:
    std::array<uint64_t, N> mBitsets_;

    constexpr CoreBitmaskBase() noexcept
        : mBitsets_()
    {}

    // Ctor for setting a single bit
    constexpr CoreBitmaskBase(const uint64_t& Bit) noexcept
        : mBitsets_(InitSetBit(Bit))
    {}

    constexpr std::array<uint64_t, N> InitSetBit(const uint64_t& Bit);
};

template<int N>
constexpr std::array<uint64_t, N> CoreBitmaskBase<N>::InitSetBit(const uint64_t& Bit)
{
    return std::array<uint64_t, N>({ (uint64_t)1 << Bit });
}

// if setting a bit index > 63, adjust mBitsets_'s second element
template<>
constexpr std::array<uint64_t, 2> CoreBitmaskBase<2>::InitSetBit(const uint64_t& Bit)
{
    if (Bit < 64) return std::array<uint64_t, 2>({ (uint64_t)1 << Bit, 0 });
    else return std::array<uint64_t, 2>({ 0, (uint64_t)1 << (Bit % 64) });
}

// B is number of bits we need for a mask
template<int B, typename Enable = void>
class CoreBitmask : public CoreBitmaskBase<1>
{
    using BaseType = CoreBitmaskBase<1>;

public:
    constexpr CoreBitmask() noexcept
    {
    }

    constexpr CoreBitmask(const uint64_t& SetBit) noexcept
        : BaseType(SetBit)
    {
    }
};

// specialization for bitmask larger than 64 bits
template<int B>
class CoreBitmask<B, typename std::enable_if<(B > 64)>::type> : public CoreBitmaskBase<2>
{
    using BaseType = CoreBitmaskBase<2>;

public:
    constexpr CoreBitmask() noexcept
    {
    }

    constexpr CoreBitmask(const uint64_t& SetBit) noexcept
        : BaseType(SetBit)
    {
    }
};
</code>
main.cpp
<code>#include "CoreBitmask.h"

CoreBitmask<128> Mask1(67); // no warning

constexpr CoreBitmask<128> Mask2(67);
// E0028 expression must have a constant value
// access to uninitialized subobject(member "std::array<_Ty, _Size>::_Elems [with _Ty=uint64_t, _Size=2U]")
</code>
Comment: tldr, normally compilers are smart and only super experienced developers are likely to create some false positive.
Comment: Not to mention, VS' modern standard support is crap. Probably something wasn't implemented, thus yielding an error.
Answer: I found a solution. The intellisense warning goes away when adding std::move to the problematic ctor, as below:
<code>// Ctor for setting a single bit
constexpr CoreBitmaskBase(const uint64_t& Bit) noexcept
    : mBitsets_(std::move(InitSetBit(Bit)))
{}
</code>


How to choose prior in Laplace Smoothing Naive Bayes?

Question: Please check the image for reference
How to choose the prior probability of each feature .
Should we use the same prior for every feature or different features use different prior.
for example P(Color = Blue | Stolen = Yes )  = (0 + 1(1/3)) / 5 + 1  , where I used the smoothing parameter (alpha) = 1 and p = 1/3 as color can have 3 values i.e Red Blue and Yellow. So I am a little confused here , should I consider Blue also here or should I just consider Red and Yellow
Also for the other features should I use the same p = 1/3 or for them it should be p=1/2 as they only have two values .
Kindly check the image
Comment: Could you give us more details on what exactly were you asked to do and what exactly is the Laplace smoothing formula you are referring to? The [usual definition of Laplace smoothing](https://stats.stackexchange.com/questions/421307/variance-maybe-of-categorical-data/421316#421316) has only one parameter.
Comment: Given the Attributes that are`< Color = Blue , Type = Sports , Origin= Domestic >`, predict using Naive Bayes that whether the car can be stolen or not.

The formula for Laplace smoothing is almost the same as you provide, however in the numerator, a prior P is multiplied to the alpha.
[Here is the image for further reference](https://imgur.com/a/EKbgJDo)
Answer: The more standard definition of Laplace smoothing is defined as adding a fixed quantity $\alpha$ to each count
$$
\hat p_i = \frac{n_i+\alpha}{\sum_{j=1}^K n_j+\alpha} =  \frac{n_i+\alpha}{(\sum_{j=1}^K n_j) + K\alpha}
$$
where $\alpha$'s can be thought as "pseudocounts", i.e. with $\alpha=1$ you assume that for each of the categories you observed $+1$ sample like this, with higher values leading to more smoothing and lower values to less smoothing.
Splitting $\alpha$ to the two parameters $m$ and $P$ so $mP=\alpha$,  to me seem unnecessarily complicated. Still, if you remember that $mP$ is a "pseudocount" added to each observed count, it may be easier to grasp an intuition on what the reasonable values could be.
Comment: so K here is the no of values in that feature ?
Assume training set contains 10 positive examples, and the feature
"Size" has 3 values, but 1 value (size=medium) is not observed in :
`4: small
0: medium
6: large`

so K here will be 3 ?

`P(small | positive) = (4 + 1) / (10 + 3) = 0.394
P(medium | positive) = (0 + 1) / (10 + 3) = 0.03`
Comment: @Skywalker correct, $K$ is the number of categories, so as in your example, if there are three possible sizes, $K=3$.


Boolean value set to state toggles on it's own despite value is true

Question: I've created a component that contains a form used to validate youtube urls that has a state property that evaluates to true or false depending on whether or not the url (or any value) that's typed into the input field is a valid youtube url or not.
The function validateUrl() is the one responsible to return a boolean value depending on whether or not the URL is valid, the problem is despite this function returning true, the state of my component toggles between true and false every keystroke. Click here to see a visual representation
Here is the code:
const youtubeRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/gi;

class Converter extends Component {
  state = {
    id: null,
    url: "",
    urlValid: false
  };

  /**
   * Sets state whenever user types
   * @params {Object} event
   * @returns {void}
   */

  handleChange = event => {
    const { value } = event.target;
    const valid = this.validateUrl(value);
    this.setState({
      id: Math.floor(Math.random() * 100),
      url: value,
      urlValid: valid
    });
  };

  validateUrl = url => {
    return youtubeRegex.test(url);
  };

  handleSubmit = event => {
    ...logic for submission
  };

  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          <input
            value={this.state.url}
            onChange={this.handleChange}
            autoComplete="off"
            type="text"
            placeholder="Add a link to convert..."
          />

{this.state.urlValid.toString() + " " + this.state.url}

          <button type="submit">Submit</button>
        </form>

    );
  }
}

Don't mind the names of the variables and such, I've changed them a few times while trying to debug this. I have checked stackoverflow for similar situations and the most remotely close one I found was related to toggling a boolean state, my situation I believe is quite different.
Does this have to do with setState() being asynchronous? If so how would I go about fixing this issue?
Answer: Issue is with the test method on the Regex. You need to remove the global flag(/g) from the regex.

If the regex has the global flag set, test() will advance the
  lastIndex of the regex. A subsequent use of test() will start the
  search at the substring of str specified by lastIndex (exec() will
  also advance the lastIndex property). It is worth noting that the
  lastIndex will not reset when testing a different string.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test


Prove that for any natural number $n$ there exists a prime number $p$ greater than $n$

Question: Prove that for any natural number n there exists a natural prime number p , such that $ p>n $. How can I prove that ? Thank you.
Comment: The "proof verification" tag is for when you have provided a proof and want to know if it is correct.
Comment: This question is equivalent to prove that there is infinity of prime numbers!
Comment: If not, then all the prime numbers will be less than a fixed integer. So..
Comment: Here is thought, prove that there exist $ \; k \in \mathbb{N}$ and $ \; k \ge n \; $, where $ \; 2^k + 1 \; $ or $ \; 2^k - 1 \; $ is prime.
Answer: First thing prove that there are infinite number of primes,you can use the Euclid proof imagine that there are $n$ primes and name the $k$-th prime $p_k$ than the number $t=p_1p_2\cdots p_{n-1}p_n+1$ isn't divisible by any prime $p_k$ where $1\leq k\leq n$ so there is another prime which divides $t$.Now it's easy to show that $p_k> k$ for every $k\in\mathbb{N}$ since the first prime is $p_1=2$ and $p_{k+1}>p_k$
Answer: Think about the prime factors of $n!+1$.
Comment: I think this answer is just fine, but maybe it is the case to make it less cryptical since it was marked as low-quality.
Answer: Use Bertrand's postulate for the number $n$ or any number greater than it.
Answer: We know that there are infinitely many natural prime numbers.
Now, for some natural number n, let there do not exist any natural prime p such that $p \gt n$. This implies that all prime numbers are less than or equal to the natural number n. Since, even the total number of natural numbers less than or equal to n is finite, the number of natural prime numbers must be finite which contradicts the above fact.
Hence our assumption is false, therefore its negation must be true i.e., for every natural number n, there exists atleast one natural prime p such that $p \gt n.$
Comment: This isn't better or worse. I just proved that the statement "There are infinitely many prime numbers" implies that "for every natural number n, there exists a natural prime p such that p>n." to show that these two statements are equivalent though i didn't prove the converse because that is very obvious. Since the proof of existence of infinite primes by Euclid is well known, one can use that to prove this implied statement.


Como traduzir um site em PHP?

Question: Estou fazendo um site simples com apenas algumas páginas PHP.
Eu gostaria que esta página fosse traduzível para português e inglês.
Já utilizo a função gettext em python e vi que no PHP a sintaxe é muito semelhante.
Código: gettext('TEXT') ou _('TEXT')
Saída esperada:
inglês: TEXT
português: TEXTO
Para extrair o arquivo .po utilizei o comando xgettext e consegui gerar o arquivo de tradução e converter para binário .mo tranquilamente. Porém a minha maior dificuldade é carregar os arquivos de tradução no PHP e fazer funcionar corretamente.
Como devo proceder no caso de tradução de arquivos PHP depois disto?
Comment: Dê uma olhada neste site, talvez ajude: http://www.devin.com.br/php-gettext/
Comment: Se você tiver o hábito de ler docs em inglês, aqui segue um outro tutorial também. http://www.onlamp.com/pub/a/php/2002/06/13/php.html
Comment: Obrigado, @abfurlan, era isso que eu precisava!
Comment: @digofreitas será que me podia dar umas luzes/tutos para iniciantes para criar os ficheiros .po e como usar o gettext? Ou alguma ferramenta? Estou completamente as escuras.
Comment: @jorge-b é só ir no link que o romulos recomendou, que explica muito bem
Comment: obrigado @digofreitas mas já cheguei lá sozinho ;)
Comment: Talvez seja interessante pensar num caminho alternativo. Traduzir o site, imagino, seja ter um site em mais de um idioma, certo? Então eu fortemente recomendo usar um CMS, que já traz isso pronto pra você. Sei que seu site é pequeno, mas mesmo assim, um bom CMS pode reduzir MUITO seu trabalho. Os melhores candidatos são WordPress e Joomla. Obs: eu tenho um site em Joomla, com partes feitas em código PHP.
Answer: A extensão GetText pode não estar disponível no serviço de hospedagem. Além disso ela não te ajudará muito com tradução de URLs ou registros do BD. Por isso, minha sugestão é você trabalhar com um sistema de tradução mais completo, que pode ser implantado em qualquer site PHP sem dependência da extensão GetText. Essa solução envolve 3 partes:
Tradução de textos estáticos
Envolve a tradução dos textos fixos do seu site, que estão codificados diretamente no HTML (ou seja, aqueles textos que não são recuperados de um banco de dados). Para esse texto crie arquivos de tradução e uma função que mapeia isso pra você. Grave o idioma do usuário em alguma lugar (sessão ou cookie) de modo que você possa saber a preferência dele e qual mapeamento usar:
en_us.php
<?php
return array(
    'A Empresa'=>'The Company',
    'Contato'=> 'Contact',
    ...
);

translator.php
<?php
function _($text)
{
     session_start();

     // Exemplo recuperando o idioma da sessao.
     $lang = isset($_SESSION['lang'])?$_SESSION['lang']:'';

     if (!empty($lang))
     {
          // Carrega o array de mapeamento de textos.
          $mapping = require_once $lang.'.php';
          return isset($mapping[$text])?$mapping[$text]:$text;
     }

     return $text;
}

exemplo-de-uso.php
<?php
require_once 'translator.php';
session_start();

// Apenas para teste. O idioma deve ser
// escolhido pelo usuário.
$_SESSION['lang'] = 'en_us';

echo _('Contato');

Tradução de textos dinâmicos (do banco de dados)
Crie uma coluna adicional em cada tabela, que especifica o idioma do registro.
Por exemplo, uma tabela de notícias poderia ser:
id    titulo              texto                    data          **idioma_id**
----------------------------------------------------------------------------
1     Noticia de teste    Apenas uma noticia      2014-05-16     1
2     Test new            Just a new              2014-05-16     2

Na hora de consultar os registros, traga apenas aqueles do idioma desejado:
SELECT * FROM noticia WHERE idioma_id = 2;

Tradução de URLs
Envolve a tradução das URLs do site. Para isso funcionar é necessário utilizar um script único de entrada para seu site. Através de um arquivo .htaccess você pode fazer isso, redirecionando qualquer acesso para um arquivo index.php. Após redirecionar, você pode usar um mapeamento das URLs, assim como feito para os textos estáticos:
.htaccess
RewriteEngine on

# Nao aplica o redirecionamento caso
# o que esteja sendo acessado seja um arquivo ou pasta.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Redireciona para o arquivo index.php
RewriteRule . index.php

en_us_routes.php
<?php
    return array(
        'the-company'=>'a_empresa.php',
        'contact'=> 'contato.php',
        ...
    );

index.php
// Remove da URL a pasta da aplicacao,
// deixando apenas os parametros.
$aux = str_replace('index.php', '', $_SERVER['SCRIPT_NAME']);
$parameters = str_replace($aux, '', $_SERVER['REQUEST_URI']);

// Recupera as partes da URL.
// Se você acessar http://meusite.com.br/empresa
// $urlParts será:
//      array('empresa')
//
// Se você acessar http://meusite.com.br/contato
// $urlParts será:
//      array('contato')
$urlParts = explode('/', $parameters);

// Para simplificar, aqui trata uma URL com
// apenas uma parte. Mas você pode generalizar para urls
// com suburls também (Ex: "empresa/onde-estamos").
$url = $urlParts[0];

// Apenas para teste. O idioma pode estar
// associado ao perfil do usuário e ser setado
// na sessão no login.
$_SESSION['lang'] = 'en_us';

// Carrega o array de mapeamento de URLs.
$mappingFileName = $_SESSION['lang'].'_routes.php';
$mapping = require_once $mappingFileName ;

if (isset($mapping[$url]))
{
    require_once $mapping[$url];
}
else
{
    require_once 'erro_404.php';
}

Os códigos citado são apenas exemplos para passar a ideia (não foram testados).
Comment: Boa resposta. +1. Mas, fica a dica: "*news*" é [incontável](https://jakubmarian.com/news-is-vs-news-are-jeans-is-vs-jeans-are-etc-in-english/) em inglês. :)
Comment: Você cobriu bastante terreno com a sua resposta, inclusive um que poucos sites se dão ao trabalho de fazer que é a tradução dos URIs. Mas faltou justamente a parte que o autor citou que é o uso de GetText. Teria como você completar? Se não eu monto um texto bacana aqui.
Comment: O princípio de funcionamento do gettext é o mesmo do citado em "Tradução de textos estáticos". Entretanto, se desejar usar o gettext tem um bom tutorial em http://www.devin.com.br/php-gettext/. Eu particularmente sugiro utilizar um framework que já incorpore classes/métodos de tradução, tal como o Yii Framework (http://www.yiiframework.com/).
Comment: Eu não, obrigado. :) Também sugiro um framework, pelo menos um de domínio específico, só para a tradução pelo menos, principalmente pelo fato de a GetTeext não ser uma extensão muito consoiderada pelas empresas de hospedagem.
Comment: Exato. O problema do GetText é esse! :)
Comment: Obrigado pelo capricho na resposta, @arivan-bastos mas realmente esta abordagem não era o que eu queria.
Consegui realizar tudo que precisava com este tutorial:
http://www.devin.com.br/php-gettext/
Answer: O que eu faria era:
1) criava uma pasta com o nome "lang"
2) colocava 2 ficheiro eng.php e (pt.php ou eng.php)
exemplo:
    eng.php
    <?php
      $titulo = "My title";
    ?>

pt.php
    <?php
      $titulo = "O meu titulo";
    ?>

3)faria um botão que adicionava index.php?lang=en, para o caso do ingles
4)Ao longo de todo o site eu atribuia variaveis e nesse ficheiros eu utilizava-as para colocar a respectiva tradução utilizava.
    if($_GET['lang'] == "en"){
        include 'eng.php';
     }

      <title> <?php echo $titulo; ?></title>

Desta forma iria evitar o uso de uma base de dados para cada palavra.
Espero ter ajudado.

Como traduzir um site em PHP?


A question on limits of functions of a sequence and removable singularities

Question: Let $f$ be analytic in $D_r(z_0)$\ {$z_0$}. Suppose for each sequence {$z_n$} in $D_r(z_0)$\ {$z_0$} such that $z_n\rightarrow z_0$ there is a subsequence {$z_{r_n}$} such that $f(z_{r_n})\rightarrow 0$. This is what confuses me. Clearly the sebsequence too converges to $z_0$. So doesn't it imply that $f(z_n)\rightarrow 0$ as well? Which then would imply that $f(z)\rightarrow 0$ as $z\rightarrow z_0$ making $z_0$ a removable singularity. Is my thinking correct? Thanks
Comment: you need to prove it.
Comment: @Krish Prove what?
Comment: "Clearly the sebsequence too converges to $z_0$. So doesn't it imply that $f(z_n)\rightarrow 0$ as well?" this is the part you need to prove.
Comment: Ya but for that I need to know whether it is correct or not
Comment: @Krish I asked because I could not prove it
Answer: Claim: $f$ is bounded in a near  $z_0.$
If not, then given any $n \in \mathbb{N},$ there exists $z_n \in D(z_0, r)$ with $|z_n - z_0| < \frac{1}{n}$ such that $|f(z_n)| > n.$ This contradicts the given condition.
Since $f$ is bounded near $z_0,$ it has a removable singularity at $z_0.$ (to see this use use the Laurent series expression of $f$.)
$\bf{EDIT:}$ Let $f(z) = \sum_{n \in \mathbb{Z}}a_n(z-z_0)^n$ be a Laurent series expression of $f$ centered at $z_0.$ Suppose $|f(z)| \leq M$ near $z_0$ and $r > 0$ be small. Then $|a_n| \leq \frac{M}{r^n}.$ If $n < 0,$ then $\frac{M}{r^n} \rightarrow 0$ as $r \rightarrow 0.$ This shows that $a_n = 0$ for $n < 0.$ So $f$ has a removable singularity at $z_0.$
Comment: $a_n = \dfrac{1}{2\pi i} \int_{|z-z_0| = r} \dfrac{f(z)}{(z - z_o)^{n+1}}dz \Rightarrow |a_n| \leq \dfrac{1}{2\pi} \dfrac{M}{r^{n + 1}}(2 \pi r).$ See http://en.wikipedia.org/wiki/Estimation_lemma
Comment: How would one use the Laurent series expansion?
Comment: @JonasMeyer: I have edited the answer to include your question.
Comment: How did you conclude that $|a_n|\leq \dfrac{M}{r^n}$?
Comment: Thanks Krish, I appreciate your time in clarifying this for me, it was very helpful.
Comment: @JonasMeyer: you are welcome. :)
Answer: Your conclusion is correct, but your logic in getting there isn't clear.  For a given sequence $\{z_n\}$ converging to $z_0$, the fact that it has a subsequence $\{z_{r_n}\}$ such that $\{f(z_{r_n})\}$ converges to $0$ does not imply that $\{f(z_n)\}$ converges to $0$. For example, consider $f(z) =\sin(1/z)$, $z_0=0$, and $z_n=\dfrac{2}{n\pi}$. In that case $\{f(z_n)\}$ does not converge, but $\{f(z_{2n})\}$ converges to $0$.
However, the fact that such a subsequence exists for every sequence converging to $z_0$ does imply that $\lim\limits_{z\to z_0}f(z) = 0$.  (The previous example does not satisfy the hypothesis.)  To see this by contraposition, suppose that it is not the case that $f(z)\to 0$ as $z\to z_0$.  Then there exists $\varepsilon>0$ such that for all $\delta>0$ there exists $z$ with $|z-z_0|<\delta$ and $|f(z)|\geq\varepsilon$.  Thus, for some fixed $\varepsilon>0$, there exists for each $n$ a $z_n\in\mathbb C$ such that $|z_n-z_0|<\frac1n$ and $|f(z)|\geq \varepsilon$.  This implies that $\{z_n\}$ converges to $z_0$, but there exists no subsequence $\{z_{r_n}\}$ such that $\{f(z_{r_n})\}$ converges to $0$.


How do you use the ansatz of rotationally invariant solutions to derive a ODE from a PDE?

Question:
For a) I want to find a ODE by substituting $u(\mathbf x)=f(r)$
I did some calculations. Maybe you could take a look at them.
$$\begin{aligned} &\frac{\partial f(\lvert x\rvert)}{\partial x_1}=f'(\lvert x\rvert)\frac{x_1}{\sqrt{\lvert x\rvert}} \\ & \frac{\partial^2 f(\lvert x\rvert)}{\partial x_1^2}=f''(\lvert x\rvert)\frac{x_1^2}{\sqrt{\lvert x\rvert}}-f'(\lvert x\rvert)\frac{x_1^2}{\lvert x\rvert^{\frac{3}{2}}} \\ & \space \space . \\ & \space \space . \\ & \frac{\partial^n f(\lvert x\rvert)}{\partial x_i^n}=\frac{f^{(n)}(\lvert x\rvert)}{\lvert x\rvert} \sum_{i=1}^n x_i^2-...\end{aligned}$$
$$\implies \Delta u(\mathbf x)+k^2 u(\mathbf x)=0 \longrightarrow \frac{\partial^n f(\lvert x\rvert)}{\partial x_i^n}=\frac{f^{(n)}(\lvert x\rvert)}{\lvert x\rvert} \sum_{i=1}^n x_i^2-...+k^2f(\lvert x \rvert)=0$$
Is this correct? How do I summarize the last term in my second equality?
Answer: You are mixing the order of the derivatives with the variable of derivation. You have to compute the second derivative with respect to all the variables and add them up. Let $r=|x|$. Then
$$\begin{align}
\frac{\partial f(r)}{\partial x_i}&=\frac{x_i}{r}\,f'(r),\\
\frac{\partial^2 f(r)}{\partial x_i^2}&=\frac{r-x_i\,\tfrac{x_i}{r}}{r^3}\,f´(r)+\frac{x_i^2}{r^2}\,f''(r)=\frac{r^2-x_i^2}{r^3}\,f´(r)+\frac{x_i^2}{r^2}\,f''(r).
\end{align}$$
Summing from $i=1$ to $n$, and keeping in mind that $\sum_{i=1}^nx_i^2=r^2$, we get
$$
\Delta f(r)=f''(r)+\frac{n-1}{r}\,f´(r).
$$
Comment: Well that makes a ton more sense. It also gives me the correct equation for b). Thank you very much!
Comment: Just a quick question. Shouldn't it be $\frac{n-1}{r}$?
Comment: Thank you for noticing. Corrected.


using LEFT OUTER JOIN to retrieve data

Question: I want to be able to match a field in Table1 and echo data from Table1 along with the matching fields in Table2. I tried the below but did not work.
Example:

I want to echo data in this order: items(Table1), category(Table1), preice(Table2), buyer(Table1)
$serchRslt = "fr732001";
$result = mysql_query("SELECT Table1.items, Table1.category, Table1.buyer, Table2.price, Table2.stocks Table2
                       LEFT OUTER JOIN Table1 ON Table2.item = Table1.items FROM Table1 WHERE Table1.items  = '".$serchRslt."'");

while($line = mysql_fetch_array($result)) {
echo $line["items"];
echo $line["category"];
echo $line["price"];
echo $line["buyer"];
}

Expected result: fr732001 fruits 3.20 AS1
Answer: Your Sql Syntax looks a bit wonky. Try:
SELECT
  Table1.items,
  Table1.category,
  Table1.buyer,
  Table2.price,
  Table2.stocks
FROM Table1
LEFT OUTER JOIN Table2 ON Table2.item = Table1.items
WHERE Table1.items  = $...

Answer: Query should be
SELECT Table1.items,
Table1.category,
Table1.buyer,
Table2.price,
Table2.stocks
from Table1
LEFT OUTER JOIN Table2
ON Table2.item = Table1.items
WHERE Table1.items  = 'fr732001';

using LEFT OUTER JOIN to retrieve data


Holomorphic function with real values on boundary

Question: I am wondering if the next statement is true:
If $f:\Omega \rightarrow\mathbb{C}$ be an holomorphic function where $\Omega$ is a bounded connected subset of $\mathbb{C}$ such that for every $z\in \partial\Omega$ we have that $f(z)\in \mathbb{R}$ then f is constant and $f$ analytic and continuous on closure of $\Omega$.
I know that this is true if $\Omega$ is a symetric set because of schwarz reflection principle and Liouville theorem.
And the statement hold if $\Omega$ a disk of radius $R$ centered at a point $z_0$ because then composing $f$ with then function $g(z)=z-z_0$.
We would have have that $ f\circ g : D(0,R) \rightarrow\mathbb{C}$ so by the preceding argument we have $f\circ g$ is constant so is $f$.
The condition that $\Omega$ is bounded is important since there exist function being real on boundary of $\Omega$ but not constant. For exemple $Id:H \rightarrow \mathbb{C}$  where $H=\{z \mid \Im z \gt 0\}$
But I don't know if this is true in general cases and I didn't find counterexample so if someone can give me an answer it would be super great
Thanks in advance !
Comment: It's unclear what you're saying is true because the second sentence doesn't include a proposition.
Comment: I think you mean that the assumption should imply that $f$ is constant?
Comment: Oh yes sorry I edit my post (I mean if f takes real value on bondary then f constant)
Answer: The answer will depend on how regular do you want the function $f$ to be near $\delta\Omega$ and on topological properties of $\Omega$ that you are probably assuming, but not writing. For example:
The function $$g(z)=\begin{cases}\frac{\frac{z}{2}+\frac{1}{2}}{\frac{zi}{2}-\frac{i}{2}},&z\neq 1\\0,&z=1\end{cases}$$ satisfies that for $|z|=1$
$$\overline{g(z)}=\frac{\frac{\overline{z}}{2}+\frac{1}{2}}{-\frac{\overline{z}i}{2}+\frac{i}{2}}=\frac{\frac{1}{2z}+\frac{1}{2}}{-\frac{i}{2z}+\frac{i}{2}}=\frac{\frac{z}{2}+\frac{1}{2}}{\frac{zi}{2}-\frac{i}{2}}=g(z)$$
Therefore, it takes real values on the unit circle. This function takes the unit disc to the upper half-plane. Therefore, it is essentially your own example of the identity on the upper half-plane, after the conformal transformation $g(z)$.

Should $f$ be continuous on $\overline{\Omega}$? In that case we have that $f=\overline{f}$ on $\delta\Omega$. Therefore $f-\overline{f}$ is harmonic, zero on the boundary, and continuous on $\Omega$. Therefore, by the maximum principle, it is zero in the interior of the domain. Hence $f=\overline{f}$, which implies that $f$ is locally constant.

There is also the connectivity of the set $\Omega$. If $\Omega$ is not connected, $f$ could be real and constant on each connected component, but not constant over all.
Comment: Yes of course I was assuming that $\Omega$ was a connected set
Comment: @SamiMir Well, who knows what are the assumptions if they are not written. What about how regular is $f$ near the boundary? By the way, it is better to start with the actual domain of the function and then say all properties it satisfies on certain subsets of it. If you say $f:\Omega\to\mathbb{C}$, then maybe $f$ is not a function defined on $\delta\Omega$, and if it is, you need some relation between the values on $\Omega$ and the values on $\delta\Omega$.
Comment: I edited the post but yes sorry to missed some hypothesis or not being explicit
Answer: You want to assume $f$ is analytic in a neighbourhood of $\Omega$.  The $\text{Im}(f(z))$ is harmonic, and $0$ on $\partial \Omega$.  If it were not identically $0$, it would have a maximum or minimum in $\Omega$, and that is impossible.


Solve the differential equation $\frac{dy}{dx} - xy=1$

Question:
Solve the differential equation $\frac{dy}{dx} - xy=1$ given $y(0)=1$

The given differential equation is a first order linear differential equation of the form $\frac{dy}{dx} + Py=Q$
The integrating factor is $$e^{\int Pdx}=e^{-\int xdx}=e^{-\frac{x^2}{2}}$$
Solution is $$ye^{-\frac{x^2}{2}}=\int e^{-\frac{x^2}{2}}dx + c$$
But how do I integrate the second term?
Comment: Just call it the error function - https://en.wikipedia.org/wiki/Error_function
Comment: it is $\int { { e }^{ -{ \frac { { x }^{ 2 } }{ 2 }  } } } dx=\sqrt { \frac { \pi  }{ 2 }  } erf\left( \frac { x }{ \sqrt { 2 }  }  \right) +C$
Comment: the solution is given by $$\left\{\left\{y(x)\to c_1 e^{\frac{x^2}{2}}+\sqrt{\frac{\pi }{2}} e^{\frac{x^2}{2}}
   \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right\}\right\}$$
Answer: So far, you've solved the differential equation correctly.

The integral you are considering does not have an elementary antiderivative. Regardless, we can still obtain an exact solution in terms of the error function. The considered integral is:
$$\int e^{-\frac{x^2}{2}}~dx$$
Now, substitute $$u=\frac{x}{\sqrt{2}} \implies du=\frac{1}{\sqrt{2}}~dx\implies dx=\sqrt{2}~du$$ This gives an integral which is contained in the definition of the error function:
$$\int e^{-\frac{x^2}{2}}~dx=\sqrt{2}\cdot \int e^{-u^2}~du$$
The definition of the error function is:

$$\operatorname*{erf}(x)=\frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2}~dt$$

It follows from the definition that:
$$\int e^{-u^2}~du=\frac{\sqrt{\pi}}{2}\cdot \operatorname*{erf}(u)+C$$
Can you continue? From solving the integral, you can find the general solution to your ODE, and then find the solution where $y(0)=1$.


Alias an URL in Apache in order to route requests on a certain URL through a PHP-script

Question: I am using Apache 2.2.6 with suPHP 0.6.2 and PHP 5.2.6 and I am trying to use an Alias in order to route all requests on a certain URL trough a PHP script. I want all requests to /test to go through index.php. In the Apache virtualhost config I have set up an Alias Alias /test /index.php. index.php is just a dummy script containing the following:
<?php
phpinfo();
?>

Requesting http://localhost/index.php works and gives the expected output, however requesting http://localhost/test does not and gives me a 403 error, the error.log contains the following:
[Wed Jan 27 17:13:19 2010] [error] [client 127.0.0.1] client denied by server configuration: /index.php

What is wrong with my Alias?
Edit:
I almost forgot to mention that rewriting /test to /index.php through mod_rewrite works as well, however I want to avoid mod_rewrite on my production server if possible.
Answer: Alias requires an absolute path, so Alias /test /var/www/index.php made it work.