What does it mean "they differ in parameter space" regarding the compound symmetry and random intercept model?

Question: I read discussions on how the random intercept model is not equivalent to the compound symmetry. I understand, that the CS model allows for a case, where the responses are more similar across subjects than "within subjects", but there is one thing I don't understand - "parameter space". In addition to the simplified answer, it was said, that "both methods differ in parameter spaces". What does it mean? What kind of parameters is mentioned?
For example: Is it possible to fit mixed-models via gls?

Also beware of the difference in parameter spaces: the parameter space
  for the compound symmetry model is bigger than it is for the random
  intercept model. The random-effect variance is necessarily
  non-negative which leads to a non-negative corr but the corr in the
  compound symmetry model can also be negative (though not too much). So
  while two model fits can be equivalent (if ρ≥0) they need not be (if
  ρ<0) and strictly speaking the underlying models are not the same. –
  Rune H Christensen May 23 '18 at 6:35
Comment: Please reference or cite the context of "parameter space". At present you leave us guessing. Also have a look at this question/answer: https://stats.stackexchange.com/a/15107/182480
Comment: @Carsten Thank you. I updated my answer.
Answer: Let's assume that we have two measurements per subject $i$. The random intercepts model postulates that for any $j$ and $j'$, the correlation between the outcome measurements $Y_{ij}$ and $Y_{ij'}$ is
$$\mbox{cor}(Y_{ij}, Y_{ij'}) = \frac{\sigma_b^2}{\sigma_b^2 + \sigma^2},$$
where $\sigma_b^2$ is the variance of the random intercepts and $\sigma^2$ is the variance of the error terms. The important note is that this correlation cannot be negative. This is because both the numerator and denominator are non-negative because they involve variance terms that are restricted to be non-negative.
However, the general compound symmetry matrix postulates that the same correlation is
$$\mbox{cor}(Y_{ij}, Y_{ij'}) = \rho,$$
where $\rho$ can freely vary in the interval $(-1, 1)$.
Hence, if this correlation in your data is, say $-0.2$, then you can never get that with a random-intercepts model. The random-intercepts model would tell you that the correlation is zero (because this is the closest permissible value to the true value of $-0.2$).
Comment: Thank you very much for the answer. Tell me, please, what is the relationship to the "parameter space", as in my question? Is this that RI model calculates 2 parameters (RI variance and error variance), while the CS only one - the ρ? But it says the opposite - that the parameter space for CS is bigger... So, is this about the range of values it can take? Then yes, in CS ρ can be also negative, while in RI - only positive...? I feel the difference between the two models, but I don't understand the "parameter space" term. Space of what parameters? And why in CS it's bigger?
Comment: @dasivalana The parameter space is the permissible range of values for the correlation. In the random intercepts model, the parameter space for $\rho$ is the interval $(0, 1)$. In the general compound symmetry model the parameter space for $\rho$ is the interval $(-1, 1)$.
Comment: And now it makes sense perfectly. Thank you!
Comment: It is not true that $\rho$ freely varies in $(-1,1)$. The $n\times n$ matrix with $1$ at each diagonal entry and $\rho$ at all other entries is positive definite if and only if $1 > \rho > - \frac{1}{n-1}$. I'm not sure how this extends to a block-diagonal matrix; maybe the lower bound on $\rho$ is $-\frac{1}{N-1}$ with $N = \max J(i)$,  ,denoting by $J(i)$ the number of $y_{ij}$? cc @dasivalana
Comment: @StéphaneLaurent you are right. I had in my mind the situations with two repeated measurements in which case the $\rho$ varies in $(-1, 1)$. I have updated the answer to mention that.


Predicted probability at the mean decreases when more variables are added to a Logistic regression model

Question: I have been thinking about this question for the past couple days and have not been able to come to a conclusion.
I am running a logistic regression and want to calculate the % change in predicted probability from adding a variable of interest. I am using STATA for this is and here is my code.
First, I run a regression with the full specification and calculate the predicted probability for the average individual:
use http://www.stata-press.com/data/r13/margex
quietly logit outcome i.sex age distance i.group
margins, atmeans

I get the following:
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .0586319    .018623     3.15   0.002     .0221315    .0951323

If I calculate the predicted probability excluding without distance for the average individual,
quietly logit outcome i.sex age i.group
margins, atmeans

        |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .0962654   .0072607    13.26   0.000     .0820347     .110496

I find this quite strange in that the predicted probability at the mean decreases when you add another variable. Even though this is an example, I found the same to be true in my research. I am baffled at why this is so and do not think this is overfitting because I am using the same dataset in all cases.
Any insights would be appreciated.
Answer: First, you are making a prediction for a Frankenstein of hypothetical case when calculating for the average person. For example, your average person in this dataset in half female and half male! This does not make much sense.
If you set the categorical variables to their base values, this would work somewhat better (especially coupled with carefully chosen base levels):
margins, at((mean) _continuous (base) _factor)

Personally, I would just calculate the average of the predictions (rather than a prediction for the average person) with:
margins

This will give you the same prediction from both models: .1696667.
The difference you see with your code is both because you have a different average person and a different model when you take distance into account. You can get much closer predictions if you evaluate at own value of distance, keeping other variables at their means. This is much more of an apples-to-apples comparison (though a slight difference remains since by including distance you are changing the variance and the coefficients are scaled by the standard deviation of the error):
. use http://www.stata-press.com/data/r13/margex, clear
(Artificial data for margins)

. qui logit outcome i.sex age i.group distance

. margins, at((mean) sex age group (asobserved) distance)

Predictive margins                              Number of obs     =      3,000
Model VCE    : OIM

Expression   : Pr(outcome), predict()
at           : 0.sex           =    .4993333 (mean)
               1.sex           =    .5006667 (mean)
               age             =      39.799 (mean)
               1.group         =    .3996667 (mean)
               2.group         =    .3726667 (mean)
               3.group         =    .2276667 (mean)

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .0961625   .0072624    13.24   0.000     .0819284    .1103966
------------------------------------------------------------------------------

. qui logit outcome i.sex age i.group

. margins, atmeans

Adjusted predictions                            Number of obs     =      3,000
Model VCE    : OIM

Expression   : Pr(outcome), predict()
at           : 0.sex           =    .4993333 (mean)
               1.sex           =    .5006667 (mean)
               age             =      39.799 (mean)
               1.group         =    .3996667 (mean)
               2.group         =    .3726667 (mean)
               3.group         =    .2276667 (mean)

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   .0962654   .0072607    13.26   0.000     .0820347     .110496
------------------------------------------------------------------------------


What kind of index to create for solr search?

Question: I have got a solr instance up and running locally on my drupal 7 server.
I have added the server to the search config on my drupal site and now I'm trying to create the 'index' part of the search configuration.
As per this guide http://valuebound.com/resources/blog/installing-configuring-apache-solr-520-with-drupal-7-using-search-api-ubuntu-1404 I have gotten to the very end where I must set up the index for the files.
The guide says to select 'Node' from the drop-down list under 'Item type' but I don't see that option.  Is there another option I can select?
I am planning on indexing a bunch of 'rich' file types such as PDFs, DOCS, XLS as well as JSON and XML.
I am looking for help in setting up the search index for my solr server.
Answer: The item dropdown says "Content" instead of "node". But "content" == "node" in this case.


Alterar posição do botão de próximo do Carousel Bootstrap

Question: Ao diminuir o tamanho do slide apareceu o seguinte problema: O posicionamento do botão de "next" está afastado do slide, como na imagem abaixo. Quero que ela fique no extremo lado da imagem, da mesma forma que o botão do lado esquerdo está. Porém todas as tentativas que fiz não resolveu.

HTML:

Teste 1

Teste 2

        Previous

        Next

CSS:
#div-fig-cafe {
    width: 70%; /*Caso eu retire essa config, o botão se ajusta perfeitamente, porém o tamanho do slide aumenta muito*/
}

Comment: o slide é responsivo então ficara com a largura total do espaço disponivel, tente colocar o slide dentro de um container ou dentro de uma coluna com tamanho que você definir...
Comment: Obrigado Rafael! Deu certo. bem simples! hehe
Comment: Coloquei a resposta por favor, marque como resolvido! :)
Answer: O slide é responsivo, logo, ele ocupara o espaço que tiver disponível.
Coloque o slide dentro de um container ou dentro de uma col-, desta maneira ele irá seguir o tamanho que você indicar o elemento "pai".


Como fazer a posição de uma div que se movimenta ser salva aoutomaticamente?

Question: Desenvolvi um widget para meu projeto e agora preciso que, ao move-lo, sua posição fique salva.
Exemplo: Posição inicial do widget 80px x 120px, após movimento lo, posição inicial do widget 210px x 300px.
Espero que minha dúvida fique clara.
Comment: Entender eu acho que dá, mas em qual parte do procedimento você está com dificuldade?
Comment: Tipo a parte onde ele pega a posição que eu deixei e salva no css
Comment: @Daniel alterar o arquivo CSS vai dar muito trabalho, acredito que `localStorage` seja uma boa opção.
Answer: Se entendi sua pergunta, você tem uma div que se desloca sobre a página e você quer que sempre a ultima posição ocupada por ela fique salva ao carregar a pagina novamente, correto ? Bom, se for isto mesmo, desenvolvi um script e usando o localStorage salvo a ultima posição, left e top, da div.Não será possível implementar o código no snippet do StackOverflow por que ele não permite a utilização do localStorage por motivos de segurança. Você pode ver a implementação funcionando perfeitamente no jsfiddle.
Script:
window.addEventListener('DOMContentLoaded', function() {
  var box = document.getElementById('box');
  var draggable = false;
  var bLeft = localStorage.getItem('bLeft') || '';
  var bTop = localStorage.getItem('bTop') || '';

  box.style.left = bLeft;
  box.style.top = bTop;

  box.addEventListener('mousedown', function() {
    draggable = true;
  });

  window.addEventListener('mouseup', function() {
    draggable = false;
  });

  window.addEventListener('mousemove', function(e) {
    if(draggable) {
      box.style.left = (e.clientX - 50) + 'px';
      box.style.top = (e.clientY - 50) + 'px';

      localStorage.setItem('bLeft', box.style.left);
      localStorage.setItem('bTop', box.style.top);

    }
  });
});

Veja funcionando no jsfiddle

Referência: MDN - localStorage
Comment: Mano tudo certo so um probleminha, ele fica selecionado não importa oque eu faço.
Comment: Boa. Daniel: isso vai salvar a posição no computador e no browser que você estiver usando. Se quiser que persista entre computadores ou browsers diferentes, você vai precisar salvar a posicao num banco de dados, ou num arquivo no servidor.
Comment: @Daniel talvez por que o `mouseup` estivesse no `box`, alterei para o objeto `window`, teste parar ver se para.
Comment: @devgaspa alterei certinho, só que o problema é que ele acaba abrindo uma margem de uns '50 px' do cursor do mouse
Comment: @Daniel se você olhar no código, essa parte `(e.clientX - 50)`, tanto left como o top são subtraídos a metade da largura e altura do box para que o mouse fique centralizado no mesmo. Enfim, você tem que alterar o valor `50` para a metade do seu box


Homotopy equivalence of two spaces, homework

Question: I need to prove that spaces $\mathbb R^2 \setminus \{e_1,-e_1\}$ and $S(e_1,1)\cup S(-e_1,1)$ are homotopy equivalent. $e_1$ is basis vector $(1,0)$ and $S(e_1,1)$ is a sphere centered on $e_1$ with radius 1 (one-dimensional sphere).
Two spaces, $A$, $B$ are homotopy equivalent if there exists continuous $f: A \rightarrow B$ to which there exists continous $g: B \rightarrow A$ such that $g \circ f \sim id_A$ and $f \circ g \sim id_B$. ($\sim$ means the two maps are homotopic.)
I know, cause it says so in the book that sphere of dimension $n-1$ is homotopy equivalent to $\mathbb R^n \setminus \{\bar 0\}$. Function $f$ is inclusion and $g$ is $x/|x|$. But here I don't take away one but two points and neither is the origin.
Edit:
I was wondering if function $f=\frac{x+(1,0)}{|x+(1,0)|}-(1,0), x<0, \frac{x-(1,0)}{|x-(1,0)|}+(1,0), x \ge 0$ would be continuous and if it can be used as the function from $\mathbb R^2 \setminus \{e_1,-e_1\}$ to $S(e_1,1)\cup S(-e_1,1)$. It projects the negative half-plane to $S(-e_1,1)$ and positive to $S(e_1,1)$.
I am convinced that I need to define the function by parts. But I think that one isn't continuous on the $y$-axis (no point there has a neighborhood that maps continously) and I cannot figure how to make it continuous there.
Answer: First, note that topological spaces are homotopic, not sets; I assume you have the standard topologies on each set. Second, I assume your notation $S(e_1,1)$ is talking about circles in the plane (one-dimensional spheres).
You're right that the standard radial projections on each half-plane do not match continuously when pasted together. It seems clear that a map that sends the entire $y$-axis to the origin would be most convenient. What about a map that is the radial projections inside both circles, and also outside both circles except in the vertical strip of width 2 centered on the $y$-axis, on which the map is a vertical projection instead?
Comment: Yes, thanks. I used one that projects the insides of spheres to the edge, the strip around y-axis on the spheres and all else constantly to $e_1$ and $-e_1$.
Comment: Well, $\pm e_1$ are not points on your target space....
Comment: Dammit, I meant $2e_1$ and $-2e_1$.


jQuery ajax post data to form mail

Question: I'm trying to make jQuery post some data to an PHP form mail via Ajax, so i can sent the data in an email.
But my problem is that it doesn't post anything in the mail. It's empty.
Here is my javascript:
$(document).ready(function() {
  $('#food_requirements').hide();
  $('#name_allergy').hide();
  $('#food').click(function(e) {
    $('#food_requirements').fadeIn('slow');
  });
  $('#allergy').click(function(e) {
    $('#name_allergy').fadeIn('slow');
  });

  $('.confirm input').click(function(e) {
    $(".confirm").removeClass('red-border');
  });
  $('.checkin').click(function() {
    $(this).attr("src", 'images/loader.gif');
    var checkBoxs = document.getElementsByName("confirmation");
    var confirmation = '';
    for (var i = 0; i < checkBoxs.length; i++) {
      if (checkBoxs[i].checked) {
        confirmation += checkBoxs[i].value + " - ";
      }
    }
    if (confirmation == '') {
      $('.confirm').addClass('red-border');
      $(this).attr("src", 'images/checkin.jpg');
      return false;
    }
    if (document.getElementById("food").checked) {
      var food = "yes";
    } else {
      var food = "no";
    }
    var food_requirements = $('#food_requirements').val();
    if (food == 'yes') {
      if (food_requirements == '') {
        $('#food_requirements').addClass('red-border');
        $('#food_requirements').focus();
        $(this).attr("src", 'images/checkin.jpg');
        return false;
      } else {
        $("#food_requirements").removeClass('red-border');
      }
    }
    if (document.getElementsByName("allergy").checked) {
      var allergy = "yes";
    } else {
      var allergy = "no";
    }
    var name_allergy = $('#name_allergy').val();
    if (allergy == 'yes') {
      if (name_allergy == '') {
        $('#name_allergy').addClass('red-border');
        $('#name_allergy').focus();
        $(this).attr("src", 'images/checkin.jpg');
        return false;
      } else {
        $("#name_allergy").removeClass('red-border');
      }
    }
    var firstname1 = $('#firstname1').val();
    if (firstname1 == '') {
      $('#firstname1').addClass('red-border');
      $('#firstname1').focus();
      $(this).attr("src", 'images/checkin.jpg');
      return false;
    } else {
      $("#firstname1").removeClass('red-border');
    }
    var lastname1 = $('#lastname1').val();
    if (lastname1 == '') {
      $('#lastname1').addClass('red-border');
      $('#lastname1').focus();
      $(this).attr("src", 'images/checkin.jpg');
      return false;
    } else {
      $("#lastname1").removeClass('red-border');
    }
    var age1 = $('#age1').val();
    if (age1 == '') {
      $('#age1').addClass('red-border');
      $('#age1').focus();
      $(this).attr("src", 'images/checkin.jpg');
      return false;
    } else {
      $("#age1").removeClass('red-border');
    }
    var fname = "";
    var firstname = document.getElementsByName("firstname");
    for (var i = 0; i < firstname.length; i++) {
      if (firstname[i].value != '') {
        if (firstname[i].value != '') fname += firstname[i].value + " / ";
      }
    }
    var lname = "";
    var lastname = document.getElementsByName("lastname");
    for (var i = 0; i < lastname.length; i++) {
      if (lastname[i].value != '') lname += lastname[i].value + " / ";
    }
    var ages = "";
    var age = document.getElementsByName("age");
    for (var i = 0; i < age.length; i++) {
      if (age[i].value != '') ages += age[i].value + " / ";
    }

    var data = "&confirmation=Events: " + confirmation + "&firstname=First names: " + fname + "&lastname=Last names: " + lname + "&age=Ages: " + ages;
        if (food_requirements != '') data = data + "&food_requirements=Food requirements: " + food_requirements;
        if (name_allergy != '') data = data + "&allergy=Allergy: " + name_allergy;
        var url = "rsvp.php";
        $('#form').html('Your CHECK-IN is done!.
 Thank you very much.');
        $.post(url, data, function(msg) {
          $('#form').addClass('formfinal');
            alert(data)
          window.scrollTo(0, 0);
          if (msg.substr(0, 2) == "ok") {
            $('#form').html('Your CHECK-IN is done!.
 Thank you very much.');
          } else {
            $('#form').html('There has been an error with the CHECK-IN. Please try again.');
            return false;
          }
        });

  });
});
function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}
function addguest() {
  $("#guests").append("<input class='firstname' name='firstname' placeholder='First Name' /><input class='lastname' name='lastname' placeholder='Last Name' /><input class='age' name='age' placeholder='Age' />

");
}

I get this value when i alert "data"
"&confirmation=Events:Bollywood - &firstname=First names: andreas / john / james / &lastname=Last names: Johnson / Jamesson / Hansen / &age= Ages: 24 / 26 / 42 / &food_requirements=Food requirements: Does it work"
This is my php(rsvp.php) form. I've tried some different stuff just to get some sort of value, but without any luck. I just receive an empty email.
<?php
   $email = 'email@example.com';
   $message = 'firstname' . $firstname . '';
   $to = 'firstname.lastname@example.com';
   mail($to, 'my subject', $message, $email);
?>

Please let me know what to do.
Comment: In your ajax call you do not seem to have any parameters named fname or data, yet in you PHP script you are trying to retrieve data from those. And in your PHP, even though you do not define $fname, you use it to construct $message.
Answer: the Problem is here
you expecting $firstname = $_POST['fname']; but passing firstname
var data = "&confirmation=Events: " + confirmation + "&firstname=First names: " + fname + "&lastname=Last names: " + lname + "&age=Ages: " + ages;

Comment: Thanks Volkinc. I tried what you suggested, but it doesn't work. It still doesn't write any value in the mail?

Here is what my PHP look like now:
Comment: mail("firstname.lastname@example.com", 'my subject', "my message"); //try the hardcoded version? will you get something?
Comment: hi. mail ( string $to , string $subject , string $message ,$additional_headers ) , so, the forth parameter is a headers, so try only with first three

jQuery ajax post data to form mail


Does the following proof use the axiom of choice.

Question: I was looking at a proof for the countability of set of isolated points of any subset of separable metric space posted on another stack exchange thread. I suspect (but I'm not sure) that this proof uses the axiom of choice in determining $r_x$ and the function $f(x)$ discussed in the answer.
Can someone help confirm if this is truly the case. If yes is there a way to proof this without using the axiom of choice?
Comment: I disagree with the vote to close. I think that asking for clarification of an answer on the site, with the difficulty explained is fine. It's not linking off-site.
Comment: It definitely uses the axiom of choice twice: once to fix a a radii for balls centered at any point $x \in C$ (the $r_{x}$'s) and then for the definition of $f$ there's a second use of the axiom of choice
Answer: No, there is no actual use of choice. We can always assume the distance is rational, since once $B_r(x)=\{x\}$, then for every $r'<r$, it is also true that $B_{r'}(x)=\{x\}$, so in particular we can assume that $r$ was a rational number. Since the rationals are countable, we can enumerate them and choose the least one (in the enumeration!) that works.
And since $A$, the dense set, is countable, we can again enumerate it and choose the least one.
So, while the phrasing is one that relies on choice, in actuality, we can easily avoid it.
Comment: @samuelokon Under the normal order, this is true. But since $\mathbb{Q}$ can be put into bijection with the well-ordered set $\mathbb{N}$, we can use this bijection to give $\mathbb{Q}$ a well-order. We use this well-order to make all choices.
Comment: @samuelokon We are only making at most one choice. Making finitely many choices doesn't require the axiom of choice. And the standard proof that $\mathbb{Q}$ can be put into bijection with $\mathbb{N}$ can easily be seen to define a specific bijection between the two of them, so we don't even need to make one arbitrary choice.
Comment: I'm confused about your use of "least". I thought the set of positive rationals isn't well ordered and doesn't have a least element.
Comment: Never mind, I get what you meant. You just defined $r_x$ and $f(x)$ using their enumerations.
Comment: @MarkSaving sorry if I'm dragging this issue longer than usual. I'm trying to understand all the edge cases. In using the bijection to make choices, won't we have to make a choice on the bijection we use. Since there may be multiple bijections.


How long will items be kept in an In-Place Archive with Microsoft's Default MDM Policy?

Question: I did a lot of research to find an answer to this question, but without luck so far.
The situation is as follows:

Exchange Online with EO Plan 1, E3, and E5 licenses
No modifications were done to Microsoft's default MDM Policy
Enabled Personal Archive for each Mailbox in EAC | Recipients | Mailboxes

The "Default MDM Policy" has a Retention Tag named "Default 2 year move to archive". That means each Item > 2 years old will be automatically moved to the In-Place Archive by the Managed Folder Assistant.
I also know that all Retention Tags of type "new tag applied automatically to the entire mailbox (default)" will apply to a user's mailbox and his In-Place Archive.
Means, if I would add another "default"-Tag to the Default MDM Policy and set it to "Permanently delete" after 7 years, all Items > 7 years old (either in the User's mailbox or his In-Place Archive) would be deleted.
But what happens to items in In-Place Archives, when I only have the "Default 2-year move to archive" Tag? I mean, when I do not modify the "Default MDM Policy".
Will Exchange keep In-Place Archive Items forever, or am I missing something?
Also, I know I could have some kind of Hold on some/all items, but I have it not configured.
Answer: According to my research, there are some tags in the default retention policy, a DPT,a RPT, 9 PTs.
The Default MRM Policy doesn't include a DPT to automatically delete items (but it does contain personal tags with the delete retention action that users can apply to mailbox items). If you want to automatically delete items after a specified period, you can create a DPT with the required delete action and add it to the policy.
For more details: Default Retention Policy in Exchange Online and Exchange Server
Comment: Thank you Joy. I was wondering, if this applies also to In-Place Archives.
Answer: Can anyone confirm that a default policy tag (DPT) for deletion applies to the in-place archive mailbox? My initial testing is showing that it is not.
Comment: I think, according to Joy's research, a in-place archive has no DPT by default. Means, when a user deletes items in his in-place archive, they will be kept for a while in the invisible recoverable items store and will then be permanently deleted. If you want to have an immutable archive, you have to put the whole mailbox on-hold.


differentiating "n" question

Question: i would like to know the difference here (this is no longer a homework question but rather concept differentiation)
we know that probability = s/n (where s = success and n = total outcomes)
in this question:
<code>    For a certain style of new automobile, the colors
blue, white, black, and green are in equal demand.
Three  successive  orders  are  placed  for  automo-
biles of this style. Find the following probabilities
a  One  blue,  one  white,  and  one  green  are
ordered.
b  Two blues are ordered.
c  At least one black is ordered.
d  Exactly  two  of  the  orders  are  for  the  same
color.
</code>
the "n" is simply 4 x 4 x 4 = "64" in each letter
while in this type of question
<code>An  assembly  operation  for  a  computer  circuit
board  consists  of  four  operations  that  can  be
performed in any order.
a  In how many ways can the assembly opera-
tion be performed?
b  One  of  the  operations  involves  soldering
wire to a microchip. If all possible assembly
orderings  are  equally  likely,  what  is  the
probability that the soldering comes first or
second?
</code>
the "n" in letter b is "24" (which is simply 4! or 4 x 3 x 2 x 1)
whats the difference of n between the 2 questions. im having difficulty to understand n here.
Comment: What is the word *concept* referring to, here?
Comment: its referring to differentiating the "n" midst various situations
Comment: Then use *difference* or whatever, but not [concept](http://en.wikipedia.org/wiki/Concept_%28disambiguation%29).
Comment: ok edited. tnx.
Answer: Firstly, some assumptions are being made. We should be explicit about them, so that we understand what's going on. We are assuming every outcome to be equally likely. This is a very special assumption. It's what lets us say, since outcome X can happen in 10 different ways, and there are 20 total possibilities, we deduce that outcome X has probability $1/2$.
Other than that, the only key idea is that the first question allows replacement. So we might have Blue, Blue, Blue. In the second, we cannot have Solder, Solder, Solder, Solder. In elementary questions, there are only a few different aspects that can change. The 4 most important are: the number of objects, how many are to be chosen, whether they are chosen with replacement (i.e. whether they can or cannot repeat - this is what's going on here), or whether different objects can be distinguished.
If you can identify these 4 aspects fully, you likely have gotten all the information you need to go to some form of formulae or other direct computation.
Answer: In the first question, you have 4 choices for the color of the first car, and for each such choice you have four choices for the color of the second car, and similarly for the third. So you have $4\times 4\times 4$ possibilities.
In the second example, after you have made one of the four choices for the first operation, you are not allowed to use that operation as the second operation again. So you have only 3 choices for the second operation. Similiarly, you are not allowed to use one of the first two choices for the third operation, so only two remain. After this choice is made, only one operation remains. So you have $4\times 3\times  2\times 1$ possibilities.
Comment: thx! ur explanation helps

differentiating "n" question


Fixing orientation of connected smooth manifold in $\mathbb{R}^n$ by fixing a frame in any of its tangent spaces

Question: I would like to show that fixing the orientation of $ k $ -manifold smooth connected $ S $ in $ \mathbb {R} ^ n $ is equivalent to fixing a frame for one of its tangent spaces. (Source: Zorich, Mathematical Analysis II, 'orientation of surfaces', pag.175)
What I know is that different orientations correspond to orienting atlases containing maps that cannot be consistent with maps in other orienting atlases of other equivalence classes, when their domains of action overlap.
How could we pass from this fact, to the fact that it is enough to fix a frame anywhere $ x_0 \in S $ to determine the orientation of $ S $?
Answer: It seems from the question that you are defining an orientation of a connected, orientable manifold $M$ to be a maximal oriented atlas (i.e. a maximal atlas such that all transition functions have Jacobians with uniformly positive determinant). If you are instead using an equivalence class of atlases, the maximal atlas is just the union of the equivalence class.
One can show $M$ has exactly two such orientations, which we can call $\mathcal{A}$ and $-\mathcal{A}$, and any overlapping charts $(U,\varphi)\in\mathcal{A}$ and $(V,\psi)\in-\mathcal{A}$ are incompatible, i.e the Jacobian of the transition function between them has uniformly negative determinant.
Choose a basis $E=(e_1,\dots,e_n)$ for $T_pM$. Given a chart $(U,\varphi)$ with $p\in U$, we define the coordinate representation of $E$, denoted $E^i_j$,as the matrix whose columns are coordinate representations of the $e_j$, i.e. $E^i_j=dx^i(e_j)$. We say that $E$ is consistently oriented with $\varphi$ if $E^i_j$ has positive determinant. When changing to a different chart $\bar{\varphi}$, we have $\bar{E}^i_j=\frac{\partial \bar{x}^i}{\partial x^k}E^k_j$, and so $\det(\bar{E}^i_j)=\det(d\Phi)\det(E^i_j)$, where $\Phi$ is the transition function.
Given an orientation $\mathcal{A}$, we say $E$ is consistently oriented with $\mathcal{A}$ if $E$ is consitently oriented with some (and thus any) chart around $p$ in $\mathcal{A}$. Note that $E$  is consistently oriented with exactly one of the two orientations of $M$.
Therefore, given any basis for any tangent space, we may choose the unique orientation consistently oriented with that basis.


Mediatr get command name

Question: At the moment we have auditting of our entities that happens in our ApplicationDbContext by checking all the entities in the changetracker.
We'd like to expand the Audit records by logging the name of the command that triggered the data manipulations.
Anyone have an example on how to get this command name?
Answer: MediatR has the options to add a Pre- or Postprocessor. Read this article

I.e. you could add a logger into such a processor
<code>public class CommandPreProcessor : IRequestPreProcessor<ICommand>
{
    public CommandPreProcessor(ILogger<CommandPreProcessor> logger)
    {
        _logger = logger;
    }

    public Task Process(ICommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Issued command: {commandName}", request.GetType().Name);
        return Task.CompletedTask;
    }

    private readonly ILogger<CommandPreProcessor> _logger;
}
</code>

Mediatr get command name


Unique decomposition of a positive definite matrix into a sum of outer products ${\bf x}_k{\bf x}_k^{\rm T}$ and a diagonal matrix?

Question: Given a (symmetric) positive definite matrix ${\bf A}\in\mathbb{R}^{N\times N}$, I know that it can always be expressed as a sum of $N$ rank-one matrices using the singular value decomposition ${\bf U\Sigma V^\ast}$ of the corresponding Cholesky matrix $\bf L$:
$${\bf A} = {\bf L}{\bf L}^{\rm T} = {\bf U\Sigma V^\ast}({\bf U\Sigma V^\ast})^{\rm T} = \sum_{i,j=1}^N \sigma_i \sigma_j {\bf u}_i {\bf v}^{\rm T}_i {\bf v}_j {\bf u}^{\rm T}_i= \sum_{i=1}^N \sigma_i^2 {\bf u}_i {\bf u}^{\rm T}_i,$$
with ${\bf u}_i$ being the $i$-th column of $\bf U$. So the matrix terms here are all outer products (dyads) of a vector with itself.
Can such a matrix also be expressed as the sum of a diagonal positive definite matrix $\bf D$ of full rank with $D_{ii} = d_i^2 > 0$ and a series of $M$ outer products ${\bf x}{\bf x}^{\rm T}$ (${\bf x}\in \mathbb{R}^N$)?
That is:
$${\bf A} = {\bf D} + \sum_{k=1}^M {\bf x}_k{\bf x}_k^{\rm T}$$
Basically, this is just one large system of $N(N+1)/2$ quadratic equations with $N(M+1)$ unknowns $\{d_i, x_{k,i}\}$. Using small test values for $N$ and $M$, I was able to find numerical solutions to this
equation system for specific example matrices, but it would be nice to have an analytic solution.
I suspect this should always be possible, at least for large enough values of $M$.
If so, what is the minimal value of $M$ for which such a decomposition exists? What can be said about the relationship of ${\bf d}={\rm diag}({\bf D})$ and the different ${\bf x}_k$?
Is there some $M$ for which the decomposition is unique?
If not, how can a counterexample be constructed?
Some thoughts on this:

for $N=1$, this is trivial, as one can always choose $\bf D=A$ and $M=0$
for $N\geq2$, I thought of choosing $D_{ii} = A_{ii}$ as a starting point and applying the Cholesky/SVD strategy on the difference ${\bf A}-{\bf D}$ to get the ${\bf x}_k$. However, for $N=2$ at least, this doesn't work, since the difference matrix is not positive definite. So I guess a related question is: For which $N\times N$ diagonal matrices ${\bf D}$ does ${\bf A}-{\bf D}$ remain positive definite?
from a geometric perspective, a positive definite matrix ${\bf A}$ defines an $N$-dimensional ellipsoid $\{{\bf z}\in\mathbb{R}:{\bf z}^{\rm T}{\bf A}{\bf z}={\rm const.}\}$. If the matrix is diagonal, the semi-axes of this ellipsoid are aligned with the coordinate axes.
In constrast, an outer-product-like term ${\bf x}{\bf x}^{\rm T}$ defines a pair of hyperplanes $\{{\bf z}\in\mathbb{R}:{\bf z}^{\rm T}{\bf x}{\bf x}^{\rm T}{\bf z}=\|{\bf z}^{\rm T}{\bf x}\|^2={\rm const.}\}$. So the above problem is equivalent to asking whether any $N$-dimensional ellipsoid can be understood as a "superposition" of an axis-aligned ellipsoid and a series of hyperplane pairs, although the meaning of "superposition" is somewhat vague in this context...
the above system of equations can be written using the tensor product $\otimes$:
$
\left(\sum_{i,j} a_{i,j}\,{\bf e}_i\otimes{\bf e}_j\right)
=
\left(\sum_i d_i^2\,{\bf e}_i\otimes{\bf e}_i\right)
+
\sum_k
  \left(\sum_i x_{k,i}{\bf e}_i\right) \otimes
  \left(\sum_j x_{k,j}{\bf e}_j\right)
$. Maybe some tensor algebra can come in handy?
Comment: The number of rank-one terms needed to represent $A-D$ is simply the rank of $A-D$, so the question of minimizing $M$ can be equivalently expressed as follows: Given a symmetric positive definite matrix $A$, what is the lowest-rank positive definite matrix of the form $A-D$ where $D$ is diagonal? As my comment on Batman's answer shows, you can always achieve rank $N-1$, but maybe it's possible to do better.
Answer: Let $A$ be positive definite, and $\xi$ be the smallest eigenvalue. Then, $A-\frac{\xi}{2} I$ is also positive definite (this just shifts the eigenvalues by $\frac{\xi}{2}$). The eigendecomposition of $A - \frac{\xi}{2} I= \sum_i \lambda_i u_i u_i^T$ where $\lambda_i, u_i$ are the eigenvalues+vectors of $A - \frac{\xi}{2}I$.
Then, you can write $A = \xi/2 I + \sum_i (\sqrt{\lambda_i} u_i) (\sqrt{\lambda_i} u_i)^T$.
Note that you can play around with this; so long as you replace $\frac{\xi}{2}$ with something $\leq \xi$, this idea works. Will it give you the minimum number of terms in the sum? not necessarily. For example, take $A$ to be diagonal with positive entries. You can then just take $A=D$ but this will give you terms in the sum.
Comment: You can do slightly better: $A-\xi I$ is a positive semidefinite matrix of rank $N-1$ or less, so you can do the same thing but with one fewer outer product (i.e. one of the $\lambda_i$ is zero, and in the notation of the question, we have $M=N-1$). But I suspect this may still not be the best possible.
Comment: Yeah -- my last comment alluded to that. You can have $M=0$ if $A$ is a diagonal matrix with positive diagonal. But, dealing with the minimality is trickier in general.
Comment: That's true. I was just saying if you're going to subtract a multiple of the identity, there's no reason not to use $\xi I$ itself. That way you can always get a rank-$(N-1)$ matrix instead of always rank $N$.
Comment: Sorry it took so long to get back to you: had some start-of-year things to attend to :) Yes, I have thought of choosing $D=\xi I$, but as you say, I suspect there may be an even better solution. The extreme case with $A$ being diagonal can be resolved with $M=0$, and there is presumably a whole set of matrices which can be constructed with just $M=1$ terms in the sum. I'm just wondering whether a general statement can be made about matrices which can be expressed with arbitrary $M$. How large is this set for every value of $M$, compared to the full set of positive definite matrices?


VS 2015 Cordova structure and NuGet

Question: I am working on a Win81 Cordova app. It seems that the default install location for NuGet packages is not quite right. I am sure I am doing this wrong, but I do not know which part I should do differently.
From a fresh Cordova app in 2015, I add WinJS via NuGet. This puts WinJS in a folder at the project level. However, the new structure in 2015 seems to want this in the www folder. I can move the WinJS folder down, but I am curious if that is a sign I am structuring this incorrectly. What would be the standard approach in this case?

Move the WinJS to the www
Tell NuGet to put WinJS in www (I don't see how to do this)
Leave WinJS in project root and reference it there (I haven't been able to make this work yet)
User a different PM for Cordova apps
Comment: This may be a duplicate of http://stackoverflow.com/questions/30097425/using-nuget-on-vs2015-rc-tools-for-apache-cordova. However, as of VS 2015 RTM, this still seems to be a mismatch? I appologize if this is truly a dupe. In that case, how can I "refresh" the original to get current feedback?
Answer: NuGet puts the WinJS files in the project root to support Windows Store app development, so yes, for Cordova apps it needs to be moved to the www folder.
Comment: No, it would need to be in www folder. There will be a workaround published for this compatibility issue with Cordova/Nuget soon.
Comment: Would a Cordova app not need it in root for store deployment?
Comment: Glad this is getting fixed, I had to also find out, by trail-and-error that I had to drag the WinJS folder down a level to the www folder. Tried altering the src attribute of the script element but you can't point 'up' the way.

VS 2015 Cordova structure and NuGet


É possível salvar formulários  no localStorage com Javascript puro?

Question: Sou iniciante em Javascript e estou fazendo um protótipo de aplicação para um trabalho da faculdade, e não queria utilizar banco de dados nem nada, pois não vale a pena, preciso apenas testar o funcionamento da GUI.
Na minha aplicação, eu tenho um formulário, e gostaria de salvá-lo no localStorage.
Mas eu preciso salvar O formulário de forma que seus campos fiquem vinculados ao formulário lo local Storage. Como se fosse um objeto Json com seus atributos. (Também não sei salvar em Json).
Eu imaginei algo assim:
<form onsubmit="return guardaFormulario();">

             Nome:
            <input type="text" id="nome" />

             Agência:
            <input type="text" id="agencia" />

            <button type="submit">Enviar sua mensagem</button>

    </form>

E a função acionada ao submeter o formulário:
function guardaFormulario(){

   /*De alguma forma que eu não sei
 Guardo o formulário com seus atributos no local Storage */

}

Comment: Como é um trabalho de faculdade você pode armazenar um objeto JSON no formato string na storage. Ou se você quiser algo parecido com banco de dados pesquisa sobre Web SQL que os navegadores modernos suportam.
Comment: Qual parte você já sabe e qual tem dúvida? Sua pergunta envolve várias questões, entre elas 3 fundamentais: recuperar dados do form todo, serializar os dados, persistir no local storage. Seria melhor [edit] a pergunta e resolver uma etapa por vez, abrindo novas questões para os passos seguintes à medida que for resolvendo cada um.
Comment: @Bacco dá uma olhada agora por favor?
Comment: Veja resposta em https://pt.stackoverflow.com/questions/293265/como-salvar-objetos-javascript-no-formato-json-na-localstorage-e-depois-desseri/293275#293275
Answer: O localStorage é bem simples de usar você usa o setItem() para armazenar:
localStorage.setItem("chave", "valor");
//Ou
localStorage.chave = "valor";

E o getItem() para recuperar esse valor:
localStorage.getItem("chave");
//Ou
localStorage.chave;

No W3School tem mais alguns exemplos
Um exemplo de uso:
<form>
  <input type='text' id='chave'>
  <input type='button' id='salvar' value='Salvar'>
</form>

Para salvar um objeto JSON use stringfy() e parse():
localStorage.chave = JSON.stringfy({subchave1 = "valor1", subchave2: true});

var objeto = JSON.parse(localStorage.chave);
console.log(objeto.subchave1);

Comment: Editei a resposta com um uso. Não é necessário submeter o formulário, apenas adicione um ouvinte de evento, num botão por exemplo, e salve/busque no localStorage
Comment: então você pode fazer como o @Thiagosilr comentou, crie um objeto e salve ele como string: `joão: "{chave1: true, chave2: 15.3, ...}"`
Comment: Adiconei a resposta como manipular objetos JSON
Comment: Algo como `localStorage.joao = {agencia: document.getElementById('agencia').value, conta: document.getElementById('conta').value}`
Comment: Ok, mas a questão é como salvar o formulário. Para isso, eu poderia, ao invés de indicar uma página web no "action" do formulário, utilizar uma chamada de função que salva ele no localStorage? Como ficaria o código pra isso?
Comment: Mas dessa forma você está salvando cada campo do formulário sozinho, correto? Eu queria, com um formulário, salvar um "objeto" "conta de um cliente", de forma que eu pudesse recuperar os dados dessa conta pelo nome do cliente, por exemplo.
Comment: Isso, mas tipo, eu crio um objeto javascript, e salvo ele no localStorage daí? Como fica isso?
Comment: Posso usar um atributo como chave, e os demais como subchaves? Exemplo:         var nome = getElementById('nome');
   var agencia = getElementById('agencia');
   var conta = getElementById('conta');     localStorage.meuObjeto = JSON.stringfy(nome= "nome"{subchave1 = "agencia", subchave2: "conta"});
Comment: Vou fazer uma pergunta específica...
Comment: Você quer guardar todo html do formulário com os valores dos sues inputs?
Comment: Tipo isso. Ao preencher este formulário, eu estou criando um cliente com sua agência e conta.
Comment: Fiz uma pergunta específica a respeito de salvar este objeto originado do formulário como Json aqui: https://pt.stackoverflow.com/questions/293265/como-salvar-objetos-javascript-no-formato-json-na-localstorage-e-depois-desseri
Comment: Exatamente! Vou tentar
Answer: Com localStorage você consegue armazenar os dados de um formulário em formato de string JSON.
Usando FormData você armazena todos os elementos do formulário em um objeto, em seguida fazendo um for você adiciona as entradas em um objeto, ficará neste formato, sendo os pares name => value:
{"nome":"fulano","email":"email@example.com" ... }

Para recuperar os dados, você usa o JSON.parse para converter os dados salvos no localStorage em objeto JSON e usar um for para popular o formulário com os valores salvos.
Nesse for você busca os elementos do formulário pelo seu name e insere o respectivo valor. Mas é preciso verificar também o tipo (type) dos elementos, porque alguns irão receber value (input, select, button, textarea...) e outros checked (radio e checkbox).
Escrevi o código abaixo que irá fazer tudo isso.
Neste link você pode testar em um formulário básico.
Código:
// pega o click do botão de submit do formulário
document.body.querySelector("button").addEventListener("click", function(){

   var form = document.body.querySelector("form"),
       data = new FormData(form),
       json = {}; // objeto que irá guardar os dados

   for(var dados of form){

      var typ = document.body.querySelector("[name='"+dados.name+"']").type,
          val = dados.value;

      if(typ == "radio"){
         val = document.body.querySelector("[name='"+dados.name+"']:checked").value;
      }else if(typ == "checkbox"){
         val = document.body.querySelector("[name='"+dados.name+"']").checked;
      }else if(typ == "select-multiple"){

         var mul = [],
             els = document.body.querySelector("[name='"+dados.name+"']").options;
            for(var x=0; x<els.length; x++){
               if(els[x].selected){
               mul.push(els[x].value);
               }
            }
         val = mul;
      }

      json[dados.name] = val;
   }

   localStorage.setItem("formulario", JSON.stringify(json));

});

// recuperação dos dados guardados no localStorage
document.addEventListener("DOMContentLoaded", function(){

   var formulario = localStorage.getItem("formulario");

   if(formulario){ // verifico se o localStorage existe

      var form = document.body.querySelector("form");

      formulario = JSON.parse(formulario);

      for(var dados in formulario){

         var tag = document.body.querySelector("[name='"+dados+"']").tagName,
             typ = document.body.querySelector("[name='"+dados+"']").type;

         if(tag.match(/INPUT|SELECT|TEXTAREA/) && !typ.match(/radio|checkbox|select-multiple/)){

            document.body.querySelector("[name='"+dados+"']").value = formulario[dados];

         }else if(typ == "checkbox"){

            document.body.querySelector("[name='"+dados+"']").checked = formulario[dados];

         }else if(typ == "select-multiple"){
            var mul = formulario[dados];

            for(var item of mul){
               document.body.querySelector("[name='"+dados+"'] option[value='"+item+"']").selected = true;
            }

         }else if(typ == "radio"){
            document.body.querySelector("[name='"+dados+"'][value='"+formulario[dados]+"']").checked = true;
         }

      }

   }
});


Prove $\sum_{v=0}^n{\alpha \choose v}{\beta \choose n-v} = {\alpha + \beta \choose n}$ using induction on $n$

Question: For $\alpha, \beta \in \mathbb{C}$ and $v \in \mathbb{N}$ let
$${\alpha \choose 0} = 1 \ \ \text{and} \ \ {\alpha \choose v} = \prod_{j=1}^v\frac{\alpha - j + 1}{j}.$$
The claim is that
$$\sum_{v=0}^n{\alpha \choose v}{\beta \choose n-v} = {\alpha + \beta \choose n}.$$
I try to prove this by using induction $n$.
The base cases are $n = 0$ and $n = 1$:
$$n = 0:  {\alpha \choose 0}{\beta \choose 0} = 1 = {\alpha + \beta \choose 0}$$
$$n = 1:  {\alpha \choose 0}{\beta \choose 1} + {\alpha \choose 1}{\beta \choose 0} = {\beta\choose 1} + {\alpha \choose 1} = \beta + \alpha = {\alpha + \beta \choose 1}$$
Induction hypothesis: assume for $n = k-1$
$$\sum_{v=0}^{k-1}{\alpha \choose v}{\beta \choose k-v} = {\alpha + \beta \choose k-1}.$$
Then for $n = k$,
\begin{align}
\sum_{v=0}^{k}{\alpha \choose v}{\beta \choose k-v} &= \sum_{v=0}^{k-1}{\alpha \choose v}{\beta \choose k-v} + {\alpha \choose k}{\beta \choose 0}\\
&= \sum_{v=0}^{k-1}{\alpha \choose v}{\beta \choose k-v} + {\alpha \choose k}\\
&= {\alpha + \beta \choose k-1} + {\alpha \choose k}\\
&= \prod_{j=1}^{k-1}\frac{\alpha + \beta - j + 1}{j} + \prod_{j=1}^k\frac{\alpha - j + 1}{j}\\
&= \prod_{j=1}^{k-1}\frac{\alpha + \beta - j + 1}{j} + \prod_{j=0}^{k-1}\frac{\alpha - j}{k-j}
\end{align}
Now I'm stuck. I'd appreciate it if someone can help me.
Comment: @JeanMarie Thank you for the link. However, they don't use induction. I was wondering if we can still prove it using induction.
Comment: It is the well-known Vandermonde identity (https://en.wikipedia.org/wiki/Vandermonde%27s_identity)
Comment: @yisishoujo But $\alpha$ and $\beta$ are complex  numbers. So I can't do that right?
Comment: then you multiply $n$ on both side and split $n$ as $n-v+v$
Comment: @yisishoujo I'm not sure I understand. So we have then
$$(n-v+v)\prod_{j=1}^{k-1}\frac{\alpha + \beta - j + 1}{j} + (n-v+v)\prod_{j=0}^{k-1}\frac{\alpha - j}{k-j}$$
on the RHS
Answer: I mean LHS is equal to
\begin{equation}
\begin{split}
&\frac{1}{n}  \sum v\binom{\alpha}{v} \cdot \binom{\beta}{n-v} + \binom{\alpha}{v} \cdot (n-v)\binom{\beta}{n-v} \\
= & \frac{1}{n}  \sum \alpha \binom{\alpha-1}{v-1} \cdot \binom{\beta}{n-v} + \binom{\alpha}{v} \cdot \beta \binom{\beta-1}{n-1-v} \\
= & \frac{1}{n} (\alpha + \beta) \binom{\alpha+\beta-1}{n-1} \\
= & \binom{\alpha + \beta}{n}
\end{split}
\end{equation}
Comment: So you dont need the induction hypothesis here?
Comment: it is used in the third line to get $\binom{\alpha+\beta-1}{n-1}$


Statistical test for Twitter Volume

Question: I have 2 Twitter datasets, one from 2014 and the other from 2015. I want compare the difference in Twitter volume (number of posts) between these two years. Would a t-test make sense here? I'm confused if I can compare volume instead of 2 means.
Thank you!
Comment: Please dexcribe the data and the question further. If you only have one count for one year and one count for the other, there is no way of telling, if one is significantly higher than the other, because there is no information, how large the counts usually vary from year to year. Further Explanation of the given data andrResearch question should lead to better answers.
Answer: A possible idea is to apply a poisson glm model, so you can retrieve the significance of the categorical variable.
E.g. on R:
y<-c(2164,2652,1236)
x<-c("2001","2002","2001","2002")
mod<-glm(y~x,family=poisson)
summary(mod)
Also, you better dig a little bit more about the topic. There's plenty of publications or web pages, like https://www.researchgate.net/post/Which_is_the_most_appropriate_method_to_analyze_counts.

Statistical test for Twitter Volume


Correct definition of antiderivative function

Question: I am looking for the correct definition of antiderivative  function  on a set $I\subset \mathbb{R}$ (think of the case where $I = \mathbb{R}  / \mathbb{Q}$ )
Let $f: \mathbb{R} \to \mathbb{R}$  and a set $I\subset \mathbb{R}$ (edit  $f$ is supposed to be defined on $ \mathbb{R}$ or on an open set containing $I$)
definition 1: an antidérivative  function   of $f$ on $I$ is a function $F$ differentiable on an open $J$ containing $I$ such that $F '= f$ on $I$
definition 2: an antidérivative  function   of $f $ on $I$ is a function $F$ (edit  $F$ is supposed to be defined on $ \mathbb{R}$ or on an open set containing $I$) differentiable on all points of  $I$ such that $F '= f$ on $I$
definition 3:  may be
Comment: What do you want to use this definition for? Usually, derivatives are only defined on open sets in $\mathbb{R}$.
Comment: See this question: https://math.stackexchange.com/questions/268914/why-does-the-condition-of-a-function-being-differentiable-always-require-an-open
Comment: @Sambo i want to know if  $f$ is a continuous function on a set $I\subset \mathbb{R}$. Does there always exist an antideravative of f  ? with definition 1
 https://math.stackexchange.com/questions/2853575/existence-of-an-antiderivative-for-a-continuous-function-on-an-arbitrary-subset
Comment: Definitions are made up, and choosing a good definition depends on what it's used for. As you found out in the post you linked, definition 1 leads to a negative answer to your question. As for definition 2, you'll need to define what it means for $F$ to have a derivative at all points of $I$. For example, how would you define the derivative of a function on $I=\{1,2,3\}$?
Comment: Why do you want to know whether a function always has an antiderivative? In any context I can think of, we don't need to define on antiderivative on anything other than an open set.
Comment: of course , f is supposed to be defined on $\mathbb{R} $ or on an open containing I. Derivability in 1,2,3 is well known. what your choice 1 or 2
Comment: I meant differentiability of $F$. Is $F$ supposed to be defined outside of $I$ as well?
Comment: yes , I edited définition 1
Comment: The Fundamental Theorem of Calculus (Part One): Let $f:I\to \Bbb R$ be continuous where $I$ is  a non-empty open interval. Let $a\in I.$ For all $x\in I$ we have:  $F(x)=\int_a^xf(y)dy$ exists  and $\frac {dF(x)}{dx}=f(x).$... Part Two (with $I$ and $f$ as in Part One) is that if $G'(x)=f(x)$ for all $x\in I$ then for any $a \in I$ there exists $K_a\in \Bbb R$ such that $G(x)=K_a+\int_a^x f(y)dy$ for all $x\in I.$
Answer: $\newcommand{\R}{\mathbb{R}}$
$%$
Personally, I would say that definition 2 makes more sense; that is:

If we have functions $f,F: \R \rightarrow \R$ and a set $I \subset \R$, then we say $F$ is an antiderivative of $f$ on $I$ if $F$ is differentiable on $I$ and $F'(x) = f(x)$ for every $x \in I$.

I don't see a reason why we should require $F$ to be differentiable on open sets around $I$. However, this requirement may be useful for applications of this definition, of which I know none. As I pointed out in a comment, it really depends on how one plans to use this definition.
Comment: @ SamboThank's. Are you ok with: If we have functions f,F :$D\subset R→R$ definded on open set D  and a set I⊂D, then we say F is an antiderivative of f on I if F is differentiable on I and F′(x)=f(x) for every x∈I.
Comment: Yes, that would also be reasonable.
Comment: Thank's , I will ask a new question with this definition https://math.stackexchange.com/questions/2855483/antiderivative-function/2855485#2855485


Problem regarding the concept of random error component in simple regression model and the nature of its variance

Question: I have just started learning regression analysis and have doubts on its basic assumptions. Specifically, I do not have a clear idea over the use of the random error component $\epsilon$ in the regression model.

Assumption $1$ : The simple linear regression model is given as $$Y_i=\beta_0+\beta_1.X_i+\epsilon_i$$, where $Y$ is response variable, $X$ is regressor (deterministic), $\beta_0$ is the intercept, $\beta_1$ is slope and $\epsilon_i$ is the random error component.
Assumption $2$ : $\epsilon_i \sim \mathcal {N(0,\sigma^2)}$ and $\epsilon_i$ and $\epsilon_j$ are independent of each other.

Now let me elaborate my problem.
Suppose I am a restaurant owner and I have a huge record of numbers of meals ordered with bill amount and the tip amount for each meal ordered. I want to predict what the next tip amount should be, for any given bill amount. But there I'm stuck.
\begin{array}{| c | c | c |}
\hline
\\\text{Number of Meals Ordered} & \text{Bill Amount per Meal (in Dollar)} & \text{Tip Amount (in Dollar)} \\
&(X) & (Y)\\\hline  1& x_1& y_1 \\\\\hline 2& x_2& y_2\\\\\hline 3& x_3& y_3\\\\\hline 4& x_4& y_4\\\\\hline .& .& .\\. & .& .\\. & .& .\\ .& .& .\\\hline 100000 & x_{100000} & y_{100000}\\\\\hline
\end{array}
If we treat this data-set as population and if we take any sample of size $100$ or of size $1000$, then we can find out $$Y_i=\widehat{\beta_0}+\widehat{\beta_1}.X_i+e_i\\\Longrightarrow Y_i=\widehat{\beta_0}+\widehat{\beta_1}.X_i+Y_i - \widehat{Y_i}\\\Longrightarrow \widehat{Y_i}=\widehat{\beta_0}+\widehat{\beta_1}.X_i$$ and later we go for model adequacy checking etc.
 - Here in the diagram I just tried to understand, how does the concept of $\epsilon_i$ arise into the general model.
So, from Assumption $1$ - I have the questions

Nowhere in the analysis we are using or estimating $\epsilon_i$, then how does the concept of random error component arise in the model?
  If $\epsilon_i$ is unknown, then how can $e_i$ estimate $\epsilon_i$?

From Assumption $2$, we have $\epsilon_i$ and $\epsilon_j$ are independent of each other and the amount of error in $\epsilon_i$ and $\epsilon_j$ are different, therefore their variance should be different. Then $\epsilon_i$ should have heteroscadastic variance rather than homoscadastic variance.
Any help is highly appreciated.
Comment: Regarding your last point, variables can be independent but still be drawn from the same distribution with the same governing parameters (e.g., variance). So, $\epsilon_i$ and $\epsilon_j$ can be independent but come from the same distribution (i.e., have the same variance).
Comment: Assuming that the variance is constant for your model is not reasonable. Large bills will have large tips. Why would large tips have the same variance as small tips? It doesn't make a sense to me
Comment: By amount of error do you mean the value of $\epsilon_i$ for each unit? If you draw a sample from any single distribution, the value of the variables will differ. They can still be drawn from the same distribution with the same variance.
Comment: You need to pick the model that is reasonable for your problem. For instance, you could model the percentage ratio of the tip to the bill. For the ratio you could reasonably argue that the variance can be constant. You have to test the assumption, but at least it will have a chance to hold. The absolute amount of the tip has no chance to have the constant variance of error.
Comment: Cannot resume the diagram here. Any help please?
Comment: @Noah, some texts say that the - amount of errors are not same. if amount of errors are not same how can they have homoscadastic variance?
Comment: @Aksakal, that is my question - if we talk about constant variance, then bills and tips should have almost similar values.
Comment: @Aksakal, the example I used here is given to me for exercise. From your last suggestion it is clear that the homoscadasticity does not work in this example. Therefore, is linear regression modeling applicable here? And how can I understand whether the model (that I have picked) is reasonable?
Comment: Is this a home work? It sounds like it.
Comment: @Noah, one thing related to this topic I need to learn (a little deviated) - what is the method to plot (by hand ) the distribution for each $Y_i$ along the line $\beta_0+\beta_1.X_i$?
Comment: @Aksakal, I am practicing but do not have clear idea over regression analysis.
Answer: You do not observe the random errors $\varepsilon$, neither do you observe the  coefficients $\beta$. Yet, you have no problem estimating coefficients, but have an issue estimating errors. The purpose of modeling is often estimation of unobserved parameters or quantities.


How to replace single character in large MySQL tables

Question: I had some problems with upgrading joomla from 1.0 to 1.5 (I have to go all the way to 1.7 ;).
Anyway, my client has an old joomla 1.0 instalation and the site is hudge and in Croatian. That means I have to deal with characters like Č,č,Ć,ć,Đ,đ... Old database is in latin1_swedish_ci collation, and I've transferred it with migration script to new database of joomla 1.5 that is in utf8_general_ci.
That resulted (as expected) in some character confusion, so for example:
ć became è, È --> Č, etc...
Converting 1.0 database to utf8 collation is not an option, since it cuts off rest of the content on the first appearance of Č,ć,đ,đ etc...
So, what I was doing is this query:
update jos_content
    set introtext = replace(introtext, 'È', 'Č');

What this does is get the joomla content table and in all intro texts replaces È with Č.
I did this for titles as well, but when I try to do it with fulltext, I get this error:
Error
SQL query:

UPDATE jos_content SET FULLTEXT = REPLACE( introtext,  'È',  'Č' ) ;

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fulltext = replace(introtext, 'È', 'Č')' at line 2

SO, is this some kind of memory issue (since this is a full text after all) or am I just doing something wrong. Also, if there's a better way to replace all this characters please tell me, this is what I figured out from MySQL "unreadable" documentation.
Comment: Also note the copy error (?): SET \`fulltext\` = REPLACE(\`fulltext\`, ...
Answer: FULLTEXT is a reserved word in mysql and need to be escaped by back ticks (`) if your column name have the same name.
UPDATE jos_content SET `FULLTEXT` = REPLACE(introtext, 'È', 'Č');

Comment: LOL, Thank you very much, I completely forgot that fulltext is reserved word.


devexpress xtratreelist poor performance

Question: I have a simple xtratreelist on a form and I have a simple firebird data table with 846 rows. I select 5 columns from the database and I populate the treelist.
Here is the code:
ConnectToDb(fbconn, CEGNEV)
    fbcommand.Connection = fbconn
    fbcommand.CommandText = "select szamlaszam, szamlanev, szamlacsop, szamlatip, szamlakat from szamlatukor order by szamlaszam"
    fbadapter.SelectCommand = fbcommand
    fbadapter.Fill(fbdataset)
    fbdataset.Tables(0).TableName = "szamlatukor"
    trlSzamlatukor.DataMember = "szamlatukor"
    trlSzamlatukor.DataSource = fbdataset
    trlSzamlatukor.ParentFieldName = "szamlaszam"
    trlSzamlatukor.PopulateColumns()
    fbconn.Close()

Populating the treelist takes 18 seconds! This is slow, very slow.
I added a xtragridcontrol too and populate this with the same table. It happens in a time of a mouseclick.
What could be the reason for the poor performance of the treelist?
Comment: Was the answer below helpfull? Have you made any progress, what have you tried? Could you pinpoint the source of the slow population?
I assume it would help your reputation if you would be polite enough to reply if someone has tried to help you.
Answer: What is about trying this, which avoids immediate visual updates?
trlSzamlatukor.BeginUpdate()
trlSzamlatukor.PopulateColumns()
trlSzamlatukor.EndUpdate()

Comment: Because I have given this answer: Meanwhile I learned that BeginUpdate does not have any effect on PopulateColumns().
When I do some simple measurements, I can recognize that PopulateColumns() for the XtraTreeList has kind of an O(n*n) dependency in the number of items.
However, it's much better than 18s for only 845 items, e.g. about 800ms for 10000 items (and then already 13500ms for 40000 items).
But I did not use a dataset, only a datatable.

1) Using DataTable.Rows.Add
2) Using a real table in SQL Server Express.

There are almost the same results.


What is the name of this man who made three pianos play at once?

Question: I remember hearing a segment (almost certainly on NPR) about a man who played a piano while two other pre-programmed pianos used an algorithm to change what he was playing into another pattern and play along at the same time. Does anyone know who this artist is?
Comment: My read is that it's an identification question, which are off topic.
Comment: Please see conversations around https://music.meta.stackexchange.com/search?q=identification. This SE doesn't cover simple "what is this" questions, and "who is this" is basically the same thing.
Comment: Welcome! Please check out [the topics that are covered here](https://music.stackexchange.com/help/on-topic). This might be a bit too much of a "trivia" question to be on-topic. But you might edit it to ask more about *how* this was accomplished, which would be much more relevant. Please explain a bit more, too; I'm wondering why "pianos" were used when a computer running Reaktor or the like would be a lot easier. Unless it means this was done in an entirely analog and mechanical way, which would be FASCINATING.
Comment: @AndyBonner I'm not sure how this is a trivia question and not just an identification question, since I don't know the answer and I'm asking if someone in the community can find the answer for me. I really don't remember much, but all I seem to recall is that there were three pianos, and two of them were playing by themselves.
Answer: Maybe Ólafur Arnalds?  I've seen him live, he has pianos rigged with some kind of responsive system - they seem to be reacting to the audience murmurs  before he'd even come on stage.
Edit: he calls them "Ghost Pianos", and has definitely done a Tiny Desk
Comment: And there's an actual NPR article, probably what the OP is remembering: https://www.npr.org/2018/07/19/630111211/one-key-many-notes-lafur-arnalds-piano-rig-fuses-technology-and-musicality
Comment: I'm pretty sure this is it. Thank you for your answer!


In-house Trusted Certificate

Question: Hi there I'm a developer looking at introducing ClickOnce deployment for an internal .NET Winforms application that will be distributed via the corporate network.
Now I would like to deploy this application under the full trust model however in order for that to happen I need to sign the software with a certificate. I can do that with a "test" certificate that has no information of the publisher etc, however that means an extra step will occur on the users workstation where they will have to confirm that the software is OK.
So what I want to know is. is there a way I can get my IT Infrastructure guys to create me a an "internal" certificate from the domains Certificate Authority, or do I have to go and pay for a certificate from somebody like VeriSign?
Thanks
Comment: I'm more than capable of deciding when it is an appropriate time given my circumstances to ask a question thank you.
Comment: You really should be asking this of your IT people FIRST.
Answer: Yes, you can create an internal certificate and then a MS Group Policy can be setup whereby each computer in the domain automatically "trusts" any code signed with that certificate.
The Group Policy Item is:
<code>Computer Configuration -> Windows Settings -> Security Settings -> Public Key Policies
</code>
In our case, we created an internal CA and put any certs made by that CA as trusted.  I.e. it was in the Trusted Root Certification Authority section.
Comment: That sounds exactly what I'm after. Thank you for pointing me in the right direction!
Answer: Your IT staff should be able to create a cert for you. As you said it will not be completely trusted and the user will be prompted to trust the cert. For testing purposes this is completely viable option. If you have a  separate security team this may fall under their responsibility.
Comment: I'm talking about the production environment and I don't want the users to have to trust the cert. I'm able to create a test cert, it's a trusted cert on the network I'm interested in. Thanks
Answer: if they already have a PKI I can't imagine that they would not have already created a trusted root infrastructure.  Usually you deploy the certificate of the root CA in the default domain policy's trusted root certification autorities section.

In-house Trusted Certificate


Angular async detect changes

Question: How can I "detect changes" in testing Angular without testbed?
With a component, I will have this:
it('should work', async(() => {
  const fixture = TestBed.createComponent(TestComponent);
  // do some async call
  fixture.detectChanges();   // <=== This is what I want
  expect(something).toEqual(somethingElse);
});

With a service, I don't always have a testbed. How to tell angular to wait before asserting? Example:
it('should work', async(() => {
  const service = new MyService();
  const sub = service.emitter$.subscribe((val) => {
    // expect(val).toEqual(otherVal);
  });
  service.doAsyncWork();
});

How to get these connected? What if I have two phases to check (e.g. once before that async work, once after, but all after some initial period)?
Answer: use fakeAsync with the tick function to simulate time period.
it('should work', fakeAsync(() => {
  const fixture = TestBed.createComponent(TestComponent);
  // do some async call
  tick(10000);
  expect(something).toEqual(somethingElse);
});

Comment: That's a temporary solution, in some occasions I depend on things outside my control for this incoming data. Thanks though.

Angular async detect changes


Powershell Get-ChildItem cmlet with '-recurse' optional

Question: I'm trying to figure out if it's possible to use the parameter -Recurse into Get-ChildItem cmdlet depending on a value of another variable.
I mean, let's say that we have the boolean parameter $flag, if $flag is True I would like to insert the parameter -Recurse into Get-ChildItem execution, otwerwise not.
Many Thanks.
Answer: Switch parameters do allow for a boolean to be passed in if used with a colon ':'
Example:
$flag = $true
Get-ChildItem -Recurse:$flag

Will use -Recurse
$flag = $false
Get-ChildItem -Recurse:$flag

Will NOT use -Recurse
Comment: I don't see this technique being used very much, seems to be something from "the old days".
Comment: Hadn't really noticed tbh. "From the old days" seems to imply that there's a new way...share the knowledge @Snak3d0c , I want to know! :D
Comment: That's not what i meant hehe. I'm just saying that this technique isn't been used that often anymore (or so it seems). I used to come across it a bit more.
Comment: I use it quite often with -Confirm


Probability Of Rolling A Strictly Increasing Sequence On A Six-Sided Die

Question:
By rolling a six-sided die 6 times, a strictly increasing sequence of
  numbers was obtained, what is the probability of such an event?

I have no ideas on how to attack this. It says, an increasing sequence for the $6$ times were obtained. So this means, that on the first roll, you get $1$, and on second you get $2$, on the third you get $3$, and so on. The total sample space is given by $6^6$ and the probability of obtaining the set $\{1,2,3,4,5,6\}$ is $\frac{1}{6^6}$? Please help.
Answer: I think you are correct. No problem.
Answer: For each roll of the die, there are $6$ possible outcomes — ${1,2,3,4,5,6}$. You roll $6$ times, so there are $6$ possible outcomes for the first, for each of these there are $6$ possible outcomes for the second roll, and so on. This means there are $6 \cdot 6 \cdot 6 \cdot 6 \cdot 6 \cdot 6 = 6^6$ sequences possible. Only one of these is the sequence you want, so your chance of getting that sequence is $\frac{1}{6^6}$.

Alternatively, you can see it this way. There is a $\frac{1}{6}$ chance of getting a $1$ on your first roll, a $\frac{1}{6}$ chance of getting a $2$ on your second roll, and so on. This means the total probability of getting this particular sequence, is $\frac{1}{6} \cdot \frac{1}{6} \cdot \frac{1}{6} \cdot \frac{1}{6} \cdot \frac{1}{6} \cdot \frac{1}{6} = \frac{1}{6^6}$.


Electron.js app freezes after an hour unused

Question: I wrote an app with electron.js and vuetify.js for Windows 64bit; everything is ok about the app and its usual use case. The problem is: when the app is running and the user doesn't do anything with it, I mean leave it running (app main window is open) without any other processing, after about 1 hour, when the user tries to work with the program, the program hangs up and does not work, and the user is forced to close and reopen the program.
The same problem happens when the user runs the program and takes Windows to Hibernate mode, and after the restart of Windows, the program does not respond and and does not work.

electron version : 3.0.0

Solution:
the problem was solved with just one line code in the background.js file of electron, the problem came from Hardware Acceleration and because of that the app use more resources and and some hours make app not respond
<code>app.disableHardwareAcceleration();
</code>
by adding above code in the background process file the app runs and work very fast
Comment: Please read the [help] before posting.
Comment: It is likely due to a problem with the app, not Electron. Try profiling it, maybe there is a memory leak or an infinite loop, although it might be just a bug
Comment: @ᆼᆺᆼ , I also thought that there was a problem with the program
But for myself, no problem occurs on my computer, and on the other hand, the high consumption of RAM is common with chromium inside electron.
Answer: Sounds like a memory leak. Without more information though it's tough to resolve, but you could start here :
https://v2.vuejs.org/v2/cookbook/avoiding-memory-leaks.html
Comment: Thank you to post your answer, that's point you mentioned is very important but for my problem this not the real solution and no memory leaks was there! I was updated my question post and add the solution the problem came from Hardware Acceleration


in-line 'try' statement in C# possible?

Question: Is it possible to somehow invoke inline try statement in C#?
I'm detecting languages for my website and sometimes, when language is something like en-GR on client side for some reason .NET throws exception. So I need to use try and also catch even though I'm not really catching anything.
It just seems as a total overkill in this situation.
// Set allowed languages
string[] allowedLanguages = { "en", "fr", "ru" };

// Get all possible values
var routeLanguage = (filterContext.RouteData.Values["lang"] != null && allowedLanguages.Contains(filterContext.RouteData.Values["lang"].ToString())) ? filterContext.RouteData.Values["lang"].ToString() : null;
var cookieLanguage = (filterContext.HttpContext.Request.Cookies["lang"] != null && allowedLanguages.Contains(filterContext.HttpContext.Request.Cookies["lang"].Value)) ? filterContext.HttpContext.Request.Cookies["lang"].Value : null;
string clientLanguage = null;
try
{
    clientLanguage = (filterContext.HttpContext.Request.UserLanguages != null) ? new CultureInfo(filterContext.HttpContext.Request.UserLanguages[0]).TwoLetterISOLanguageName : null; // Exception sometimes without `try`
}
catch (Exception)
{
}

Edit
Exception is not something I can fix since I have no control over what user has in his culture info. .NET just sees en-FR as invalid one.
Comment: @Steve No, you *can* fix it.
Comment: Nah. You're approaching this the wrong way. Fix your error instead of trying to silence it!
Comment: Exception is not something I can fix since I have no control over what user has in his culture info. .NET just sees `en-FR` as invalid one.
Comment: what do you mean with inline try?
Comment: What exception is it throwing?
Comment: "Exception sometimes without `try`" It's not the index out of bounds exception, is it?
Comment: @dasblinkenlight At the sound of it, `CultureNotFoundException`.
Answer: First off, it is always better to figure out how to avoid the exception in the first place. Concentrate on that first. There is some reason why that exception is being thrown, and if you can determine what it is, then don't do that.
To actually answer your question: there is no out-of-the-box "eat all the exceptions in this expression" mechanism, but building your own is straightforward:
static T EatExceptions(Func<T> func)
{
  try { return func(); } catch { }
  return default(T);
}
...
clientLanguage = (filterContext.HttpContext.Request.UserLanguages != null) ?
  EatExceptions(() => new CultureInfo(filterContext.HttpContext.Request.UserLanguages[0]).TwoLetterISOLanguageName) :
  null; }

If someone tried to pull shenanigans like that in code I was reviewing then I would... well let's just say that the change would not get checked in. Eating exceptions like this is a very bad idea 99% of the time. Again: figure out what you are doing wrong and stop doing it. Don't do something wrong and then handle the failure.
Comment: @DanAtkinson: The issue is not that exceptions are slow. Exceptions are slow in comparison to, say, addition, but that's because addition is *insanely fast*.  You could throw thousands of exceptions a second and not worry about the perf implications.  The issue is that exceptions are *supposed to be exceptional*. A throw is a *non local goto*; it is hard to imagine a more potentially confusing and damaging control flow than that. So it should be limited to only rare, carefully analyzed cases.
Comment: I completely agree with the fact that you should always avoid the exception as it's not very performant. I had a case where I wanted my application to attempt doing something and if it failed, it didn't really matter as it was a superfluous.
Comment: I of course agree with what you're saying. This answer is probably a sticking plaster on a wider problem, and 'covering up' any attempt to deal with it is counter-intuitive. :-)
Answer: Have you tried getting rid of the try/catch statement completely?
string clientLanguage = null;
var userLanguages = filterContext.HttpContext.Request.UserLanguages;
if (userLanguages != null && userLanguages.Length > 0)
{
    var culture = CultureInfo
        .GetCultures(CultureTypes.AllCultures)
        .FirstOrDefault(
            x => string.Equals(
                x.Name,
                userLanguages[0].Name,
                StringComparison.OrdinalIgnoreCase
            )
        );
    if (culture != null)
    {
        clientLanguage = culture.TwoLetterISOLanguageName;
    }
}

Use try/catch only for handling exceptions that are out of your control. As their name suggests exceptions should be used for handling exceptional cases.
In this case you are doing standard parsing so it is much better to do defensive programming instead of trying, throwing, catching, ...
Comment: Of course that it is not out of control. Look at my code. I am controlling it. The OP was trying to pass the `TwoLetterISOLanguageName` directly to the CultureInfo constructor. Obviously this could throw an exception if the client has passed some invalid language. In my example I am attempting to find the corresponding CultureInfo from the list of all possible values which cannot throw.
Comment: I think that this exception is pretty much out of control, is it not? (Edited my post)
Comment: Well, the FirstOrDefault returns a CultureInfo, but you're assigning it to a string. Like the idea though.
Comment: @JoachimIsaksson, good point, let me fix that. Answer updated.
Comment: if this one is too slow, you can turn it into a `Dictionary`
Answer: _.Try(() => __YourStatementHere__ );

Using a little helper class like this:
///
/// Other utility functions.
///
public static class _ {

    ///
    /// Tries to execute the given action. If it fails, nothing happens.
    ///
    public static void Try(Action action) {
        try {
            action();
        }
        catch {
        }
    }

}

I know, this solution is not optimal either, but up to now the most concise one I could find.
Answer: First try to avoid the exception. Just because the string comes from a source you don't control, doesn't mean you can't validate it.
If you can't avoid it, you should catch the specific exception you expect and encapsulate that logic in a method. Don't catch all exceptions.
For example:
public static CultureInfo TryGetCultureByName(string name)
{
   try
   {
     return new CultureInfo(name);
   }
   catch(CultureNotFoundException)//Only catching CultureNotFoundException
   {
     return null;
   }
}

That way, if you later discover a better way to handle this specific error, you can easily replace it.
For example you could create a Dictionary<string, CultureInfo>, fill it from CultureInfo.GetCultures() and use TryGetValue to look up a culture without ever throwing an exception.
Answer: What you did is the right way to do it. You stated, why you cannot get rid of the exception (and I assume this is the case). So you have to handle it. Alas, C# does not have a try-catch as an expression (not sure how that would work - the catch "clause" would need to return a value).
Alternatively you can build a little helper function that takes a Func<T>, invokes it and passes through the value to the caller. If an exception occurres it returns (for example) default(T). That takes away a lot of the clutter and is reusable.
Answer: I've built an in-line try catch mechanic that may suit this purpose. I was going for a sort of LINQ-like or Callback function-y syntax. This is done using a couple of wrappers, a TryWrapper and a CatchWrapper so that the dot operators prompt the next steps appropriately, that implicitly cast to type of T.

You could also do something like
Try(() => UpdateSweetGreen("21", SweetGreen))
.Catch(LogToDb(e.Message))
.Catch(LogToFile(e.Message).Finally(ReportNewSweetGreen(SweetGreen);

Basically a CatchWrapper extends TryWrapper. So you could catch an exception off of another catch block. In this instance logging a failure of your method to a database, then if that fails to a file, then no matter what reporting the SweetGreen variable to some other component.
This all extends from TryWrapper
    public class TryWrapper<T>
    {
        protected internal T Result { get; set; } = default(T);

        protected internal Exception Exception { get; set; } = null;

        public static implicit operator T(TryWrapper<T> wrapper)
        {
            return wrapper.Result;
        }

        public static implicit operator Exception(TryWrapper<T> wrapper)
        {
            return wrapper.Exception;
        }
    }

and CatchWrapper which simply extends TryWrapper and cannot be invoked directly, instead only appearing after a try as you'd expect with standard implementation
    public class CatchWrapper<T> : TryWrapper<T>
    {
    }

Then a series of static extension methods
        public static TryWrapper<T> Try<T>(Func<T> func)
        {
            var product = new TryWrapper<T>();

            try
            {
                product.Result = func.Invoke();
            }
            catch (Exception e)
            {
                product.Exception = e;
            }

            return product;
        }

        public static TryWrapper<T> Try<T>(Action action)
        {
            var product = new TryWrapper<T>();

            try
            {
                action.Invoke();
            }
            catch (Exception e)
            {
                product.Exception = e;
            }

            return product;
        }

        public static CatchWrapper<T> Catch<T>(this TryWrapper<T> wrapper, Action<Exception> response)
        {
            if (wrapper.Exception is null) return wrapper as CatchWrapper<T>;

            response.Invoke(wrapper);
            wrapper.Exception = null;

            return wrapper as CatchWrapper<T>;
        }

        public static TryWrapper<T> Finally<T>(this TryWrapper<T> wrapper, Action<T> response)
        {
            response.Invoke(wrapper);

            return wrapper;
        }

        public static TryWrapper<T> Finally<T>(this TryWrapper<T> wrapper, Func<T> response)
        {
            wrapper.Result = response.Invoke();

            return wrapper;
        }

        public static TryWrapper<T> Finally<T>(this TryWrapper<T> wrapper, Action response)
        {
            response.Invoke();

            return wrapper;
        }

Now this does achieve that inline syntax the OP was asking for but I'd hazard to say its a touch less efficient since you could just deal with the exception directly in a standard try-catch. Still kindof cool to be able to specify the return directly before the Try, though this is risky if  defaults to null.
Answer: Well, leaving aside the (good) advice about pre-checking, there are several rather mundane/prosaic/obvious ways to do this:
First, you could wrap it in a function.  I assume that this would not be general enough for you.
Or, you could collapse the catch branch:
try
{
    clientLanguage = (filterContext.HttpContext.Request.UserLanguages != null) ? new CultureInfo(filterContext.HttpContext.Request.UserLanguages[0]).TwoLetterISOLanguageName : null; // Exception sometimes without `try`
} catch (Exception) { }

Or, you could just collapse the whole thing to a single line:
try { clientLanguage = (filterContext.HttpContext.Request.UserLanguages != null) ? new CultureInfo(filterContext.HttpContext.Request.UserLanguages[0]).TwoLetterISOLanguageName : null; } catch (Exception) { }

Not elegant, but simple, and it works.
Answer: This is one another way:
await new @try(async () => { user = await GetItemAsync(userId); })
         .@catch<Exception>(async () => { user = new User(); });

I think it's more verbose than the try/catch:
try { return await GetItemAsync(userId); }
catch (Exception ex) { return new User(); }

The helper class:
public class @try
{
    private Func<Task> func;
    private Action action;

    public @try(Func<Task> func)
    {
        this.func = func;
    }

    public @try(Action action)
    {
        this.action = action;
    }

    public async Task @catch<T>(Func<Task> fallback) where T : Exception
    {
        try
        {
            await func.Invoke();
        }
        catch(T ex)
        {
            await fallback.Invoke();
        }
    }

    public void @catch<T>(Action fallback) where T : Exception
    {
        try
        {
            action.Invoke();
        }
        catch (T ex)
        {
            fallback.Invoke();
        }
    }
}

Comment: Inspired on @Andy class

in-line 'try' statement in C# possible?


Definir posição da caixa suspensa utilizando o .append()

Question: Atualmente a minha caixa suspensa está aparecendo abaixo de todos os outros elementos:

Eu gostaria que ela aparecesse acima do botão Radar 1 e da caixa de texto ao lado.
Pois bem, eu tentei definir a posição da seguinte forma:

                <form action="" method="post" id="url-setter1">
                    <button class="button" id="botaoradar1" onclick="radarzinho1()">Radar 1</button>
                    <input type="text" name="url1" id="url1" style="width: 283px;" />

 Segundo elemento

Terceiro elemento

<button>Click para inserir o primeiro elemento</button>


FTP into existing Docker Containers

Question: I'm looking to see if it is possible to somehow FTP into an already existing Docker container? For example, I'm using the dockerfile/ghost in combination with jwilder/nginx-proxy, and once I deploy/build  a container, I'd like for the user to be able to FTP into the container running Ghost so they can upload additional files such as themes, stylesheets, etc. What would be the best method in accomplishing this? Thanks in advance!
Answer: You have a few choices:

run ftp in the Ghost container and expose a port
use a host directory to store the user content and give them FTP to the host (not the best choice)
map the same host directory into both the Ghost container and the FTP server container

Personally I thnk the last one is the best and the most work though the advantages will be worth it in the long run. I'm making the assumption that the uploaded content should survive container termination which is why I recommend using a mapped host directory, if this is not the case you can use linked volumes between the FTP container and the Ghost container.
Answer: Probably the most "dockery" way of doing this would be to run a container for your ftp server (something such as this https://github.com/gizur/docker-ftpserver) and a separate one for ghost, then mount a common volume.
The best way to synchronize these is with a version 2 docker-compose.yml
https://docs.docker.com/compose/compose-file/#volume-configuration-reference
The docker-compose.yml file might look something like this:
<code>version: '2'
services:
  ghost:
    build:
      context: ./ghost
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - "ftpsharevolume:/mnt/ftp"
    depends_on:
      - ftp
  ftp:
    image: someftpdockerimage
    volumes:
      - "ftpsharevolume:/srv/ftp"
    ports:
      - "21:21"
      - "20:20"
volumes:
  ftpsharevolume:
     driver: local
</code>

FTP into existing Docker Containers


Cauchy's real line and math philosophy till XIX

Question: I have to write an essay concerning philosophy of mathematics until the end of $XIX$ century. I've heard that the reason why the Cauchy's theorem (if continuous functions $f_n \rightarrow f$ then $f$ is continuous too) is wrong nowadays is the fact that his real numbers line was different then the modern one. It is indeed a very interesting topic but I couldn't find anything specific about it. Could you direct me to some sources or suggest a different topic?
Comment: I have seen an old reference to that thing once, but unfortunately, I've forgot where it is. I guess you'll have to wait for other people, sorry.
Comment: Maybe this is helpful: https://books.google.com/books?id=CVRZEXFVsZkC&pg=PA181&lpg=PA181&dq=history+of+Cauchy%27s+theorem&source=bl&ots=idBybBzxVi&sig=F2otOk481wjuJx5d5rJgrE5BosE&hl=en&sa=X&ved=0ahUKEwiq5M_Nhe7MAhULcj4KHUzCCDYQ6AEIKjAC#v=onepage&q=history%20of%20Cauchy's%20theorem&f=false
Comment: You can see also **Ch.4.3 Cauchy and Continuity** of Jeremy Gray, [The Real and the Complex: A History of Analysis in the 19th Century](https://books.google.it/books?id=zpDDCgAAQBAJ&pg=PA39) (2015).
Comment: This would perhaps be a better fit for [hsm.se].
Comment: User @leg14able, it may be helpful to replace "real line" by "number system" in your question.
Answer: Some scholars have argued that Cauchy's conception of the number line incorporated infinitesimals and his notion of convergence therefore imposes additional conditions (for example, convergence at infinitesimal points).
Thus, historian and mathematician Detlef Laugwitz argued that Cauchy's theorem was correct as stated.
Actually Cauchy himself published an article in 1853 where he gives additional details that make it clear that at least in this article his notion of convergence is stronger.
There is a review of these issues in this recent article.


A way to find out if my coin tosses are independent from each other or not

Question: Background:
Suppose I toss a coin 9 times. The outcome (i.e., $H ~or ~T$) of these $9$ tosses turn out to be:
$H ~T ~H ~H ~H~ T~ H~ T~ H$
Now, I have $10,000$ other people each toss a similar coin 9 times and I record the outcome of their tosses as well.
As a crude measure of correlation between my tosses, I define the following:
I consider the number of switches from  $H$ to $T$  or from $T$ to $H$.
Using this measure, I find 6 such switches in the outcome of my own tosses.
I apply this measure to the outcome of the tosses of the other $10,000$ people as well which results in the following frequency distribution (see below).
Question
My number of switches (i.e., 6) doesn't seem to be among the most frequently occurring number of switches by $10,000$ people, who just repeated my coin toss experiment.
What can I say about the independence of my coin tosses from each other based on this frequency distribution?
Comment: The results don't imply correlation.  It could just be that the coins are biased (p not equal 0.5).  However if you have long runs of heads and/or tails for example you might have correlation and the runs test can be used to show the existence of the correlation.
Comment: Look at my answer.  The test I employ only decides that the correlation is not zero.
Answer: If you toss the coin a large number of times you can test for independence verse correlation with just one sequence using the Wald-Wolfowitz runs test which counts the number of runs which is the number of times you get a sequence of runs.  In your example of 9 tosses, you have seven runs.  A small number of runs indicates independence.  Say the number of tosses is N.  Let N$_h$ be the number of runs of heads and N$_t$ be the number of runs of tails. Then N=N$_h$ + N$_t$ and it is known that under the null hypothesis that the distribution of runs is approximately normal with mean 2N$_h$ N$_t$/N +1 and variance 2 N$_h$ N$_t$(2 N$_h$ N$_t$-N)/(N$^2$(N-1)). Using this you can apply the test and reject the null hypothesis if the number of runs is much higher or lower than the mean.
In a way, this is similar to your counting of switches but it is known what is large and what is small. I do not think the distribution of your switches is established and there is no need to repeat the experiment many times with different coins.
You can read more about this by googling Wald-Wofowitz runs test.